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

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

Introduction

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

Prototype

public static String removeExtension(String filename) 

Source Link

Document

Removes the extension from a filename.

Usage

From source file:org.cesecore.audit.audit.SigningFileOutputStream.java

/**
 * Generates a signature file with the same name as the export file but with .sig extension.
 * //from w ww.jav a  2 s .  c o m
 * @param exportFile the exported file.
 * @param cryptoToken the crypto token that will be used to fetch the necessary keys.
 * @param signatureDetails
 *            Set properties containing signature details like
 *            keyAlias(EXPORT_SIGN_KEYALIAS), algorithm(EXPORT_SIGN_ALG) and
 *            certificate( EXPORT_SIGN_CERT ).
 * @return the full pathname of the signature file
 */
public SigningFileOutputStream(final File file, final CryptoToken cryptoToken,
        final Map<String, Object> signatureDetails) throws FileNotFoundException, CryptoTokenOfflineException,
        NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    super(file);
    signatureFilename = String.format("%s.sig", FilenameUtils.removeExtension(file.getAbsolutePath()));
    final String keyAlias = (String) signatureDetails.get(SigningFileOutputStream.EXPORT_SIGN_KEYALIAS);
    final PrivateKey privateKey = cryptoToken.getPrivateKey(keyAlias);
    final PublicKey publicKey = cryptoToken.getPublicKey(keyAlias);
    final String algorithm = (String) signatureDetails.get(SigningFileOutputStream.EXPORT_SIGN_ALG);
    signature = Signature.getInstance(algorithm, cryptoToken.getSignProviderName());
    signature.initSign(privateKey);
    signValidate = Signature.getInstance(algorithm, cryptoToken.getSignProviderName());
    final Certificate cert = (Certificate) signatureDetails.get(SigningFileOutputStream.EXPORT_SIGN_CERT);
    if (cert != null) {
        signValidate.initVerify(cert);
    } else {
        signValidate.initVerify(publicKey);
    }
}

From source file:org.cesecore.audit.log.LogPerformanceTest.java

private void assertExportAndSignatureExists(final String exportFilename) {
    final File exportFile = new File(exportFilename);
    assertTrue("file does not exist, " + exportFile.getAbsolutePath(), exportFile.exists());
    assertTrue("file length is not > 0, " + exportFile.getAbsolutePath(), exportFile.length() > 0);
    assertTrue("file can not be deleted, " + exportFile.getAbsolutePath(), exportFile.delete());
    final File signatureFile = new File(
            String.format("%s.sig", FilenameUtils.removeExtension(exportFile.getAbsolutePath())));
    assertTrue("signatureFile does not exist, " + signatureFile.getAbsolutePath(), signatureFile.exists());
    assertTrue("signatureFile length is not > 0, " + signatureFile.getAbsolutePath(),
            signatureFile.length() > 0);
    assertTrue("signatureFile can not be deleted, " + signatureFile.getAbsolutePath(), signatureFile.delete());
}

From source file:org.cgiar.ccafs.marlo.action.BaseAction.java

