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

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

Introduction

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

Prototype

public static String normalize(String filename) 

Source Link

Document

Normalizes a path, removing double and single dot path steps.

Usage

From source file:com.enderville.enderinstaller.util.InstallScript.java

/**
 * Make backup copies of important files/folders in case the backup fails.
 *
 * @throws IOException/*w ww .  j av a2 s .co  m*/
 */
private static void createBackup() throws IOException {
    //TODO what other folders to backup?
    FileUtils.copyFile(new File(InstallerConfig.getMinecraftJar()),
            new File(InstallerConfig.getMinecraftJar() + ".backup"));
    File mods = new File(InstallerConfig.getMinecraftModsFolder());
    File modsBackup = new File(InstallerConfig.getMinecraftModsFolder() + "_backup/");
    if (modsBackup.exists()) {
        FileUtils.deleteDirectory(modsBackup);
    }
    if (mods.exists()) {
        FileUtils.copyDirectory(mods, modsBackup);
    }

    for (String name : otherThingsToBackup) {
        String fname = FilenameUtils
                .normalize(FilenameUtils.concat(InstallerConfig.getMinecraftFolder(), name));
        String fnameBackup = fname + "_backup";
        File f = new File(fname);
        File backup = new File(fnameBackup);
        if (backup.exists()) {
            FileUtils.deleteDirectory(backup);
        }
        if (f.exists()) {
            FileUtils.copyDirectory(f, backup);
        }
    }
}

From source file:net.grinder.engine.agent.PropertyBuilder.java

private String getPath(File file, boolean useAbsolutePath) {
    return useAbsolutePath ? FilenameUtils.normalize(file.getAbsolutePath()) : file.getPath();
}

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  a  va2 s  . 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:com.ariht.maven.plugins.config.generator.ConfigGeneratorImpl.java

/**
 * Prepare output io: base-path/filter-sub-dir/template-dir/template.name
 *///from  w w w . java 2  s. c o  m
private String createOutputDirectory(final FileInfo template, final FileInfo filter,
        final String outputBasePath) throws IOException {
    final String outputDirectory = getOutputPath(template, filter, outputBasePath);
    final File outputDir = new File(outputDirectory);
    if (!outputDir.exists()) {
        log.debug("Creating : " + outputDir);
        FileUtils.forceMkdir(outputDir);
    }
    return FilenameUtils.normalize(outputDirectory);
}

From source file:com.iyonger.apm.web.configuration.Config.java

/**
 * Resolve nGrinder extended home path.// w  w w. jav a2 s  .  c  o  m
 *
 * @return resolved home
 */
protected Home resolveExHome() {
    String exHomeFromEnv = System.getenv("NGRINDER_EX_HOME");
    String exHomeFromProperty = System.getProperty("ngrinder.ex_home");
    if (!StringUtils.equals(exHomeFromEnv, exHomeFromProperty)) {
        CoreLogger.LOGGER.warn("The path to ngrinder ex home is ambiguous:");
        CoreLogger.LOGGER.warn("    System Environment:  NGRINDER_EX_HOME=" + exHomeFromEnv);
        CoreLogger.LOGGER.warn("    Java System Property:  ngrinder.ex_home=" + exHomeFromProperty);
        CoreLogger.LOGGER.warn("    '" + exHomeFromProperty + "' is accepted.");
    }
    String userHome = StringUtils.defaultIfEmpty(exHomeFromProperty, exHomeFromEnv);

    if (StringUtils.isEmpty(userHome)) {
        userHome = System.getProperty("user.home") + File.separator + NGRINDER_EX_FOLDER;
    } else if (StringUtils.startsWith(userHome, "~" + File.separator)) {
        userHome = System.getProperty("user.home") + File.separator + userHome.substring(2);
    } else if (StringUtils.startsWith(userHome, "." + File.separator)) {
        userHome = System.getProperty("user.dir") + File.separator + userHome.substring(2);
    }

    userHome = FilenameUtils.normalize(userHome);
    File exHomeDirectory = new File(userHome);
    CoreLogger.LOGGER.info("nGrinder ex home directory:{}.", exHomeDirectory);
    try {
        //noinspection ResultOfMethodCallIgnored
        exHomeDirectory.mkdirs();
    } catch (Exception e) {
        // If it's not possible.. do it... without real directory.
        noOp();
    }
    return new Home(exHomeDirectory, false);
}

From source file:com.enderville.enderinstaller.util.InstallScript.java

/**
 * If the install fails, restore everything that we backed up.
 *
 * @throws IOException//from   w  w w  .  j ava  2 s.  c  o m
 */
private static void restoreBackup() throws IOException {
    //TODO what other folders to restore?
    FileUtils.copyFile(new File(InstallerConfig.getMinecraftJar() + ".backup"),
            new File(InstallerConfig.getMinecraftJar()));
    File mods = new File(InstallerConfig.getMinecraftModsFolder());
    File modsBackup = new File(InstallerConfig.getMinecraftModsFolder() + "_backup");
    if (modsBackup.exists()) {
        FileUtils.deleteDirectory(mods);
        FileUtils.copyDirectory(modsBackup, mods);
    }
    for (String name : otherThingsToBackup) {
        String fname = FilenameUtils
                .normalize(FilenameUtils.concat(InstallerConfig.getMinecraftFolder(), name));
        String fnameBackup = fname + "_backup";
        File f = new File(fname);
        File backup = new File(fnameBackup);
        if (backup.exists()) {
            FileUtils.copyDirectory(backup, f);
        }
    }
}

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

