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:org.sonar.plugins.web.api.ProjectFileManager.java

/**
 * getRelativePath("c:/foo/src/my/package/Hello.java", ["c:/bar", "c:/foo/src"]) is "my/package/Hello.java".
 * <p>/*from   w w w.ja  va2  s  . c o  m*/
 * Relative path is composed of slashes. Windows backslaches are replaced by /
 * </p>
 *
 * @return null if file is not in dir (including recursive subdirectories)
 */
public static String getRelativePath(File file, List<File> dirs) {
    List<String> stack = new ArrayList<String>();
    String path = FilenameUtils.normalize(file.getAbsolutePath());
    File cursor = new File(path);
    while (cursor != null) {
        if (containsFile(dirs, cursor)) {
            return StringUtils.join(stack, "/");
        }
        stack.add(0, cursor.getName());
        cursor = cursor.getParentFile();
    }
    return null;
}

From source file:org.sonar.vary.plugin.utils.VaryReportSensor.java

public static List<File> getReports(Settings conf, String baseDirPath, String reportPathPropertyKey,
        String defaultReportPath) {
    String reportPath = conf.getString(reportPathPropertyKey);
    if (reportPath == null) {
        reportPath = defaultReportPath;// ww w  .  j av  a2 s.  c om
    }
    reportPath = FilenameUtils.normalize(reportPath);

    VaryUtils.LOG.debug("Using pattern '{}' to find reports", reportPath);

    DirectoryScanner scanner = new DirectoryScanner();
    String[] includes = new String[1];
    includes[0] = reportPath;
    scanner.setIncludes(includes);
    scanner.setBasedir(new File(baseDirPath));
    scanner.scan();
    String[] relPaths = scanner.getIncludedFiles();

    List<File> reports = new ArrayList<File>();
    for (String relPath : relPaths) {
        String path = VaryUtils.normalizePath(new File(baseDirPath, relPath).getAbsolutePath());
        reports.add(new File(path));
    }

    return reports;
}

From source file:org.sparkcommerce.cms.file.service.StaticAssetStorageServiceImpl.java

@Transactional("blTransactionManagerAssetStorageInfo")
@Override/*w  w w.  ja  v a2  s.c  o  m*/
public void createStaticAssetStorageFromFile(MultipartFile file, StaticAsset staticAsset) throws IOException {
    if (StorageType.DATABASE.equals(staticAsset.getStorageType())) {
        StaticAssetStorage storage = staticAssetStorageDao.create();
        storage.setStaticAssetId(staticAsset.getId());
        Blob uploadBlob = staticAssetStorageDao.createBlob(file);
        storage.setFileData(uploadBlob);
        staticAssetStorageDao.save(storage);
    } else if (StorageType.FILESYSTEM.equals(staticAsset.getStorageType())) {
        FileWorkArea tempWorkArea = sparkFileService.initializeWorkArea();
        // Convert the given URL from the asset to a system-specific suitable file path
        String destFileName = FilenameUtils.normalize(tempWorkArea.getFilePathLocation() + File.separator
                + FilenameUtils.separatorsToSystem(staticAsset.getFullUrl()));

        InputStream input = file.getInputStream();
        byte[] buffer = new byte[fileBufferSize];

        File destFile = new File(destFileName);
        if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                if (!destFile.getParentFile().exists()) {
                    throw new RuntimeException("Unable to create parent directories for file: " + destFileName);
                }
            }
        }

        OutputStream output = new FileOutputStream(destFile);
        boolean deleteFile = false;
        try {
            int bytesRead;
            int totalBytesRead = 0;
            while ((bytesRead = input.read(buffer)) != -1) {
                totalBytesRead += bytesRead;
                if (totalBytesRead > maxUploadableFileSize) {
                    deleteFile = true;
                    throw new IOException("Maximum Upload File Size Exceeded");
                }
                output.write(buffer, 0, bytesRead);
            }

            // close the output file stream prior to moving files around

            output.close();
            sparkFileService.addOrUpdateResource(tempWorkArea, destFile, deleteFile);
        } finally {
            IOUtils.closeQuietly(output);
            sparkFileService.closeWorkArea(tempWorkArea);
        }
    }
}

From source file:org.sparkcommerce.common.file.service.FileSystemFileServiceProviderTest.java

