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:com.cedarsoft.file.FileNameTest.java

License:asdf

@Test
public void testFileNameUtils() {
    assertEquals("", FilenameUtils.getExtension("asdf"));
    assertEquals("", FilenameUtils.getExtension("asdf."));

    assertEquals("asdf", FilenameUtils.getBaseName("asdf."));
}

From source file:com.gs.obevo.mithra.MithraSchemaConverter.java

public void convertMithraDdlsToDaFormat(final Platform platform, File inputDir, File outputDir,
        final String schemaName, boolean generateBaseline) {
    if (!inputDir.canRead()) {
        throw new IllegalArgumentException("Cannot read input directory: " + inputDir);
    }/*  www.j  a va2 s  .com*/
    final MutableList<ChangeEntry> changeEntries = ArrayAdapter
            .adapt(inputDir.listFiles(AquaRevengMain.VCS_FILE_FILTER))
            .flatCollect(new Function<File, Iterable<ChangeEntry>>() {
                @Override
                public Iterable<ChangeEntry> valueOf(File file) {
                    final String objectName = FilenameUtils.getBaseName(file.getName());
                    final String fileExtension = FilenameUtils.getExtension(file.getName());

                    final Function<Pair<String, Integer>, ChangeEntry> func;
                    if (fileExtension.equalsIgnoreCase("ddl")) {
                        func = new Function<Pair<String, Integer>, ChangeEntry>() {
                            @Override
                            public ChangeEntry valueOf(Pair<String, Integer> sqlIndexPair) {
                                return getTableChange(platform, schemaName, objectName, sqlIndexPair.getOne(),
                                        sqlIndexPair.getTwo());
                            }
                        };
                    } else if (fileExtension.equalsIgnoreCase("fk")) {
                        func = new Function<Pair<String, Integer>, ChangeEntry>() {
                            @Override
                            public ChangeEntry valueOf(Pair<String, Integer> sqlIndexPair) {
                                return getFkChange(platform, schemaName, objectName, sqlIndexPair.getOne(),
                                        sqlIndexPair.getTwo());
                            }
                        };
                    } else if (fileExtension.equalsIgnoreCase("idx")) {
                        func = new Function<Pair<String, Integer>, ChangeEntry>() {
                            @Override
                            public ChangeEntry valueOf(Pair<String, Integer> sqlIndexPair) {
                                return getIndexChange(platform, schemaName, objectName, sqlIndexPair.getOne(),
                                        sqlIndexPair.getTwo());
                            }
                        };
                    } else {
                        LOG.warn(
                                "Unexpected file extension {} for file {}, so we are not processing this file. Expecting extensions: .ddl, .fx, .idx",
                                fileExtension, file);
                        // unexpected
                        return Lists.mutable.empty();
                    }

                    final RichIterable<String> sqls = splitSqlBySemicolon(
                            FileUtilsCobra.readFileToString(file));
                    return sqls.asLazy().reject(DAStringUtil.STRING_IS_BLANK).zipWithIndex().collect(func);
                }
            });

    new RevengWriter().write(platform, changeEntries, outputDir, generateBaseline,
            RevengWriter.defaultShouldOverwritePredicate(), null, null, null);
}

From source file:de.monticore.io.paths.ModelCoordinateImpl.java

@Override
public String getBaseName() {
    if (hasLocation()) {
        return FilenameUtils.getBaseName(location.toString());
    } else {//ww w  .ja v  a  2s  .  c o m
        return FilenameUtils.getBaseName(qualifiedPath.toString());
    }
}

From source file:de.uzk.hki.da.convert.PublishPDFConversionStrategy.java

