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

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

Introduction

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

Prototype

public static String getPath(String filename) 

Source Link

Document

Gets the path from a full filename, which excludes the prefix.

Usage

From source file:com.quinsoft.zeidon.utils.JoeUtils.java

/**
 * Returns an input stream for a resource/filename.  Logic will first attempt to find
 * a filename that matches the resourceName (search is case-insensitive).  If a file
 * is found, the stream is for the file.
 *
 * If a file is not found, an attempt is made to find the resource on the classpath.
 *
 * @param task - If not null then the ZEIDON_HOME directory will be searched if all
 *                other attempts fail./*from  ww w  .  j a v a 2  s.c  om*/
 * @param resourceName - Name of resource to open.
 * @param classLoader - ClassLoader used to find resources.  If null then the system
 *                class loader is used.
 *
 * @return the InputStream or null if it wasn't found.
 */
public static ZeidonInputStream getInputStream(Task task, String resourceName, ClassLoader classLoader) {
    // If the resourceName contains a '|' then it is a list of resources.  We'll return the first
    // one that is valid.
    String[] resourceList = PIPE_DELIMITER.split(resourceName);
    if (resourceList.length > 1) {
        for (String resource : resourceList) {
            ZeidonInputStream stream = getInputStream(task, resource.trim(), classLoader);
            if (stream != null)
                return stream;
        }

        // If we get here then none of the resources in the list were found so return null.
        return null;
    }

    try {
        //
        // Default is to assume resourceName is a filename.
        //
        File file = getFile(resourceName);
        if (file.exists())
            return ZeidonInputStream.create(file);

        if (classLoader == null) {
            if (task != null)
                classLoader = task.getClass().getClassLoader();
            if (classLoader == null)
                classLoader = new JoeUtils().getClass().getClassLoader();
            if (classLoader == null)
                classLoader = resourceName.getClass().getClassLoader();
            if (classLoader == null)
                classLoader = ClassLoader.getSystemClassLoader();
        }

        //
        // Try loading as a resource (e.g. from a .jar).
        //
        int count = 0;
        ZeidonInputStream stream = null;
        URL prevUrl = null;
        String md5hash = null;
        for (Enumeration<URL> url = classLoader.getResources(resourceName); url.hasMoreElements();) {
            URL element = url.nextElement();
            if (task != null)
                task.log().debug("Found resource at " + element);
            else
                LOG.debug("--Found resource at " + element);

            count++;
            if (count > 1) {
                // We'll allow duplicate resources if they have the same MD5 hash.
                if (md5hash == null)
                    md5hash = computeHash(prevUrl);

                if (!md5hash.equals(computeHash(element)))
                    throw new ZeidonException("Found multiple different resources that match resourceName %s",
                            resourceName);

                if (task != null)
                    task.log().warn(
                            "Multiple, identical resources found of %s.  This usually means your classpath has duplicates",
                            resourceName);
                else
                    LOG.warn("Multiple, identical resources found of " + resourceName
                            + " This usually means your classpath has duplicates");

            }

            stream = ZeidonInputStream.create(element);
            prevUrl = element;
        }

        if (stream != null)
            return stream;

        //
        // Try loading as a lower-case resource name.
        //
        String name = FilenameUtils.getName(resourceName);
        if (StringUtils.isBlank(name))
            return null;

        String path = FilenameUtils.getPath(resourceName);
        String newName;
        if (StringUtils.isBlank(path))
            newName = name.toLowerCase();
        else
            newName = path + name.toLowerCase();

        stream = ZeidonInputStream.create(classLoader, newName);
        if (stream != null)
            return stream;

        // If task is null then we don't know anything else to try.
        if (task == null)
            return null;

        //
        // Try loading with ZEIDON_HOME prefix.
        //
        newName = task.getObjectEngine().getHomeDirectory() + "/" + resourceName;
        file = getFile(newName);
        if (file.exists())
            return ZeidonInputStream.create(file);

        return null;
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependFilename(resourceName);
    }
}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Export all collections in the repository.
 * /*from www.ja v  a 2 s  .c  om*/
 * @param repository - repository to export
 * @throws IOException 
 */