public FileDB getFileDB(FileDB preview, File file, String fileFileName, String path) {

    try {//from   w w  w  .  j a va2 s .  c  o m

        FileInputStream fis = new FileInputStream(file);
        String md5 = DigestUtils.md5Hex(fis);
        FileDB dbFile = null;

        if (preview != null) {

            if (preview.getFileName().equals(fileFileName) && !md5.equals(preview.getTokenId())) {
                dbFile = new FileDB(fileFileName, md5);
                FileDB dbFilePrev = preview;
                Path prevFile = Paths.get(path + dbFilePrev.getFileName());
                String newName = FilenameUtils.removeExtension(fileFileName) + "_"
                        + UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileFileName);
                newName = newName.replaceAll(":", "-");
                Files.move(prevFile, prevFile.resolveSibling(newName));
                dbFilePrev.setFileName(newName);
                fileDBManager.saveFileDB(dbFilePrev);
            } else {
                if (preview.getFileName().equals(fileFileName) && md5.equals(preview.getTokenId())) {
                    dbFile = preview;
                } else {
                    dbFile = new FileDB(fileFileName, md5);
                }
            }

        } else {
            dbFile = new FileDB(fileFileName, md5);
        }
        fileDBManager.saveFileDB(dbFile);
        return dbFile;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:org.cirdles.squid.web.SquidReportingService.java

public Path generateReports(String myFileName, InputStream prawnFile, InputStream taskFile, boolean useSBM,
        boolean userLinFits, String refMatFilter, String concRefMatFilter, String preferredIndexIsotopeName)
        throws IOException, JAXBException, SAXException {

    IndexIsoptopesEnum preferredIndexIsotope = IndexIsoptopesEnum.valueOf(preferredIndexIsotopeName);

    // Posix attributes added to support web service on Linux - ignoring windows for now
    Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ);

    // detect if prawnfile is zipped
    boolean prawnIsZip = false;
    String fileName = "";
    if (myFileName == null) {
        fileName = DEFAULT_PRAWNFILE_NAME;
    } else if (myFileName.toLowerCase().endsWith(".zip")) {
        fileName = FilenameUtils.removeExtension(myFileName);
        prawnIsZip = true;//from  ww  w.ja  v a2  s.c  om
    } else {
        fileName = myFileName;
    }

    SquidProject squidProject = new SquidProject();
    prawnFileHandler = squidProject.getPrawnFileHandler();

    CalamariFileUtilities.initSampleParametersModels();

    Path reportsZip = null;
    Path reportsFolder = null;
    try {
        Path uploadDirectory = Files.createTempDirectory("upload");
        Path uploadDirectory2 = Files.createTempDirectory("upload2");

        Path prawnFilePath;
        Path taskFilePath;
        if (prawnIsZip) {
            Path prawnFilePathZip = uploadDirectory.resolve("prawn-file.zip");
            Files.copy(prawnFile, prawnFilePathZip);
            prawnFilePath = extractZippedFile(prawnFilePathZip.toFile(), uploadDirectory.toFile());
        } else {
            prawnFilePath = uploadDirectory.resolve("prawn-file.xml");
            Files.copy(prawnFile, prawnFilePath);
        }

        taskFilePath = uploadDirectory2.resolve("task-file.xls");
        Files.copy(taskFile, taskFilePath);

        ShrimpDataFileInterface prawnFileData = prawnFileHandler
                .unmarshallPrawnFileXML(prawnFilePath.toString(), true);
        squidProject.setPrawnFile(prawnFileData);

        // hard-wired for now
        squidProject.getTask().setCommonPbModel(CommonPbModel.getDefaultModel("GA Common Lead 2018", "1.0"));
        squidProject.getTask().setPhysicalConstantsModel(
                PhysicalConstantsModel.getDefaultModel(SQUID2_DEFAULT_PHYSICAL_CONSTANTS_MODEL_V1, "1.0"));
        File squidTaskFile = taskFilePath.toFile();

        squidProject.createTaskFromImportedSquid25Task(squidTaskFile);

        squidProject.setDelimiterForUnknownNames("-");

        TaskInterface task = squidProject.getTask();
        task.setFilterForRefMatSpotNames(refMatFilter);
        task.setFilterForConcRefMatSpotNames(concRefMatFilter);
        task.setUseSBM(useSBM);
        task.setUserLinFits(userLinFits);
        task.setSelectedIndexIsotope(preferredIndexIsotope);

        // process task           
        task.applyTaskIsotopeLabelsToMassStations();

        Path calamariReportsFolderAliasParent = Files.createTempDirectory("reports-destination");
        Path calamariReportsFolderAlias = calamariReportsFolderAliasParent
                .resolve(DEFAULT_SQUID3_REPORTS_FOLDER.getName() + "-from Web Service");
        File reportsDestinationFile = calamariReportsFolderAlias.toFile();

        reportsEngine = prawnFileHandler.getReportsEngine();
        prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName);
        reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile);

        reportsEngine.produceReports(task.getShrimpFractions(), (ShrimpFraction) task.getUnknownSpots().get(0),
                task.getReferenceMaterialSpots().size() > 0
                        ? (ShrimpFraction) task.getReferenceMaterialSpots().get(0)
                        : (ShrimpFraction) task.getUnknownSpots().get(0),
                true, false);

        squidProject.produceTaskAudit();

        squidProject.produceUnknownsCSV(true);
        squidProject.produceReferenceMaterialCSV(true);
        // next line report will show only super sample for now
        squidProject.produceUnknownsBySampleForETReduxCSV(true);

        Files.delete(prawnFilePath);

        reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReports().getParentFile().getPath());

    } catch (IOException | JAXBException | SAXException | SquidException iOException) {

        Path config = Files.createTempFile("SquidWebServiceMessage", "txt",
                PosixFilePermissions.asFileAttribute(perms));
        try (BufferedWriter writer = Files.newBufferedWriter(config, StandardCharsets.UTF_8)) {
            writer.write("Squid Reporting web service was not able to process supplied files.");
            writer.newLine();
            writer.write(iOException.getMessage());
            writer.newLine();
        }
        File message = config.toFile();

        Path messageDirectory = Files.createTempDirectory("message");
        Path messageFilePath = messageDirectory.resolve("Squid Web Service Message.txt");
        Files.copy(message.toPath(), messageFilePath);

        reportsFolder = messageFilePath.getParent();
    }

    reportsZip = ZipUtility.recursivelyZip(reportsFolder);
    FileUtilities.recursiveDelete(reportsFolder);

    return reportsZip;
}

