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, boolean unixSeparator) 

Source Link

Document

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

Usage

From source file:com.iyonger.apm.web.repository.FileEntryRepository.java

/**
 * Return all {@link FileEntry}s under the given path.
 *
 * @param user      user/*from  w  ww  .  j av a 2s .  co  m*/
 * @param path      path under which files are searched.
 * @param revision  null if head.
 * @param recursive true if recursive finding
 * @return found {@link FileEntry}s
 */
public List<FileEntry> findAll(User user, final String path, Long revision, boolean recursive) {
    SVNRevision svnRevision = SVNRevision.HEAD;
    if (revision != null && -1L != revision) {
        svnRevision = SVNRevision.create(revision);
    }
    final List<FileEntry> fileEntries = newArrayList();
    SVNClientManager svnClientManager = getSVNClientManager();
    try {
        svnClientManager.getLogClient().doList(
                SVNURL.fromFile(getUserRepoDirectory(user)).appendPath(path, true), svnRevision, svnRevision,
                true, recursive, new ISVNDirEntryHandler() {
                    @Override
                    public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException {

                        FileEntry script = new FileEntry();
                        // Exclude base path "/"
                        if (StringUtils.isBlank(dirEntry.getRelativePath())) {
                            return;
                        }
                        script.setPath(FilenameUtils.normalize(path + "/" + dirEntry.getRelativePath(), true));
                        script.setCreatedDate(dirEntry.getDate());
                        script.setLastModifiedDate(dirEntry.getDate());
                        script.setDescription(dirEntry.getCommitMessage());
                        script.setRevision(dirEntry.getRevision());
                        if (dirEntry.getKind() == SVNNodeKind.DIR) {
                            script.setFileType(FileType.DIR);
                        } else {
                            script.getFileType();
                            script.setFileSize(dirEntry.getSize());
                        }
                        fileEntries.add(script);
                    }
                });
    } catch (Exception e) {
        LOG.debug("findAll() to the not existing folder {}", path);
    } finally {
        closeSVNClientManagerQuietly(svnClientManager);
    }
    return fileEntries;
}

From source file:hudson.plugins.testcomplete.TestCompleteInputMetric.java

/**
 * This method extracts all XML files inside a MHT file produced by
 * TestComplete/TestExecute into a temporary directory and returns a
 * reference to such directory.//from w  ww .  j  a  va 2s.  c om
 * 
 * @param inputFile
 *            MHT file to process
 * @param params
 *            map where parameter with key "baseUrl" and value returned by
 *            {@link MHTInputStream#getBaseUrl()} is added
 * @return temporary file that contains all the extracted XML files from
 *         input MHT file
 * @throws MHTException
 *             if and MHT error occurs
 * @throws IOException
 *             if an I/O error ocurrs
 */
private File extractXMLFilesFromMHTFile(File inputFile, Map<String, Object> params) throws IOException {
    File tempDir = Files.createTempDir();
    MHTInputStream mis = null;

    try {
        mis = new MHTInputStream(new FileInputStream(inputFile));

        if (params != null) {
            params.put(INTERNAL_PARAM_BASE_URL, mis.getBaseUrl());
            // It seems that backslashes should be escaped in XSL references
            // so we just convert to UNIX format
            // that works also on Windows for Java.
            params.put(INTERNAL_PARAM_BASE_PATH, FilenameUtils.normalize(tempDir.getAbsolutePath(), true));
        }

        MHTEntry entry = null;
        byte buffer[] = new byte[1024];
        int readBytes = 0;

        while ((entry = mis.getNextEntry()) != null) {
            if (CONTENT_TYPE_XML.equals(entry.getContentType())) {
                File out = new File(tempDir, entry.getName());
                out.createNewFile();
                FileOutputStream fos = new FileOutputStream(out);
                try {
                    while ((readBytes = mis.read(buffer)) > 0) {
                        fos.write(buffer, 0, readBytes);
                    }
                } finally {
                    fos.close();
                }
            }
        }

        return tempDir;

    } catch (IOException e) {
        // Cleanup temporary directory here upon failure
        FileUtils.deleteDirectory(tempDir);
        throw e;
    } finally {
        if (mis != null) {
            mis.close();
        }
    }
}