/**
 * For example, if the URL is /product/myproductimage.jpg, then the MD5 would be
 * 35ec52a8dbd8cf3e2c650495001fe55f resulting in the following file on the filesystem
 * {assetFileSystemPath}/64/a7/myproductimage.jpg.
 * //from   w  w w . j  a va 2s.co m
 * If there is a "siteId" in the SparkRequestContext then the site is also distributed
 * using a similar algorithm but the system attempts to keep images for sites in their own
 * directory resulting in an extra two folders required to reach any given product.   So, for
 * site with id 125, the system will MD5 "site125" in order to build the URL string.   "site125" has an md5
 * string of "7d905e85b8cb72a0477632be2c342bd6".    
 * 
 * So, in this case with the above product URL in site125, the full URL on the filesystem
 * will be:
 * 
 * {assetFileSystemPath}/7d/site125/64/a7/myproductimage.jpg.
 * @throws Exception
 */
public void testBuildFileName() throws Exception {
    FileSystemFileServiceProvider provider = new FileSystemFileServiceProvider();
    String tmpdir = FileUtils.getTempDirectoryPath();
    if (!tmpdir.endsWith(File.separator)) {
        tmpdir = tmpdir + File.separator;
    }
    provider.fileSystemBaseDirectory = FilenameUtils.concat(tmpdir, "test");
    provider.maxGeneratedDirectoryDepth = 2;
    File file = provider.getResource("/product/myproductimage.jpg");

    String resultPath = tmpdir
            + StringUtils.join(new String[] { "test", "35", "ec", "myproductimage.jpg" }, File.separator);
    assertEquals(file.getAbsolutePath(), FilenameUtils.normalize(resultPath));

    SparkRequestContext brc = new SparkRequestContext();
    SparkRequestContext.setSparkRequestContext(brc);

    Site site = new SiteImpl();
    site.setId(125L);
    brc.setSite(site);

    // try with site specific directory
    file = provider.getResource("/product/myproductimage.jpg");
    resultPath = tmpdir + StringUtils
            .join(new String[] { "test", "c8", "site-125", "35", "ec", "myproductimage.jpg" }, File.separator);
    assertEquals(file.getAbsolutePath(), resultPath);

    // try with 3 max generated directories
    provider.maxGeneratedDirectoryDepth = 3;
    file = provider.getResource("/product/myproductimage.jpg");
    resultPath = tmpdir + StringUtils.join(
            new String[] { "test", "c8", "site-125", "35", "ec", "52", "myproductimage.jpg" }, File.separator);
    assertEquals(file.getAbsolutePath(), resultPath);

    // Remove the request context from thread local so it doesn't get in the way of subsequent tests
    SparkRequestContext.setSparkRequestContext(null);
}

From source file:org.splevo.ui.vpexplorer.providers.VPExplorerContentProvider.java

private String getNormalizedWorkspacePath() {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    String workspaceBasePath = root.getLocation().toPortableString();
    workspaceBasePath = FilenameUtils.normalize(workspaceBasePath);
    return workspaceBasePath;
}

From source file:org.structr.files.cmis.StructrCMISService.java

@Override
public ObjectData getObjectByPath(final String repositoryId, final String path, final String propertyFilter,
        final Boolean includeAllowableActions, final IncludeRelationships includeRelationships,
        final String renditionFilter, final Boolean includePolicyIds, final Boolean includeAcl,
        final ExtensionsData extension) {

    final String cleanPath = FilenameUtils.normalize(path);

    if (CMISInfo.ROOT_FOLDER_ID.equals(cleanPath) || cleanPath == null || path == null) {
        return new CMISRootFolder(propertyFilter, includeAllowableActions);
    }/*from www. j  a  va2 s  . c o m*/

    return objectService.getObjectByPath(repositoryId, cleanPath, propertyFilter, includeAllowableActions,
            includeRelationships, renditionFilter, includePolicyIds, includeAcl, extension);
}

From source file:org.vafer.jdependency.Clazzpath.java