From source file:org.cirdles.webServices.calamari.PrawnFileHandlerService.java

public Path generateReportsZip(String myFileName, InputStream prawnFile, boolean useSBM, boolean userLinFits,
        String firstLetterRM) throws IOException, JAXBException, SAXException {

    String fileName = myFileName;
    if (myFileName == null) {
        fileName = DEFAULT_PRAWNFILE_NAME;
    }//from  w  w  w  . j  av a 2s  .c o m

    Path uploadDirectory = Files.createTempDirectory("upload");
    Path prawnFilePathZip = uploadDirectory.resolve("prawn-file.zip");

    Files.copy(prawnFile, prawnFilePathZip);

    //file path string to extracted xml
    String extract = extract(prawnFilePathZip.toFile(), uploadDirectory.toFile());

    Path calamarirReportsFolderAlias = Files.createTempDirectory("reports-destination");
    File reportsDestinationFile = calamarirReportsFolderAlias.toFile();

    reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile);
    fileName = FilenameUtils.removeExtension(fileName);

    // this gives reportengine the name of the Prawnfile for use in report names
    prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName);
    prawnFileHandler.writeReportsFromPrawnFile(extract, useSBM, userLinFits, firstLetterRM);

    Files.delete(prawnFilePathZip);

    Path reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReportsPath()).getParent()
            .toAbsolutePath();

    Path reports = Files.list(reportsFolder).findFirst().orElseThrow(() -> new IllegalStateException());

    Path reportsZip = zip(reports);
    recursiveDelete(reports);

    return reportsZip;
}

From source file:org.cobol85.TestGenerator.java

