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:de.uzk.hki.da.cb.ShortenFileNamesAction.java

@Override
public boolean implementation() throws FileNotFoundException, IOException {

    String metadataFile = o.getMetadata_file();

    // rename results of conversions
    for (Event e : o.getLatestPackage().getEvents()) {

        logger.debug("checking if event is CONVERT for {}", e);

        if (!"CONVERT".equals(e.getType()))
            continue;

        logger.debug("event is CONVERT: {}", e);

        DAFile daFile = e.getTarget_file();
        if (!daFile.getRep_name().startsWith(WorkArea.TMP_PIPS))
            continue;

        final File file = wa.toFile(daFile);
        final String filePath = daFile.getRelative_path();
        logger.debug("filePath: " + filePath);
        String extension = FilenameUtils.getExtension(filePath);
        logger.debug("extension: " + extension);

        String newFilePath;/* w  ww  .java 2 s  . co  m*/
        if (filePath.equals(metadataFile)) {
            logger.warn("Metadata file should not be subject to a conversion!");
            continue;
        } else {
            final String hash = DigestUtils.md5Hex(filePath);
            logger.debug("hash: " + hash);
            newFilePath = "_" + hash + "." + extension;
        }

        logger.debug("newFilePath: " + newFilePath);
        File newFile = new File(file.getAbsolutePath().replaceAll(Pattern.quote(filePath) + "$", newFilePath));
        logger.debug("newFile: " + newFile.getAbsolutePath());

        daFile.setRelative_path(newFilePath);
        FileUtils.moveFile(file, newFile);
        map.put(newFilePath, filePath);

        deleteEmptyDirsRecursively(file.getAbsolutePath());

    }

    return true;

}

From source file:com.github.wesjd.overcastmappacker.xml.DocumentHandler.java

public DocumentHandler(File documentFile) {
    try {/*from   w  w w  . jav a 2s .c o  m*/
        Validate.isTrue(documentFile.exists(), "Document must exist for DocumentHandler to handle it.");
        Validate.isTrue(FilenameUtils.getExtension(documentFile.getPath()).equals("xml"),
                "Document supplied is not an XML file.");

        this.documentFile = documentFile;

        documentBuilder = XMLConstants.DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
        document = documentBuilder.parse(new FileInputStream(documentFile));

        transformer = XMLConstants.TRANSFORMER_FACTORY.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    } catch (ParserConfigurationException | IOException | SAXException | TransformerConfigurationException ex) {
        ex.printStackTrace();
    }
}

From source file:com.thoughtworks.go.server.service.lookups.CommandRepositoryDirectoryWalker.java

@Override
protected void handleFile(File file, int depth, Collection results) {
    String fileName = file.getName();
    if (!FilenameUtils.getExtension(fileName).equalsIgnoreCase(XML_EXTENSION)) {
        return;//  w w w. j a va2 s  .c  om
    }

    String xmlContentOfFie = safeReadFileToString(file);
    if (xmlContentOfFie == null || !file.canRead()) {
        serverHealthService.update(ServerHealthState.warning("Command Repository",
                "Failed to access command snippet XML file located in Go Server Directory at " + file.getPath()
                        + ". Go does not have sufficient permissions to access it.",
                HealthStateType.commandRepositoryAccessibilityIssue(),
                systemEnvironment.getCommandRepoWarningTimeout()));
        LOGGER.warn(
                "[Command Repository] Failed to access command snippet XML file located in Go Server Directory at {}. Go does not have sufficient permissions to access it.",
                file.getAbsolutePath());
        return;
    }

    try {
        String relativeFilePath = FileUtil.removeLeadingPath(commandRepositoryBaseDirectory.get(),
                file.getAbsolutePath());
        results.add(commandSnippetXmlParser.parse(xmlContentOfFie, FilenameUtils.getBaseName(fileName),
                relativeFilePath));
    } catch (Exception e) {
        LOGGER.warn("Failed loading command snippet from {}", file.getAbsolutePath());
        LOGGER.debug(null, e);
    }
}

From source file:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java

/**
 * Returns an ImageReader given the input file
 * /*ww w.j ava  2  s.  c o m*/
 * @param file
 * @return
 * @throws IOException
 */
public static ImageReader getImageReader(File file) throws IOException {
    String ext = FilenameUtils.getExtension(file.getName().toLowerCase());
    ImageReader reader = null;

    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersBySuffix(ext);
    if (imageReaders.hasNext()) {
        reader = imageReaders.next();
        ImageInputStream stream = ImageIO.createImageInputStream(file);
        reader.setInput(stream);
    }
    return reader;
}

