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.apporiented.hermesftp.usermanager.model.PermissionData.java

private String replacePlaceholders(String ftproot, String username) throws FtpConfigException {
    VarMerger varMerger = new VarMerger(getTemplate());
    Properties props = new Properties();
    props.setProperty("ftproot", FilenameUtils.separatorsToUnix(ftproot));
    props.setProperty("user", username);
    varMerger.merge(props);/*from  w  ww.  ja  v  a  2s  .  c o  m*/
    if (!varMerger.isReplacementComplete()) {
        throw new FtpConfigException("Unresolved placeholders in user configuration file found.");
    }
    return varMerger.getText();
}

From source file:cz.hobrasoft.pdfmu.operation.signature.SslKeystore.java

/**
 * Set the system properties that configure this SSL keystore.
 *
 * @param file the keystore file/*from w  ww  .j  av a  2  s  . c  om*/
 * @param type the type of the keystore
 * @param password the password of the keystore
 * @throws OperationException if the keystore file does not exist
 */
public void setSystemProperties(File file, String type, String password) throws OperationException {
    if (file != null) {
        // https://access.redhat.com/documentation/en-US/Fuse_MQ_Enterprise/7.1/html/Security_Guide/files/SSL-SysProps.html
        // > On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.
        String location = FilenameUtils.separatorsToUnix(file.getPath());
        if (!file.exists()) {
            throw new OperationException(errorTypeNotFound,
                    new AbstractMap.SimpleEntry<String, Object>("location", location));
        }
        LOGGER.info(String.format("%s: Configuring to use the keystore file %s.", name, location));
        System.setProperty(keyLocation, location);
    }

    if (type != null) {
        if (file == null) {
            LOGGER.warning(String.format("%s: Type has been specified but location has not.", name));
        }
        // TODO: Warn if `file` extension is inconsistent with `type`
        System.setProperty(keyType, type);
    }

    if (password != null) {
        if (file == null) {
            LOGGER.warning(String.format("%s: Password has been specified but location has not.", name));
        }
        System.setProperty(keyPassword, password);
    }
}

From source file:com.sap.prd.mobile.ios.mios.FileUtils.java

/**
 * Get the relative path from one file to another, specifying the directory separator. If one of
 * the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
 * '\'.//from   w w w .  j a  v  a2s  .com
 * 
 * Copied from http://stackoverflow.com/a/3054692/933106.
 * 
 * @param target
 *          targetPath is calculated to this file
 * @param base
 *          basePath is calculated from this file
 * @param separator
 *          directory separator. The platform default is not assumed so that we can test Unix
 *          behaviour when running on Windows (for example)
 * @return
 */
