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.jahia.modules.external.modules.osgi.ModulesSourceHttpServiceTracker.java

protected String getResourcePath(File file) {
    return StringUtils.substringAfterLast(FilenameUtils.separatorsToUnix(file.getPath()),
            "/src/main/resources");
}

From source file:org.jahia.services.templates.SvnSourceControlManagement.java

@Override
protected Map<String, Status> createStatusMap() throws IOException {
    Map<String, Status> newMap = new HashMap<String, Status>();
    ExecutionResult result = executeCommand(executable, new String[] { "status" });
    for (String line : readLines(result.out)) {
        if (StringUtils.isBlank(line)) {
            continue;
        }//from w  w  w  . j  a  va  2s  .  com
        String path = line.substring(8);
        char firstColumn = line.charAt(0);
        Status status = null;
        if (firstColumn == 'C' || line.charAt(1) == 'C' || line.charAt(6) == 'C') {
            status = Status.UNMERGED;
        } else if (firstColumn == 'A') {
            status = Status.ADDED;
        } else if (firstColumn == 'D' || firstColumn == '!') {
            status = Status.DELETED;
        } else if (firstColumn == 'M') {
            status = Status.MODIFIED;
        } else if (firstColumn == '?') {
            status = Status.UNTRACKED;
        }
        if (status != null) {
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            path = FilenameUtils.separatorsToUnix(path);
            newMap.put(path, status);
            String[] pathSegments = StringUtils.split(path, '/');
            StringBuilder subPath = new StringBuilder(64);
            for (String segment : pathSegments) {
                newMap.put(subPath.length() == 0 ? "/" : subPath.toString(), Status.MODIFIED);
                subPath.append('/');
                subPath.append(segment);
            }
        }
    }
    return newMap;
}

From source file:org.jamwiki.parser.image.ImageUtil.java

/**
 * Utility method for building the URL to an uploaded file (NOT the file's
 * topic page).  If the file does not exist then this method will return
 * <code>null</code>.//www.  ja  v a  2  s .  c o m
 *
 * @param context The servlet context root.
 * @param filename The relative path of the file.  See
 *  {@link org.jamwiki.model.WikiFile#getUrl}.
 * @param forceAbsoluteUrl Set to <code>true</code> if the returned URL should
 *  always be absolute.  By default an absolute URL will only be returned if
 *  the PROP_FILE_SERVER_URL property is not empty and differs from the
 *  PROP_SERVER_URL property.
 * @return The URL to an uploaded file (not the file's topic page) or
 *  <code>null</code> if the file does not exist.
 */
public static String buildImageUrl(String context, String filename, boolean forceAbsoluteUrl) {
    String relativeFileRoot = FilenameUtils.normalize(context + "/" + DEFAULT_RELATIVE_FILE_DIRECTORY);
    if (Environment.getValue(Environment.PROP_FILE_UPLOAD_STORAGE)
            .equals(WikiBase.UPLOAD_STORAGE.DOCROOT.toString())) {
        relativeFileRoot = Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH);
    }
    String url = FilenameUtils.normalize(relativeFileRoot + "/" + filename);
    if (isImagesOnFS()) {
        String fileServerUrl = Environment.getValue(Environment.PROP_FILE_SERVER_URL);
        String absoluteServerUrl = Environment.getValue(Environment.PROP_SERVER_URL);
        if (!StringUtils.isBlank(fileServerUrl)
                && !StringUtils.equalsIgnoreCase(fileServerUrl, absoluteServerUrl)) {
            // file server URL is not the same as server URL, so make the image URL absolute
            url = LinkUtil.normalize(fileServerUrl + url);
        } else if (forceAbsoluteUrl) {
            // caller requested an absolute URL when one would not have otherwise been
            // required, so use the server URL to generate an absolute URL
            url = LinkUtil.normalize(absoluteServerUrl + url);
        }
    }
    return FilenameUtils.separatorsToUnix(url);
}

From source file:org.jasig.maven.plugin.sass.AbstractSassMojo.java