@Override
public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) throws IOException {

    if (ci.getConversion_routine() == null)
        throw new IllegalStateException("conversionRoutine not set");
    if (ci.getConversion_routine().getTarget_suffix().isEmpty())
        throw new IllegalStateException("target suffix in conversionRoutine not set");

    List<Event> results = new ArrayList<Event>();

    String input = wa.toFile(ci.getSource_file()).getAbsolutePath();

    for (String audience : audiences) {

        String audience_lc = audience.toLowerCase();

        DAFile target = new DAFile(pips + "/" + audience_lc, StringUtilities.slashize(ci.getTarget_folder())
                + FilenameUtils.getBaseName(input) + "." + ci.getConversion_routine().getTarget_suffix());
        wa.toFile(target).getParentFile().mkdirs();

        String numberOfPagesText = null;
        if (getPublicationRightForAudience(audience) != null)
            if (getPublicationRightForAudience(audience).getTextRestriction() != null)
                if (getPublicationRightForAudience(audience).getTextRestriction().getPages() != null)
                    numberOfPagesText = getPublicationRightForAudience(audience).getTextRestriction().getPages()
                            .toString();

        String certainPagesText = null;
        if (getPublicationRightForAudience(audience) != null) {
            certainPagesText = "";
            if (getPublicationRightForAudience(audience).getTextRestriction() != null)
                if (getPublicationRightForAudience(audience).getTextRestriction().getCertainPages() != null)
                    for (int i = 0; i < getPublicationRightForAudience(audience).getTextRestriction()
                            .getCertainPages().length; i++) {
                        if (!certainPagesText.equals(""))
                            certainPagesText += " ";
                        certainPagesText += getPublicationRightForAudience(audience).getTextRestriction()
                                .getCertainPages()[i];
                    }// w w  w .  j ava 2 s.co  m
        }

        // copy whole file if no restrictions are found
        if (StringUtilities.isNotSet(numberOfPagesText) && StringUtilities.isNotSet(certainPagesText)) {
            try {
                logger.debug("AUDIENCE " + audience + ": COPY " + input + " to " + target);
                FileUtils.copyFileToDirectory(new File(input), wa.toFile(target).getParentFile());
                Event e = new Event();
                e.setDetail("Copied PDF");
                e.setSource_file(ci.getSource_file());
                e.setTarget_file(target);
                e.setType("CONVERT");
                e.setDate(new Date());
                results.add(e);
            } catch (IOException e) {
                throw new RuntimeException("Could not copy PDF!", e);
            }
            continue;
        }
        logger.debug("AUDIENCE " + audience
                + ": Converted with PDFBox, only certain pages wanted: NumberOfPagesMax:(" + numberOfPagesText
                + "), CertainPages:(" + certainPagesText + ")");
        PdfService pdf = new PdfService(new File(input), wa.toFile(target));
        pdf.reduceToCertainPages(numberOfPagesText, certainPagesText);
        Event e = new Event();
        e.setDetail("converted with PDFBox");
        e.setSource_file(ci.getSource_file());
        e.setTarget_file(target);
        e.setType("CONVERT");
        e.setDate(new Date());
        results.add(e);
    }
    return results;

}

From source file:gov.nih.nci.cabig.caaers.service.adverseevent.AdditionalInformationDocumentService.java

public AdditionalInformationDocument uploadFile(String fileName, AdditionalInformation additionalInformation,
        InputStream inputStream, AdditionalInformationDocumentType additionalInformationDocumentType) {

    try {/*  ww w .jav  a  2s .co m*/

        String aeAttachmentsLocation = configuration.get(Configuration.AE_ATTACHMENTS_LOCATION);

        String directory = FilenameUtils.normalize(aeAttachmentsLocation + "/" + additionalInformation.getId());

        String extension = StringUtils.isNotBlank(FilenameUtils.getExtension(fileName))
                ? "." + FilenameUtils.getExtension(fileName)
                : "";

        String filePath = FilenameUtils.normalize(directory + "/" + FilenameUtils.getBaseName(fileName)
                + Calendar.getInstance().getTimeInMillis() + RandomUtils.nextInt(100) + extension);

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("creating file  %s of type %s for additional information %s at %s ",
                    fileName, additionalInformationDocumentType, additionalInformation.getId(), filePath));
        }

        FileUtils.forceMkdir(new File(directory));

        File file = new File(filePath);
        if (file.createNewFile()) {
            long bytesCopied = IOUtils.copyLarge(inputStream, new FileOutputStream(file));

            AdditionalInformationDocument additionalInformationDocument = new AdditionalInformationDocument();
            additionalInformationDocument
                    .setAdditionalInformationDocumentType(additionalInformationDocumentType);
            additionalInformationDocument.setAdditionalInformation(additionalInformation);
            additionalInformationDocument.setFileId(DigestUtils.md5Hex(file.getAbsolutePath()));
            additionalInformationDocument.setOriginalFileName(fileName);
            additionalInformationDocument.setFileName(file.getName());

            additionalInformationDocument.setFilePath(file.getCanonicalPath());
            additionalInformationDocument.setRelativePath(file.getAbsolutePath());
            additionalInformationDocument.setFileSize(bytesCopied);
            additionalInformationDocumentDao.save(additionalInformationDocument);
            if (logger.isDebugEnabled()) {
                logger.debug(String.format(
                        "successfully created file  %s of type %s for additional information %s at %s. File information is - %s ",
                        fileName, additionalInformationDocumentType, additionalInformation.getId(), filePath,
                        additionalInformationDocument));
            }

            return additionalInformationDocument;
        } else {
            String errorMessage = String.format(
                    "error while creating  file  %s of type %s for additional information %s ", fileName,
                    additionalInformationDocumentType, additionalInformation.getId());
            throw new RuntimeException(errorMessage);
        }
    } catch (Exception e) {
        String errorMessage = String.format(
                "error while creating  file  %s of type %s for additional information %s ", fileName,
                additionalInformationDocumentType, additionalInformation.getId());

        logger.error(errorMessage, e);
        return null;
    }

}

