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:org.abstracthorizon.proximity.storage.remote.CommonsNetFtpRemotePeer.java

/**
 * Construct item properties from get response.
 * //from ww w . ja v a  2 s  .  co m
 * @param path the path
 * @param originatingUrlString the originating url string
 * @param remoteFile the remote file
 * 
 * @return the item properties
 * 
 * @throws MalformedURLException the malformed URL exception
 */
protected ItemProperties constructItemPropertiesFromGetResponse(String path, String originatingUrlString,
        FTPFile remoteFile) throws MalformedURLException {
    URL originatingUrl = new URL(originatingUrlString);
    ItemProperties result = new HashMapItemPropertiesImpl();
    result.setDirectoryPath(
            FilenameUtils.separatorsToUnix(FilenameUtils.getPath(FilenameUtils.getFullPath(path))));
    result.setDirectory(remoteFile.isDirectory());
    result.setFile(remoteFile.isFile());
    result.setLastModified(remoteFile.getTimestamp().getTime());
    result.setName(FilenameUtils.getName(originatingUrl.getPath()));
    if (result.isFile()) {
        result.setSize(remoteFile.getSize());
    } else {
        result.setSize(0);
    }
    result.setRemoteUrl(originatingUrl.toString());
    return result;
}

From source file:org.abstracthorizon.proximity.webapp.webdav.ProximityWebdavStorageAdapter.java

public void setResourceContent(String resourceUri, InputStream content, String contentType,
        String characterEncoding) throws WebdavException {
    logger.debug("setResourceContent");
    try {//from w  ww  .  j  a va 2 s.c om
        createdButNotStoredResources.remove(resourceUri);
        ProximityRequest request = createRequest(resourceUri, false);
        Item item = new Item();
        ItemProperties itemProperties = new HashMapItemPropertiesImpl();
        itemProperties.setDirectoryPath(
                FilenameUtils.separatorsToUnix(FilenameUtils.getFullPathNoEndSeparator(resourceUri)));
        itemProperties.setName(FilenameUtils.getName(resourceUri));
        itemProperties.setLastModified(new Date());
        itemProperties.setDirectory(false);
        itemProperties.setFile(true);
        item.setProperties(itemProperties);
        item.setStream(content);
        proximity.storeItem(request, item);
    } catch (ProximityException ex) {
        logger.error("Proximity throw exception.", ex);
        throw new WebdavException("Proximity throw " + ex.getMessage());
    }
}

From source file:org.apache.archiva.consumers.functors.ConsumerWantsFilePredicate.java

@Override
public boolean evaluate(Object object) {
    boolean satisfies = false;

    if (object instanceof RepositoryContentConsumer) {
        RepositoryContentConsumer consumer = (RepositoryContentConsumer) object;
        if (wantsFile(consumer, FilenameUtils.separatorsToUnix(basefile.getRelativePath()))) {
            satisfies = true;/*from   www .  ja  v a2s. c o m*/

            // regardless of the timestamp, we record that it was wanted so it doesn't get counted as invalid
            wantedFileCount++;

            if (!consumer.isProcessUnmodified()) {
                // Timestamp finished points to the last successful scan, not this current one.
                if (basefile.lastModified() < changesSince) {
                    // Skip file as no change has occurred.
                    satisfies = false;
                }
            }
        }
    }

    return satisfies;
}

From source file:org.apache.archiva.proxy.DefaultRepositoryProxyConnectors.java

