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

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

Introduction

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

Prototype

public static String normalizeNoEndSeparator(String filename) 

Source Link

Document

Normalizes a path, removing double and single dot path steps, and removing any final directory separator.

Usage

From source file:org.jwebsocket.plugins.tts.SpeakAloudProvider.java

public void setTextPath(String aTextPath) {
    // is only working under Windows!
    mTextPath = FilenameUtils.normalizeNoEndSeparator(aTextPath) + "\\";
}

From source file:org.larz.dom4.editor.ResourceUtils.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
 * '\'./*w w  w.  j a  v a2  s . co  m*/
 * 
 * @param targetPath targetPath is calculated to this file
 * @param basePath basePath is calculated from this file
 * @param pathSeparator 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.
    StringBuffer common = new StringBuffer();

    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;
    }

    StringBuffer relative = new StringBuffer();

    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:org.nuxeo.ecm.platform.importer.properties.MetadataCollector.java

public void addProperties(String contextPath, Map<String, Serializable> collectedProperties) {
    try {/*from   w w w  .ja  v  a2 s  .com*/
        lock.writeLock().lock();
        contextPath = FilenameUtils.normalizeNoEndSeparator(contextPath);
        if (staticInherit) {
            File file = new File(contextPath);
            while (!StringUtils.isEmpty(file.getParent())) {
                file = file.getParentFile();
                Map<String, Serializable> parentProperties = collectedMetadata.get(file.toString());
                if (parentProperties != null) {
                    for (String name : parentProperties.keySet()) {
                        if (!collectedProperties.containsKey(name)) {
                            collectedProperties.put(name, parentProperties.get(name));
                        }
                    }
                }
            }
        }
        collectedMetadata.put(contextPath, collectedProperties);
    } finally {
        lock.writeLock().unlock();
    }

}

From source file:org.nuxeo.ecm.platform.importer.properties.MetadataCollector.java

public Map<String, Serializable> getProperties(String contextPath) {

    contextPath = FilenameUtils.normalizeNoEndSeparator(contextPath);

    try {//  w ww  .  j a  v  a  2 s .co m
        lock.readLock().lock();
        Map<String, Serializable> props = collectedMetadata.get(contextPath);

        if (props == null) {
            File file = new File(contextPath);
            while (props == null && !StringUtils.isEmpty(file.getParent())) {
                file = file.getParentFile();
                props = collectedMetadata.get(file.getPath().toString());
            }
        }

        if (props != null) {
            props = Collections.unmodifiableMap(props);
        }
        return props;
    } finally {
        lock.readLock().unlock();
    }
}

From source file:org.openehealth.ipf.commons.lbs.store.DiskStore.java

private void ensureDirectoriesExist(File file) {
    File parentDir = file.getParentFile();
    String baseDirPath = fileSystemLayout.getBaseDir().getAbsolutePath();
    baseDirPath = FilenameUtils.normalizeNoEndSeparator(baseDirPath);
    String parentDirPath = parentDir.getAbsolutePath();
    parentDirPath = FilenameUtils.normalizeNoEndSeparator(parentDirPath);
    if (FilenameUtils.equalsOnSystem(parentDirPath, baseDirPath)) {
        return;// w  ww  .  j a v  a  2 s. co  m
    }

    if (!parentDir.mkdirs()) {
        throw new ResourceIOException(
                "Unable to create directory: parentDir=" + parentDirPath + ", baseDir=" + baseDirPath);
    }
}

From source file:org.openoffice.maven.Environment.java

/**
 * Guess office home from search path./* ww w .j  ava2 s.com*/
 * This method has default visibility for testing.
 *
 * @param path the path
 * @return the file
 */
static File guessOfficeHomeFromPATH(String path) {
    String[] pathElements = StringUtils.split(path, File.pathSeparatorChar);
    String baseDirName = getBaseDirName();
    for (int i = 0; i < pathElements.length; i++) {
        String pathname = FilenameUtils.separatorsToUnix(pathElements[i]);
        pathname = FilenameUtils.normalizeNoEndSeparator(pathname);
        int n = pathname.lastIndexOf(baseDirName);
        if (n > 0) {
            return new File(pathname.substring(0, n));
        }
    }
    return null;
}

From source file:org.ownchan.server.joint.init.InitHelper.java

public static void checkRequiredOwnchanServerSystemProperties() {
    String confDir = FilenameUtils.normalizeNoEndSeparator(System.getProperty(PROPERTY_CONF_DIR));
    String logDir = FilenameUtils.normalizeNoEndSeparator(System.getProperty(PROPERTY_LOG_DIR));

    requireParam(PROPERTY_CONF_DIR, confDir);
    requireParam(PROPERTY_LOG_DIR, logDir);

    System.setProperty(PROPERTY_CONF_DIR, confDir);
    System.setProperty(PROPERTY_LOG_DIR, logDir);
}

From source file:org.panbox.desktop.common.gui.PanboxClientGUI.java