From source file:minij.MiniJCompilerTest.java

@Test
public void testCompileExamples() throws IOException {

    System.out.println("Testing compiler input from file \"" + file.toString() + "\"");

    Configuration config = new Configuration(new String[] { file.toString() });
    config.outputFile = "out" + File.separator + config.outputFile;

    try {/*from   w ww  .java2 s .c  o  m*/
        compiler.compile(config);
        String output = compiler.runExecutable(config, 15);
        if (exceptionClass != null) {
            fail("The example " + file.toString() + " should have failed with exception " + exceptionClass
                    + ", but was accepted by the compiler.");
        }

        byte[] content = Files.readAllBytes(new File("src/test/resources/minij-examples-outputs/working/"
                + FilenameUtils.getBaseName(file.toString()) + ".txt").toPath());
        String expectedOutput = new String(content);

        if (!output.equals(expectedOutput)) {
            fail("The example " + file.toString() + " should have printed '" + expectedOutput
                    + "' but printed '" + output + "'");
        }
    } catch (Exception e) {

        if (exceptionClass == null) {
            e.printStackTrace();
            fail("The example " + file.toString() + " should have been accepted by the compiler but failed: "
                    + e.getMessage());
        }

        if (!exceptionClass.isInstance(e)) {
            fail("The example " + file.toString() + " should have failed with exception " + exceptionClass
                    + " but with failed with exception " + e.getClass() + ", " + e.getMessage());
        }
    }
}

From source file:MSUmpire.DIA.DIAMapClusterUnit.java

@Override
public void run() {
    //For each identified PSM
    for (PSM psm : pepIonID.GetPSMList()) {
        int ClusterIndex = -1;
        if (psm.GetRawNameString() == null ? Q1Name == null
                : psm.GetRawNameString().equals(FilenameUtils.getBaseName(Q1Name))) {
            if (!ScanClusterMap_Q1.containsKey(psm.ScanNo)) {
                Logger.getRootLogger().error("ScanClusterMapping error");
                Logger.getRootLogger()
                        .error("ScanClusterMapping " + Q1Name + " doesn't have " + psm.SpecNumber);
                System.exit(3);//from   w ww .ja v a2s . c o  m
            }
            //Get cluster index fro Q1
            ClusterIndex = ScanClusterMap_Q1.get(psm.ScanNo);
            PeakCluster Cluster = ms1lcms.PeakClusters.get(ClusterIndex - 1);
            Cluster.Identified = true;
            if (!pepIonID.MS1PeakClusters.contains(Cluster)) {
                pepIonID.MS1PeakClusters.add(Cluster);
            }
        } else if (psm.GetRawNameString() == null ? Q2Name == null
                : psm.GetRawNameString().equals(FilenameUtils.getBaseName(Q2Name))) {
            if (!ScanClusterMap_Q2.containsKey(psm.ScanNo)) {
                Logger.getRootLogger().error("ScanClusterMapping error");
                Logger.getRootLogger()
                        .error("ScanClusterMapping " + Q2Name + " doesn't have " + psm.SpecNumber);
                System.exit(3);
            }

            //Get cluster index fro Q2
            ClusterIndex = ScanClusterMap_Q2.get(psm.ScanNo);
            PeakCluster Cluster = ms1lcms.PeakClusters.get(ClusterIndex - 1);
            Cluster.Identified = true;
            if (!pepIonID.MS1PeakClusters.contains(Cluster)) {
                pepIonID.MS1PeakClusters.add(Cluster);
            }
        } else if (psm.GetRawNameString() == null ? Q3Name == null
                : psm.GetRawNameString().equals(FilenameUtils.getBaseName(Q3Name))) {
            String WindowClusterIndex = ScanClusterMap_Q3.get(psm.ScanNo);
            if (!ScanClusterMap_Q3.containsKey(psm.ScanNo)) {
                Logger.getRootLogger().error("ScanClusterMapping error");
                Logger.getRootLogger()
                        .error("ScanClusterMapping " + Q3Name + " doesn't have " + psm.SpecNumber);
                System.exit(3);
            }
            if (WindowClusterIndex.split(";").length == 2) {
                String windowname = WindowClusterIndex.split(";")[0];
                if (windowname.equals(DIAWindow.WindowID)) {
                    //Get cluster index fro Q3
                    ClusterIndex = Integer.parseInt(WindowClusterIndex.split(";")[1]);
                    PeakCluster Cluster = DIAWindow.PeakClusters.get(ClusterIndex - 1);
                    Cluster.Identified = true;
                    pepIonID.MS2UnfragPeakClusters.add(Cluster);
                    ArrayList<PeakCluster> ms1list = ms1lcms.FindPeakClustersByMassRTRange(
                            Cluster.NeutralMass(), Cluster.Charge, Cluster.startRT, Cluster.endRT);
                    for (PeakCluster ms1cluster : ms1list) {
                        ms1cluster.Identified = true;
                        if (!pepIonID.MS1PeakClusters.contains(ms1cluster)) {
                            pepIonID.MS1PeakClusters.add(ms1cluster);
                        }
                    }
                }
            } else {
                //Get cluster index fro Q3
                ClusterIndex = Integer.parseInt(WindowClusterIndex);
                if (DIAWindow.UnFragIonClu2Cur.containsKey(ClusterIndex)) {
                    PeakCluster Cluster = DIAWindow.PeakClusters.get(ClusterIndex - 1);
                    if (Cluster.Charge == psm.Charge
                            && Math.abs(Cluster.TargetMz() - psm.ObserPrecursorMz()) < 0.01f
                            && Math.abs(Cluster.PeakHeightRT[0] - psm.RetentionTime) < 0.1f) {
                        Cluster.Identified = true;
                        pepIonID.MS2UnfragPeakClusters.add(Cluster);
                    }
                    ArrayList<PeakCluster> ms1list = ms1lcms.FindPeakClustersByMassRTRange(
                            Cluster.NeutralMass(), Cluster.Charge, Cluster.startRT, Cluster.endRT);
                    for (PeakCluster ms1cluster : ms1list) {
                        ms1cluster.Identified = true;
                        if (!pepIonID.MS1PeakClusters.contains(ms1cluster)) {
                            pepIonID.MS1PeakClusters.add(ms1cluster);
                        }
                    }
                }
            }
        }
    }

    if (pepIonID.MS1PeakClusters.isEmpty() && pepIonID.MS2UnfragPeakClusters.isEmpty()) {
        Logger.getRootLogger().trace("Cannot find feature for identified peptide ion : " + pepIonID.GetKey()
                + " mz: " + pepIonID.ObservedMz + " in isolation window " + DIAWindow.WindowID);
    }
}

