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

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

Introduction

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

Prototype

public static String getBaseName(String filename) 

Source Link

Document

Gets the base name, minus the full path and extension, from a full filename.

Usage

From source file:ddf.catalog.impl.operations.OperationsMetacardSupport.java

void generateMetacardAndContentItems(List<ContentItem> incomingContentItems, Map<String, Metacard> metacardMap,
        List<ContentItem> contentItems, Map<String, Map<String, Path>> tmpContentPaths) throws IngestException {
    for (ContentItem contentItem : incomingContentItems) {
        try {/*from w  ww  . j a v  a2 s .c  o m*/
            Path tmpPath = null;
            String fileName;
            long size;
            try (InputStream inputStream = contentItem.getInputStream()) {
                fileName = contentItem.getFilename();
                if (inputStream == null) {
                    throw new IngestException("Could not copy bytes of content message.  Message was NULL.");
                }

                if (!InputValidation.isFileNameClientSideSafe(fileName)) {
                    throw new IngestException("Ignored filename found.");
                }

                String sanitizedFilename = InputValidation.sanitizeFilename(fileName);
                tmpPath = Files.createTempFile(FilenameUtils.getBaseName(sanitizedFilename),
                        FilenameUtils.getExtension(sanitizedFilename));
                Files.copy(inputStream, tmpPath, StandardCopyOption.REPLACE_EXISTING);
                size = Files.size(tmpPath);

                final String key = contentItem.getId();
                Map<String, Path> pathAndQualifiers = tmpContentPaths.get(key);

                if (pathAndQualifiers == null) {
                    pathAndQualifiers = new HashMap<>();
                    pathAndQualifiers.put(contentItem.getQualifier(), tmpPath);
                    tmpContentPaths.put(key, pathAndQualifiers);
                } else {
                    pathAndQualifiers.put(contentItem.getQualifier(), tmpPath);
                }

            } catch (IOException e) {
                if (tmpPath != null) {
                    FileUtils.deleteQuietly(tmpPath.toFile());
                }
                throw new IngestException("Could not copy bytes of content message.", e);
            }
            String mimeTypeRaw = contentItem.getMimeTypeRawData();
            mimeTypeRaw = guessMimeType(mimeTypeRaw, fileName, tmpPath);

            if (!InputValidation.isMimeTypeClientSideSafe(mimeTypeRaw)) {
                throw new IngestException("Unsupported mime type.");
            }

            // If any sanitization was done, rename file name to sanitized file name.
            if (!InputValidation.sanitizeFilename(fileName).equals(fileName)) {
                fileName = InputValidation.sanitizeFilename(fileName);
            } else {
                fileName = updateFileExtension(mimeTypeRaw, fileName);
            }

            Metacard metacard;
            boolean qualifiedContent = StringUtils.isNotEmpty(contentItem.getQualifier());
            if (qualifiedContent) {
                metacard = contentItem.getMetacard();
            } else {
                metacard = metacardFactory.generateMetacard(mimeTypeRaw, contentItem.getId(), fileName,
                        tmpPath);
            }
            metacardMap.put(metacard.getId(), metacard);

            ContentItem generatedContentItem = new ContentItemImpl(metacard.getId(),
                    qualifiedContent ? contentItem.getQualifier() : "",
                    com.google.common.io.Files.asByteSource(tmpPath.toFile()), mimeTypeRaw, fileName, size,
                    metacard);
            contentItems.add(generatedContentItem);
        } catch (Exception e) {
            tmpContentPaths.values().stream().flatMap(id -> id.values().stream())
                    .forEach(path -> FileUtils.deleteQuietly(path.toFile()));
            tmpContentPaths.clear();
            throw new IngestException("Could not create metacard.", e);
        }
    }
}

From source file:MSUmpire.SeqUtility.FastaParser.java