From source file:com.igormaznitsa.jcp.context.PreprocessorContext.java

/**
 * Set patterns for excluded folders./*www  .j  a  v a 2s  . c  om*/
 * @param patterns array contains Ant path patterns
 */
public void setExcludedFolderPatterns(@MustNotContainNull @Nonnull final String... patterns) {
    final String[] value = Assertions.assertDoesntContainNull(Assertions.assertNotNull(patterns));
    final String[] normalized = new String[value.length];
    for (int i = 0; i < value.length; i++) {
        normalized[i] = FilenameUtils.normalize(value[i], true);
    }
    this.excludedFolderPatterns = normalized;
}

From source file:net.certiv.antlr.project.regen.ReGenConfig.java

public void saveRuleSet(String filename, RuleSet rules, boolean force) throws IOException {
    rules.projectBasePath = FilenameUtils.normalize(rules.projectBasePath, true);
    rules.modelBasePath = FilenameUtils.normalize(rules.modelBasePath, true);
    try {/*from w  w  w  . jav a  2s .c  om*/
        saveObj2Json(filename, rules);
    } catch (IOException | JsonSyntaxException e) {
        Log.error(this, "Failed to save configuration file " + filename, e);
        throw e;
    }
}

From source file:cec.easyshop.storefront.filters.AcceleratorAddOnFilter.java

protected String getFullPathNameFromRequest(final HttpServletRequest request) {
    final String ctxPath = request.getContextPath();
    String requestUri = request.getRequestURI();

    if (requestUri.startsWith(ctxPath)) {
        requestUri = requestUri.substring(ctxPath.length());
    }/*from w  w  w .  j a v  a  2s . c  o m*/

    return FilenameUtils.normalize(request.getSession().getServletContext().getRealPath(requestUri), true);
}

From source file:com.exxonmobile.ace.hybris.storefront.filters.AcceleratorAddOnFilter.java

protected String getFullPathNameFromRequest(final HttpServletRequest request) {

    final String ctxPath = request.getContextPath();
    String requestUri = request.getRequestURI();
    if (requestUri.startsWith(ctxPath)) {
        requestUri = requestUri.substring(ctxPath.length());
    }/*ww w. j av  a 2s  . co  m*/
    final String realPath = FilenameUtils
            .normalize(request.getSession().getServletContext().getRealPath(requestUri), true);
    return realPath;
}

From source file:com.iyonger.apm.web.handler.GroovyMavenProjectScriptHandler.java

private void createFileEntries(User user, String path, String name, String url, String scriptContent)
        throws IOException {
    File scriptTemplateDir;/*from w w  w . j a va 2 s  .c o m*/
    scriptTemplateDir = new ClassPathResource("/script_template/" + getKey()).getFile();
    for (File each : FileUtils.listFiles(scriptTemplateDir, null, true)) {
        try {
            String subpath = each.getPath().substring(scriptTemplateDir.getPath().length());
            String fileContent = FileUtils.readFileToString(each, "UTF8");
            if (subpath.endsWith("TestRunner.groovy")) {
                fileContent = scriptContent;
            } else {
                fileContent = fileContent.replace("${userName}", user.getUserName());
                fileContent = fileContent.replace("${name}", name);
                fileContent = fileContent.replace("${url}", url);
            }
            FileEntry fileEntry = new FileEntry();
            fileEntry.setContent(fileContent);
            fileEntry.setPath(FilenameUtils.normalize(PathUtils.join(path, subpath), true));
            fileEntry.setDescription("create groovy maven project");
            String hostName = UrlUtils.getHost(url);
            if (StringUtils.isNotEmpty(hostName)
                    && fileEntry.getFileType().getFileCategory() == FileCategory.SCRIPT) {
                Map<String, String> properties = newHashMap();
                properties.put("targetHosts", UrlUtils.getHost(url));
                fileEntry.setProperties(properties);
            }
            getFileEntryRepository().save(user, fileEntry, "UTF8");
        } catch (IOException e) {
            throw processException("Error while saving " + each.getName(), e);
        }
    }
}

