Example usage for org.apache.commons.io FilenameUtils getExtension

List of usage examples for org.apache.commons.io FilenameUtils getExtension

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getExtension.

Prototype

public static String getExtension(String filename) 

Source Link

Document

Gets the extension of a filename.

Usage

From source file:com.mgmtp.jfunk.core.ui.ScriptsTreeModel.java

private File[] listContents(final File dir) {
    File[] files = dir.listFiles(new FileFilter() {
        @Override//from   w  ww .  j  a  va 2s  .  c  o  m
        public boolean accept(final File file) {
            String ext = FilenameUtils.getExtension(file.getName());
            return file.isDirectory() && !".svn".equals(file.getName()) || "script".equals(ext)
                    || "groovy".equals(ext);
        }
    });
    return files;
}

From source file:com.eufar.asmm.server.UploadFunction.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("UploadFunction - the function started");
    response.setContentType("text/html;charset=UTF-8");
    response.addHeader("Cache-Control", "no-cache,no-store");
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {//www .ja v  a 2s  . c o  m
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj;
            if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) {
                if (item.isFormField()) {
                    String name = item.getName();
                    String value = "";
                    if (name.compareTo("textBoxFormElement") == 0) {
                        value = item.getString();
                    } else {
                        value = item.getString();
                    }
                    response.getWriter().write(name + "=" + value + "\n");
                } else {
                    byte[] fileContents = item.get();
                    String message = new String(fileContents);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(message);
                    System.out.println("UploadFunction - file uploaded");
                }
            } else {
                System.out.println("UploadFunction - file rejected: wrong format");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("format");
            }
        }
    } catch (Exception ex) {
        System.out.println("UploadFunction - a problem occured: " + ex);
        response.getWriter().write("ERROR:" + ex.getMessage());
    }
}

From source file:ec.edu.chyc.manejopersonal.managebean.util.BeansUtils.java

/***
 * Abre un stream para descargar un archivo
 * @param direccionArchivoOrigen Archivo a descargar
 * @param nombreArchivoDescarga Nombre del archivo como se quiere descargar, puede ser diferente al nombre original
 * @return Stream de descarga// w ww . java2s . com
 * @throws FileNotFoundException En caso de no encontrar el archivo
 */
public static StreamedContent streamParaDescarga(Path direccionArchivoOrigen, String nombreArchivoDescarga)
        throws FileNotFoundException {
    String nombreArchivoGuardado = direccionArchivoOrigen.getFileName().toString();
    String extension = FilenameUtils.getExtension(nombreArchivoGuardado);

    String nuevoNombre = ServerUtils.convertirNombreArchivo(nombreArchivoDescarga, extension, 40);

    Path pathArchivo = direccionArchivoOrigen;
    InputStream stream = new BufferedInputStream(new FileInputStream(pathArchivo.toFile()));

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    StreamedContent streamParaDescarga = new DefaultStreamedContent(stream,
            externalContext.getMimeType(nuevoNombre), nuevoNombre);
    return streamParaDescarga;
}

From source file:com.esri.geoevent.test.performance.report.AbstractFileRollOverReportWriter.java

protected void rollOver(String fileName) {
    File target;//  ww  w. j  ava2s  .  c  o  m
    File file;
    boolean renameSucceeded = true;

    if (!new File(fileName).exists()) {
        return;
    }

    // If maxBackups <= 0, then there is no file renaming to be done.
    if (getMaxNumberOfReportFiles() > 0) {
        // Delete the oldest file, to keep Windows happy.
        String ext = FilenameUtils.getExtension(fileName);
        String baseFileName = FilenameUtils.getFullPath(fileName) + FilenameUtils.getBaseName(fileName);

        file = new File(baseFileName + getMaxNumberOfReportFiles() + '.' + ext);
        if (file.exists()) {
            renameSucceeded = file.delete();
        }

        // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
        for (int i = getMaxNumberOfReportFiles() - 1; i >= 1 && renameSucceeded; i--) {
            file = new File(baseFileName + i + "." + ext);
            if (file.exists()) {
                target = new File(baseFileName + (i + 1) + '.' + ext);
                renameSucceeded = file.renameTo(target);
            }
        }

        if (renameSucceeded) {
            // Rename fileName to fileName.1
            target = new File(baseFileName + 1 + "." + ext);
            file = new File(fileName);
            renameSucceeded = file.renameTo(target);
        }
    }
}