public boolean FasterSerialzationWrite(String Filename) throws FileNotFoundException {
    try {//  w w  w . j  av  a 2s.c  om
        org.apache.log4j.Logger.getRootLogger().info("Writing fasta serialization to file:"
                + FilenameUtils.getFullPath(Filename) + FilenameUtils.getBaseName(Filename) + ".FastaSer...");
        FileOutputStream fout = new FileOutputStream(
                FilenameUtils.getFullPath(Filename) + FilenameUtils.getBaseName(Filename) + ".FastaSer", false);
        FSTObjectOutput out = new FSTObjectOutput(fout);
        out.writeObject(this);
        out.close();
        fout.close();
    } catch (Exception ex) {
        org.apache.log4j.Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
        return false;
    }
    return true;
}

From source file:MSUmpire.PSMDataStructure.FragmentSelection.java

public void GeneratePepFragScoreMap() {
    for (LCMSID IDSummary : FileList) {
        for (String key : IDSummary.GetPepIonList().keySet()) {
            if (!PepFragScore.containsKey(key)) {
                PepFragScore.put(key, new HashMap<String, Float>());
            }//from   w w  w.  j av a  2s  .  com
        }
        for (String key : IDSummary.GetMappedPepIonList().keySet()) {
            if (!PepFragScore.containsKey(key)) {
                PepFragScore.put(key, new HashMap<String, Float>());
            }
        }
    }

    for (String PepKey : PepFragScore.keySet()) {
        int IDNo = 0;
        HashMap<String, Float> fragmentscore = new HashMap<>();
        HashMap<String, Integer> fragmentfreq = new HashMap<>();

        for (LCMSID IDSummary : FileList) {
            PepIonID pep = null;
            if (IDSummary.GetPepIonList().containsKey(PepKey)) {
                pep = IDSummary.GetPepIonList().get(PepKey);
            } else if (IDSummary.GetMappedPepIonList().containsKey(PepKey)) {
                pep = IDSummary.GetMappedPepIonList().get(PepKey);
            }
            if (pep != null) {
                IDNo++;
                for (FragmentPeak frag : pep.FragmentPeaks) {
                    if (frag.corr > CorrelationThreshold && frag.FragMZ >= MinFragMZ) {
                        if (!fragmentscore.containsKey(frag.GetFragKey())) {
                            fragmentscore.put(frag.GetFragKey(), 0f);
                            fragmentfreq.put(frag.GetFragKey(), 0);
                        }
                        if (scoring == Scoring.Intensity) {
                            fragmentscore.put(frag.GetFragKey(),
                                    fragmentscore.get(frag.GetFragKey()) + frag.intensity);
                        } else if (scoring == Scoring.IntensityCorr) {
                            fragmentscore.put(frag.GetFragKey(),
                                    fragmentscore.get(frag.GetFragKey()) + frag.corr * frag.intensity);
                        }
                        fragmentfreq.put(frag.GetFragKey(), fragmentfreq.get(frag.GetFragKey()) + 1);

                        if (!FragInt.containsKey(pep.GetKey() + "_" + frag.GetFragKey())) {
                            FragInt.put(pep.GetKey() + "_" + frag.GetFragKey(), new HashMap<String, Float>());
                        }
                        FragInt.get(pep.GetKey() + "_" + frag.GetFragKey())
                                .put(FilenameUtils.getBaseName(IDSummary.Filename), frag.intensity);
                    }
                }
            }
        }
        for (String fragkey : fragmentfreq.keySet()) {
            if (fragmentfreq.get(fragkey) > IDNo * freqPercent) {
                PepFragScore.get(PepKey).put(fragkey, fragmentscore.get(fragkey));
            }
        }
    }
}

From source file:com.piketec.jenkins.plugins.tpt.publisher.TPTReportPublisher.java

/**
 * Creates the directories on the build directory, loops over all JenkinsConfigurations and
 * extract from each one the data from the "test_summary.xml". Then it sets the failed tests and
 * finally it creates the TPTReportPage action . (Thats the one who is displaying the files,
 * piechart and failed tests)/* w  w  w . j a v a2 s  . c om*/
 */
