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

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

Introduction

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

Prototype

public static String separatorsToUnix(String path) 

Source Link

Document

Converts all separators to the Unix separator of forward slash.

Usage

From source file:com.thoughtworks.go.util.FileUtil.java

public static String join(File defaultWorkingDir, String actualFileToUse) {
    if (actualFileToUse == null) {
        LOGGER.trace("Using the default Directory->{}", defaultWorkingDir);
        return FilenameUtils.separatorsToUnix(defaultWorkingDir.getPath());
    }// w  w  w .  ja v  a  2  s.c  o  m
    return applyBaseDirIfRelativeAndNormalize(defaultWorkingDir, new File(actualFileToUse));
}

From source file:hudson.gridmaven.MavenModuleSetBuild.java

/**
 * Returns the filtered changeset entries that match the given module.
 *//*from  w ww .j  a va 2  s .  c om*/
/*package*/ List<ChangeLogSet.Entry> getChangeSetFor(final MavenModule mod) {
    return new ArrayList<ChangeLogSet.Entry>() {
        private static final long serialVersionUID = 5572368347535713298L;
        {
            // modules that are under 'mod'. lazily computed
            List<MavenModule> subsidiaries = null;

            for (ChangeLogSet.Entry e : getChangeSet()) {
                if (isDescendantOf(e, mod)) {
                    if (subsidiaries == null)
                        subsidiaries = mod.getSubsidiaries();

                    // make sure at least one change belongs to this module proper,
                    // and not its subsidiary module
                    if (notInSubsidiary(subsidiaries, e))
                        add(e);
                }
            }
        }

        private boolean notInSubsidiary(List<MavenModule> subsidiaries, ChangeLogSet.Entry e) {
            for (String path : e.getAffectedPaths())
                if (!belongsToSubsidiary(subsidiaries, path))
                    return true;
            return false;
        }

        private boolean belongsToSubsidiary(List<MavenModule> subsidiaries, String path) {
            for (MavenModule sub : subsidiaries)
                if (FilenameUtils.separatorsToUnix(path).startsWith(normalizePath(sub.getRelativePath())))
                    return true;
            return false;
        }

        /**
         * Does this change happen somewhere in the given module or its descendants?
         */
        private boolean isDescendantOf(ChangeLogSet.Entry e, MavenModule mod) {
            for (String path : e.getAffectedPaths()) {
                if (FilenameUtils.separatorsToUnix(path).startsWith(normalizePath(mod.getRelativePath())))
                    return true;
            }
            return false;
        }
    };
}

From source file:com.acc.storefront.web.theme.StorefrontResourceBundleSource.java

protected String getExtensionNameForWebroot(final ApplicationContext appContext) {
    String extensionName = null;// w w w  . ja v a  2s .c om
    try {
        final String currentWebinfPath = appContext.getResource("/WEB-INF").getFile().getCanonicalPath();
        final Map<String, String> installedWebModules = Utilities.getInstalledWebModules();
        final Set<String> installedWebModuleNames = installedWebModules.keySet();

        for (final String webModuleName : installedWebModuleNames) {
            final String webModuleWebinf = webModuleName + "/web/webroot/WEB-INF";

            if (FilenameUtils.separatorsToUnix(currentWebinfPath).contains(webModuleWebinf)) {
                extensionName = webModuleName;
                break;
            }
        }
    } catch (final IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No WEB-INF found");
        }
    }
    return extensionName;
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java