public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {

    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new PathResolutionException("No common path element found for '" + normalizedTargetPath
                + "' and '" + normalizedBasePath + "'");
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    // 
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append(".." + pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:com.consol.citrus.admin.service.TestCaseServiceImpl.java

@Override
public List<TestCaseData> getTests(Project project) {
    List<TestCaseData> tests = new ArrayList<TestCaseData>();

    List<File> testFiles = FileUtils.getTestFiles(getTestDirectory(project));
    for (File file : testFiles) {
        String testName = FilenameUtils.getBaseName(file.getName());
        String testPackageName = file.getPath().substring(getTestDirectory(project).length(),
                file.getPath().length() - file.getName().length()).replace(File.separatorChar, '.');

        if (testPackageName.endsWith(".")) {
            testPackageName = testPackageName.substring(0, testPackageName.length() - 1);
        }/*from w  w w . j a v  a  2s. c om*/

        TestCaseData testCase = new TestCaseData();
        testCase.setType(TestCaseType.XML);
        testCase.setName(testName);
        testCase.setPackageName(testPackageName);
        testCase.setFile(file.getParentFile().getAbsolutePath() + File.separator
                + FilenameUtils.getBaseName(file.getName()));
        testCase.setLastModified(file.lastModified());

        tests.add(testCase);
    }

    try {
        Resource[] javaSources = new PathMatchingResourcePatternResolver().getResources(
                "file:" + FilenameUtils.separatorsToUnix(getJavaDirectory(project)) + "**/*.java");

        for (Resource resource : javaSources) {
            File file = resource.getFile();
            String testName = FilenameUtils.getBaseName(file.getName());
            String testPackage = file.getParentFile().getAbsolutePath()
                    .substring(getJavaDirectory(project).length()).replace(File.separatorChar, '.');

            if (knownToClasspath(testPackage, testName)) {
                tests.addAll(getTestCaseInfoFromClass(testPackage, testName, file));
            } else {
                tests.addAll(getTestCaseInfoFromFile(testPackage, testName, file));
            }
        }
    } catch (IOException e) {
        log.warn("Failed to read Java source files - list of test cases for this project is incomplete", e);
    }

    return tests;
}

From source file:com.thoughtworks.go.publishers.GoArtifactsManipulator.java

public void publish(DefaultGoPublisher goPublisher, String destPath, File source, JobIdentifier jobIdentifier) {
    if (!source.exists()) {
        String message = "Failed to find " + source.getAbsolutePath();
        goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message);
        bomb(message);//from   w  ww  .j av a2s  .  c  o m
    }

    int publishingAttempts = 0;
    Throwable lastException = null;
    while (publishingAttempts < PUBLISH_MAX_RETRIES) {
        File tmpDir = null;
        try {
            publishingAttempts++;

            tmpDir = FileUtil.createTempFolder();
            File dataToUpload = new File(tmpDir, source.getName() + ".zip");
            zipUtil.zip(source, dataToUpload, Deflater.BEST_SPEED);

            long size = 0;
            if (source.isDirectory()) {
                size = FileUtils.sizeOfDirectory(source);
            } else {
                size = source.length();
            }

            goPublisher.taggedConsumeLineWithPrefix(PUBLISH,
                    "Uploading artifacts from " + source.getAbsolutePath() + " to " + getDestPath(destPath));

            String normalizedDestPath = FilenameUtils.separatorsToUnix(destPath);
            String url = urlService.getUploadUrlOfAgent(jobIdentifier, normalizedDestPath, publishingAttempts);

            int statusCode = httpService.upload(url, size, dataToUpload,
                    artifactChecksums(source, normalizedDestPath));

            if (statusCode == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) {
                String message = String.format(
                        "Artifact upload for file %s (Size: %s) was denied by the server. This usually happens when server runs out of disk space.",
                        source.getAbsolutePath(), size);
                goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message);
                LOGGER.error(
                        "[Artifact Upload] Artifact upload was denied by the server. This usually happens when server runs out of disk space.");
                publishingAttempts = PUBLISH_MAX_RETRIES;
                bomb(message + ".  HTTP return code is " + statusCode);
            }
            if (statusCode < HttpServletResponse.SC_OK
                    || statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES) {
                bomb("Failed to upload " + source.getAbsolutePath() + ".  HTTP return code is " + statusCode);
            }
            return;
        } catch (Throwable e) {
            String message = "Failed to upload " + source.getAbsolutePath();
            LOGGER.error(message, e);
            goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message);
            lastException = e;
        } finally {
            FileUtils.deleteQuietly(tmpDir);
        }
    }
    if (lastException != null) {
        throw new RuntimeException(lastException);
    }
}

From source file:com.geewhiz.pacify.commandline.TestPreConfigure.java

@Test
public void testPreConfigure() throws IOException {
    File testResourceFolder = new File("src/test/resources/testPreConfigure");
    File targetResourceFolder = new File("target/test-resources/testPreConfigure");

    TestUtil.removeOldTestResourcesAndCopyAgain(testResourceFolder, targetResourceFolder);

    File myTestProperty = new File(targetResourceFolder, "properties/myTest.properties");
    File myPackagePath = new File(targetResourceFolder, "package");
    File myExpectedResultPath = new File(targetResourceFolder, "expectedResult");

    ListAppender listAppender = TestUtil.addListAppenderToLogger();

    PacifyViaCommandline pacifyViaCommandline = new PacifyViaCommandline();

    int result = pacifyViaCommandline.mainInternal(new String[] { "--info", "preConfigure",
            "--resolvers=FileResolver", "--packagePath=" + myPackagePath.getAbsolutePath(),
            "-RFileResolver.file=" + myTestProperty.getAbsolutePath() });

    Assert.assertEquals("Configuration returned with errors.", 0, result);
    TestUtil.checkIfResultIsAsExpected(myPackagePath, myExpectedResultPath);

    String[] output = listAppender.getLogMessages().toArray(new String[0]);
    String[] expect = { ".*== Executing PreConfigure \\[Version=.*",
            ".*commandline/target/test-resources/testPreConfigure/package\\]",
            "== Found \\[3\\] pacify marker files", "== Validating...",
            ".*commandline/target/test-resources/testPreConfigure/package/parent-CMFile.pacify\\]",
            ".*commandline/target/test-resources/testPreConfigure/package/folder/folder1-CMFile.pacify\\]",
            ".*commandline/target/test-resources/testPreConfigure/package/folder/folder2-CMFile.pacify\\]",
            "== Replacing...",
            ".*commandline/target/test-resources/testPreConfigure/package/parent-CMFile.pacify\\]",
            "      Customize File \\[someParentConf.conf\\]", "          \\[2\\] placeholders replaced.",
            ".*commandline/target/test-resources/testPreConfigure/package/folder/folder1-CMFile.pacify\\]",
            "      Customize File \\[someFolderConf.conf\\]", "          \\[1\\] placeholders replaced.",
            "      Customize File \\[subfolder/someSubFolderConf.conf\\]",
            "          \\[0\\] placeholders replaced.",
            ".*commandline/target/test-resources/testPreConfigure/package/folder/folder2-CMFile.pacify\\]",
            "      Customize File \\[anotherFolderConf.conf\\]", "          \\[1\\] placeholders replaced.",
            "== Properties which are not resolved \\[2\\] ...", "   foo", "   foobar3",
            "== Successfully finished" };

    Assert.assertThat(output.length, is(expect.length));

    for (int i = 0; i < output.length; i++) {
        String outputLine = FilenameUtils.separatorsToUnix(output[i]);
        String expectedLine = expect[i];
        Assert.assertThat(outputLine, RegexMatcher.matchesRegex(expectedLine));
    }// w w w  .ja  v  a  2 s  .  co m
}