@Override
public boolean perform(@SuppressWarnings("rawtypes") final AbstractBuild build, final Launcher launcher,
        final BuildListener listener) throws IOException, InterruptedException {

    TptLogger logger = new TptLogger(listener.getLogger());
    logger.info("Starting Post Build Action \"TPT Report\"");

    List<JenkinsConfiguration> jenkinsConfigurationsToPublishForThisWorkspace = TPTBuildStepEntries
            .getEntries(build);

    if (jenkinsConfigurationsToPublishForThisWorkspace == null) {
        logger.info("Nothing to publish");
        return false;
    }

    ArrayList<FilePath> uniqueTestDataDir = new ArrayList<>();
    ArrayList<FilePath> uniqueReportDataDir = new ArrayList<>();
    ArrayList<TPTFile> tptFiles = new ArrayList<>();
    ArrayList<TPTTestCase> failedTests = new ArrayList<>();
    // global file in Build
    FilePath workspace = build.getWorkspace();
    File piketectptDir = new File(build.getRootDir().getAbsolutePath() + File.separator + "Piketec-TPT");
    if (!piketectptDir.exists()) {
        if (!piketectptDir.mkdirs()) {
            throw new IOException("Could not create directory \"" + piketectptDir.getAbsolutePath() + "\"");
        }
    }

    for (JenkinsConfiguration cfg : jenkinsConfigurationsToPublishForThisWorkspace) {
        // make file in build und copy report dir
        String tptFileName = FilenameUtils.getBaseName(cfg.getTptFile());
        File dir = new File(piketectptDir.getAbsolutePath() + File.separator + tptFileName);
        if (!dir.isDirectory()) {
            if (!dir.mkdirs()) {
                throw new IOException("Could not create directory \"" + dir.getAbsolutePath() + "\"");
            }
        }
        File dirExConfig = new File(piketectptDir.getAbsolutePath() + File.separator + tptFileName
                + File.separator + cfg.getConfiguration());
        if (!dirExConfig.mkdirs()) {
            throw new IOException("Could not create directory \"" + dirExConfig.getAbsolutePath() + "\"");
        }
        FilePath reportDir = new FilePath(workspace, Utils.getGeneratedReportDir(cfg));
        FilePath testDataDir = new FilePath(workspace, Utils.getGeneratedTestDataDir(cfg));
        if (reportDir.exists()) {
            reportDir.copyRecursiveTo(new FilePath(dirExConfig));
        }
        FilePath reportXML = new FilePath(testDataDir, "test_summary.xml");
        if (reportXML.exists()) {
            TPTFile newTPTFile = new TPTFile(tptFileName, cfg.getConfiguration());
            // get the remote path, then cut the path and get just what is needed (the last part),
            // see getLinkToFailedReport() in TPTReportSAXHandler.
            parse(reportXML, newTPTFile, failedTests, reportDir.getRemote(), cfg.getConfiguration(), logger);
            tptFiles.add(newTPTFile);
        } else {
            logger.error(
                    "There is no test_summary.xml for the file \"" + tptFileName + "\".It won't be published ");
            continue;
        }
        // Check if the Testdata dir and the Report are unique, otherwise throw an exception
        if (uniqueReportDataDir.contains(reportDir) || uniqueTestDataDir.contains(testDataDir)) {
            throw new IOException("The directory \"" + cfg.getReportDir() + "\" or the directoy \""
                    + cfg.getTestdataDir() + "\" is already used, please choose another one");
        }
        uniqueReportDataDir.add(reportDir);
        uniqueTestDataDir.add(testDataDir);
    }

    // Failed Since. Look up test in previous build. If failed there. extract failed since
    // information and add 1
    AbstractBuild lastSuccBuild = (AbstractBuild) build.getPreviousNotFailedBuild();
    // the tpt report of last successful build
    TPTReportPage lastTptFilesAction = (lastSuccBuild == null) ? null
            : lastSuccBuild.getAction(TPTReportPage.class);
    if (lastTptFilesAction != null) {
        HashMap<FailedTestKey, TPTTestCase> prevFailed = new HashMap<FailedTestKey, TPTTestCase>();
        for (TPTTestCase tptTestCase : lastTptFilesAction.getFailedTests()) {
            prevFailed.put(new FailedTestKey(tptTestCase.getId(), tptTestCase.getFileName(),
                    tptTestCase.getExecutionConfiguration(), tptTestCase.getPlatform()), tptTestCase);
        }
        for (TPTTestCase t : failedTests) {
            String id = t.getId();
            String fileName = t.getFileName();
            String exeConfig = t.getExecutionConfiguration();
            String platform = t.getPlatform();
            FailedTestKey ftk = new FailedTestKey(id, fileName, exeConfig, platform);
            if (prevFailed.containsKey(ftk)) {
                t.setFailedSince(prevFailed.get(ftk).getFailedSince() + 1);
            }
        }
    }
    TPTReportPage filesAction = new TPTReportPage(build, failedTests, tptFiles);
    filesAction.createGraph();
    build.addAction(filesAction);
    listener.getLogger().println("Finished Post Build Action");
    if (!failedTests.isEmpty()) {
        build.setResult(Result.UNSTABLE);
    }
    return true;
}

