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.tocsi.images.ReceivedImageController.java

public void handleFileUpload(FileUploadEvent event) {
    if (event.getFile() != null) {
        try {//from ww  w  . j  a  v  a2s .com
            UploadedFile uf = (UploadedFile) event.getFile();
            File folder = new File(GlobalsBean.destOriginal);
            //File folderThumb = new File(destThumbnail);
            String filename = FilenameUtils.getBaseName(uf.getFileName());
            String extension = FilenameUtils.getExtension(uf.getFileName());
            File file = File.createTempFile(filename + "-", "." + extension, folder);
            //File fileThumb = File.createTempFile(filename + "-", "." + extension, folderThumb);

            //resize image here
            BufferedImage originalImage = ImageIO.read(uf.getInputstream());
            InputStream is = uf.getInputstream();
            if (originalImage.getWidth() > 700) { //resize image if image's width excess 700px
                BufferedImage origImage = Scalr.resize(originalImage, Scalr.Method.QUALITY,
                        Scalr.Mode.FIT_TO_WIDTH, 640,
                        (int) ((originalImage.getHeight() / ((double) (originalImage.getWidth() / 700.0)))),
                        Scalr.OP_ANTIALIAS);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(origImage, extension, os);
                is = new ByteArrayInputStream(os.toByteArray());
            }

            //create thumbnail
            BufferedImage thumbnail = Scalr.resize(ImageIO.read(uf.getInputstream()), 150);
            ByteArrayOutputStream osThumb = new ByteArrayOutputStream();
            ImageIO.write(thumbnail, extension, osThumb);
            InputStream isThumbnail = new ByteArrayInputStream(osThumb.toByteArray());

            try (InputStream input = is) {
                Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            try (InputStream input = isThumbnail) {
                Files.copy(input, Paths.get(GlobalsBean.destThumbnail + GlobalsBean.separator + file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }

            //File chartFile = new File(file.getAbsolutePath());
            //chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/jpg");
            ImageBean ib = new ImageBean();
            ib.setFilename(file.getName());
            ib.setThumbFile(file.getName());
            ib.setImageFileLocation(GlobalsBean.destOriginal + GlobalsBean.separator + file.getName());
            imageList.add(ib);

        } catch (IOException | IllegalArgumentException | ImagingOpException ex) {
            Utilities.displayError(ex.getMessage());
        }
    }
}

From source file:com.frostwire.search.yify.YifySearchResult.java

private static String buildFileName(String detailsUrl) {
    return FilenameUtils.getBaseName(detailsUrl) + ".torrent";
}

From source file:filehandling.FileUploadBean.java

public void fileUploadListener(FileUploadEvent e) {

    UploadedFile file = e.getFile();//from  w  w w  . jav  a 2s .c  o  m

    if (Master.DEBUG_LEVEL > Master.LOW)
        System.out.println("Uploaded file is " + file.getFileName() + " (" + file.getSize() + ")");

    String filename = FilenameUtils.getBaseName(file.getFileName());
    String extension = FilenameUtils.getExtension(file.getFileName());
    extension = extension.equals("") ? "xml" : extension;

    byte[] bytes = file.getContents();
    List<FileData> result = FilePreprocessor.extractMDFilesFromXMLEmbedding(bytes, filename, extension);
    // this.addFilesToDisplayList(result); //!!!!!
    this.uploadedSth = true;
    if (fireOpenEvent) {
        StringBuilder sb = new StringBuilder();
        for (FileData fd : result) {
            if (sb.length() != 0) {
                sb.append(',');
            }
            sb.append(fd.getDisplayname());
        }
        sb.insert(0, "fireBasicEvent(\'MDEuploadedMD\' ,{filename:\'[");
        sb.append("]\'});");
        String command = sb.toString();

        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println(command);
        RequestContext.getCurrentInstance().execute(command);
    }

    RequestContext.getCurrentInstance().update(GUIrefs.getClientId(GUIrefs.fileDispDlg));
    GUIrefs.updateComponent(GUIrefs.filesToShow);
    // String command = "doFireEvent(\'file upload event\',\'" +
    // file.getFileName() + "\' );";
    // RequestContext.getCurrentInstance().execute(command);
}

From source file:eu.hydrologis.jgrass.formeditor.OpenFormEditorAction.java

public void run(IAction action) {

    Display.getDefault().asyncExec(new Runnable() {

        public void run() {

            try {

                IMap activeMap = ApplicationGIS.getActiveMap();
                ILayer selectedLayer = null;
                if (activeMap != null) {
                    selectedLayer = activeMap.getEditManager().getSelectedLayer();
                } else {
                    MessageDialog.openError(window.getShell(), "ERROR",
                            "To use the form editor you need to select a feature layer to work on.");
                    return;
                }//from  w ww  .ja  v  a 2s  .c om
                if (selectedLayer == null || !selectedLayer.hasResource(FeatureSource.class)) {
                    MessageDialog.openError(window.getShell(), "ERROR",
                            "To use the form editor you need to select a feature layer to work on.");
                    return;
                }

                IGeoResource geoResource = selectedLayer.getGeoResource();
                ID id = geoResource.getID();
                boolean isFile = id.isFile();
                if (isFile) {
                    File f = id.toFile();
                    String baseName = FilenameUtils.getBaseName(f.getName());
                    File newF = new File(f.getParentFile(), baseName + ".form");
                    if (!newF.exists()) {
                        newF.createNewFile();
                    }

                    openEditor(newF);

                    return;
                }
                /*
                 * try to see if we can find one in the bboard for this layer
                 */
                IStyleBlackboard blackboard = selectedLayer.getStyleBlackboard();
                String path = blackboard.getString(FormEditor.ID);
                if (path != null) {
                    final File f = new File(path);
                    openEditor(f);
                    return;
                }
                /*
                 * it is not file based or no project/map is there. Just ask 
                 * for a file on which to save.
                 */
                FileDialog fileDialog = new FileDialog(window.getShell(), SWT.SAVE);
                fileDialog.setText("Please select the file to which to save the form.");
                fileDialog.setFilterExtensions(new String[] { "*.form" });
                path = fileDialog.open();
                if (path == null || path.length() < 1) {
                    return;
                }

                final File f = new File(path);
                openEditor(f);
                // the path will live in the bboard, if not as a sidecar file
                blackboard.putString(FormEditor.ID, path);

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

    });

}

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

private void addSummariesForFile(final File mzxmlFile, final Integer fileIndex,
        final Map<ScanIndex, ITraqScanSummary> scanMap, final ITraqMatchBuilderOptions options,
        boolean useScanNumber) {
    // Parse the mzxml files
    final InputStream inputStream = FILE_UTILS.getFileInputStream(mzxmlFile);
    try {//ww w .  j  a  v a  2  s.  com
        final Iterator<Scan> scans = peakListParser.parse(inputStream);
        while (scans.hasNext()) {
            final Scan mzxmlScan = scans.next();
            final int number = useScanNumber ? mzxmlScan.getNumber() : mzxmlScan.getIndex();
            final short charge = mzxmlScan.getPrecursorCharge();
            // System.out.println("UseNumber:" + useScanNumber + " " + number + " <- number charge ->" + charge + " " + mzxmlScan.getIndex() + " "
            // + mzxmlScan.getNumber());
            final double[] peaks = mzxmlScan.getPeaks();
            final ScanIndex scanIndex = new ScanIndex(mzxmlScan.getParentName(), fileIndex, number, charge,
                    Lists.newArrayList(mzxmlScan.getParentName(),
                            FilenameUtils.getBaseName(mzxmlFile.getName()), mzxmlFile.getName()));
            scanMap.put(scanIndex,
                    ITraqScanSummary.fromPeaks(number, number, charge, options.getITraqLabels(), peaks));
        }
    } finally {
        IO_UTILS.closeQuietly(inputStream);
    }
}

From source file:com.github.maven_nar.cpptasks.compiler.AbstractCompiler.java

protected String getBaseOutputName(final String inputFile) {
    return FilenameUtils.getBaseName(inputFile);
}

From source file:com.bbc.remarc.util.ResourceManager.java

private static void processUploadDir(File uploadFolder, String resourcesDir) {

    log.debug("processing resources within " + uploadFolder.getPath());

    List<File> directories = new ArrayList<File>();
    HashMap<String, List<File>> fileMap = new HashMap<String, List<File>>();
    HashMap<String, ResourceType> typeMap = new HashMap<String, ResourceType>();
    File properties = null;//from   w ww  . j  av  a2  s .c  o m

    //iterate through all files in the upload folder
    File[] contents = uploadFolder.listFiles();
    for (File f : contents) {

        String filename = f.getName();

        //if the file is a directory, add it to the list, we'll process this later.
        if (f.isDirectory()) {
            log.debug("directory: " + filename);
            directories.add(f);
        } else {

            String extension = FilenameUtils.getExtension(filename);
            String nameId = FilenameUtils.getBaseName(filename);

            log.debug("file: " + nameId + "(" + extension + ")");

            //determine the type of resource for the FILE
            ResourceType resourceType = getTypeFromExtension(extension);

            if (resourceType == null) {

                log.debug("unrecognised extention (" + extension + "), skipping file");

            } else if (resourceType == ResourceType.PROPERTIES) {

                log.debug("found the properties file");
                properties = f;

            } else {

                //add the file to the fileMap, key'd on the nameId
                if (!fileMap.containsKey(nameId)) {
                    List<File> fileList = new ArrayList<File>();
                    fileList.add(f);
                    fileMap.put(nameId, new ArrayList<File>(fileList));
                } else {
                    fileMap.get(nameId).add(f);
                }

                //get the current type of resource for the DOCUMENT & update it: VIDEO > AUDIO > IMAGES
                ResourceType documentType = (typeMap.containsKey(nameId)) ? typeMap.get(nameId)
                        : ResourceType.IMAGE;
                documentType = (resourceType.getValue() > documentType.getValue()) ? resourceType
                        : documentType;

                //add the document type to the typeMap, key'd on the nameId
                typeMap.put(nameId, documentType);
            }

        }

    }

    createDocumentsFromFileMap(fileMap, typeMap, properties, resourcesDir);

    log.debug("upload finished for " + uploadFolder.getPath());

    //now call the same method for each directory
    for (File dir : directories) {
        processUploadDir(dir, resourcesDir);
    }

}

From source file:com.progressiveaccess.cmlspeech.base.FileHandler.java

/**
 * Writes a document to a CML file./*from w ww. j a  v  a2s  .c o  m*/
 *
 * @param doc
 *          The output document.
 * @param fileName
 *          The base filename.
 * @param extension
 *          The additional extension.
 *
 * @throws IOException
 *           Problems with opening output file.
 * @throws CDKException
 *           Problems with writing the CML XOM.
 */
public static void writeFile(final Document doc, final String fileName, final String extension)
        throws IOException, CDKException {
    final String basename = FilenameUtils.getBaseName(fileName);
    final OutputStream outFile = new BufferedOutputStream(
            new FileOutputStream(basename + "-" + extension + ".cml"));
    final PrintWriter output = new PrintWriter(outFile);
    output.write(XOMUtil.toPrettyXML(doc));
    output.flush();
    output.close();
}

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;/*from  ww  w  .ja  va 2s  .co m*/
    }

    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:edu.cornell.med.icb.goby.util.FoldChangeForExonPairs.java

private void process(String[] args) throws FileNotFoundException {
    String inputFilenames = CLI.getOption(args, "--data", "expression-data.tsv,expression-data2.tsv");
    String pairsFilename = CLI.getOption(args, "--pairs", "pairs.tsv");
    String log2AverageId = CLI.getOption(args, "--group", "average log2_RPKM group UHR(BUQ)");
    String outputFilename = CLI.getOption(args, "--output", "/data/gc-weights/exons/out.tsv");
    String averageCountId = CLI.getOption(args, "--threshold-id", "average count group Brain");
    int thresholdValue = CLI.getIntOption(args, "--threshold-value", 20);

    //  String groupB= CLI.getOption(args,"-2","average RPKM group UHR(BUQ)");
    int log2AverageColumnIndex = -1;
    Object2DoubleMap<MutableString> exonExpressionData;

    ObjectArrayList<Pair> pairs = loadPairs(pairsFilename);
    PrintWriter output = new PrintWriter(outputFilename);
    output.printf("experiment\texonId1\texonId2\tlog2RpkmExon1-log2RpkmExon2%n");
    for (String inputFilename : inputFilenames.split("[,]")) {

        System.out.println("Processing " + inputFilename);
        exonExpressionData = loadData(inputFilename, log2AverageId, averageCountId, thresholdValue);
        System.out.println("Size: " + exonExpressionData.size());
        System.out.println("Writing data..");
        for (Pair pair : pairs) {
            //calculate log2 RPKM exonId1 - exonId2:
            if (exonExpressionData.containsKey(pair.exonId1) && exonExpressionData.containsKey(pair.exonId2)) {
                double log2FoldChangeExons = exonExpressionData.get(pair.exonId1)
                        - exonExpressionData.get(pair.exonId2);
                output.printf("%s\t%s\t%s\t%g%n", FilenameUtils.getBaseName(inputFilename), pair.exonId1,
                        pair.exonId2, log2FoldChangeExons);
            }//from w  w  w  . j  a  va  2  s .  co  m

        }
    }

}