public List<X509Certificate> getSigners(URL url) throws IOException, ParserConfigurationException, SAXException,
        TransformerException, MarshalException, XMLSignatureException, JAXBException {
    List<X509Certificate> signers = new LinkedList<X509Certificate>();
    List<String> signatureResourceNames = getSignatureResourceNames(url);
    if (signatureResourceNames.isEmpty()) {
        LOG.debug("no signature resources");
    }/*from w w w  .j  av a2s  .c  o  m*/
    for (String signatureResourceName : signatureResourceNames) {
        Document signatureDocument = getSignatureDocument(url, signatureResourceName);
        if (null == signatureDocument) {
            continue;
        }

        NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (0 == signatureNodeList.getLength()) {
            return null;
        }
        Node signatureNode = signatureNodeList.item(0);

        KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
        DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode);
        domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
        OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(url);
        domValidateContext.setURIDereferencer(dereferencer);

        XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
        XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
        boolean valid = xmlSignature.validate(domValidateContext);

        if (!valid) {
            LOG.debug("not a valid signature");
            continue;
        }

        /*
         * Check the content of idPackageObject.
         */
        List<XMLObject> objects = xmlSignature.getObjects();
        XMLObject idPackageObject = null;
        for (XMLObject object : objects) {
            if ("idPackageObject".equals(object.getId())) {
                idPackageObject = object;
                break;
            }
        }
        if (null == idPackageObject) {
            LOG.debug("idPackageObject ds:Object not present");
            continue;
        }
        List<XMLStructure> idPackageObjectContent = idPackageObject.getContent();
        Manifest idPackageObjectManifest = null;
        for (XMLStructure content : idPackageObjectContent) {
            if (content instanceof Manifest) {
                idPackageObjectManifest = (Manifest) content;
                break;
            }
        }
        if (null == idPackageObjectManifest) {
            LOG.debug("no ds:Manifest present within idPackageObject ds:Object");
            continue;
        }
        LOG.debug("ds:Manifest present within idPackageObject ds:Object");
        List<Reference> idPackageObjectReferences = idPackageObjectManifest.getReferences();
        Set<String> idPackageObjectReferenceUris = new HashSet<String>();
        Set<String> remainingIdPackageObjectReferenceUris = new HashSet<String>();
        for (Reference idPackageObjectReference : idPackageObjectReferences) {
            idPackageObjectReferenceUris.add(idPackageObjectReference.getURI());
            remainingIdPackageObjectReferenceUris.add(idPackageObjectReference.getURI());
        }
        LOG.debug("idPackageObject ds:Reference URIs: " + idPackageObjectReferenceUris);
        CTTypes contentTypes = getContentTypes(url);
        List<String> relsEntryNames = getRelsEntryNames(url);
        for (String relsEntryName : relsEntryNames) {
            LOG.debug("---- relationship entry name: " + relsEntryName);
            CTRelationships relationships = getRelationships(url, relsEntryName);
            List<CTRelationship> relationshipList = relationships.getRelationship();
            boolean includeRelationshipInSignature = false;
            for (CTRelationship relationship : relationshipList) {
                String relationshipType = relationship.getType();
                STTargetMode targetMode = relationship.getTargetMode();
                if (null != targetMode) {
                    LOG.debug("TargetMode: " + targetMode.name());
                    if (targetMode == STTargetMode.EXTERNAL) {
                        /*
                         * ECMA-376 Part 2 - 3rd edition
                         * 
                         * 13.2.4.16 Manifest Element
                         * 
                         * "The producer shall not create a Manifest element that references any data outside of the package."
                         */
                        continue;
                    }
                }
                if (false == OOXMLSignatureFacet.isSignedRelationship(relationshipType)) {
                    continue;
                }
                String relationshipTarget = relationship.getTarget();
                String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/"));
                String streamEntry = baseUri + relationshipTarget;
                LOG.debug("stream entry: " + streamEntry);
                streamEntry = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(streamEntry));
                LOG.debug("normalized stream entry: " + streamEntry);
                String contentType = getContentType(contentTypes, streamEntry);
                if (relationshipType.endsWith("customXml")) {
                    if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) {
                        LOG.debug("skipping customXml with content type: " + contentType);
                        continue;
                    }
                }
                includeRelationshipInSignature = true;
                LOG.debug("content type: " + contentType);
                String referenceUri = streamEntry + "?ContentType=" + contentType;
                LOG.debug("reference URI: " + referenceUri);
                if (false == idPackageObjectReferenceUris.contains(referenceUri)) {
                    throw new RuntimeException(
                            "no reference in idPackageObject ds:Object for relationship target: "
                                    + streamEntry);
                }
                remainingIdPackageObjectReferenceUris.remove(referenceUri);
            }
            String relsReferenceUri = "/" + relsEntryName
                    + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
            if (includeRelationshipInSignature
                    && false == idPackageObjectReferenceUris.contains(relsReferenceUri)) {
                LOG.debug("missing ds:Reference for: " + relsEntryName);
                throw new RuntimeException("missing ds:Reference for: " + relsEntryName);
            }
            remainingIdPackageObjectReferenceUris.remove(relsReferenceUri);
        }
        if (false == remainingIdPackageObjectReferenceUris.isEmpty()) {
            LOG.debug("remaining idPackageObject reference URIs" + idPackageObjectReferenceUris);
            throw new RuntimeException("idPackageObject manifest contains unknown ds:References: "
                    + remainingIdPackageObjectReferenceUris);
        }

        X509Certificate signer = keySelector.getCertificate();
        signers.add(signer);
    }
    return signers;
}

From source file:de.teamgrit.grit.report.TexGenerator.java