protected void buildBasicSASSScript(final StringBuilder sassScript) throws MojoExecutionException {
    final Log log = this.getLog();

    sassScript.append("require 'rubygems'\n");

    if (gemPaths.length > 0) {
        sassScript.append("env = { 'GEM_PATH' => [\n");
        for (final String gemPath : gemPaths) {
            sassScript.append("    '").append(gemPath).append("',\n");
        }//from   w w w.  j a  va2s.  c om
        sassScript.setLength(sassScript.length() - 2); // remove trailing comma
        sassScript.append("\n");
        sassScript.append("] }\n");
        sassScript.append("env['GEM_PATH'] += ENV['GEM_PATH'] unless ENV['GEM_PATH'].nil?\n");
        sassScript.append("Gem.paths = env\n");
    }

    for (final String gem : gems) {
        sassScript.append("require '").append(gem).append("'\n");
    }

    sassScript.append("require 'sass/plugin'\n");
    sassScript.append("require 'java'\n");

    if (this.useCompass) {
        log.info("Running with Compass enabled.");
        sassScript.append("require 'compass'\n");
        sassScript.append("require 'compass/exec'\n");
        sassScript.append(
                "Compass.add_project_configuration(File.join('" + this.sassConfigFile.toString() + "'))\n");
        this.sassOptions.put("load_paths", "Compass.configuration.sass_load_paths");
        // manually specify these paths
        sassScript.append(
                "Compass::Frameworks.register_directory('jar:'+ File.join(Compass.base_directory, 'frameworks/compass'))\n");
        sassScript.append(
                "Compass::Frameworks.register_directory('jar:'+ File.join(Compass.base_directory, 'frameworks/blueprint'))\n");
    }

    // Get all template locations from resources and set option 'template_location' and
    // 'css_location' (to override default "./public/stylesheets/sass", "./public/stylesheets")
    // remaining locations are added later with 'add_template_location'
    final Iterator<Entry<String, String>> templateLocations = getTemplateLocations();
    if (templateLocations.hasNext()) {
        Entry<String, String> location = templateLocations.next();
        sassOptions.put("template_location", "'" + location.getKey() + "'");
        sassOptions.put("css_location", "'" + location.getValue() + "'");
    }

    //If not explicitly set place the cache location in the target dir
    if (!this.sassOptions.containsKey("cache_location")) {
        final File sassCacheDir = new File(this.buildDirectory, "sass_cache");
        final String sassCacheDirStr = sassCacheDir.toString();
        this.sassOptions.put("cache_location", "'" + FilenameUtils.separatorsToUnix(sassCacheDirStr) + "'");
    }

    //Add the plugin configuration options
    sassScript.append("Sass::Plugin.options.merge!(\n");
    for (final Iterator<Entry<String, String>> entryItr = this.sassOptions.entrySet().iterator(); entryItr
            .hasNext();) {
        final Entry<String, String> optEntry = entryItr.next();
        final String opt = optEntry.getKey();
        final String value = optEntry.getValue();
        sassScript.append("    :").append(opt).append(" => ").append(value);
        if (entryItr.hasNext()) {
            sassScript.append(",");
        }
        sassScript.append("\n");
    }
    sassScript.append(")\n");

    // add remaining template locations with 'add_template_location' (need to be done after options.merge)
    while (templateLocations.hasNext()) {
        Entry<String, String> location = templateLocations.next();
        sassScript.append("Sass::Plugin.add_template_location('").append(location.getKey()).append("', '")
                .append(location.getValue()).append("')\n");
    }

    // set up sass compiler callback for reporting
    sassScript.append(
            "Sass::Plugin.on_compilation_error {|error, template, css| $compiler_callback.compilationError(error.message, template, css) }\n");
    sassScript.append(
            "Sass::Plugin.on_updated_stylesheet {|template, css| $compiler_callback.updatedStylesheeet(template, css) }\n");
    sassScript.append(
            "Sass::Plugin.on_template_modified {|template| $compiler_callback.templateModified(template) }\n");
    sassScript.append(
            "Sass::Plugin.on_template_created {|template| $compiler_callback.templateCreated(template) }\n");
    sassScript.append(
            "Sass::Plugin.on_template_deleted {|template| $compiler_callback.templateDeleted(template) }\n");

    // make ruby give use some debugging info when requested
    if (log.isDebugEnabled()) {
        sassScript.append("require 'pp'\npp Sass::Plugin.options\n");
        if (useCompass) {
            sassScript.append("pp Compass::configuration\n");
        }
    }
}

From source file:org.jasig.maven.plugin.sass.Resource.java

public Map<String, String> getDirectoriesAndDestinations() {

    final File sourceDirectory = new File(source.getDirectory());

    // Scan for directories
    final DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(sourceDirectory);
    scanner.setIncludes(source.getIncludes().toArray(new String[source.getIncludes().size()]));
    scanner.setExcludes(source.getExcludes().toArray(new String[source.getExcludes().size()]));

    // Add default excludes to the list of excludes (see http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/AbstractScanner.html#DEFAULTEXCLUDES
    // or http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/AbstractScanner.html#addDefaultExcludes() )
    scanner.addDefaultExcludes();// w w w  . j  a  v a  2s .co  m

    scanner.scan();

    final Map<String, String> result = new LinkedHashMap<String, String>();

    result.put(FilenameUtils.separatorsToUnix(sourceDirectory.toString()),
            FilenameUtils.separatorsToUnix(destination.toString()));

    for (String included : scanner.getIncludedDirectories()) {
        if (!included.isEmpty()) {
            final String subdir = StringUtils.difference(sourceDirectory.toString(), included);

            final File sourceDir = new File(sourceDirectory, included);

            File destDir = new File(this.destination, subdir);
            if (this.relativeOutputDirectory != null && !this.relativeOutputDirectory.isEmpty()) {
                destDir = new File(destDir, this.relativeOutputDirectory);
            }

            result.put(FilenameUtils.separatorsToUnix(sourceDir.toString()),
                    FilenameUtils.separatorsToUnix(destDir.toString()));
        }
    }

    return result;
}