From source file:com.silverpeas.gallery.model.Media.java

/**
 * Gets the Application URL thumbnail of the media according the specified media resolution.
 * @param mediaResolution// w w  w .j a v a  2 s  .  c  om
 * @return the URL of media thumbnail.
 */
public String getApplicationThumbnailUrl(MediaResolution mediaResolution) {
    if (mediaResolution == null) {
        mediaResolution = MediaResolution.PREVIEW;
    }
    String thumbnailUrl = URLManager.getApplicationURL() + "/gallery/jsp/icons/"
            + getType().name().toLowerCase() + "_";
    switch (mediaResolution) {
    case TINY:
        thumbnailUrl += MediaResolution.TINY.getLabel();
        break;
    case SMALL:
        thumbnailUrl += MediaResolution.SMALL.getLabel();
        break;
    case WATERMARK:
        return "";
    default:
        thumbnailUrl += MediaResolution.MEDIUM.getLabel();
        break;
    }
    thumbnailUrl += ".png";
    return FilenameUtils.normalize(thumbnailUrl, true);
}

From source file:edu.kit.dama.staging.util.DataOrganizationUtils.java

/**
 * Creates a DataOrganizationNode from a local path. This method will take
 * pLocalFile, removed pLocalBasePath from the file's path and creates a new
 * DataOrganizationNode consisting of pNewBaseURL and the relative path of
 * pLocalFile. Directories are included by iterative calls until the end of
 * the directory structure was reached.//from w  w w .j a  v  a2s  .  c  o  m
 *
 * @param pDigitalObjectId The digital object ID used for the root node
 * @param pAbstractFile The file/directory forming the DataOrganizationNode
 * @param pBaseUrl The base URL which will be removed from all LFNs in order
 * to get its relative path.
 * @param pNewBaseUrl The base URL to which the relative path of pFile is
 * appended to form a DataOrganizationNode. It is expected that this URL is
 * a directory.
 * @param pIncludeAttributes If TRUE obtainable file attributes (e.g.
 * filesize, directory/file flag, lastModified) are included into the tree.
 *
 * @return An IDataOrganizationNode object representing the entire file
 * structure below pLocalFile.
 *
 * @throws AdalapiException If the access to pFile fails.
 * @throws MalformedURLException If pBaseUrl is invalid.
 */