public ClazzpathUnit addClazzpathUnit(final File pFile, final String pId) throws IOException {
    if (pFile.isFile()) {
        return addClazzpathUnit(new FileInputStream(pFile), pId);
    }/*from w  w w .j a  v  a 2  s .c  o m*/
    if (pFile.isDirectory()) {
        final String prefix = FilenameUtils.separatorsToUnix(FilenameUtils
                .normalize(new StringBuilder(pFile.getAbsolutePath()).append(File.separatorChar).toString()));
        final boolean recursive = true;
        @SuppressWarnings("unchecked")
        final Iterator<File> files = FileUtils.iterateFiles(pFile, new String[] { "class" }, recursive);
        return addClazzpathUnit(new Iterable<Resource>() {

            public Iterator<Resource> iterator() {
                return new Iterator<Clazzpath.Resource>() {

                    public boolean hasNext() {
                        return files.hasNext();
                    }

                    public Resource next() {
                        final File file = files.next();
                        return new Resource(file.getAbsolutePath().substring(prefix.length())) {

                            @Override
                            InputStream getInputStream() throws IOException {
                                return new FileInputStream(file);
                            }
                        };
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }

        }, pId, true);
    }
    throw new IllegalArgumentException();
}

From source file:org.wisdom.template.thymeleaf.impl.WisdomURLResourceResolver.java

@Override
public InputStream getResourceAsStream(TemplateProcessingParameters templateProcessingParameters,
        String resourceName) {//w w w.  ja  v  a2s .  c  o m
    // Check whether we have a 'parent' template
    // If so and if the given template name is 'simple' (not absolute), we compute the full path.
    final Template mayBeParentTemplate = (Template) templateProcessingParameters.getContext().getVariables()
            .get("__TEMPLATE__");

    ThymeLeafTemplateImplementation template = engine.getTemplateByResourceName(resourceName);

    if (template == null && mayBeParentTemplate != null && !isAbsoluteUrl(resourceName)) {
        // Compute the new name, we retrieve the 'full' path of the parent. It's not the complete URL just the path.
        String path = mayBeParentTemplate.name();
        String absolute = resourceName;
        if (path.contains("/")) {
            // If the path contains a /, remove the part after the / and append the given name
            absolute = path.substring(0, path.lastIndexOf('/')) + "/" + resourceName;
        }
        // Else Nothing do do, we already have the path (root).

        // We normalize to manage the .. case
        absolute = FilenameUtils.normalize(absolute);
        template = engine.getTemplateByResourceName(absolute);
    }

    if (template == null && !resourceName.startsWith("/")) {
        // Try as absolute
        template = engine.getTemplateByResourceName("/" + resourceName);
    }

    if (template == null) {
        LoggerFactory.getLogger(this.getClass()).error("Cannot resolve the template {}, "
                + "neither {} nor {}.thl.html exist in the template directory or is available in bundles.",
                resourceName, resourceName, resourceName);
    } else {
        try {
            return template.getURL().openStream();
        } catch (IOException e) {
            LoggerFactory.getLogger(this.getClass()).error(
                    "Cannot resolve the template {} ({}): cannot open the " + "file.", resourceName,
                    template.getURL().toExternalForm(), e);
        }
    }
    return null;
}

From source file:org.wso2.carbon.registry.resource.services.utils.GetTextContentUtil.java

public static String getTextContent(String path, Registry registry) throws Exception {

    try {// www  .j a v a2s.  com
        if (path != null && path.contains("..")) {
            path = FilenameUtils.normalize(path);
        }

        Resource resource = registry.get(path);

        byte[] content = (byte[]) resource.getContent();
        String contentString = "";
        if (content != null) {
            contentString = RegistryUtils.decodeBytes(content);
        }
        resource.discard();

        return contentString;

    } catch (RegistryException e) {

        String msg = "Could not get the content of the resource " + path + ". Caused by: "
                + ((e.getCause() instanceof SQLException) ? "" : e.getMessage());
        log.error(msg, e);
        throw new RegistryException(msg, e);
    }
}

From source file:org.wso2.carbon.registry.resource.ui.clients.ResourceServiceClient.java

public String getTextContent(HttpServletRequest request) throws Exception {

    String path = RegistryUtil.getPath(request);
    if (path != null && path.contains("..")) {
        path = FilenameUtils.normalize(path);
    }//  ww w  .j  av a2  s  . com

    String textContent = null;
    try {
        textContent = stub.getTextContent(path);
        MetadataBean metadataBean = stub.getMetadata(path);
        String resourceVersion = metadataBean.getResourceVersion();
        request.getSession().setAttribute("resourceVersion", resourceVersion);

    } catch (Exception e) {

        String msg = "Failed get text content of the resource " + path + ". " + e.getMessage();
        log.error(msg, e);
        throw e;
    }
    return textContent;
}