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

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

Introduction

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

Prototype

public static String getFullPath(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path.

Usage

From source file:org.apache.flex.compiler.internal.parsing.as.IncludeHandler.java

/**
 * Given an the canonical path of a file that contains an include directive
 * with the specified string, return an {@link IFileSpecification} for the
 * file the include directive references.
 * <p>/*from w  w w  .  j  av a  2 s.  c o  m*/
 * <ol>
 * <li>If {@code includeString} is an absolute path, a
 * {@code IFileSpecification} for that location will be returned.</li>
 * <li>Otherwise, if this object has a reference to {@code IASProject},
 * the included file path will be resolved firstly in the current directory
 * of the including file, then in each of the source folders on the project
 * until the first existing file is found.</li>
 * <li>If no on-disk file is found for the included file, a
 * {@code IFileSpecification} pointing to the intended default location will
 * be returned.</li>
 * </ol>
 * 
 * @param includer The canonical path of a file that contains the include
 * directive.
 * @param includeString Unquoted string that refers to a file to be
 * included.
 * @return An {@link IFileSpecification} for the included file, or null if
 * can't resolve.
 */
protected IFileSpecification getFileSpecificationForInclude(String includer, String includeString) {
    if (Strings.isNullOrEmpty(includer) || Strings.isNullOrEmpty(includeString))
        return null;

    if (new File(includeString).isAbsolute()) {
        // If included file path is already absolute, do not try to resolve
        // in any other folder contexts.
        return getFileSpec(FilenameNormalization.normalize(includeString));
    } else {
        final String includingFolder = FilenameNormalization.normalize(FilenameUtils.getFullPath(includer));
        final File includedFileInDefaultFolder = new File(includingFolder, includeString);
        if (includedFileInDefaultFolder.isFile()) {
            // Always resolve to the including file's containing source folder first.
            return getFileSpec(FilenameNormalization.normalizeFileToPath(includedFileInDefaultFolder));
        } else if (project != null) {
            // Try other source folders if "project" was given.
            final String sourceFileFromSourcePath = project.getSourceFileFromSourcePath(includeString);
            if (sourceFileFromSourcePath != null && new File(sourceFileFromSourcePath).isFile())
                return getFileSpec(sourceFileFromSourcePath);
        }

        /**
         * Can't resolve included file name in all source folders. Return
         * the IFileSpecification intended to resolve in the including
         * file's parent folder. This helps generate reasonable error
         * message in the IDE.
         */
        return getFileSpec(FilenameNormalization.normalizeFileToPath(includedFileInDefaultFolder));
    }
}

From source file:org.apache.flex.compiler.internal.targets.SWCTarget.java

/**
 * Loops over all externally visible definitions in all compilation units
 * for this target, looking for class definitions with [IconFile(...)] metadata.
 * <p>//  ww w  . j  ava2 s  . com
 * Suppose we find [IconFile("MyComponent.png")] on the class foo.bar.MyComponent.
 * Then the returned map will have an entry whose key is "foo/bar/MyComponent"
 * and whose value is a file specification that can be used to read the contents
 * of this file. A file with the same contents will get created at foo/bar/MyComponent
 * inside the SWC.
 */
private Map<String, FileEntryValue> computeIconFiles() {
    Map<String, FileEntryValue> iconFiles = new HashMap<String, FileEntryValue>();

    try {
        Collection<ICompilationUnit> compilationUnits = librarySWFTarget.getCompilationUnits();
        for (IDefinition definition : getAllExternallyVisibleDefinitions(compilationUnits)) {
            if (!(definition instanceof IClassDefinition))
                continue;

            IClassDefinition classDefinition = (IClassDefinition) definition;

            IMetaTag iconFileMetaTag = classDefinition
                    .getMetaTagByName(IMetaAttributeConstants.ATTRIBUTE_ICON_FILE);

            String iconFilePath = classDefinition.getIconFile();
            if (iconFilePath == null)
                continue;

            String packageName = classDefinition.getPackageName();
            String key = packageName.replaceAll("\\.", "/") + "/" + iconFilePath;

            ICompilationUnit cu = project.getScope().getCompilationUnitForDefinition(classDefinition);
            IBinaryFileSpecification fileSpec = null;
            if (cu.getCompilationUnitType() == UnitType.SWC_UNIT) {
                ISWC swc = project.getWorkspace().getSWCManager().get(new File(cu.getAbsoluteFilename()));
                ISWCFileEntry swcFileEntry = swc.getFile(key);
                fileSpec = new SWCFileSpecification(key, swcFileEntry);
            } else {
                String sourcePath = classDefinition.getSourcePath();
                iconFilePath = FilenameUtils.getFullPath(sourcePath) + iconFilePath;
                fileSpec = project.getWorkspace().getLatestBinaryFileSpecification(iconFilePath);
            }

            FileEntryValue value = new FileEntryValue(fileSpec, iconFileMetaTag);
            iconFiles.put(key, value);
        }
    } catch (InterruptedException e) {
    }

    return iconFiles;
}

From source file:org.apache.flex.compiler.internal.units.FXGCompilationUnit.java

@Override
protected IOutgoingDependenciesRequestResult handleOutgoingDependenciesRequest() throws InterruptedException {
    startProfile(Operation.GET_SEMANTIC_PROBLEMS);

    final Collection<ICompilerProblem> problems = new ArrayList<ICompilerProblem>();
    Map<ITag, ITag> extraTags = new HashMap<ITag, ITag>();
    FXGSymbolClass symbolClass = null;//from   ww w .  ja  v a2 s . co m
    FileNode fileNode = null;
    ASProjectScope projectScope = getProject().getScope();

    try {
        FXGSyntaxTreeRequestResult syntaxTreeResult = (FXGSyntaxTreeRequestResult) getSyntaxTreeRequest().get();
        IFXGNode tree = syntaxTreeResult.getRootNode();

        FlexFXG2SWFTranscoder transcoder = new FlexFXG2SWFTranscoder(getProject());
        transcoder.setResourceResolver(
                new FXGFileResolver(FilenameUtils.getFullPath(getRootFileSpecification().getPath())));

        symbolClass = transcoder.transcode(tree, Multiname.getPackageNameForQName(qname),
                Multiname.getBaseNameForQName(qname), extraTags, problems);

        //Add dependencies to the classes required by the FXG processed by this compilation unit
        for (ITypeDefinition definition : transcoder.getDependencies()) {
            getProject().addDependency(this, projectScope.getCompilationUnitForDefinition(definition),
                    DependencyType.EXPRESSION, definition.getQualifiedName());
        }

        StringBuilder sb = new StringBuilder(symbolClass.getGeneratedSource());
        if (symbolClass.getAdditionalSymbolClasses() != null) {
            for (FXGSymbolClass symbol : symbolClass.getAdditionalSymbolClasses()) {
                sb.append(symbol.getGeneratedSource());
            }
        }

        IFileSpecification virtualSymbolSource = new GeneratedSourceFileSpecfication(qname, sb.toString());
        fileNode = ASParser.parseFile(virtualSymbolSource, getProject().getWorkspace());
        fileNode.runPostProcess(EnumSet.of(PostProcessStep.POPULATE_SCOPE));

        projectScope.addScopeForCompilationUnit(this, fileNode.getFileScope());

        updateEmbedCompilationUnitDependencies(fileNode.getEmbedNodes(), problems);
    } catch (Exception e) {
        e.printStackTrace();
        problems.add(new InternalCompilerProblem2(getAbsoluteFilename(), e, SUB_SYSTEM));
    } finally {
        stopProfile(Operation.GET_SEMANTIC_PROBLEMS);
    }

    return new FXGOutgoingDependenciesResult(fileNode, symbolClass, extraTags, problems);
}

From source file:org.apache.maven.plugins.linkcheck.LinkcheckReportGenerator.java

private void generateDetailsSection(Locale locale, LinkcheckModel linkcheckModel, Sink sink) {
    sink.section1();//from ww  w.  jav a2 s.  c  o  m
    sink.sectionTitle1();
    sink.text(i18n.getString("linkcheck-report", locale, "report.linkcheck.detail"));
    sink.sectionTitle1_();

    sink.paragraph();
    sink.rawText(i18n.getString("linkcheck-report", locale, "report.linkcheck.detail.overview"));
    sink.paragraph_();

    sink.table();

    // Header
    generateTableHeader(locale, true, sink);

    // Content
    List linkcheckFiles = linkcheckModel.getFiles();
    for (Object linkcheckFile1 : linkcheckFiles) {
        LinkcheckFile linkcheckFile = (LinkcheckFile) linkcheckFile1;

        sink.tableRow();

        sink.tableCell();
        if (linkcheckFile.getUnsuccessful() == 0) {
            iconValid(locale, sink);
        } else {
            iconError(locale, sink);
        }
        sink.tableCell_();

        // tableCell( createLinkPatternedText( linkcheckFile.getRelativePath(), "./"
        // + linkcheckFile.getRelativePath() ) );
        sink.tableCell();
        sink.link(linkcheckFile.getRelativePath());
        sink.text(linkcheckFile.getRelativePath());
        sink.link_();
        sink.tableCell_();
        sink.tableCell();
        sink.text(String.valueOf(linkcheckFile.getNumberOfLinks()));
        sink.tableCell_();
        sink.tableCell();
        sink.text(String.valueOf(linkcheckFile.getNumberOfLinks(LinkcheckFileResult.VALID_LEVEL)));
        sink.tableCell_();
        sink.tableCell();
        sink.text(String.valueOf(linkcheckFile.getNumberOfLinks(LinkcheckFileResult.WARNING_LEVEL)));
        sink.tableCell_();
        sink.tableCell();
        sink.text(String.valueOf(linkcheckFile.getNumberOfLinks(LinkcheckFileResult.ERROR_LEVEL)));
        sink.tableCell_();

        sink.tableRow_();

        // Detail error
        if (linkcheckFile.getUnsuccessful() != 0) {
            sink.tableRow();

            sink.tableCell();
            sink.text("");
            sink.tableCell_();

            // TODO it is due to DOXIA-78
            sink.rawText("<td colspan=\"5\">");

            sink.table();

            for (Object o : linkcheckFile.getResults()) {
                LinkcheckFileResult linkcheckFileResult = (LinkcheckFileResult) o;

                if (linkcheckFileResult.getStatusLevel() == LinkcheckFileResult.VALID_LEVEL) {
                    continue;
                }

                sink.tableRow();

                sink.tableCell();
                if (linkcheckFileResult.getStatusLevel() == LinkcheckFileResult.WARNING_LEVEL) {
                    iconWarning(locale, sink);
                } else if (linkcheckFileResult.getStatusLevel() == LinkcheckFileResult.ERROR_LEVEL) {
                    iconError(locale, sink);
                }
                sink.tableCell_();

                sink.tableCell();
                sink.italic();
                if (linkcheckFileResult.getTarget().startsWith("#")) {
                    sink.link(linkcheckFile.getRelativePath() + linkcheckFileResult.getTarget());
                } else if (linkcheckFileResult.getTarget().startsWith(".")) {
                    // We need to calculate a correct absolute path here, because target is a relative path
                    String absolutePath = FilenameUtils.getFullPath(linkcheckFile.getRelativePath())
                            + linkcheckFileResult.getTarget();
                    String normalizedPath = FilenameUtils.normalize(absolutePath);
                    if (normalizedPath == null) {
                        normalizedPath = absolutePath;
                    }
                    sink.link(normalizedPath);
                } else {
                    sink.link(linkcheckFileResult.getTarget());
                }
                // Show the link as it was written to make it easy for
                // the author to find it in the source document
                sink.text(linkcheckFileResult.getTarget());
                sink.link_();
                sink.text(": ");
                sink.text(linkcheckFileResult.getErrorMessage());
                sink.italic_();
                sink.tableCell_();

                sink.tableRow_();
            }

            sink.table_();

            sink.tableCell_();

            sink.tableRow_();
        }
    }

    sink.table_();

    sink.section1_();
}

From source file:org.artifactory.mime.NamingUtils.java

/**
 * @param classFilePath Path to a java class file (ends with .class)
 * @return Path of the matching java source path (.java).
 *///from  w  ww. j  a v a2  s  .  co  m
public static String javaSourceNameFromClassName(String classFilePath) {
    String classFileName = FilenameUtils.getName(classFilePath);
    if (!"class".equals(FilenameUtils.getExtension(classFileName))) {
        return classFilePath;
    }

    String javaFileName;
    if (classFileName.indexOf('$') > 0) {
        // it's a subclass, take the first part (the main class name)
        javaFileName = classFileName.substring(0, classFileName.indexOf('$')) + ".java";
    } else {
        javaFileName = classFileName.replace(".class", ".java");
    }

    String javaFilePath = FilenameUtils.getFullPath(classFilePath) + javaFileName;
    return javaFilePath;
}

From source file:org.atomserver.core.filestore.FileBasedContentStorage.java

/**
 * removes all of the files, except the file passed in
 * No more trash bin, files get deleted//www  .jav a2s.c o  m
 * NOTE: this method does not throw an Exception. Instead, it simply logs errors and moves on.
 *
 * @param thisRev    the file pointint at the current revision
 * @param descriptor the entry that relates to the content
 */
private void cleanupExcessFiles(final File thisRev, final EntryDescriptor descriptor) {

    String fullPath = FilenameUtils.getFullPath(thisRev.getAbsolutePath());
    File baseDir = new File(fullPath);
    if (log.isTraceEnabled()) {
        log.trace("%> cleaning up excess files at " + baseDir + " based on " + thisRev);
    }

    try {

        // get a file pointer at the previous revision of the file -- we DON'T want to delete it
        final File oneRevBack = findExistingEntryFile(descriptor, 1);

        // the set of directories to clean is the directories that contain (A) the previous
        // revision, which may or may not be the same as the current rev, and (B) the one two
        // revisions back, which may or may not be the same as the previous rev
        Set<File> directoriesToClean = new HashSet<File>(2);

        // if there was a previous rev
        if (oneRevBack != null) {
            // add it's dir to the ones to clean
            directoriesToClean.add(oneRevBack.getParentFile());
            // and if the revision is greater than 1
            if (descriptor.getRevision() > 1) {
                // then two revs back is a reasonable thing to ask for...
                File twoRevsBack = findExistingEntryFile(descriptor, 2);
                // and if it exists, add its parent to the ones to clean
                if (twoRevsBack != null) {
                    directoriesToClean.add(twoRevsBack.getParentFile());
                }
            }
        }

        // list out all of the files in the directory that are (a) files, and (b) not one of
        // the last two revisions
        for (File directoryToClean : directoriesToClean) {
            final File[] toDelete = directoryToClean.listFiles(new FileFilter() {
                public boolean accept(File fileToCheck) {

                    return fileToCheck != null && fileToCheck.exists() && fileToCheck.isFile()
                            && fileToCheck.canRead() && fileToCheck.canWrite() && !fileToCheck.isHidden()
                            && !thisRev.equals(fileToCheck)
                            && (oneRevBack == null || !oneRevBack.equals(fileToCheck));

                }
            });

            // if there's anything to delete...
            if (toDelete != null && toDelete.length > 0) {

                for (File file : toDelete) {

                    //delete the file
                    if (log.isTraceEnabled()) {
                        log.trace("deleting file" + file.getName());
                    }

                    FileUtils.forceDelete(file);
                }
                cleanUpToCollection(descriptor, directoryToClean);
            }
        }
    } catch (Exception e) {
        // if there was any exception in the move (including the one we might have just thrown
        // above) then we should log it
        log.error("Error when cleaning up dir [" + baseDir + "] when writing file (" + thisRev + ")", e);
    }
}

From source file:org.ballerinalang.composer.service.fs.LocalFileSystem.java

@Override
public JsonObject read(String path) throws IOException {
    byte[] fileContent = Files.readAllBytes(Paths.get(path));
    JsonObject fileObject = new JsonObject();
    fileObject.addProperty(FILE_FULL_PATH, path);
    fileObject.addProperty(FILE_NAME, FilenameUtils.getBaseName(path));
    fileObject.addProperty(FILE_PATH, FilenameUtils.getFullPath(path));
    fileObject.addProperty(EXTENSION, FilenameUtils.getExtension(path));
    fileObject.addProperty(FILE_CONTENT, new String(fileContent, Charset.defaultCharset()));
    return fileObject;
}

From source file:org.ballerinalang.composer.service.fs.LocalFileSystem.java

/**
 * {@inheritDoc}//  ww  w  .j  ava 2  s.com
 */
@Override
public JsonArray listFilesInPath(String path, List<String> extensions) throws IOException {
    Path ioPath = Paths.get(path);
    JsonArray dirs = new JsonArray();
    Iterator<Path> iterator = Files.list(ioPath).sorted().iterator();
    while (iterator.hasNext()) {
        Path next = iterator.next();
        if ((Files.isDirectory(next) || Files.isRegularFile(next)) && !Files.isHidden(next)
                && !isWindowsSystemFile(next)) {
            JsonObject jsnObj = getJsonObjForFile(next, extensions);
            if (Files.isRegularFile(next)) {
                Path fileName = next.getFileName();
                SuffixFileFilter fileFilter = new SuffixFileFilter(extensions, INSENSITIVE);
                if (null != fileName && fileFilter.accept(next.toFile())) {
                    jsnObj.addProperty(FILE_FULL_PATH, next.toString());
                    jsnObj.addProperty(FILE_NAME, FilenameUtils.getBaseName(next.toString()));
                    jsnObj.addProperty(FILE_PATH, FilenameUtils.getFullPath(next.toString()));
                    jsnObj.addProperty(EXTENSION, FilenameUtils.getExtension(next.toString()));
                    dirs.add(jsnObj);
                }
            } else {
                dirs.add(jsnObj);
            }

        }
    }
    return dirs;
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * Loads the juror models used for consensus.
 * @param options specific options to use when loading the model
 * @throws IOException if there is a problem accessing the model
 * @throws ClassNotFoundException if the type of the model is not recognized
 *///from  w ww  . ja v  a 2  s  .  c  om
private void loadJurorModels(final DAVOptions options) throws IOException, ClassNotFoundException {
    jurorModels.clear();

    final String pathToModel = FilenameUtils.getFullPath(modelFilename);
    final String endpointName = FilenameUtils.getBaseName(FilenameUtils.getPathNoEndSeparator(pathToModel));

    if (properties.getBoolean("bdval.consensus.jurors.embedded", false)) {
        final File tmpdir = File.createTempFile("juror-models", "");
        tmpdir.delete();
        tmpdir.mkdir();

        try {
            // load juror models from the zip file
            final ZipFile zipFile = new ZipFile(zipFilename);
            for (final String jurorPrefix : jurorModelFilenamePrefixes) {
                // zip files should always use "/" as a separator
                final String jurorFilename = "models/" + endpointName + "/" + jurorPrefix + ".zip";
                LOG.debug("Loading juror model " + jurorFilename);
                final InputStream jurorStream = zipFile.getInputStream(zipFile.getEntry(jurorFilename));

                final File jurorFile = new File(FilenameUtils.concat(tmpdir.getPath(), jurorFilename));

                // put the juror model to disk so it can be loaded with existing code
                IOUtils.copy(jurorStream, FileUtils.openOutputStream(jurorFile));

                final BDVModel jurorModel = new BDVModel(jurorFile.getPath());
                jurorModel.load(options);
                jurorModels.add(jurorModel);
            }
        } finally {
            FileUtils.forceDeleteOnExit(tmpdir);
        }
    } else {
        // load juror models from disk
        final File finalModelPath = new File(pathToModel);
        final File finalModelParentPath = new File(finalModelPath.getParent());
        // assume the model is under a directory "models" at the same level as a models
        // directory which contains the model components.
        for (final String jurorPrefix : jurorModelFilenamePrefixes) {
            final String modelComponentFilename = finalModelParentPath.getParent() + SystemUtils.FILE_SEPARATOR
                    + "models" + SystemUtils.FILE_SEPARATOR + endpointName + SystemUtils.FILE_SEPARATOR
                    + jurorPrefix;
            LOG.debug("Loading model component " + modelComponentFilename);
            final BDVModel jurorModel = new BDVModel(modelComponentFilename);
            jurorModel.load(options);
            jurorModels.add(jurorModel);
        }
    }

    if (jurorModels.size() < 1) {
        throw new IllegalStateException("No juror models could be found");
    }

    jurorModelsAreLoaded = true;
}

From source file:org.bdval.DAVMode.java

protected void setupOutput(final JSAPResult result, final DAVOptions options) {
    final String output;
    options.overwriteOutput = result.getBoolean("overwrite-output");
    if (result.getBoolean("output-stats-from-gene-list")) {
        output = makeStatsFileFromGeneListsFile(options.geneLists, result.getString("output"));
    } else {//  w  ww.  j a v  a2 s . c o m
        output = result.getString("output");
    }
    System.out.println(">>> DAVMode.Output (stats) file is " + output);

    if (output == null || output.equals("-")) {
        options.output = new PrintWriter(System.out);
        System.err.println("Output will be written to stdout");
    } else {
        try {
            // Make sure the path of the output file exists.
            final String path = FilenameUtils.getFullPath(output);
            if (StringUtils.isNotBlank(path)) {
                FileUtils.forceMkdir(new File(path));
            }
            synchronized (output.intern()) {
                final File outputFile = new File(output);
                options.outputFilePreexist = options.overwriteOutput ? false : outputFile.exists();
                options.output = new PrintWriter(new FileWriter(output, !options.overwriteOutput));
                System.out.println("Output will be written to file " + output);
            }
        } catch (IOException e) {
            System.err.println("Cannot create output file for filename " + output);
            //   e.printStackTrace();
        }
    }
}