public void export(Repository repository, File zipFileDestination) throws IOException {
    // create the path if it doesn't exist
    String path = FilenameUtils.getPath(zipFileDestination.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(zipFileDestination.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, repository.getInstitutionalCollections(),
            true);

    FileOutputStream out = new FileOutputStream(zipFileDestination);
    ArchiveOutputStream os = null;
    try {
        os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("collection.xml"));

        FileInputStream fis = null;
        try {
            log.debug("adding xml file");
            fis = new FileInputStream(collectionXmlFile);
            IOUtils.copy(fis, os);
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        }

        log.debug("adding pictures size " + allPictures.size());
        for (FileInfo fileInfo : allPictures) {
            File f = new File(fileInfo.getFullPath());
            String name = FilenameUtils.getName(fileInfo.getFullPath());
            name = name + '.' + fileInfo.getExtension();
            log.debug(" adding name " + name);
            os.putArchiveEntry(new ZipArchiveEntry(name));
            try {
                log.debug("adding input stream");
                fis = new FileInputStream(f);
                IOUtils.copy(fis, os);
            } finally {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
            }
        }

        os.closeArchiveEntry();
        out.flush();
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (os != null) {
            os.close();
            os = null;
        }
    }

    FileUtils.deleteQuietly(collectionXmlFile);

}

From source file:eu.annocultor.reports.ReportPresenter.java