From source file:de.undercouch.vertx.lang.typescript.TestExamplesRunner.java

private void getAllJavaScriptFiles(File dir, List<File> result) {
    File[] files = dir.listFiles();
    for (File f : files) {
        if (dirsToSkip != null && dirsToSkip.contains(f.getName())) {
            continue;
        }/*from  w ww.j a  v a 2s .  c  o  m*/

        if (f.isDirectory()) {
            getAllJavaScriptFiles(f, result);
        } else {
            if (f.getName().toLowerCase().endsWith(".js")) {
                if (filesToSkip == null
                        || !containsEndsWith(filesToSkip, FilenameUtils.separatorsToUnix(f.getPath()))) {
                    result.add(f);
                }
            }
        }
    }
}

From source file:com.googlecode.fascinator.common.storage.StorageUtils.java

/**
 * This method stores a File as a DigitalObject into the specified Storage.
 * The File can be stored as a linked Payload if specified.
 * /*from  w ww  .  j av a  2s  .  c  om*/
 * @param storage a Storage instance
 * @param file the File to store
 * @param linked set true to link to the original file, false to copy
 * @return a DigitalObject
 * @throws StorageException if there was an error storing the file
 */
public static DigitalObject storeFile(Storage storage, File file, boolean linked) throws StorageException {
    DigitalObject object = null;
    Payload payload = null;
    String oid = generateOid(file);
    String pid = generatePid(file);
    try {
        try {
            object = getDigitalObject(storage, oid);
            if (linked) {
                try {
                    String path = FilenameUtils.separatorsToUnix(file.getAbsolutePath());
                    payload = createLinkedPayload(object, pid, path);
                } catch (StorageException se) {
                    payload = object.getPayload(pid);
                }
            } else {
                payload = createOrUpdatePayload(object, pid, new FileInputStream(file));
            }
        } catch (StorageException se) {
            throw se;
        }
    } catch (FileNotFoundException fnfe) {
        throw new StorageException("File not found '" + oid + "'");
    } finally {
        if (payload != null) {
            payload.close();
        }
    }
    return object;
}

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

/**
 * Mthode compressant un dossier de faon rcursive au format zip.
 *
 * @param folderToZip - dossier  compresser
 * @param zipFile - fichier zip  creer/*from   w w w  . j av a2s  .co  m*/
 * @return la taille du fichier zip gnr en octets
 * @throws FileNotFoundException
 * @throws IOException
 */
public static long compressPathToZip(File folderToZip, File zipFile) throws IOException {
    ZipArchiveOutputStream zos = null;
    try {
        // cration du flux zip
        zos = new ZipArchiveOutputStream(new FileOutputStream(zipFile));
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding(CharEncoding.UTF_8);
        Collection<File> folderContent = FileUtils.listFiles(folderToZip, null, true);
        for (File file : folderContent) {
            String entryName = file.getPath().substring(folderToZip.getParent().length() + 1);
            entryName = FilenameUtils.separatorsToUnix(entryName);
            zos.putArchiveEntry(new ZipArchiveEntry(entryName));
            InputStream in = new FileInputStream(file);
            IOUtils.copy(in, zos);
            zos.closeArchiveEntry();
            IOUtils.closeQuietly(in);
        }
    } finally {
        if (zos != null) {
            IOUtils.closeQuietly(zos);
        }
    }
    return zipFile.length();
}

From source file:au.org.ala.delta.translation.naturallanguage.HtmlNaturalLanguageTranslator.java

private String imageFileName(Image image) {
    String imageFile = image.getFileName();
    File imageFilePath = new File(new File(_outputFileSelector.getImageDirectory()), imageFile);
    // Using unix file separators instead of system here because we are producing a html URL.
    return FilenameUtils.separatorsToUnix(imageFilePath.getPath());
}