@Override
public File fetchFromProxies(ManagedRepositoryContent repository, ArtifactReference artifact)
        throws ProxyDownloadException {
    File localFile = toLocalFile(repository, artifact);

    Properties requestProperties = new Properties();
    requestProperties.setProperty("filetype", "artifact");
    requestProperties.setProperty("version", artifact.getVersion());
    requestProperties.setProperty("managedRepositoryId", repository.getId());

    List<ProxyConnector> connectors = getProxyConnectors(repository);
    Map<String, Exception> previousExceptions = new LinkedHashMap<>();
    for (ProxyConnector connector : connectors) {
        if (connector.isDisabled()) {
            continue;
        }//from   w w  w . ja  v  a2 s . c o m

        RemoteRepositoryContent targetRepository = connector.getTargetRepository();
        requestProperties.setProperty("remoteRepositoryId", targetRepository.getId());

        String targetPath = targetRepository.toPath(artifact);

        if (SystemUtils.IS_OS_WINDOWS) {
            // toPath use system PATH_SEPARATOR so on windows url are \ which doesn't work very well :-)
            targetPath = FilenameUtils.separatorsToUnix(targetPath);
        }

        try {
            File downloadedFile = transferFile(connector, targetRepository, targetPath, repository, localFile,
                    requestProperties, true);

            if (fileExists(downloadedFile)) {
                log.debug("Successfully transferred: {}", downloadedFile.getAbsolutePath());
                return downloadedFile;
            }
        } catch (NotFoundException e) {
            log.debug("Artifact {} not found on repository \"{}\".", Keys.toKey(artifact),
                    targetRepository.getRepository().getId());
        } catch (NotModifiedException e) {
            log.debug("Artifact {} not updated on repository \"{}\".", Keys.toKey(artifact),
                    targetRepository.getRepository().getId());
        } catch (ProxyException | RepositoryAdminException e) {
            validatePolicies(this.downloadErrorPolicies, connector.getPolicies(), requestProperties, artifact,
                    targetRepository, localFile, e, previousExceptions);
        }
    }

    if (!previousExceptions.isEmpty()) {
        throw new ProxyDownloadException("Failures occurred downloading from some remote repositories",
                previousExceptions);
    }

    log.debug("Exhausted all target repositories, artifact {} not found.", Keys.toKey(artifact));

    return null;
}

From source file:org.apache.maven.scm.provider.git.gitexe.command.add.GitAddCommand.java

/**
 * {@inheritDoc}//w w  w.j  ava2s  .  com
 */
protected ScmResult executeAddCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message,
        boolean binary) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;

    if (fileSet.getFileList().isEmpty()) {
        throw new ScmException("You must provide at least one file/directory to add");
    }

    AddScmResult result = executeAddFileSet(fileSet);

    if (result != null) {
        return result;
    }

    // SCM-709: statusCommand uses repositoryRoot instead of workingDirectory, adjust it with relativeRepositoryPath
    Commandline clRevparse = GitStatusCommand.createRevparseShowToplevelCommand(fileSet);

    CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    URI relativeRepositoryPath = null;

    int exitCode;

    exitCode = GitCommandLineUtils.execute(clRevparse, stdout, stderr, getLogger());
    if (exitCode != 0) {
        // git-status returns non-zero if nothing to do
        if (getLogger().isInfoEnabled()) {
            getLogger().info("Could not resolve toplevel");
        }
    } else {
        relativeRepositoryPath = GitStatusConsumer.resolveURI(stdout.getOutput().trim(),
                fileSet.getBasedir().toURI());
    }

    // git-add doesn't show single files, but only summary :/
    // so we must run git-status and consume the output
    // borrow a few things from the git-status command
    Commandline clStatus = GitStatusCommand.createCommandLine(repository, fileSet);

    GitStatusConsumer statusConsumer = new GitStatusConsumer(getLogger(), fileSet.getBasedir(),
            relativeRepositoryPath);
    stderr = new CommandLineUtils.StringStreamConsumer();
    exitCode = GitCommandLineUtils.execute(clStatus, statusConsumer, stderr, getLogger());
    if (exitCode != 0) {
        // git-status returns non-zero if nothing to do
        if (getLogger().isInfoEnabled()) {
            getLogger().info("nothing added to commit but untracked files present (use \"git add\" to track)");
        }
    }

    List<ScmFile> changedFiles = new ArrayList<ScmFile>();

    // rewrite all detected files to now have status 'checked_in'
    for (ScmFile scmfile : statusConsumer.getChangedFiles()) {
        // if a specific fileSet is given, we have to check if the file is really tracked
        for (File f : fileSet.getFileList()) {
            if (FilenameUtils.separatorsToUnix(f.getPath()).equals(scmfile.getPath())) {
                changedFiles.add(scmfile);
            }
        }
    }

    Commandline cl = createCommandLine(fileSet.getBasedir(), fileSet.getFileList());
    return new AddScmResult(cl.toString(), changedFiles);
}

From source file:org.apache.maven.scm.provider.git.gitexe.command.checkin.GitCheckInCommand.java