From source file:net.sourceforge.atunes.kernel.actions.LoadNewPlayListAction.java

@Override
protected void executeAction() {
    IFileSelectorDialog dialog = this.dialogFactory.newDialog(IFileSelectorDialog.class);
    dialog.setFileFilter(this.playListIOService.getAllAcceptedPlaylistsFileFilter());
    File file = dialog.loadFile(this.statePlaylist.getLoadPlaylistPath());
    if (file != null) {
        // If exists...
        if (file.exists()) {
            this.statePlaylist.setLoadPlaylistPath(FileUtils.getPath(file.getParentFile()));

            if (this.playListIOService.isDynamicPlayList(file)) {
                this.playListIOService.readDynamicPlayList(file);
            } else {

                // Read file names
                List<String> filesToLoad = this.playListIOService.read(file);
                // Background loading - but only when returned array is not
                // null
                // (Progress dialog hangs otherwise)
                if (filesToLoad != null) {
                    LoadPlayListProcess process = (LoadPlayListProcess) this.processFactory
                            .getProcessByName("loadPlayListProcess");
                    process.setFilenamesToLoad(filesToLoad);
                    process.setReplacePlayList(this.replacePlayList);
                    process.setPlayListName(FilenameUtils.getBaseName(file.getName()));
                    process.execute();/*www .  j a va 2  s  . c  om*/
                }
            }
        } else {
            this.dialogFactory.newDialog(IErrorDialog.class)
                    .showErrorDialog(I18nUtils.getString("FILE_NOT_FOUND"));
        }
    }
}

From source file:com.norconex.jef4.status.JobSuiteStatusSnapshot.java

public static JobSuiteStatusSnapshot newSnapshot(File suiteIndex) throws IOException {
    //--- Ensure file looks good ---
    if (suiteIndex == null) {
        throw new IllegalArgumentException("Suite index file cannot be null.");
    }/*from w w  w  . j a v a  2s .c  om*/
    if (!suiteIndex.exists()) {
        return null;
    }
    if (!suiteIndex.isFile()) {
        throw new IllegalArgumentException("Suite index is not a file: " + suiteIndex.getAbsolutePath());
    }

    //--- Load XML file ---
    String suiteName = FileUtil.fromSafeFileName(FilenameUtils.getBaseName(suiteIndex.getPath()));
    XMLConfiguration xml = new XMLConfiguration();
    ConfigurationUtil.disableDelimiterParsing(xml);
    try {
        xml.load(suiteIndex);
    } catch (ConfigurationException e) {
        throw new IOException("Could not load suite index: " + suiteIndex, e);
    }

    //--- LogManager ---
    ILogManager logManager = ConfigurationUtil.newInstance(xml, "logManager");

    //--- Load status tree ---
    IJobStatusStore serial = ConfigurationUtil.newInstance(xml, "statusStore");
    return new JobSuiteStatusSnapshot(loadTreeNode(null, xml.configurationAt("job"), suiteName, serial),
            logManager);
}

From source file:eu.openanalytics.rsb.component.ResultResource.java

private PersistedResult getPersistedResultOrDie(final String applicationName, final String resourceName) {
    if (!Util.isValidApplicationName(applicationName)) {
        throw new IllegalArgumentException("Invalid application name: " + applicationName);
    }//from   w  w w  .  java  2  s .c  o m

    final UUID jobId = UUID.fromString(FilenameUtils.getBaseName(resourceName));

    final PersistedResult persistedResult = resultStore.findByApplicationNameAndJobId(applicationName,
            getUserName(), jobId);

    if (persistedResult == null) {
        throw new WebApplicationException(Response.status(Status.NOT_FOUND).build());
    }

    return persistedResult;
}