public void makeHtmlReport() throws Exception {
    File jsReportDataFile = new File(getReportDir(), "ReportData.js");
    jsReportDataFile.delete();// w w w. ja  v  a 2 s  .c om
    PrintWriter jsonReportWriter = new PrintWriter(
            new OutputStreamWriter(new FileOutputStream(jsReportDataFile), "UTF-8"));

    // Header
    jsonReportWriter.println("YAHOO.namespace (\"AnnoCultor\");");
    jsonReportWriter.println("YAHOO.AnnoCultor.Data = ");
    JSONWriter json = new JSONWriter(jsonReportWriter).object();

    // environment
    json = json.key("environment").array();
    for (KeyValuePair kvp : environment) {
        json = json.object().key("id").value(kvp.getKey()).key("value").value(kvp.getValue()).endObject();
    }
    json = json.endArray();

    // graphs
    json = json.key("graphs").array();
    for (Graphs graph : graphs) {
        json = json.object().key("id").value(graph.getId()).key("subjects").value(graph.getSubjects())
                .key("properties").value("0").key("triples").value(graph.getTriples()).key("diff").value("")
                //task.getEnvironment().getPreviousDir() == null ? "" : ("file://" + new File(task
                //.getEnvironment()
                //.getDiffDir(), graph.getId() + ".html").getCanonicalPath()))
                .endObject();
    }
    json = json.endArray();

    // rules
    json = json.key("rules").array();
    for (ObjectCountPair<RuleInvocation> ocp : invokedRules.asSorted()) {
        json = json.object().key("id").value(ocp.getObject().getId()).key("rule")
                .value(ocp.getObject().getRule()).key("tag").value(ocp.getObject().getPath()).key("firings")
                .value(ocp.getCount()).endObject();
    }
    json = json.endArray();

    // unusedtags
    json = json.key("unusedtags").array();
    for (ObjectCountPair<Id> ocp : forgottenPaths.asSorted()) {
        json = json.object().key("id").value(ocp.getObject().getId()).key("occurrences").value(ocp.getCount())
                .endObject();
    }
    json = json.endArray();

    // lookup counters
    for (VocabularyMatchResult result : VocabularyMatchResult.values()) {

        int count = 0;
        List<ObjectCountPair<Lookup>> asSorted = lookupCounters.asSorted();
        messages.add("Total " + result + ": " + asSorted.size());

        json = json.key(result.getName()).array();
        for (ObjectCountPair<Lookup> counter : asSorted) {

            Lookup object = counter.getObject();

            if (object.getResult().equals(result.getName())) {
                boolean showCode = !result.getName().equals(VocabularyMatchResult.missed.getName());
                json = json.object().key("term").value(""
                        //                        + object.getRule()
                        //                        + ":"
                        + object.getPath()
                        //                        + ":"
                        //                        + object.getResult()
                        + ":" + "<b>" + object.getLabel() + (showCode ? ("(" + object.getCode() + ")") : "")
                        + "</b>").key("count").value(counter.getCount()).endObject();
                count++;

                if (count > 500) {
                    break;
                }
            }
        }
        json = json.endArray();
    }

    // messages
    json = json.key("console").array();
    for (String line : messages) {
        json = json.object().key("line").value(line).endObject();
    }
    json = json.endArray();

    json.endObject();
    jsonReportWriter.println(";");
    jsonReportWriter.flush();
    jsonReportWriter.close();

    // ------------

    String[] reportFiles = new String[] { "/yui/datatable/assets/skins/sam/datatable.css",
            "/yui/datatable/datatable-debug.js", "/yui/logger/assets/skins/sam/logger.css",
            "/yui/tabview/assets/skins/sam/tabview.css", "/yui/logger/logger-debug.js",
            "/yui/yahoo-dom-event/yahoo-dom-event.js", "/yui/datasource/datasource-debug.js",
            "/yui/element/element-debug.js", "/yui/yuiloader/yuiloader-min.js", "/yui/tabview/tabview-min.js",
            "/ReportCode.js", "/Report.css" };

    // copy report files
    for (String fn : reportFiles) {
        new File(getReportDir(), FilenameUtils.getPath(fn)).mkdirs();
        File f = new File(getReportDir(), fn);
        Utils.copy(getClass().getResourceAsStream(fn), f);
    }

    // copy report template
    Utils.copy(getClass().getResourceAsStream("/ReportTemplate.html"), new File(getReportDir(), "index.html"));
    Utils.copy(getClass().getResourceAsStream("/ReportCode.js"), new File(getReportDir(), "ReportCode.js"));
    Utils.copy(getClass().getResourceAsStream("/Report.css"), new File(getReportDir(), "Report.css"));
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.http.archive.ArchiveBean.java

/**
 * /*from   w w  w  . j  a va 2 s. c  o  m*/
 */
@SuppressWarnings("resource")
private boolean doPack(final File targetArchiveFile, List<FileData> fileDatas,
        final ArchiveRetriverCallback<FileData> callback) {
    // ?
    if (true == targetArchiveFile.exists() && false == NioUtils.delete(targetArchiveFile, 3)) {
        throw new ArchiveException(
                String.format("[%s] exist and delete failed", targetArchiveFile.getAbsolutePath()));
    }

    boolean exist = false;
    ZipOutputStream zipOut = null;
    Set<String> entryNames = new HashSet<String>();
    BlockingQueue<Future<ArchiveEntry>> queue = new LinkedBlockingQueue<Future<ArchiveEntry>>(); // ?
    ExecutorCompletionService completionService = new ExecutorCompletionService(executor, queue);

    final File targetDir = new File(targetArchiveFile.getParentFile(),
            FilenameUtils.getBaseName(targetArchiveFile.getPath()));
    try {
        // 
        FileUtils.forceMkdir(targetDir);

        zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetArchiveFile)));
        zipOut.setLevel(Deflater.BEST_SPEED);
        // ??
        for (final FileData fileData : fileDatas) {
            if (fileData.getEventType().isDelete()) {
                continue; // delete??
            }

            String namespace = fileData.getNameSpace();
            String path = fileData.getPath();
            boolean isLocal = StringUtils.isBlank(namespace);
            String entryName = null;
            if (true == isLocal) {
                entryName = FilenameUtils.getPath(path) + FilenameUtils.getName(path);
            } else {
                entryName = namespace + File.separator + path;
            }

            // ????
            if (entryNames.contains(entryName) == false) {
                entryNames.add(entryName);
            } else {
                continue;
            }

            final String name = entryName;
            if (true == isLocal && !useLocalFileMutliThread) {
                // ??
                queue.add(new DummyFuture(new ArchiveEntry(name, callback.retrive(fileData))));
            } else {
                completionService.submit(new Callable<ArchiveEntry>() {

                    public ArchiveEntry call() throws Exception {
                        // ??
                        InputStream input = null;
                        OutputStream output = null;
                        try {
                            input = callback.retrive(fileData);

                            if (input instanceof LazyFileInputStream) {
                                input = ((LazyFileInputStream) input).getInputSteam();// ?stream
                            }

                            if (input != null) {
                                File tmp = new File(targetDir, name);
                                NioUtils.create(tmp.getParentFile(), false, 3);// ?
                                output = new FileOutputStream(tmp);
                                NioUtils.copy(input, output);// ?
                                return new ArchiveEntry(name, new File(targetDir, name));
                            } else {
                                return new ArchiveEntry(name);
                            }
                        } finally {
                            IOUtils.closeQuietly(input);
                            IOUtils.closeQuietly(output);
                        }
                    }
                });
            }
        }

        for (int i = 0; i < entryNames.size(); i++) {
            // ?
            ArchiveEntry input = null;
            InputStream stream = null;
            try {
                input = queue.take().get();
                if (input == null) {
                    continue;
                }

                stream = input.getStream();
                if (stream == null) {
                    continue;
                }

                if (stream instanceof LazyFileInputStream) {
                    stream = ((LazyFileInputStream) stream).getInputSteam();// ?stream
                }

                exist = true;
                zipOut.putNextEntry(new ZipEntry(input.getName()));
                NioUtils.copy(stream, zipOut);// ?
                zipOut.closeEntry();
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }

        if (exist) {
            zipOut.finish();
        }
    } catch (Exception e) {
        throw new ArchiveException(e);
    } finally {
        IOUtils.closeQuietly(zipOut);
        try {
            FileUtils.deleteDirectory(targetDir);// 
        } catch (IOException e) {
            // ignore
        }
    }

    return exist;
}