/** {@inheritDoc} */
protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message,
        ScmVersion version) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;

    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();

    int exitCode;

    File messageFile = FileUtils.createTempFile("maven-scm-", ".commit", null);
    try {/*from   www  .  j  av a2s.c o m*/
        FileUtils.fileWrite(messageFile.getAbsolutePath(), message);
    } catch (IOException ex) {
        return new CheckInScmResult(null,
                "Error while making a temporary file for the commit message: " + ex.getMessage(), null, false);
    }

    try {
        if (!fileSet.getFileList().isEmpty()) {
            // if specific fileSet is given, we have to git-add them first
            // otherwise we will use 'git-commit -a' later

            Commandline clAdd = GitAddCommand.createCommandLine(fileSet.getBasedir(), fileSet.getFileList());

            exitCode = GitCommandLineUtils.execute(clAdd, stdout, stderr, getLogger());

            if (exitCode != 0) {
                return new CheckInScmResult(clAdd.toString(), "The git-add command failed.", stderr.getOutput(),
                        false);
            }

        }

        // SCM-709: statusCommand uses repositoryRoot instead of workingDirectory, adjust it with
        // relativeRepositoryPath
        Commandline clRevparse = GitStatusCommand.createRevparseShowToplevelCommand(fileSet);

        stdout = new CommandLineUtils.StringStreamConsumer();
        stderr = new CommandLineUtils.StringStreamConsumer();

        URI relativeRepositoryPath = null;

        exitCode = GitCommandLineUtils.execute(clRevparse, stdout, stderr, getLogger());
        if (exitCode != 0) {
            // git-status returns non-zero if nothing to do
            if (getLogger().isInfoEnabled()) {
                getLogger().info("Could not resolve toplevel");
            }
        } else {
            relativeRepositoryPath = GitStatusConsumer.resolveURI(stdout.getOutput().trim(),
                    fileSet.getBasedir().toURI());
        }

        // git-commit doesn't show single files, but only summary :/
        // so we must run git-status and consume the output
        // borrow a few things from the git-status command
        Commandline clStatus = GitStatusCommand.createCommandLine(repository, fileSet);

        GitStatusConsumer statusConsumer = new GitStatusConsumer(getLogger(), fileSet.getBasedir(),
                relativeRepositoryPath);
        exitCode = GitCommandLineUtils.execute(clStatus, statusConsumer, stderr, getLogger());
        if (exitCode != 0) {
            // git-status returns non-zero if nothing to do
            if (getLogger().isInfoEnabled()) {
                getLogger().info(
                        "nothing added to commit but untracked files present (use \"git add\" to " + "track)");
            }
        }

        if (statusConsumer.getChangedFiles().isEmpty()) {
            return new CheckInScmResult(null, statusConsumer.getChangedFiles());
        }

        Commandline clCommit = createCommitCommandLine(repository, fileSet, messageFile);

        exitCode = GitCommandLineUtils.execute(clCommit, stdout, stderr, getLogger());
        if (exitCode != 0) {
            return new CheckInScmResult(clCommit.toString(), "The git-commit command failed.",
                    stderr.getOutput(), false);
        }

        if (repo.isPushChanges()) {
            Commandline cl = createPushCommandLine(getLogger(), repository, fileSet, version);

            exitCode = GitCommandLineUtils.execute(cl, stdout, stderr, getLogger());
            if (exitCode != 0) {
                return new CheckInScmResult(cl.toString(), "The git-push command failed.", stderr.getOutput(),
                        false);
            }
        }

        List<ScmFile> checkedInFiles = new ArrayList<ScmFile>(statusConsumer.getChangedFiles().size());

        // rewrite all detected files to now have status 'checked_in'
        for (ScmFile changedFile : statusConsumer.getChangedFiles()) {
            ScmFile scmfile = new ScmFile(changedFile.getPath(), ScmFileStatus.CHECKED_IN);

            if (fileSet.getFileList().isEmpty()) {
                checkedInFiles.add(scmfile);
            } else {
                // if a specific fileSet is given, we have to check if the file is really tracked
                for (File f : fileSet.getFileList()) {
                    if (FilenameUtils.separatorsToUnix(f.getPath()).equals(scmfile.getPath())) {
                        checkedInFiles.add(scmfile);
                    }

                }
            }
        }

        return new CheckInScmResult(clCommit.toString(), checkedInFiles);
    } finally {
        try {
            FileUtils.forceDelete(messageFile);
        } catch (IOException ex) {
            // ignore
        }
    }

}

