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:de.thischwa.pmcms.model.tool.Upload.java

public Upload(final Site site, final IConnection transfer, String checkumsFileBasename) {
    siteExportDir = PoPathInfo.getSiteExportDirectory(site);
    this.transfer = transfer;
    serverHashes = new HashMap<String, String>();
    serverDirs = new ArrayList<String>();
    localDirs = new HashSet<String>();

    // collect the exported files
    localHashesFile = new File(siteExportDir, FilenameUtils.getBaseName(checkumsFileBasename) + ".zip");
    localHashes = ChecksumTool.getFromZip(localHashesFile, checkumsFileBasename);
    for (String path : localHashes.keySet()) {
        // collect the local dirs
        if (path.contains(UploadTree.PATH_SEPARATOR + "")) {
            String parent = path.substring(0, path.lastIndexOf(UploadTree.PATH_SEPARATOR));
            localDirs.add(parent);/*www.  j  av  a 2 s . co m*/
        }
    }

    // download and read the server hashes
    try {
        File serverHashFile = File.createTempFile("checksums", ".zip", Constants.TEMP_DIR);
        if (transfer.download(FilenameUtils.getName(localHashesFile.getName()),
                new BufferedOutputStream(new FileOutputStream(serverHashFile)))) {
            serverHashes = ChecksumTool.getFromZip(serverHashFile, checkumsFileBasename);
        }
    } catch (Exception e) {
        logger.warn("Error while getting the server hashes: " + e.getMessage(), e);
    }
    // collect the server dirs
    for (String path : serverHashes.keySet()) {
        if (path.contains(UploadTree.PATH_SEPARATOR + "")) {
            String parent = path.substring(0, path.lastIndexOf(UploadTree.PATH_SEPARATOR));
            if (!serverDirs.contains(parent))
                serverDirs.add(parent);
        }
    }
}

From source file:net.sf.zekr.engine.bookmark.BookmarkSet.java

/**
 * This constructor will not load all the bookmark set file. A call to <code>load()</code> is needed first.
 * Hence, this class is in fact lazy-load.
 * //  w  w  w. jav a  2s .c om
 * @param filePath
 */
public BookmarkSet(String filePath) {
    file = new File(filePath);
    id = FilenameUtils.getBaseName(filePath);
}

From source file:com.googlecode.dex2jar.tools.Jasmin2Jar.java

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();/*from w  w w . j av  a 2s .c o  m*/
        return;
    }

    File dir = new File(remainingArgs[0]);
    if (!dir.exists()) {
        System.err.println(dir + " is not exists");
        usage();
        return;
    }

    if (output == null) {
        if (dir.isDirectory()) {
            output = new File(dir.getName() + "-jasmin2jar.jar");
        } else {
            output = new File(FilenameUtils.getBaseName(dir.getName()) + "-jasmin2jar.jar");
        }
    }

    if (output.exists() && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }

    System.out.println("assemble " + dir + " -> " + output);

    final OutHandler fo = FileOut.create(output, true);
    try {
        new FileWalker().withStreamHandler(new StreamHandler() {
            @Override
            public void handle(boolean isDir, String name, StreamOpener current, Object nameObject)
                    throws IOException {
                if (isDir || !name.endsWith(".j")) {
                    return;
                }
                try {
                    ClassFile classFile = new ClassFile();
                    Reader reader = new InputStreamReader(current.get(), encoding);
                    classFile.readJasmin(reader, name, autogenLines);

                    int errorcount = classFile.errorCount();
                    if (errorcount > 0) {
                        System.err.println(name + ": Found " + errorcount + " errors");
                        return;
                    }
                    String clzName = classFile.getClassName();
                    OutputStream os = fo.openOutput(clzName.replace('.', '/') + ".class", nameObject);
                    try {
                        classFile.write(os);
                    } finally {
                        IOUtils.closeQuietly(os);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace(System.err);
                }
            }
        }).walk(dir);
    } finally {
        IOUtils.closeQuietly(fo);
    }
}

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