From source file:com.moviejukebox.scanner.OutputDirectoryScanner.java

public void scan(Library library) {
    /*/*from   w w  w. ja  v  a 2  s .co m*/
     Map<String, Movie> xmlLibrary = new HashMap<String, Movie>();
     scanXMLFiles(xmlLibrary);
            
     // Because the XML can have additional info, the key is not stable between rns
            
     protected void scanXMLFiles(Map<String, Movie> library) {
     */
    LOG.debug("Scanning {}", scanDir);
    File scanDirFile = new FileTools.FileEx(scanDir);
    if (scanDirFile.isDirectory()) {
        MovieJukeboxXMLReader xmlReader = new MovieJukeboxXMLReader();

        for (File file : scanDirFile.listFiles()) {

            String filename = file.getName();

            if (filename.length() > 4 && "xml".equalsIgnoreCase(FilenameUtils.getExtension(filename))) {
                FileTools.fileCache.fileAdd(file);
                String filenameUpper = filename.toUpperCase();
                boolean skip = "CATEGORIES.XML".equals(filenameUpper);
                if (!skip) {
                    for (String prefix : Library.getPrefixes()) {
                        if (filenameUpper.startsWith(prefix + "_")) {
                            skip = true;
                            break;
                        }
                    }
                }

                if (skip) {
                    continue;
                }

                LOG.debug("  Found XML file: {}", filename);

                Movie movie = new Movie();
                /*
                 *  Because the XML can have more info available than the original filename did,
                 *  the usual key construction method is not stable across runs. So we have to find
                 *  what the key *would* have been, if all we knew about the movie was the filename.
                 */
                MovieFileNameDTO dto = MovieFilenameScanner.scan(file);
                movie.mergeFileNameDTO(dto);
                String key = Library.getMovieKey(movie);

                if (library.containsKey(key)) {
                    LOG.debug("  Video already in library: {}", key);
                } else {
                    if (xmlReader.parseMovieXML(file, movie)
                            && StringTools.isValidString(movie.getBaseName())) {
                        LOG.debug("  Parsed movie: {}", movie.getTitle());

                        if (!library.containsKey(Library.getMovieKey(movie))) {
                            LOG.debug("  Adding unscanned video {}", Library.getMovieKey(movie));
                            movie.setFile(file);
                            library.addMovie(key, movie);
                        }

                    } else {
                        LOG.debug("  Invalid video XML file");
                    }
                }
            } else {
                LOG.debug("  Skipping file: {}", filename);
            }
        }
    } else {
        LOG.debug("  Specified path is not a directory: {}", scanDir);
    }
}

From source file:dmh.kuebiko.view.ImageManagerTest.java

/**
 * Retrieve a list of all known image ID strings of a particular size.
 * @param size The size of the requested images.
 * @return A list of valid image IDs.// ww w .j ava 2 s.  co  m
 */
private Collection<String> getImageIds(ImageSize size) throws URISyntaxException {
    String path = String.format("images/%s/", size.toString().toLowerCase());
    File imageDir = new File(getClass().getResource(path).toURI());

    Collection<String> imageIds = Lists.newArrayList(
            Collections2.transform(Arrays.asList(imageDir.list()), new Function<String, String>() {
                @Override
                public String apply(String input) {
                    return "png".equals(FilenameUtils.getExtension(input))
                            ? FilenameUtils.removeExtension(input)
                            : "";
                }
            }));
    imageIds.removeAll(Collections.singleton(""));

    return imageIds;
}

From source file:fi.johannes.kata.ocr.utils.structs.Filename.java

private void cacheStrings() {
    fullpath = FilenameUtils.getFullPath(absolutePath.toString());
    name = FilenameUtils.getBaseName(absolutePath.toString());
    extension = FilenameUtils.getExtension(absolutePath.toString());
}

From source file:aldenjava.opticalmapping.data.mappingresult.ResultFormat.java

public static final ResultFormat lookup(String path, int format) {
    if (format == -1)
        return lookupfileext(FilenameUtils.getExtension(path));
    if (!lookupmap.containsKey(format))
        throw new InvalidFileFormatException();
    return lookupmap.get(format);
}

From source file:com.igormaznitsa.zxpspritecorrector.files.FileNameDialog.java

public static String[] makeFileNames(final String baseName) {
    final String[] result = new String[4];
    for (int i = 0; i < 4; i++) {
        result[i] = FilenameUtils.getBaseName(baseName) + '_' + i + '.' + FilenameUtils.getExtension(baseName);
    }//from w w w .j  a  v a 2 s.  c  om
    return result;
}

From source file:com.shyslav.controller.UploadController.java

@RequestMapping(value = "/uploadAction")
private String uploadAction(ModelMap mv, RedirectAttributes redirectAttributes, HttpSession ses,
        HttpServletRequest request) throws URISyntaxException {
    String name = null;//from  ww  w  .j a  v a  2s  .  c  om
    String genre = null;
    String author = null;
    String smallText = null;
    String fullText = null;
    String vision = null;
    String serverPath = null;
    Properties props = new Properties();
    try (InputStream in = UploadController.class.getResourceAsStream("application.properties")) {
        props.load(in);
    } catch (IOException ex) {
        System.out.println(ex);
    }
    DiskFileItemFactory d = new DiskFileItemFactory();
    ServletFileUpload uploadre = new ServletFileUpload(d);
    System.out.println(props.getProperty("downloadDirectory"));
    try {
        List<FileItem> list = uploadre.parseRequest(request);
        for (FileItem f : list) {
            if (f.isFormField() == false) {
                //write file to upload folder;

                if (!FilenameUtils.getExtension(f.getName()).equals("pdf")) {
                    String ext = FilenameUtils.getExtension(f.getName());
                    System.out.println(ext);
                    System.out.println("comed");
                    redirectAttributes.addFlashAttribute("error",
                            "?   ? , ?  pdf");
                    return "redirect:add.htm";
                }
                serverPath = "/" + author + "_" + name + "_" + genre + "_" + Math.random() * 100 + "."
                        + FilenameUtils.getExtension(f.getName());
                f.write(new File(props.getProperty("downloadDirectory") + serverPath));
                System.out.println(f.getName());
            } else if (f.isFormField()) {
                String fieldname = f.getFieldName();
                if (fieldname.equals("name")) {
                    name = f.getString("UTF-8");
                } else if (fieldname.equals("genre")) {
                    genre = f.getString("UTF-8");
                } else if (fieldname.equals("author")) {
                    author = f.getString("UTF-8");
                } else if (fieldname.equals("smallText")) {
                    smallText = f.getString("UTF-8");
                } else if (fieldname.equals("fullText")) {
                    fullText = f.getString("UTF-8");
                } else if (fieldname.equals("vision")) {
                    vision = f.getString("UTF-8");
                }
                System.out.println(f.getFieldName().toString());
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
    if (name == null || genre == null || author == null || smallText == null || fullText == null
            || vision == null || smallText.length() < 30 || fullText.length() < 50 || name.length() < 3) {
        redirectAttributes.addFlashAttribute("error",
                "? ? ?  ");
        return "redirect:add.htm";
    }
    try {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query query = session.createSQLQuery("INSERT INTO books\n"
                + "(name, author, genre, small_text, full_text, date_create, vision, server_Path)\n"
                + "VALUES('" + name + "', '" + author + "', " + genre + ", '" + smallText + "', '" + fullText
                + "', NOW(), '" + vision + "','" + serverPath + "')");
        System.out.println(query.toString());
        int result = query.executeUpdate();
        session.getTransaction().commit();
    } catch (Exception ex) {
        System.out.println(ex);
    }
    redirectAttributes.addFlashAttribute("sucses", " ? ");
    return "redirect:index.htm";
}