From source file:fr.ippon.wip.config.dao.DeployConfigurationDecorator.java

/**
 * Extract configurations contained in a zipFile.
 * /*from  w  w  w  .  jav a2s  .c  o m*/
 * @param zipFile
 *            the file containing the configurations
 */
private List<WIPConfiguration> unzip(final ZipFile zipFile) {
    List<WIPConfiguration> configurations = new ArrayList<WIPConfiguration>();
    Iterator<? extends ZipEntry> xmlEntries = filter(forEnumeration(zipFile.entries()), xmlPredicate);

    while (xmlEntries.hasNext()) {
        try {
            String configName = FilenameUtils.getBaseName(xmlEntries.next().getName());
            WIPConfiguration configuration = zip.unzip(zipFile, configName);

            if (configuration != null)
                configurations.add(configuration);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return configurations;
}

From source file:com.nabla.wapp.report.server.handler.UpgradeReportHandler.java

@Override
protected void update(UpgradeReport record, IUserSessionContext ctx) throws DispatchException, SQLException {
    final Connection conn = ctx.getWriteConnection();
    final PreparedStatement stmt = StatementFormat.prepare(ctx.getReadConnection(),
            "SELECT * FROM import_data WHERE id=?;", record.getFileId());
    try {//from   w  w w  .j  a  va2  s . com
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next())
                throw new ActionException(CommonServerErrors.NO_DATA);
            if (!ctx.getSessionId().equals(rs.getString("userSessionId")))
                throw new ActionException(CommonServerErrors.ACCESS_DENIED);
            final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn);
            try {
                Database.executeUpdate(conn, "DELETE FROM report_resource WHERE report_id=?;",
                        record.getReportId());
                Database.executeUpdate(conn, "DELETE FROM report_name_localized WHERE report_id=?;",
                        record.getReportId());
                if (ReportZipFile.acceptContentType(rs.getString("content_type"))) {
                    final ReportZipFile zip = new ReportZipFile(rs.getBinaryStream("content"));
                    try {
                        final ZipArchiveEntry design = zip.getReportDesign();
                        if (design == null)
                            throw new DispatchException(ReportErrors.ADD_REPORT_NO_REPORT_DESIGN_FOUND);
                        reportManager.upgradeReport(conn, record.getReportId(), design.getName(),
                                zip.getInputStream(design));
                        for (Enumeration<ZipArchiveEntry> iter = zip
                                .getEntries(ReportManager.PROPERTIES_FILE_EXTENSION); iter.hasMoreElements();) {
                            final ZipArchiveEntry e = iter.nextElement();
                            reportManager.loadLocaleReportName(conn, record.getReportId(), e.getName(),
                                    zip.getInputStream(e));
                        }
                        for (Enumeration<ZipArchiveEntry> iter = zip
                                .getEntries(ReportManager.RESOURCE_FILE_EXTENSIONS); iter.hasMoreElements();) {
                            final ZipArchiveEntry e = iter.nextElement();
                            reportManager.loadReportResource(conn, record.getReportId(), e.getName(),
                                    zip.getInputStream(e));
                        }
                    } finally {
                        zip.close();
                    }
                } else
                    reportManager.upgradeReport(conn, record.getReportId(),
                            FilenameUtils.getBaseName(rs.getString("file_name")),
                            rs.getBinaryStream("content"));
                guard.setSuccess();
            } finally {
                guard.close();
            }
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
    Database.executeUpdate(conn, "DELETE FROM import_data WHERE id=?;", record.getFileId());
}

From source file:edu.ku.brc.specify.tasks.subpane.images.ImageDataItem.java

/**
 * @return the shortName/*  w ww. j av  a2 s. c om*/
 */
public String getShortName() {
    if (shortName == null) {
        shortName = FilenameUtils.getBaseName(title);
    }
    return shortName;
}