/**
 * Writes the source code into the .tex file.
 * /*from ww  w  .ja  v  a  2s.c  om*/
 * @param file
 *            File the source code gets written into.
 * @param submission
 *            SubmissionObj the needed information gets taken from.
 * @throws IOException
 *             If something goes wrong when writing.
 */
private static void writeSourceCode(File file, Submission submission) throws IOException {
    FileWriterWithEncoding writer = new FileWriterWithEncoding(file, "UTF-8", true);

    writer.append("\\paragraph{Code}~\\\\\n");

    for (File f : FileUtils.listFiles(submission.getSourceCodeLocation().toFile(),
            FileFilterUtils.fileFileFilter(), TrueFileFilter.INSTANCE)) {

        // determines programming language of the file and adjusts the
        // lstlisting according to it
        String language = "no valid file";
        String fileExtension = FilenameUtils.getExtension(f.toString());

        if (fileExtension.matches("[Jj][Aa][Vv][Aa]")) {
            language = "Java";
        } else if (fileExtension.matches("([Ll])?[Hh][Ss]")) {
            language = "Haskell";
        } else if (fileExtension.matches("[Cc]|[Hh]")) {
            language = "C";
        } else if (fileExtension.matches("[Cc][Pp][Pp]")) {
            language = "C++";
        } else {
            // file is not a valid source file
            continue;
        }

        writer.append("\\lstinputlisting[language=" + language);

        writer.append(", breaklines=true]{" + FilenameUtils.separatorsToUnix((f.getAbsolutePath())) + "}\n");

    }
    writer.close();
}

From source file:com.apporiented.hermesftp.session.impl.FtpSessionContextImpl.java

private synchronized String getStartDir() throws FtpConfigException {
    UserData userData = (UserData) getAttribute(ATTR_USER_DATA);
    if (userData == null) {
        throw new FtpConfigException("User data not available");
    }/*w w  w  .j a va 2s.  c o m*/
    VarMerger varMerger = new VarMerger(userData.getDir());
    Properties props = new Properties();
    props.setProperty("ftproot", FilenameUtils.separatorsToUnix(options.getRootDir()));
    props.setProperty("user", user);
    varMerger.merge(props);
    if (!varMerger.isReplacementComplete()) {
        throw new FtpConfigException("Unresolved placeholders in user configuration file found.");
    }
    return varMerger.getText();
}

From source file:com.ariht.maven.plugins.config.generator.ConfigGeneratorImpl.java

/**
 * Concatenate filter io with template io
 *///  www. j  ava2 s .c  o  m
private String getOutputPath(final FileInfo template, final FileInfo filter, final String outputBasePath) {
    final String outputPath = outputBasePath + PATH_SEPARATOR + filter.getRelativeSubDirectory()
            + PATH_SEPARATOR + filter.getNameWithoutExtension() + PATH_SEPARATOR
            + template.getRelativeSubDirectory() + PATH_SEPARATOR;
    return FilenameUtils.separatorsToUnix(FilenameUtils.normalize(outputPath));
}

From source file:com.searchcode.app.jobs.repository.IndexBaseRepoJob.java

/**
 * Indexes all the documents in the repository changed file effectively performing a delta update
 * Should only be called when there is a genuine update IE something was indexed previously and
 * has has a new commit./*ww w  .j a  v  a 2s .c om*/
 */