/**
 * Concatenate filter io with template io
 *///from   w w w.  j  a  va2 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:ddf.content.provider.filesystem.FileSystemProvider.java

public void setBaseContentDirectory(final String baseDirectory) {
    String newBaseDir = "";

    if (!baseDirectory.isEmpty()) {
        String path = FilenameUtils.normalize(baseDirectory);
        File directory = new File(path);

        // Create the directory if it doesn't exist
        if ((!directory.exists() && directory.mkdirs()) || (directory.isDirectory() && directory.canRead())) {
            LOGGER.info("Setting base content directory to: " + path);
            newBaseDir = path;/*from ww w  .  jav  a 2 s .c  om*/
        }
    }

    // if invalid baseDirectory was provided or baseDirectory is
    // an empty string, default to the DEFAULT_CONTENT_REPOSITORY in <karaf.home>
    if (newBaseDir.isEmpty()) {
        try {
            final File karafHomeDir = new File(System.getProperty("karaf.home"));

            if (karafHomeDir.isDirectory()) {
                final File fspDir = new File(karafHomeDir + File.separator + DEFAULT_CONTENT_REPOSITORY);

                // if directory does not exist, try to create it
                if (fspDir.isDirectory() || fspDir.mkdirs()) {
                    LOGGER.info("Setting base content directory to: " + fspDir.getAbsolutePath());
                    newBaseDir = fspDir.getAbsolutePath();
                } else {
                    LOGGER.warn("Unable to create FileSystemProvider folder: " + fspDir.getAbsolutePath()
                            + ". Please check that DDF has permissions to create this folder.  Using default folder.");
                }
            } else {
                LOGGER.warn(
                        "Karaf home folder defined by system property karaf.home is not a directory.  Using default folder.");
            }
        } catch (NullPointerException npe) {
            LOGGER.warn(
                    "Unable to create FileSystemProvider folder - karaf.home system property not defined. Using default folder.");
        }
    }

    this.baseContentDirectory = newBaseDir;

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Set base content directory to: " + this.baseContentDirectory);
    }
}

From source file:ch.unibas.fittingwizard.presentation.fitting.FitResultPage.java

private File selectExportDirectory() {
    DirectoryChooser dirChooser = new DirectoryChooser();
    dirChooser.setTitle("Fit export destination");
    // wrapping is necessary, since directory chooser can not handle some paths.
    // maybe the problem are not normalized paths...
    File defaultExportDir = new File(
            FilenameUtils.normalize(exportFitWorkflow.getDefaultExportDir().getAbsolutePath()));
    defaultExportDir.mkdir();//from ww w .  j a  v  a  2 s  .co  m
    logger.debug("defaultExportDir=" + FilenameUtils.normalize(defaultExportDir.getAbsolutePath()));
    dirChooser.setInitialDirectory(defaultExportDir);
    File file = dirChooser.showDialog(this.getScene().getWindow());
    return file;
}

From source file:egovframework.com.utl.sys.fsm.service.FileSystemUtils.java

/**
 * Find free space on the *nix platform using the 'df' command.
 *
 * @param path  the path to get free space for
 * @param kb  whether to normalize to kilobytes
 * @param posix  whether to use the posix standard format flag
 * @return the amount of free drive space on the volume
 * @throws IOException if an error occurs
 *///ww  w.j a v a 2 s.  co m
long freeSpaceUnix(String path, boolean kb, boolean posix) throws IOException {
    if (path.length() == 0) {
        throw new IllegalArgumentException("Path must not be empty");
    }
    path = FilenameUtils.normalize(path);

    String osName = System.getProperty("os.name");

    // build and run the 'dir' command
    String flags = "-";
    if (kb && osName.indexOf("hp-ux") == -1) {
        flags += "k";
    }
    if (posix && osName.indexOf("hp-ux") == -1) {
        flags += "P";
    }

    String dfCommand = "df";

    if (osName.indexOf("hp-ux") != -1) {
        dfCommand = "bdf";
    }

    String[] cmdAttribs = (flags.length() > 1 ? new String[] { dfCommand, flags, path }
            : new String[] { dfCommand, path });

    // perform the command, asking for up to 3 lines (header, interesting, overflow)
    List lines = performCommand(cmdAttribs, 3);
    if (lines.size() < 2) {
        // unknown problem, throw exception
        throw new IOException("Command line 'df' did not return info as expected " + "for path '" + path
                + "'- response was " + lines);
    }
    String line2 = (String) lines.get(1); // the line we're interested in

    // Now, we tokenize the string. The fourth element is what we want.
    StringTokenizer tok = new StringTokenizer(line2, " ");
    if (tok.countTokens() < 4) {
        // could be long Filesystem, thus data on third line
        if (tok.countTokens() == 1 && lines.size() >= 3) {
            String line3 = (String) lines.get(2); // the line may be interested in
            tok = new StringTokenizer(line3, " ");
        } else {
            throw new IOException("Command line 'df' did not return data as expected " + "for path '" + path
                    + "'- check path is valid");
        }
    } else {
        tok.nextToken(); // Ignore Filesystem
    }
    tok.nextToken(); // Ignore 1K-blocks
    tok.nextToken(); // Ignore Used
    String freeSpace = tok.nextToken();
    return parseBytes(freeSpace, path);
}