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:edu.harvard.hul.ois.fits.tools.oisfileinfo.FileInfo.java

private Document createXml(File file) throws FitsToolException {

    Element root = new Element("fits", fitsNS);
    root.setAttribute(new Attribute("schemaLocation",
            "http://hul.harvard.edu/ois/xml/ns/fits/fits_output " + Fits.externalOutputSchema, xsiNS));
    //fileinfo section
    Element fileInfo = new Element("fileinfo", fitsNS);
    //filepath/*from w  w  w  . j av  a  2s  . co  m*/
    Element filepath = new Element("filepath", fitsNS);
    filepath.setText(file.getAbsolutePath());
    fileInfo.addContent(filepath);
    //filename
    Element fileName = new Element("filename", fitsNS);
    fileName.setText(file.getName());
    fileInfo.addContent(fileName);
    //size
    Element size = new Element("size", fitsNS);
    size.setText(String.valueOf(file.length()));
    fileInfo.addContent(size);
    //Calculate the MD5 checksum
    if (Fits.config.getBoolean("output.enable-checksum")) {
        List<String> checsumExcludes = Fits.config.getList("output.checksum-exclusions[@exclude-exts]");
        String ext = FilenameUtils.getExtension(file.getPath());
        if (!hasExcludedExtensionForMD5(ext, checsumExcludes)) {
            try {
                String md5Hash = MD5.asHex(MD5.getHash(new File(file.getPath())));
                Element signature = new Element("md5checksum", fitsNS);
                signature.setText(md5Hash);
                fileInfo.addContent(signature);
            } catch (IOException e) {
                throw new FitsToolException("Could not calculate the MD5 for " + file.getPath(), e);
            }
        }

    }
    //fslastmodified
    Element fslastmodified = new Element("fslastmodified", fitsNS);
    fslastmodified.setText(String.valueOf(file.lastModified()));
    fileInfo.addContent(fslastmodified);
    root.addContent(fileInfo);

    return new Document(root);
}

From source file:net.mitnet.tools.pdf.book.io.FileHelper.java

private static boolean checkExtensions(String[] fileExtensions, File file) {
    List<String> extensions = Arrays.asList(fileExtensions);
    String ext = FilenameUtils.getExtension(file.getName());
    boolean extThere = false;
    for (int i = 0; i < extensions.size(); i++) {
        if (ext.equalsIgnoreCase(extensions.get(i))) {
            extThere = true;/* w  ww .j  av  a  2  s . c  o m*/
        }
    }
    return extThere;
}

From source file:com.qwazr.webapps.transaction.WebappManager.java

@Override
public void accept(TrackedInterface.ChangeReason changeReason, File jsonFile) {
    String extension = FilenameUtils.getExtension(jsonFile.getName());
    if (!"json".equals(extension))
        return;//w  ww  . jav  a 2  s  .  c om
    switch (changeReason) {
    case UPDATED:
        loadWebappDefinition(jsonFile);
        break;
    case DELETED:
        unloadWebappDefinition(jsonFile);
        break;
    }
}

From source file:cz.lbenda.rcp.DialogHelper.java

/** Ask user if file can be overwrite if file exist
 * @param file file which is rewrite/*  w  w w. j  a  v a  2s  .  c  o m*/
 * @param defaultExtension if file haven't extension then default is add
 * @return file if user want rewrite it, or no file with this name exist */
public File canBeOverwriteDialog(File file, String defaultExtension) {
    if (file == null) {
        return null;
    }
    if ("".equals(FilenameUtils.getExtension(file.getName()))) {
        file = new File(file.getAbsoluteFile() + "." + defaultExtension);
    }
    if (!file.exists()) {
        return file;
    }
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle(msgCanOverwriteTitle);
    alert.setContentText(String.format(msgCanOverwriteContent, file.getName()));
    Optional<ButtonType> result = alert.showAndWait();
    return (result.isPresent()) && (result.get() == ButtonType.OK) ? file : null;
}

From source file:de.teamgrit.grit.report.PdfConcatenator.java

/**
 * Write the pdfs to the file.//from w ww.ja  va  2 s . c om
 *
 * @param outFile
 *            the out file
 * @param folderWithPdfs
 *            the folder with pdfs
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static void writeFiles(File outFile, Path folderWithPdfs) throws IOException {

    FileWriterWithEncoding writer = new FileWriterWithEncoding(outFile, "UTF-8", true);

    File[] files = folderWithPdfs.toFile().listFiles();
    if (files.length > 0) {
        for (File file : files) {

            // We only want the the PDFs as input
            if ("pdf".equals(FilenameUtils.getExtension(file.getName()))) {
                writer.append("\\includepdf[pages={1-}]{").append(file.getAbsolutePath()).append("} \n");
            }
        }
    } else {
        LOGGER.warning("No Reports available in the specified folder: " + folderWithPdfs.toString());
    }
    writer.close();
}

From source file:com.bgh.myopeninvoice.db.model.AttachmentEntity.java

@Transient
public String getFileExtension() {
    if (!StringUtils.isBlank(filename)) {
        this.fileExtension = FilenameUtils.getExtension(filename).toLowerCase();
    }//from ww  w. ja  v  a 2s  .  c  om
    return fileExtension;
}

From source file:com.github.technosf.posterer.models.KeyStoreBean.java

/**
 * Instantiates a {@code KeyStoreBean} wrapping the given keystore
 * <p>/*from w w w  .  j a  v a  2s .  c o m*/
 * Loads the Key Store file into a {@code KeyStore} and checks the password. If the Key Store
 * can be accessed successfully, validation is successful..
 * 
 * @param file
 *            the KeyStore file
 * @param password
 *            the Key Store password
 * @throws KeyStoreBeanException
 *             Thrown when a {@code KeyStoreBean} cannot be created.
 */