From source file:de.qaware.cloud.deployer.commons.config.resource.BaseResourceConfigFactory.java

/**
 * Returns the content type of a file using the file ending.
 *
 * @param file The file whose content type should be returned.
 * @return The content type of the file.
 * @throws ResourceConfigException If the content type isn't supported.
 *///from w w  w .j a v  a2  s.  co m
protected ContentType retrieveContentType(File file) throws ResourceConfigException {
    String fileEnding = FilenameUtils.getExtension(file.getName());
    switch (fileEnding) {
    case "json":
        return ContentType.JSON;
    case "yml":
        return ContentType.YAML;
    default:
        throw new ResourceConfigException(COMMONS_MESSAGE_BUNDLE
                .getMessage("DEPLOYER_COMMONS_ERROR_UNKNOWN_CONTENT_TYPE", file.getName()));
    }
}

From source file:launcher.Download.java

/**
 * This method is for downloading a file from a URL. 
 * @param fileurl The URL that the download needs to occur
 * @throws IOException //from  w  w  w  .j  a va2  s . c  o  m
 */
public static void fileDownload(String fileurl) throws IOException {
    //init var
    URL dl = null;
    File fl = null;
    String x = null;
    OutputStream os = null;
    InputStream is = null;
    ProgressListener progressListener = new ProgressListener();
    try {

        //string to the URL
        dl = new URL(fileurl);
        //grab file name
        String fileName = FilenameUtils.getBaseName(fileurl);
        String extension = FilenameUtils.getExtension(fileurl);
        //storage location
        fl = new File(
                System.getProperty("user.home").replace("\\", "/") + "/Desktop/" + fileName + "." + extension);
        //file stream output at storage location
        os = new FileOutputStream(fl);
        is = dl.openStream();
        //new instance of DownloadCountingOutputStream
        DownloadCountingOutputStream dcount = new DownloadCountingOutputStream(os);
        dcount.setListener(progressListener);

        // this line give you the total length of source stream as a double.
        filesize = Double.parseDouble(dl.openConnection().getHeaderField("Content-Length"));

        //return filename
        filename = fileName;
        // begin transfer by writing to dcount for download progress count. *not os.*
        IOUtils.copy(is, dcount);

    } catch (Exception e) {
        System.out.println(e);
    } finally {
        if (os != null) {
            os.close();
        }
        if (is != null) {
            is.close();
        }
    }
}

From source file:net.sf.jvifm.control.CopyCommand.java

protected void doFileOperator(String src, String dst, String fileName) throws Exception {
    if (Thread.currentThread().isInterrupted())
        return;//  www .  j a  va 2 s.c  o  m
    String baseName = FilenameUtils.getName(src);
    updateStatusInfo("copying file " + baseName);
    // if is same file, make a copy
    if (fileModelManager.isSameFile(src, dst)) {
        dst = FilenameUtils.concat(dst,
                FilenameUtils.getBaseName(src) + "(1)." + FilenameUtils.getExtension(src));
        new File(dst).createNewFile();
    }
    fileModelManager.cp(src, dst);
}

From source file:net.pms.dlna.ZippedEntry.java

@Override
public String getSystemName() {
    return FilenameUtils.getBaseName(file.getAbsolutePath()) + "." + FilenameUtils.getExtension(zeName);
}

From source file:app.model.game.ExeChooserModel.java

public JSONArray listfJSON(String directoryName) {
    JSONArray files = new JSONArray();
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();

    for (File file : fList) {
        if (file.isFile()) {
            if (listableFileTypes.contains(FilenameUtils.getExtension(file.getName()).toLowerCase())) {
                Map f = new LinkedHashMap();
                f.put("type", "file");
                f.put("name", file.getName());
                files.add(f);//from   w w  w  . j a v a 2 s .c  o m
            }
        }

        else if (file.isDirectory()) {
            Map folder = new LinkedHashMap();
            folder.put("type", "folder");
            folder.put("name", file.getName());
            folder.put("child", listfJSON(file.getAbsolutePath()));
            files.add(folder);
        }
    }

    return files;
}

From source file:fi.johannes.kata.ocr.utils.files.ExistingFileConnection.java

public String getExtension() {
    String ext = FilenameUtils.getExtension(p.toString());
    return ext;
}