public static void generateTestClass(final File cobol85InputFile, final File outputDirectory,
        final String packageName, final boolean isNonRepoTest) throws IOException {
    if (cobol85InputFile.isFile() && !cobol85InputFile.isHidden()) {
        final String inputFilename = firstToUpper(FilenameUtils.removeExtension(cobol85InputFile.getName()));

        final File outputFile = new File(outputDirectory + "/" + inputFilename + "Test.java");

        LOG.info("Creating {}.", outputFile);
        final boolean createdNewFile = outputFile.createNewFile();

        if (createdNewFile) {
            final PrintWriter pWriter = new PrintWriter(new FileWriter(outputFile));

            final String defaultDirectoryName = "src/test/resources/org/cobol85/";
            final String cobol85InputFileName = cobol85InputFile.getPath().replace("\\", "/");

            pWriter.write("package " + packageName + ";\n");
            pWriter.write("\n");
            pWriter.write("import java.io.File;\n");
            pWriter.write("\n");
            pWriter.write("import org.junit.Test;\n");
            pWriter.write("import org.cobol85.applicationcontext.Cobol85GrammarContextFactory;\n");
            pWriter.write("import org.cobol85.runner.Cobol85ParseTestRunner;\n");
            pWriter.write("import org.cobol85.runner.impl.Cobol85ParseTestRunnerImpl;\n");
            pWriter.write("\n");
            pWriter.write("public class " + inputFilename + "Test {\n");
            pWriter.write("\n");
            pWriter.write("   @Test\n");
            pWriter.write("   public void test() throws Exception {\n");
            pWriter.write("      Cobol85GrammarContextFactory.configureDefaultApplicationContext();\n");
            pWriter.write("\n");

            if (isNonRepoTest) {
                final String shortenedCobol85InputFileName = cobol85InputFileName.replace(defaultDirectoryName,
                        "");

                pWriter.write(/*ww  w .j ava 2 s  . c o m*/
                        "      final String testDirectoryString = System.getProperty(\"testDirectory\", \""
                                + defaultDirectoryName + "\");\n");
                pWriter.write("      final File inputFile = new File(testDirectoryString, \""
                        + shortenedCobol85InputFileName + "\");\n");
            } else {
                pWriter.write("      final File inputFile = new File(\"" + cobol85InputFileName + "\");\n");
            }

            pWriter.write("      final Cobol85ParseTestRunner runner = new Cobol85ParseTestRunnerImpl();\n");
            pWriter.write("      runner.parseFile(inputFile, null);\n");
            pWriter.write("   }\n");
            pWriter.write("}");

            pWriter.flush();
            pWriter.close();
        }
    }
}

From source file:org.codehaus.plexus.archiver.bzip2.BZip2ArchiveContentLister.java

protected List<ArchiveContentEntry> execute() throws ArchiverException {
    ArrayList<ArchiveContentEntry> archiveContentList = new ArrayList<ArchiveContentEntry>();
    getLogger().debug("listing: " + getSourceFile());

    ArchiveContentEntry ae = ArchiveContentEntry.createFileEntry(
            FilenameUtils.removeExtension(getSourceFile().getName()), new BZip2FileInfo(getSourceFile()), -1);
    archiveContentList.add(ae);//from   www  . j  av  a2  s.  c om

    getLogger().debug("listing complete");

    return archiveContentList;
}

From source file:org.codehaus.plexus.archiver.gzip.GZipArchiveContentLister.java

protected List<ArchiveContentEntry> execute() throws ArchiverException {
    ArrayList<ArchiveContentEntry> archiveContentList = new ArrayList<ArchiveContentEntry>();
    getLogger().debug("listing: " + getSourceFile());

    ArchiveContentEntry ae = ArchiveContentEntry.createFileEntry(
            FilenameUtils.removeExtension(getSourceFile().getName()), new GZipFileInfo(getSourceFile()), -1);
    archiveContentList.add(ae);/*  w w w.jav a2  s .co m*/

    getLogger().debug("listing complete");

    return archiveContentList;
}

From source file:org.codehaus.plexus.archiver.snappy.SnappyArchiveContentLister.java

protected List<ArchiveContentEntry> execute() throws ArchiverException {
    ArrayList<ArchiveContentEntry> archiveContentList = new ArrayList<ArchiveContentEntry>();
    getLogger().debug("listing: " + getSourceFile());

    ArchiveContentEntry ae = ArchiveContentEntry.createFileEntry(
            FilenameUtils.removeExtension(getSourceFile().getName()), new SnappyFileInfo(getSourceFile()), -1);
    archiveContentList.add(ae);// w ww.  ja  v  a2  s.  com

    getLogger().debug("listing complete");

    return archiveContentList;
}

From source file:org.codice.ddf.admin.application.service.command.ProfileListCommand.java

private void listProfileFiles() {
    try (Stream<Path> files = Files.list(profilePath)) {
        files.filter(Files::isRegularFile)
                .filter(file -> file.toAbsolutePath().toString().endsWith(PROFILE_EXTENSION))
                .forEach(profile -> console.println(FilenameUtils.removeExtension(profile.toFile().getName())));
    } catch (IOException e) {
        printError("Error occurred when locating profiles");
        LOGGER.error("An error occurred when locating profiles", e);
    }//  ww  w.  jav a  2 s.com
}