From source file:org.apache.maven.scm.provider.git.gitexe.command.GitCommandLineUtils.java

public static void addTarget(Commandline cl, List<File> files) {
    if (files == null || files.isEmpty()) {
        return;//from  w w w.j  a  v a  2s. c  om
    }
    final File workingDirectory = cl.getWorkingDirectory();
    try {
        final String canonicalWorkingDirectory = workingDirectory.getCanonicalPath();
        for (File file : files) {
            String relativeFile = file.getPath();

            final String canonicalFile = file.getCanonicalPath();
            if (canonicalFile.startsWith(canonicalWorkingDirectory)) {
                // so we can omit the starting characters
                relativeFile = canonicalFile.substring(canonicalWorkingDirectory.length());

                if (relativeFile.startsWith(File.separator)) {
                    relativeFile = relativeFile.substring(File.separator.length());
                }
            }

            // no setFile() since this screws up the working directory!
            cl.createArg().setValue(FilenameUtils.separatorsToUnix(relativeFile));
        }
    } catch (IOException ex) {
        throw new IllegalArgumentException("Could not get canonical paths for workingDirectory = "
                + workingDirectory + " or files=" + files, ex);
    }
}

From source file:org.apache.oodt.product.handlers.ofsn.util.OFSNUtils.java

public static Document getOFSNDoc(List<File> fileList, OFSNHandlerConfig cfg, String productRoot,
        boolean showDirSize, boolean showFileSize) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w  w w. ja  v  a2  s.  c  o m*/
    Document document;

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();

        Element root = (Element) document.createElement(DIR_RESULT_TAG);
        XMLUtils.addAttribute(document, root, "xmlns", DIR_LISTING_NS);
        document.appendChild(root);

        for (File file : fileList) {
            Element dirEntryElem = XMLUtils.addNode(document, root, DIR_ENTRY_TAG);
            String ofsn = toOFSN(file.getAbsolutePath(), productRoot);
            //This ensures that we get ofsn names with unix style separators.
            //On a Windows machine, the product server would return '\'
            //separators.
            String unixStyleOFSN = FilenameUtils.separatorsToUnix(ofsn);
            if (cfg.getType().equals(LISTING_CMD)) {
                if (!Boolean.valueOf(cfg.getHandlerConf().getProperty("isSizeCmd"))) {
                    XMLUtils.addNode(document, dirEntryElem, OFSN_TAG, unixStyleOFSN);
                }
            }

            long size = Long.MIN_VALUE;

            if (file.isDirectory()) {
                if (showDirSize) {
                    size = FileUtils.sizeOfDirectory(file);
                }
            } else {
                if (showFileSize) {
                    size = file.length();
                }
            }

            if (size != Long.MIN_VALUE) {
                XMLUtils.addNode(document, dirEntryElem, FILE_SIZE_TAG, String.valueOf(size));
            }
        }

        return document;
    } catch (ParserConfigurationException e) {
        LOG.log(Level.SEVERE, e.getMessage());
        return null;
    }

}

From source file:org.apache.rya.accumulo.mr.merge.CopyTool.java

/**
 * Converts a path string, or a sequence of strings that when joined form a path string,
 * to a {@link org.apache.hadoop.fs.Path}.
 * @param first The path string or initial part of the path string.
 * @param more Additional strings to be joined to form the path string.
 * @return the resulting {@link org.apache.hadoop.fs.Path}.
 *///from   w  w  w.  ja v  a 2 s.  c om
public static Path getPath(final String first, final String... more) {
    final java.nio.file.Path path = Paths.get(first, more);
    final String stringPath = FilenameUtils.separatorsToUnix(path.toAbsolutePath().toString());
    final Path hadoopPath = new Path(stringPath);
    return hadoopPath;
}

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Converts a {@link Path} to a {@link org.apache.hadoop.fs.Path}.
 * @param path The {@link Path}.// ww  w  .  ja va2  s .  c om
 * @return the resulting {@link org.apache.hadoop.fs.Path}.
 */
public static org.apache.hadoop.fs.Path toHadoopPath(final Path path) {
    if (path != null) {
        final String stringPath = FilenameUtils.separatorsToUnix(path.toAbsolutePath().toString());
        final org.apache.hadoop.fs.Path hadoopPath = new org.apache.hadoop.fs.Path(stringPath);
        return hadoopPath;
    }
    return null;
}