From source file:org.jasig.resourceserver.utils.aggr.ResourcesElementsProviderImpl.java

protected <T extends BasicInclude> String getElementPath(HttpServletRequest request, T basicInclude,
        String relativeRoot) {// www  .  j ava2 s.c  o m
    String path = basicInclude.getValue();

    if (!resourcesDao.isAbsolute(basicInclude)) {
        path = FilenameUtils.normalize(relativeRoot + path);
        path = FilenameUtils.separatorsToUnix(path);
        if (logger.isDebugEnabled()) {
            logger.debug("translated relative path {} to {}", basicInclude.getValue(), path);
        }
    } else if (basicInclude.isResource()) {
        path = this.resolveResourceUrl(request, path);
    }

    return path;
}

From source file:org.jfrog.bamboo.builder.GradleInitScriptHelper.java

public ConfigurationPathHolder createAndGetGradleInitScriptPath(String dependenciesDir,
        GradleBuildContext buildContext, BuildLogger logger, String scriptTemplate, Map<String, String> taskEnv,
        Map<String, String> generalEnv) {
    long selectedServerId = buildContext.getArtifactoryServerId();
    if (selectedServerId != -1) {
        //Using "getInstance()" since the field must be transient
        ServerConfig serverConfig = serverConfigManager.getServerConfigById(selectedServerId);
        if (serverConfig == null) {

            String warningMessage = "Found an ID of a selected Artifactory server configuration ("
                    + selectedServerId//from   ww w  .j  a  va 2  s .  c om
                    + ") but could not find a matching configuration. Build info collection is disabled.";
            logger.addBuildLogHeader(warningMessage, true);
            log.warn(warningMessage);
            return null;
        } else {
            String normalizedPath = FilenameUtils.separatorsToUnix(dependenciesDir);
            scriptTemplate = scriptTemplate.replace("${pluginLibDir}", normalizedPath);
            try {
                File buildProps = File.createTempFile("buildinfo", "properties");
                ArtifactoryClientConfiguration configuration = createClientConfiguration(buildContext,
                        serverConfig, taskEnv);
                // Add Bamboo build variables
                MapDifference<String, String> buildVarDifference = Maps.difference(generalEnv, System.getenv());
                Map<String, String> filteredBuildVarDifferences = buildVarDifference.entriesOnlyOnLeft();
                IncludeExcludePatterns patterns = new IncludeExcludePatterns(
                        buildContext.getEnvVarsIncludePatterns(), buildContext.getEnvVarsExcludePatterns());
                configuration.info.addBuildVariables(filteredBuildVarDifferences, patterns);
                configuration.setPropertiesFile(buildProps.getAbsolutePath());
                configuration.persistToPropertiesFile();
                File tempInitScript = File.createTempFile("artifactory.init.script", "gradle");
                FileUtils.writeStringToFile(tempInitScript, scriptTemplate, "utf-8");
                if (buildContext.isPublishBuildInfo()) {
                    this.context.getBuildResult().getCustomBuildData()
                            .put(BUILD_RESULT_COLLECTION_ACTIVATED_PARAM, "true");
                    this.context.getBuildResult().getCustomBuildData().put(BUILD_RESULT_SELECTED_SERVER_PARAM,
                            serverConfig.getUrl());
                    this.context.getBuildResult().getCustomBuildData().put(BUILD_RESULT_RELEASE_ACTIVATED_PARAM,
                            String.valueOf(
                                    buildContext.releaseManagementContext.isActivateReleaseManagement()));
                }
                return new ConfigurationPathHolder(tempInitScript.getCanonicalPath(),
                        buildProps.getCanonicalPath());
            } catch (IOException e) {
                log.warn("An error occurred while creating the gradle build info init script. "
                        + "Build-info task will not be added.", e);
            }
        }
    }

    return null;
}

From source file:org.jfrog.build.extractor.clientConfiguration.util.PublishedItemsHelper.java