private static IDataOrganizationNode createNodeFromFile(String pDigitalObjectId, AbstractFile pAbstractFile,
        String pBaseUrl, URL pNewBaseUrl, boolean pIncludeAttributes)
        throws AdalapiException, MalformedURLException {
    String sBaseUrl = pNewBaseUrl.toString();
    if (!sBaseUrl.endsWith("/")) {//add slash to base URL as this should be a directory
        sBaseUrl += "/";
    }
    LOGGER.debug("Creating node from file {} with baseUrl {} for new baseUrl {}", pAbstractFile, pBaseUrl,
            pNewBaseUrl);
    DataOrganizationNodeImpl ret;
    String fromPath = FilenameUtils.normalize(pAbstractFile.getUrl().getPath(), true);
    if (pAbstractFile.isDirectory()) {//local file is a directory, proceed accordingly in a recursive way
        CollectionNodeImpl cn = new CollectionNodeImpl(new LFNImpl(sBaseUrl));
        if (fromPath.equals(pBaseUrl)) {//we have the root path, so use the digital object ID as node identifier
            cn.setName(pDigitalObjectId);
        } else {//we have another path, so use the directory name as node identifier
            cn.setName(pAbstractFile.getName());
        }

        //list all files and add them to the current node
        Collection<AbstractFile> ls = pAbstractFile.list();
        long dirSize = 0;
        if (ls != null) {
            for (AbstractFile child : ls) {//add all children recursively
                if (child.isLocal()) {//perform symlink check
                    try {
                        if (Files.isSymbolicLink(Paths.get(pAbstractFile.getUrl().toURI()))) {
                            LOGGER.warn("Symbolic link detected in child in local file at {}. Ignoring it.",
                                    child);
                            //do nothing with this child
                        } else {
                            //no symlink, add child
                            IDataOrganizationNode childNode = createNodeFromFile(pDigitalObjectId, child,
                                    pBaseUrl, pNewBaseUrl, pIncludeAttributes);
                            cn.addChild(childNode);
                            for (IAttribute attribute : childNode.getAttributes()) {
                                if (attribute.getKey().equals(SIZE_KEY)) {
                                    dirSize += Long.parseLong(attribute.getValue());
                                }
                            }
                        }
                    } catch (URISyntaxException ex) {
                        //ignored
                    }
                } else {//for remote files we cannot perform symlink checks
                    IDataOrganizationNode childNode = createNodeFromFile(pDigitalObjectId, child, pBaseUrl,
                            pNewBaseUrl, pIncludeAttributes);
                    cn.addChild(childNode);
                    for (IAttribute attribute : childNode.getAttributes()) {
                        if (attribute.getKey().equals(SIZE_KEY)) {
                            dirSize += Long.parseLong(attribute.getValue());
                        }
                    }
                }
            }
        }

        if (pIncludeAttributes) {
            cn.addAttribute(new AttributeImpl(DIRECTORY_KEY, Boolean.TRUE.toString()));
            cn.addAttribute(new AttributeImpl(LAST_MODIFIED_KEY, Long.toString(pAbstractFile.lastModified())));
            cn.addAttribute(new AttributeImpl(SIZE_KEY, Long.toString(dirSize)));
            cn.addAttribute(new AttributeImpl(CHILDREN_KEY, Integer.toString(pAbstractFile.list().size())));
        }

        ret = cn;
    } else {//current file is no directory, just append it as filenode
        ret = new FileNodeImpl(new LFNImpl(pAbstractFile.getUrl()));
        ret.setName(pAbstractFile.getName());
        if (pIncludeAttributes) {
            ret.addAttribute(new AttributeImpl(DIRECTORY_KEY, Boolean.FALSE.toString()));
            ret.addAttribute(new AttributeImpl(LAST_MODIFIED_KEY, Long.toString(pAbstractFile.lastModified())));
            ret.addAttribute(new AttributeImpl(SIZE_KEY, Long.toString(pAbstractFile.getSize())));
        }
    }
    return ret;
}

From source file:com.igormaznitsa.jcp.JCPreprocessor.java

@Nonnull
private Set<File> findAllFiles(@Nonnull final String baseFolderCanonicalPath, @Nonnull final File dir,
        @Nonnull final AntPathMatcher antPathMatcher,
        @Nonnull @MustNotContainNull final String[] excludedFolderPatterns) throws IOException {
    final Set<File> result = new HashSet<File>();
    final File[] allowedFiles = dir.listFiles();

    final String normalizedBasePath = FilenameUtils.normalize(baseFolderCanonicalPath, true);

    for (final File file : allowedFiles) {
        if (file.isDirectory()) {
            boolean process = true;

            final String folderPath = file.getCanonicalPath();

            String excludingPattern = null;

            if (excludedFolderPatterns.length != 0) {
                final String subPathInBase = folderPath.substring(normalizedBasePath.length());

                for (final String s : excludedFolderPatterns) {
                    if (antPathMatcher.match(s, subPathInBase)) {
                        excludingPattern = s;
                        process = false;
                        break;
                    }// w  w w.  j a va2  s  . c  o  m
                }
            }

            if (process) {
                result.addAll(
                        findAllFiles(baseFolderCanonicalPath, file, antPathMatcher, excludedFolderPatterns));
            } else {
                this.context.logForVerbose(
                        "Folder '" + folderPath + "' excluded for pattern '" + excludingPattern + "'");
            }
        } else {
            result.add(file);
        }
    }
    return result;
}