public void indexDocsByDelta(Path path, String repoName, String repoLocations, String repoRemoteLocation,
        RepositoryChanged repositoryChanged) {
    SearchcodeLib scl = Singleton.getSearchCodeLib(); // Should have data object by this point
    Queue<CodeIndexDocument> codeIndexDocumentQueue = Singleton.getCodeIndexQueue();
    String fileRepoLocations = FilenameUtils.separatorsToUnix(repoLocations);

    // Used to hold the reports of what was indexed
    List<String[]> reportList = new ArrayList<>();

    for (String changedFile : repositoryChanged.getChangedFiles()) {
        if (this.shouldJobPauseOrTerminate()) {
            return;
        }

        if (Singleton.getDataService().getPersistentDelete().contains(repoName)) {
            return;
        }

        String[] split = changedFile.split("/");
        String fileName = split[split.length - 1];
        changedFile = fileRepoLocations + "/" + repoName + "/" + changedFile;
        changedFile = changedFile.replace("//", "/");

        CodeLinesReturn codeLinesReturn = this.getCodeLines(changedFile, reportList);
        if (codeLinesReturn.isError()) {
            break;
        }

        IsMinifiedReturn isMinified = this.getIsMinified(codeLinesReturn.getCodeLines(), fileName, reportList);
        if (isMinified.isMinified()) {
            break;
        }

        if (this.checkIfEmpty(codeLinesReturn.getCodeLines(), changedFile, reportList)) {
            break;
        }

        if (this.determineBinary(changedFile, fileName, codeLinesReturn.getCodeLines(), reportList)) {
            break;
        }

        String md5Hash = this.getFileMd5(changedFile);
        String languageName = Singleton.getFileClassifier().languageGuesser(changedFile,
                codeLinesReturn.getCodeLines());
        String fileLocation = this.getRelativeToProjectPath(path.toString(), changedFile);
        String fileLocationFilename = changedFile.replace(fileRepoLocations, Values.EMPTYSTRING);
        String repoLocationRepoNameLocationFilename = changedFile;
        String newString = this.getBlameFilePath(fileLocationFilename);
        String codeOwner = this.getCodeOwner(codeLinesReturn.getCodeLines(), newString, repoName,
                fileRepoLocations, scl);

        if (this.LOWMEMORY) {
            try {
                Singleton.getCodeIndexer().indexDocument(new CodeIndexDocument(
                        repoLocationRepoNameLocationFilename, repoName, fileName, fileLocation,
                        fileLocationFilename, md5Hash, languageName, codeLinesReturn.getCodeLines().size(),
                        StringUtils.join(codeLinesReturn.getCodeLines(), " "), repoRemoteLocation, codeOwner));
            } catch (IOException ex) {
                Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                        + "\n with message: " + ex.getMessage());
            }
        } else {
            this.sharedService.incrementCodeIndexLinesCount(codeLinesReturn.getCodeLines().size());
            codeIndexDocumentQueue.add(new CodeIndexDocument(repoLocationRepoNameLocationFilename, repoName,
                    fileName, fileLocation, fileLocationFilename, md5Hash, languageName,
                    codeLinesReturn.getCodeLines().size(),
                    StringUtils.join(codeLinesReturn.getCodeLines(), " "), repoRemoteLocation, codeOwner));
        }

        if (this.LOGINDEXED) {
            reportList.add(new String[] { changedFile, "included", "" });
        }
    }

    if (this.LOGINDEXED && reportList.isEmpty() == false) {
        this.logIndexed(repoName + "_delta", reportList);
    }

    for (String deletedFile : repositoryChanged.getDeletedFiles()) {
        deletedFile = fileRepoLocations + "/" + repoName + "/" + deletedFile;
        deletedFile = deletedFile.replace("//", "/");
        Singleton.getLogger().info("Missing from disk, removing from index " + deletedFile);
        try {
            Singleton.getCodeIndexer().deleteByCodeId(DigestUtils.sha1Hex(deletedFile));
        } catch (IOException ex) {
            Singleton.getLogger()
                    .warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                            + " indexDocsByDelta deleteByFileLocationFilename for " + repoName + " "
                            + deletedFile + "\n with message: " + ex.getMessage());
        }
    }
}

From source file:com.silverpeas.util.FileUtil.java

/**
 * Checking that the path doesn't contain relative navigation between pathes.
 *
 * @param path/*from w  w w  .  j a  v  a  2s.  com*/
 * @throws RelativeFileAccessException
 */
public static void checkPathNotRelative(String path) throws RelativeFileAccessException {
    String unixPath = FilenameUtils.separatorsToUnix(path);
    if (unixPath != null && (unixPath.contains("../") || unixPath.contains("/.."))) {
        throw new RelativeFileAccessException();
    }
}

From source file:com.ariht.maven.plugins.config.generator.ConfigGeneratorImpl.java

private void logConfigurationParameters() {
    if (StringUtils.isBlank(configGeneratorParameters.getEncoding())) {
        configGeneratorParameters.setEncoding(System.getProperty("file.encoding"));
        log.warn("File encoding has not been set, using platform encoding '"
                + configGeneratorParameters.getEncoding() + "', i.e. generated config is platform dependent!");
    } else if (configGeneratorParameters.isLogOutput()) {
        log.debug("Using file encoding '" + configGeneratorParameters.getEncoding()
                + "' while generating config.");
    }/*  w w  w  .jav a2 s  .com*/
    if (configGeneratorParameters.isLogOutput()) {
        log.debug("Templates path : "
                + FilenameUtils.separatorsToUnix(configGeneratorParameters.getTemplatesBasePath()));
        log.debug("Filters path   : "
                + FilenameUtils.separatorsToUnix(configGeneratorParameters.getFiltersBasePath()));
        log.debug("Output path    : "
                + FilenameUtils.separatorsToUnix(configGeneratorParameters.getOutputBasePath()));
    }
}