private void settingsApplyButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_settingsApplyButtonActionPerformed

    Settings s = Settings.getInstance();
    boolean restartRequired = false;
    String selLang = ((SupportedLanguage) languageComboBox.getSelectedItem()).getShorthand();
    if (!selLang.equals(s.getLanguage())) {
        s.setLanguage(selLang);//from w ww  .j  a  va 2 s  . c om
        // client.restartTrayIcon();
        restartRequired = true;
    }

    if (!(expertModeCheckBox.isSelected() == s.getExpertMode())) {
        s.setExpertMode(expertModeCheckBox.isSelected());
    }

    if (!(uriHandlerCheckbox.isSelected() == s.isUriHandlerSupported())) {
        s.setUriHandlerSupported(uriHandlerCheckbox.isSelected());
        restartRequired = true;
    }

    if (uriHandlerCheckbox.isSelected()
            && !(clipboardHandlerCheckbox.isSelected() == s.isClipboardHandlerSupported())) {
        s.setClipboardHandlerSupported(clipboardHandlerCheckbox.isSelected());
        restartRequired = true;
    }

    if (!(mailtoSchemeCheckbox.isSelected() == s.isMailtoSchemeSupported())) {
        s.setMailtoSchemeSupported(mailtoSchemeCheckbox.isSelected());
        restartRequired = true;
    }

    File newConfDir = new File(settingsFolderTextField.getText());
    File oldConfDir = new File(s.getConfDir());
    if (!FilenameUtils.equalsNormalizedOnSystem(newConfDir.getAbsolutePath(), oldConfDir.getAbsolutePath())) {
        if (newConfDir.exists()) {
            s.setConfDir(FilenameUtils.normalizeNoEndSeparator(newConfDir.getAbsolutePath()));
            client.settingsFolderChanged(newConfDir);
        } else {
            JOptionPane.showMessageDialog(this, bundle.getString("client.settings.panboxConfDirNotExisting"));
            settingsFolderTextField.setText(s.getConfDir());
        }
    }

    // If this is not true currently no IP-Address is available. So use the
    // current one.
    if (networkAddressComboBox.getModel().getSelectedItem() instanceof InetAddress) {
        InetAddress address = (InetAddress) networkAddressComboBox.getModel().getSelectedItem();
        s.setPairingAddress(address);
    }

    // save csp specific settings
    if (selectedCSPContentPanel.getComponentCount() > 0) {
        Component c = selectedCSPContentPanel.getComponent(0);
        if ((c != null) && (c instanceof Flushable)) {
            try {
                ((Flushable) c).flush();
            } catch (IOException e) {
                logger.error("Error flushing csp settings config panel!", e);
            }
        } else {
            logger.error("Invalid csp content panel content!");
        }
    }

    String newPath = panboxFolderTextField.getText();
    String oldPath = s.getMountDir();
    if (!FilenameUtils.equalsNormalizedOnSystem(newPath, oldPath)) {
        s.setMountDir(newPath);
        // client.panboxFolderChanged(newPath);
        restartRequired = true;
    }

    if (restartRequired) {
        int ret = JOptionPane.showConfirmDialog(this, bundle.getString("PanboxClientGUI.restartMessage"),
                bundle.getString("PanboxClientGUI.restartMessage.title"), JOptionPane.YES_NO_OPTION);
        try {
            if (ret == JOptionPane.YES_OPTION) {
                client.restartApplication();
            }
        } catch (IOException e) {
            logger.error("Error while restarting the appication!", e);
            JOptionPane.showMessageDialog(this, bundle.getString("PanboxClientGUI.restartError"),
                    bundle.getString("error"), JOptionPane.ERROR_MESSAGE);
        }
    }

    // reset the buttons
    resetSettingsApplyDiscardButtons();

}

From source file:org.pentaho.cdf.context.ContextEngine.java

protected JSONObject buildLegacyStructure(final JSONObject contextObj, String path,
        SecurityParameterProvider securityParams) throws JSONException {

    logger.warn("CDF: using legacy structure for Dashboard.context; "
            + "this is a deprecated structure and should not be used. This is a configurable option via plugin's settings"
            + ".xml");

    if (securityParams != null) {
        contextObj.put("isAdmin",
                Boolean.valueOf((String) securityParams.getParameter("principalAdministrator")));
    }//  w ww .j av  a2s  .com

    if (!StringUtils.isEmpty(path)) {

        if (!contextObj.has(Parameter.FULL_PATH)) {
            contextObj.put(Parameter.FULL_PATH, path); // create fullPath ctx attribute
        }

        // now parse full path into legacy structure of solution, path, file

        if (path.startsWith(String.valueOf(RepositoryHelper.SEPARATOR))) {
            path = path.replaceFirst(String.valueOf(RepositoryHelper.SEPARATOR), StringUtils.EMPTY);
        }

        // we must determine if this is a full path to a folder or to a file
        boolean isPathToFile = !StringUtils.isEmpty(FilenameUtils.getExtension(path));

        if (isPathToFile) {
            contextObj.put(Parameter.FILE, FilenameUtils.getName(path)); // create file ctx attribute
            path = path.replace(FilenameUtils.getName(path), StringUtils.EMPTY); // remove and continue on
        }

        path = FilenameUtils.normalizeNoEndSeparator(path);

        String[] parsedPath = path.split(String.valueOf(RepositoryHelper.SEPARATOR));

        if (parsedPath.length == 0) {

            contextObj.put(Parameter.SOLUTION, StringUtils.EMPTY); // create solution ctx attribute
            contextObj.put(Parameter.PATH, StringUtils.EMPTY); // create path ctx attribute

        } else if (parsedPath.length == 1) {

            contextObj.put(Parameter.SOLUTION, parsedPath[0]); // create solution ctx attribute
            contextObj.put(Parameter.PATH, StringUtils.EMPTY); // create path ctx attribute

        } else {

            contextObj.put(Parameter.SOLUTION, parsedPath[0]); // create solution ctx attribute
            path = path.replace(FilenameUtils.getName(parsedPath[0]), StringUtils.EMPTY); // remove and continue on
            path = path.replaceFirst(String.valueOf(RepositoryHelper.SEPARATOR), StringUtils.EMPTY);
            contextObj.put(Parameter.PATH, path); // create path ctx attribute
        }
    }

    return contextObj;
}

From source file:org.sourcepit.common.utils.path.PathUtils.java

public static String normalize(String targetPath, String pathSeparator) {
    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);

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

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

    } else {/*from w w  w .  j  a va 2  s.c  o m*/
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }
    return normalizedTargetPath;
}