public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException {
    file = keyStoreFile;
    password = keyStorePassword;

    InputStream inputStream = null;

    /*
     * Check file existence
     */
    if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead())
    // Key Store File cannot be read
    {
        throw new KeyStoreBeanException("Cannot read Key Store file");
    }

    try
    // to get the file input stream
    {
        inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ);
    } catch (IOException e) {
        throw new KeyStoreBeanException("Error reading Key Store file", e);
    }

    // Get the file name and extension
    fileName = FilenameUtils.getName(keyStoreFile.getName());
    String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase());

    /*
     * Identify keystore type, and create an instance
     */
    try {
        switch (fileExtension) {
        case "p12":
            keyStore = KeyStore.getInstance("PKCS12");
            break;
        case "jks":
            keyStore = KeyStore.getInstance("JKS");
            break;
        default:
            throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot get keystore instance");
    }

    /*
     * Load the keystore data into the keystore instance
     */
    try {
        keyStore.load(inputStream, password.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new KeyStoreBeanException("Cannot load the KeyStore", e);
    }

    /*
     * Key store loaded, so config the bean
     */
    try {
        type = keyStore.getType();
        size = keyStore.size();

        Enumeration<String> aliasIterator = keyStore.aliases();
        while (aliasIterator.hasMoreElements()) {
            String alias = aliasIterator.nextElement();
            certificates.put(alias, keyStore.getCertificate(alias));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot process the KeyStore", e);
    }
}

From source file:edu.umn.msi.tropix.proteomics.itraqquantitation.impl.QuantitationClosureImpl.java

public void apply(final QuantitationOptions options) {
    final List<ITraqLabel> labels = ITraqLabels.getLabels(options.getQuantificationType());

    LOG.info("Building data entries for quantitation analysis");
    final List<ITraqMatch> iTraqMatchs = iTraqMatchBuilder.buildDataEntries(options.getInputMzxmlFiles(),
            options.getInputReport(), new ITraqMatchBuilder.ITraqMatchBuilderOptions(labels,
                    options.getGroupType(), options.getThreads()));

    Function<Double, Double> trainingFunction = null;
    if (options.getWeights() != null) {
        LOG.info("Building iTraq matches for training data");
        // final List<ITraqMatch> trainingMatches = iTraqMatchBuilder.buildDataEntries(options.getInputMzxmlFiles(), options.getInputScaffoldReport(),
        // new ITraqMatchBuilder.ITraqMatchBuilderOptions(labels));
        trainingFunction = new TrainingWeightFunctionImpl(options.getWeights());
    }//from w ww.ja v a  2s.c o  m

    LOG.info("Building report summary for quantitation analysis");
    final ReportSummary summary = new ReportSummary(iTraqMatchs, labels, options.getGroupType());

    final Collection<ITraqRatio> iTraqRatios = ITraqLabels.buildRatios(labels);

    LOG.info("Running quantitation analysis.");
    final QuantificationResults results = quantifier.quantify(iTraqRatios, summary, trainingFunction,
            options.includeNormalized());

    final File outputFile = options.getOutputFile();
    if (FilenameUtils.getExtension(outputFile.getName()).toLowerCase().equals("xml")) {
        final XMLUtility<QuantificationResults> resultXmlUtility = new XMLUtility<QuantificationResults>(
                QuantificationResults.class);

        LOG.info("Writing XML resluts");
        resultXmlUtility.serialize(results, outputFile);
    } else {
        final OutputStream outputStream = FILE_UTILS.getFileOutputStream(outputFile);
        try {
            QuantificationResultsExporter.writeAsSpreadsheet(results, outputStream, options.getGroupType());
        } finally {
            IO_UTILS.closeQuietly(outputStream);
        }
    }

}

From source file:com.artemisa.service.ProductoServiceImpl.java

public void uploadProductImage(com.artemisa.domain.Producto producto, String fileName, InputStream stream)
        throws IOException {
    String ext = FilenameUtils.getExtension(fileName);
    String uniqueName = UUID.randomUUID().toString();

    Parametro path = parametroService.findByField("nombre", com.artemisa.dao.ParametroDao.UPLOAD_PATH);

    try {/*from   w ww.j  av  a2 s . co m*/
        String name = uniqueName + "." + ext;

        File.upload(path.getValor(), name, stream);
        producto.setFoto(name);

        this.service.update(producto);
    } catch (IOException ex) {
        throw new IOException(ex.getMessage());
    }
}

From source file:de.hybris.platform.refund.RefundServiceTest.java

private boolean hasExtension(final String fileName) {
    return FilenameUtils.getExtension(fileName).equals("") ? false : true;
}