From source file:com.qualogy.qafe.business.resource.rdb.RDBDatasource.java

private URI fileLocationToURI(final ApplicationContext context, final FileLocation stmtFileName) {

    URI uri = null;/*from  w  w  w  . j  a  v a 2s  .  c  o  m*/

    final String stmtFileLocation = stmtFileName.getLocation();

    if ((stmtFileLocation.startsWith(FileLocation.SCHEME_HTTP + FileLocation.COMMON_SCHEME_DELIM))
            || (stmtFileLocation.startsWith(FileLocation.SCHEME_FILE))) {
        uri = stmtFileName.toURI();
    } else {
        LOG.info(" Statement [" + stmtFileName
                + "] file could not be found. Now iterating the filelocations in the applicationmapping");

        final List<FileLocation> list = context.getMappingFileLocations();
        if (list != null) {
            for (FileLocation fileLocation : list) {
                LOG.info("Trying Statement [" + fileLocation.getLocation() + File.separator + stmtFileName
                        + "] file could not be found. Now iterating the filelocations in the applicationmapping");

                final String baseLocation;
                if (FilenameUtils.indexOfExtension(fileLocation.getLocation()) == -1) {
                    baseLocation = fileLocation.getLocation();
                } else {
                    baseLocation = FilenameUtils.getPath(fileLocation.getLocation());
                }

                final FileLocation fileLoc = new FileLocation(context.getRoot(),
                        baseLocation + File.separator + stmtFileName.getLocation());
                uri = fileLoc.toURI();
                if (uri != null) {
                    break;
                }
            }
        } else {
            uri = stmtFileName.toURI();
        }
    }
    return uri;
}

From source file:com.iyonger.apm.web.handler.ScriptHandler.java

/**
 * Get the appropriated distribution path for the given file entry.
 *
 * @param basePath  distribution base path
 * @param fileEntry fileEntry to be distributed
 * @return the resolved destination path.
 *//*from   www.  java  2s .  c om*/
protected String calcDistSubPath(String basePath, FileEntry fileEntry) {
    String path = FilenameUtils.getPath(fileEntry.getPath());
    path = path.substring(basePath.length());
    return path;
}

From source file:com.iyonger.apm.web.handler.ScriptHandler.java

/**
 * Get all resources and lib entries belonging to the given user and
 * scriptEntry.//from  w  w  w. ja va 2s.c  o m
 *
 * @param user        user
 * @param scriptEntry script entry
 * @param revision    revision of the script entry.
 * @return file entry list
 */
public List<FileEntry> getLibAndResourceEntries(User user, FileEntry scriptEntry, long revision) {
    String path = FilenameUtils.getPath(scriptEntry.getPath());
    List<FileEntry> fileList = newArrayList();
    for (FileEntry eachFileEntry : getFileEntryRepository().findAll(user, path + "lib/", revision, true)) {
        // Skip jython 2.5... it's already included.
        if (startsWithIgnoreCase(eachFileEntry.getFileName(), "jython-2.5.")
                || startsWithIgnoreCase(eachFileEntry.getFileName(), "jython-standalone-2.5.")) {
            continue;
        }
        FileType fileType = eachFileEntry.getFileType();
        if (fileType.isLibDistributable()) {
            fileList.add(eachFileEntry);
        }
    }
    for (FileEntry eachFileEntry : getFileEntryRepository().findAll(user, path + "resources/", revision,
            true)) {
        FileType fileType = eachFileEntry.getFileType();
        if (fileType.isResourceDistributable()) {
            fileList.add(eachFileEntry);
        }
    }
    return fileList;
}

From source file:com.alibaba.otter.node.etl.load.loader.db.FileLoadAction.java