/**
 * Splits a given property value to pairs of source and target strings (the splitter is '=>'
 * the source represents the Ant Pattern to search for
 * the target represents the target path to deploy the found artifacts
 * Multi values as acceptable by new lined or comma separated.
 *
 * @param publishedItemsPropertyValue the string value to split, if the splitter '=>' was not found
 *                                    then the value is treated as a source only (target will be "").
 * @return a Map containing the sources as keys and targets as values
 *//*from  w  w  w . j a v  a2s  .com*/
public static Multimap<String, String> getPublishedItemsPatternPairs(String publishedItemsPropertyValue) {
    Multimap<String, String> patternPairMap = HashMultimap.create();
    if (StringUtils.isNotBlank(publishedItemsPropertyValue)) {

        List<String> patternPairs = parsePatternsFromProperty(publishedItemsPropertyValue);
        for (String patternPair : patternPairs) {

            String[] splitPattern = patternPair.split("=>");

            String sourcePattern = "";
            String targetPattern = "";

            if (splitPattern.length > 0) {
                sourcePattern = FilenameUtils.separatorsToUnix(splitPattern[0].trim());
            }

            // We allow an empty target, in that case it will be ""
            if (splitPattern.length > 1) {
                targetPattern = FilenameUtils.separatorsToUnix(splitPattern[1].trim());
            }

            if (StringUtils.isNotBlank(sourcePattern)) {
                patternPairMap.put(sourcePattern, targetPattern);
            }
        }
    }
    return patternPairMap;
}

From source file:org.jfrog.build.extractor.clientConfiguration.util.PublishedItemsHelper.java

/**
 * Calculates the target deployment path of an artifact by it's name
 *
 * @param targetPattern an Ant pattern of the target path
 * @param artifactFile  the artifact file to calculate target deployment path for
 * @return the calculated target path//from  w  w w .ja  v a2 s  .c  om
 */
public static String calculateTargetPath(String targetPattern, File artifactFile) {
    String relativePath = calculateTargetRelativePath(artifactFile);
    if (relativePath == null) {
        throw new IllegalArgumentException("Cannot calculate a target path given a null relative path.");
    }

    if (StringUtils.isBlank(targetPattern)) {
        return relativePath;
    }

    relativePath = FilenameUtils.separatorsToUnix(relativePath);
    targetPattern = FilenameUtils.separatorsToUnix(targetPattern);

    // take care of absolute path
    if (StringUtils.startsWith(targetPattern, "/")) {
        return targetPattern + "/" + artifactFile.getName();
    }

    // take care of relative paths with patterns.
    StringBuilder itemPathBuilder = new StringBuilder();

    String[] targetTokens = targetPattern.split("/");

    boolean addedRelativeParent = false;
    for (int i = 0; i < targetTokens.length; i++) {

        boolean lastToken = (i == (targetTokens.length - 1));

        String targetToken = targetTokens[i];

        if ("**".equals(targetToken)) {
            if (!lastToken) {
                String relativeParentPath = FilenameUtils.getPathNoEndSeparator(relativePath);
                itemPathBuilder.append(relativeParentPath);
                addedRelativeParent = true;
            } else {
                itemPathBuilder.append(relativePath);
            }
        } else if (targetToken.startsWith("*.")) {
            String newFileName = FilenameUtils.removeExtension(FilenameUtils.getName(relativePath))
                    + targetToken.substring(1);
            itemPathBuilder.append(newFileName);
        } else if ("*".equals(targetToken)) {
            itemPathBuilder.append(FilenameUtils.getName(relativePath));
        } else {
            if (StringUtils.isNotBlank(targetToken)) {
                itemPathBuilder.append(targetToken);
            }
            if (lastToken) {
                if (itemPathBuilder.length() > 0) {
                    itemPathBuilder.append("/");
                }
                if (addedRelativeParent) {
                    itemPathBuilder.append(FilenameUtils.getName(relativePath));
                } else {
                    itemPathBuilder.append(relativePath);
                }
            }
        }

        if (!lastToken) {
            itemPathBuilder.append("/");
        }
    }
    return itemPathBuilder.toString();
}

From source file:org.jfrog.build.extractor.clientConfiguration.util.PublishedItemsHelper.java

private static String calculateTargetRelativePath(File artifactFile) {
    String relativePath = artifactFile.getAbsolutePath();
    String parentDir = artifactFile.getParent();
    if (!StringUtils.isBlank(parentDir)) {
        relativePath = StringUtils.removeStart(artifactFile.getAbsolutePath(), parentDir);
    }/*  w  ww  . j  a va 2 s.  c  o  m*/
    relativePath = FilenameUtils.separatorsToUnix(relativePath);
    relativePath = StringUtils.removeStart(relativePath, "/");
    return relativePath;
}