From source file:org.openhab.io.caldav.internal.Util.java

public static String getFilename(String name) {
    name = FilenameUtils.getBaseName(name);
    name = name.replaceAll("[^a-zA-Z0-9-_]", "_");
    return name;//from   w  w  w  .j  a v  a2 s  .c om
}

From source file:in.arun.faces.fo.pdf.FoOutputStream.java

@Override
public void close() throws IOException {
    if (closed) {
        throw new IOException("Stream has already been closed");
    }/*from w w  w. j  a va  2s  . com*/

    closed = true;
    PdfResult result = buildPdf(this);

    FacesContext context = FacesContext.getCurrentInstance();

    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

    response.reset();

    String fileName;
    if (null == (fileName = request.getParameter("output"))) {
        fileName = FilenameUtils.getBaseName(request.getRequestURL().toString());
    }

    fileName += ".pdf";

    response.setContentType(result.contentType);
    response.setContentLength(result.content.length);
    response.setHeader("content-disposition", "inline; FileName=\"" + fileName + "\"");

    OutputStream outputStream = response.getOutputStream();
    outputStream.write(result.content);
    outputStream.flush();

    context.responseComplete();
}

From source file:de.uzk.hki.da.at.ATMigrationRight.java

@Test
public void test() throws IOException {
    ath.awaitObjectState(ORIG_NAME, Object.ObjectStatus.ArchivedAndValidAndNotInWorkflow);

    ath.putSIPtoIngestArea(ORIG_NAME, C.FILE_EXTENSION_TGZ, ORIG_NAME);

    ath.awaitObjectState(ORIG_NAME, Object.ObjectStatus.InWorkflow);
    ath.awaitObjectState(ORIG_NAME, Object.ObjectStatus.ArchivedAndValidAndNotInWorkflow);

    o = ath.getObject(ORIG_NAME);//from   ww  w .j  ava 2s  . c om
    ath.retrieveAIP(o, UNPACKED_DIP, "1");

    String brep = "";
    File[] fList = Path.makeFile(UNPACKED_DIP.toString(), "data").listFiles();
    for (File file : fList) {
        if (file.getAbsolutePath().endsWith("+b")) {
            brep = FilenameUtils.getBaseName(file.getAbsolutePath());
            System.out.println(":" + brep);
        }
    }

    assertTrue(Path.makeFile(UNPACKED_DIP.toString(), "data", brep, "image42.tif").exists());

}