private void dryRun(FileLoadContext context, List<FileData> fileDatas, File rootDir) {
    for (FileData fileData : fileDatas) {
        boolean isLocal = StringUtils.isBlank(fileData.getNameSpace());
        String entryName = null;/*from  w w w . j a v  a  2  s .  c o  m*/
        if (true == isLocal) {
            entryName = FilenameUtils.getPath(fileData.getPath()) + FilenameUtils.getName(fileData.getPath());
        } else {
            entryName = fileData.getNameSpace() + File.separator + fileData.getPath();
        }
        File sourceFile = new File(rootDir, entryName);
        if (true == sourceFile.exists() && false == sourceFile.isDirectory()) {
            if (false == isLocal) {
                throw new LoadException(fileData + " is not support!");
            } else {
                // meta?
                fileData.setSize(sourceFile.length());
                fileData.setLastModifiedTime(sourceFile.lastModified());
                context.getProcessedDatas().add(fileData);
            }

            LoadCounter counter = loadStatsTracker.getStat(context.getIdentity()).getStat(fileData.getPairId());
            counter.getFileCount().incrementAndGet();
            counter.getFileSize().addAndGet(fileData.getSize());
        } else if (fileData.getEventType().isDelete()) {
            // 
            if (false == isLocal) {
                throw new LoadException(fileData + " is not support!");
            } else {
                context.getProcessedDatas().add(fileData);
            }
        } else {
            context.getFailedDatas().add(fileData);// 
        }
    }
}

From source file:com.frostwire.android.gui.Librarian.java

public EphemeralPlaylist createEphemeralPlaylist(final Context context, FileDescriptor fd) {
    List<FileDescriptor> fds = getFiles(context, Constants.FILE_TYPE_AUDIO, FilenameUtils.getPath(fd.filePath),
            false);/*from   www  . j a  va2s .com*/

    if (fds.size() == 0) { // just in case
        Log.w(TAG, "Logic error creating ephemeral playlist");
        fds.add(fd);
    }

    EphemeralPlaylist playlist = new EphemeralPlaylist(fds);
    playlist.setNextItem(new PlaylistItem(fd));

    return playlist;
}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Generate an xml file with the specified collections.
 * /*from ww  w  .j a  va2 s. com*/
 * @see edu.ur.dspace.export.CollectionExporter#generateCollectionXMLFile(java.io.File, java.util.Collection)
 */
public Set<FileInfo> createXmlFile(File f, Collection<InstitutionalCollection> collections,
        boolean includeChildren) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    Set<FileInfo> allPictures = new HashSet<FileInfo>();
    String path = FilenameUtils.getPath(f.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(f.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    if (!f.exists()) {
        if (!f.createNewFile()) {
            throw new IllegalStateException("could not create file");
        }
    }

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "institutionalCollections", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
        fos = new FileOutputStream(f);

        try {
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
        writer = new BufferedWriter(outputStreamWriter);
        lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (InstitutionalCollection c : collections) {
        Element collection = doc.createElement("collection");

        this.addIdElement(collection, c.getId().toString(), doc);
        this.addNameElement(collection, c.getName(), doc);
        this.addDescription(collection, c.getDescription(), doc);
        this.addCopyright(collection, c.getCopyright(), doc);

        if (c.getPrimaryPicture() != null) {
            this.addPrimaryImage(collection, c.getPrimaryPicture().getFileInfo().getNameWithExtension(), doc);
            allPictures.add(c.getPrimaryPicture().getFileInfo());
        }
        Set<IrFile> pictures = c.getPictures();

        if (pictures.size() > 0) {
            Element pics = doc.createElement("pictures");
            for (IrFile irFile : pictures) {
                Element picture = doc.createElement("picture");
                this.addImage(picture, irFile.getFileInfo().getNameWithExtension(), doc);
                pics.appendChild(picture);
                allPictures.add(irFile.getFileInfo());
            }
            collection.appendChild(pics);
        }

        if (c.getLinks().size() > 0) {
            Element links = doc.createElement("links");
            for (InstitutionalCollectionLink l : c.getLinks()) {
                this.addLink(links, l, doc);
            }
            collection.appendChild(links);
        }

        if (includeChildren) {
            for (InstitutionalCollection child : c.getChildren()) {
                addChild(child, collection, doc, allPictures);
            }
        }
        root.appendChild(collection);
    }
    serializer.write(root, lsOut);

    try {
        fos.close();
        writer.close();
        outputStreamWriter.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return allPictures;
}