@Override
public List<Event> convertFile(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 = ci.getSource_file().toRegularFile().getAbsolutePath();

    for (String audience : audiences) {

        String audience_lc = audience.toLowerCase();

        DAFile target = new DAFile(object.getLatestPackage(), pips + "/" + audience_lc,
                Utilities.slashize(ci.getTarget_folder()) + FilenameUtils.getBaseName(input) + "."
                        + ci.getConversion_routine().getTarget_suffix());
        target.toRegularFile().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  . ja  v a2 s  .c om
            logger.debug("reduce to certain pages: " + certainPagesText);

        }

        // copy whole file if no restrictions are found
        if (numberOfPagesText == null && certainPagesText == null) {
            try {
                FileUtils.copyFileToDirectory(new File(input), target.toRegularFile().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;
        }
        PdfService pdf = new PdfService(new File(input), target.toRegularFile());
        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:biz.dfch.j.graylog.plugin.filter.metricsValidation.java

public metricsValidation() throws IOException, URISyntaxException {
    try {//from   w w w .ja  v  a 2 s .  c  om
        LOG.debug(String.format("[%d] Initialising plugin ...\r\n", Thread.currentThread().getId()));

        // get config file
        CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource();
        URI uri = codeSource.getLocation().toURI();

        // String path = uri.getSchemeSpecificPart();
        // path would contain absolute path including jar file name with extension
        // String path = FilenameUtils.getPath(uri.getPath());
        // path would contain relative path (no leading '/' and no jar file name

        String path = FilenameUtils.getPath(uri.getPath());
        if (!path.startsWith("/")) {
            path = String.format("/%s", path);
        }
        String baseName = FilenameUtils.getBaseName(uri.getSchemeSpecificPart());
        if (null == baseName || baseName.isEmpty()) {
            baseName = this.getClass().getPackage().getName();
        }

        // get config values
        configurationFileName = FilenameUtils.concat(path, baseName + ".conf");
        JSONParser jsonParser = new JSONParser();
        LOG.info(String.format("Loading configuration file '%s' ...", configurationFileName));
        Object object = jsonParser.parse(new FileReader(configurationFileName));

        JSONObject jsonObject = (JSONObject) object;
        String pluginPriority = (String) jsonObject.get(DF_PLUGIN_PRIORITY);
        Boolean pluginDropMessage = (Boolean) jsonObject.get(DF_PLUGIN_DROP_MESSAGE);
        Boolean pluginDisabled = (Boolean) jsonObject.get(DF_PLUGIN_DISABLED);
        //            metrics = (HashMap) jsonObject.get("metrics");
        //            String fieldName = "cpu.average";
        //            Set<String> keys = metrics.keySet();
        //            for(String key : keys)
        //            {
        //                Map metric = (Map) metrics.get(key);
        //                LOG.info(String.format("%s [type %s] [range %s .. %s]", key, metric.get("type").toString(), metric.get("minValue").toString(), metric.get("maxValue").toString()));
        //            }
        // set configuration
        Map<String, Object> map = new HashMap<>();
        map.put(DF_PLUGIN_PRIORITY, pluginPriority);
        map.put(DF_PLUGIN_DROP_MESSAGE, pluginDropMessage);
        map.put(DF_PLUGIN_DISABLED, pluginDisabled);
        //map.put(DF_PLUGIN_METRICS, metrics);

        initialize(new Configuration(map));
    } catch (IOException ex) {
        LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n%s\r\n",
                Thread.currentThread().getId(), ex.getMessage()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - IOException - Filter will be disabled.");
        ex.printStackTrace();
    } catch (Exception ex) {
        LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n",
                Thread.currentThread().getId()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - Exception - Filter will be disabled.");
        ex.printStackTrace();
    }
}

From source file:avantssar.aslanpp.testing.DiskTestTask.java

@Override
public Verdict getExpectedVerdict() {
    if (FilenameUtils.getBaseName(aslanPP.getAbsolutePath()).endsWith("_Safe")) {
        return Verdict.NoAttack;
    } else {// w w  w .  j a v a2s .c o m
        return Verdict.Attack;
    }
}

From source file:me.jdknight.ums.ccml.tmp.RealFileWithVirtualFolderThumbnails.java

/**
 * Return the input stream to use for this file's thumbnail.
 * //from   w w  w .  ja  va 2  s.  co  m
 * @return The input stream.
 * 
 * @throws IOException Thrown when the creation of an input stream has failed. 
 */
@Override
public InputStream getThumbnailInputStream() throws IOException {
    // Virtual folder support.
    if ((getParent() instanceof VirtualFolder) == false) {
        return super.getThumbnailInputStream();
    }

    File file = getFile();
    File foundThumbnail = null;

    // Attempt to find the thumbnail for this resource:
    //  -Check for local thumbnail.
    //  -Check for thumbnail in alternate directory.
    boolean shouldCheckForAlternatives = true;
    String resourcePath = file.getParent() + File.separator;
    do {
        String resourceBaseName = FilenameUtils.getBaseName(file.getName());

        foundThumbnail = new File(resourcePath + resourceBaseName + ".png"); //$NON-NLS-1$
        if (foundThumbnail.isFile() == false)
            foundThumbnail = new File(resourcePath + resourceBaseName + ".jpg"); //$NON-NLS-1$
        if (foundThumbnail.isFile() == false)
            foundThumbnail = new File(resourcePath + file.getName() + ".cover.png"); //$NON-NLS-1$
        if (foundThumbnail.isFile() == false)
            foundThumbnail = new File(resourcePath + file.getName() + ".cover.jpg"); //$NON-NLS-1$

        if (shouldCheckForAlternatives == true && foundThumbnail.isFile() == false) {
            String alternativeThumbnailFolder = PMS.getConfiguration().getAlternateThumbFolder();
            if (new File(alternativeThumbnailFolder).isDirectory() == false) {
                resourcePath = alternativeThumbnailFolder + File.separator;
                shouldCheckForAlternatives = false;
            }
        }

        if (shouldCheckForAlternatives == false) {
            break;
        }
        shouldCheckForAlternatives = false;
    } while (true);

    // No thumbnail found? Try to grab the local folder's thumbnail.
    if (foundThumbnail == null || foundThumbnail.isFile() == false) {
        foundThumbnail = new File(file.getParent() + File.separator + "folder.png"); //$NON-NLS-1$

        if (foundThumbnail.isFile() == false) {
            foundThumbnail = new File(file.getParent() + File.separator + "folder.jpg"); //$NON-NLS-1$
        }
    }

    // Still no thumbnail found? Just resort to default in original method.
    if (foundThumbnail == null || foundThumbnail.isFile() == false) {
        return super.getThumbnailInputStream();
    } else {
        return new FileInputStream(foundThumbnail);
    }
}

From source file:com.igormaznitsa.nbmindmap.utils.FakeFileObject.java

@Override
public String getName() {
    return FilenameUtils.getBaseName(this.wrappedFile.getName());
}

From source file:egovframework.rte.bat.core.listener.EgovOutputFileListener.java

/**
 * stepExecutionContext? inputKeyName ? ? outputKeyName? put 
 * //from   ww w  .  ja  v  a  2 s  .  c o m
 * @param stepExecution
 */
@BeforeStep
public void createOutputNameFromInput(StepExecution stepExecution) {
    ExecutionContext executionContext = stepExecution.getExecutionContext();
    String inputName = stepExecution.getStepName().replace(":", "-");
    if (executionContext.containsKey(inputKeyName)) {
        inputName = executionContext.getString(inputKeyName);
    }
    if (!executionContext.containsKey(outputKeyName)) {
        executionContext.putString(outputKeyName, path + FilenameUtils.getBaseName(inputName) + ".csv");
    }
}

From source file:com.frostwire.search.youtube2.YouTubeCrawledSearchResult.java

private String readFilename(FilePackage filePackage) {
    DownloadLink dl = filePackage.getChildren().get(0);
    if (dl.getStringProperty("convertto", "").equals("AUDIOMP3")) {
        return FilenameUtils.getBaseName(dl.getName()) + ".mp3";
    }/*from   w w  w  . j av a  2 s.  co m*/

    return dl.getName();
}