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.broadleafcommerce.common.file.service.BroadleafFileServiceImpl.java

protected ClassPathResource lookupResourceOnClassPath(String name) {
    if (fileServiceClasspathDirectory != null && !"".equals(fileServiceClasspathDirectory)) {
        try {//from  w  w  w.  jav  a 2 s .co m
            String resourceName = FilenameUtils
                    .separatorsToUnix(FilenameUtils.normalize(fileServiceClasspathDirectory + '/' + name));
            ClassPathResource resource = new ClassPathResource(resourceName);
            if (resource.exists()) {
                return resource;
            }
        } catch (Exception e) {
            LOG.error("Error getting resource from classpath", e);
        }
    }
    return null;
}

From source file:org.broadleafcommerce.common.file.service.FileSystemFileServiceProvider.java

@Override
public File getResource(String url, FileApplicationType applicationType) {
    String fileName = buildResourceName(url);
    String baseDirectory = getBaseDirectory(true);
    ExtensionResultHolder<String> holder = new ExtensionResultHolder<String>();
    if (extensionManager != null) {
        ExtensionResultStatusType result = extensionManager.getProxy().processPathForSite(baseDirectory,
                fileName, holder);//from  w w w . ja  v a 2s .com
        if (!ExtensionResultStatusType.NOT_HANDLED.equals(result)) {
            return new File(holder.getResult());
        }
    }
    String filePath = FilenameUtils.normalize(getBaseDirectory(false) + File.separator + fileName);
    return new File(filePath);
}

From source file:org.broadleafcommerce.common.file.service.FileSystemFileServiceProvider.java

@Override
public List<String> addOrUpdateResourcesForPaths(FileWorkArea workArea, List<File> files,
        boolean removeFilesFromWorkArea) {
    List<String> result = new ArrayList<String>();
    for (File srcFile : files) {
        if (!srcFile.getAbsolutePath().startsWith(workArea.getFilePathLocation())) {
            throw new FileServiceException("Attempt to update file " + srcFile.getAbsolutePath()
                    + " that is not in the passed in WorkArea " + workArea.getFilePathLocation());
        }//from   w w  w .  jav  a 2  s. com

        String fileName = srcFile.getAbsolutePath().substring(workArea.getFilePathLocation().length());

        // before building the resource name, convert the file path to a url-like path
        String url = FilenameUtils.separatorsToUnix(fileName);
        String resourceName = buildResourceName(url);
        String destinationFilePath = FilenameUtils
                .normalize(getBaseDirectory(false) + File.separator + resourceName);
        File destFile = new File(destinationFilePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }

        try {
            if (removeFilesFromWorkArea) {
                if (destFile.exists()) {
                    FileUtils.deleteQuietly(destFile);
                }
                FileUtils.moveFile(srcFile, destFile);
            } else {
                FileUtils.copyFile(srcFile, destFile);
            }
            result.add(fileName);
        } catch (IOException ioe) {
            throw new FileServiceException("Error copying resource named " + fileName + " from workArea "
                    + workArea.getFilePathLocation() + " to " + resourceName, ioe);
        }
    }
    return result;
}

From source file:org.broadleafcommerce.common.file.service.FileSystemFileServiceProvider.java

@Override
public boolean removeResource(String name) {
    String resourceName = buildResourceName(name);
    String filePathToRemove = FilenameUtils.normalize(getBaseDirectory(false) + File.separator + resourceName);
    File fileToRemove = new File(filePathToRemove);
    return fileToRemove.delete();
}

From source file:org.broadleafcommerce.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  ww w.  ja  v a2s  .  c om*/
 * If there is a "siteId" in the BroadleafRequestContext 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));

    BroadleafRequestContext brc = new BroadleafRequestContext();
    BroadleafRequestContext.setBroadleafRequestContext(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
    BroadleafRequestContext.setBroadleafRequestContext(null);
}

From source file:org.broadleafcommerce.common.sitemap.service.SiteMapServiceImpl.java

/**
 * Gzip a file and then delete the file//from   w w w.  ja  v  a 2  s.c o m
 * 
 * @param fileName
 */
protected void gzipAndDeleteFiles(FileWorkArea fileWorkArea, List<String> fileNames) {
    for (String fileName : fileNames) {
        try {
            String fileNameWithPath = FilenameUtils
                    .normalize(fileWorkArea.getFilePathLocation() + File.separator + fileName);

            FileInputStream fis = new FileInputStream(fileNameWithPath);
            FileOutputStream fos = new FileOutputStream(fileNameWithPath + ENCODING_EXTENSION);
            GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                gzipOS.write(buffer, 0, len);
            }
            //close resources
            gzipOS.close();
            fos.close();
            fis.close();

            File originalFile = new File(fileNameWithPath);
            originalFile.delete();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.broadleafcommerce.vendor.amazon.s3.S3FileServiceProviderTest.java

/**
 * Differs from {@link #checkTestFileExists(String)} in that this uses the S3 client directly and does
 * not go through the Broadleaf file service API. This will create a test file, upload it to S3 via the
 * Broadleaf file service API, verify that the file exists via the raw S3 client, and then delete the file
 * from the bucket via the file service API again
 * //from  w  w w . j a v  a  2s.  c om
 * @param filename the name of the file to upload
 * @param directoryName directory that the file should be stored in on S3
 */
protected void verifyFileUploadRaw(String filename, String directoryName) throws IOException {
    propService.setProperty("aws.s3.bucketSubDirectory", directoryName);

    boolean ok = uploadTestFileTestOk(filename);
    assertTrue("File added to s3 with no exception.", ok);

    // Use the S3 client directly to ensure that it was uploaded to the sub-directory
    S3Configuration s3config = configService.lookupS3Configuration();
    AmazonS3Client s3 = s3FileProvider.getAmazonS3Client(s3config);
    s3.setRegion(RegionUtils.getRegion(s3config.getDefaultBucketRegion()));
    String s3Key = s3FileProvider.getSiteSpecificResourceName(filename);
    if (StringUtils.isNotEmpty(directoryName)) {
        s3Key = directoryName + "/" + s3Key;
    }

    // Replace the starting slash and remove the double-slashes if the directory ended with a slash
    s3Key = s3Key.startsWith("/") ? s3Key.substring(1) : s3Key;
    s3Key = FilenameUtils.normalize(s3Key);

    S3Object object = s3.getObject(new GetObjectRequest(s3config.getDefaultBucketName(), s3Key));

    InputStream inputStream = object.getObjectContent();
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String fileContents = writer.toString();
    inputStream.close();
    writer.close();

    assertEquals("Retrieved the file successfully from S3", fileContents, TEST_FILE_CONTENTS);

    ok = deleteTestFile(filename);
    assertTrue("File removed from s3 with no exception.", ok);
}

From source file:org.cleverbus.core.common.file.DefaultFileRepository.java

@Override
public void commitFile(String fileId, String fileName, FileContentTypeExtEnum contentType,
        List<String> subFolders) {
    Assert.hasText(fileId, "fileId must not be empty");
    Assert.hasText(fileName, "fileName must not be empty");
    Assert.notNull(subFolders, "subFolders must not be null");

    File tmpFile = new File(tempDir, fileId);

    // check file existence
    if (!tmpFile.exists() || !tmpFile.canRead()) {
        String msg = "temp file " + tmpFile + " doesn't exist or can't be read";
        Log.error(msg);//from w w w  .  j a  v a2 s  .  c  o  m
        throw new IntegrationException(InternalErrorEnum.E115, msg);
    }

    // move file to target directory
    String targetDirName = FilenameUtils.concat(fileRepoDir.getAbsolutePath(),
            StringUtils.join(subFolders, File.separator));
    targetDirName = FilenameUtils.normalize(targetDirName);

    File targetDir = new File(targetDirName);

    try {
        FileUtils.moveFileToDirectory(tmpFile, targetDir, true);

        Log.debug("File (" + tmpFile + ") was successfully moved to directory - " + targetDir);
    } catch (IOException e) {
        String msg = "error occurred during moving temp file " + tmpFile + " to target directory - "
                + targetDirName;
        Log.error(msg);
        throw new IntegrationException(InternalErrorEnum.E115, msg);
    }

    // rename file
    File targetTmpFile = new File(targetDir, fileId);

    String targetFileName = FilenameUtils.concat(targetDir.getAbsolutePath(),
            getFileName(fileName, contentType));
    targetFileName = FilenameUtils.normalize(targetFileName);

    try {
        FileUtils.moveFile(targetTmpFile, new File(targetFileName));

        Log.debug("File (" + tmpFile + ") was successfully committed. New path: " + targetFileName);
    } catch (IOException e) {
        String msg = "error occurred during renaming temp file " + tmpFile + " to target directory - "
                + targetDirName;
        Log.error(msg);
        throw new IntegrationException(InternalErrorEnum.E115, msg);
    }
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

@SuppressFBWarnings
public void setBaseContentDirectory(final String baseDirectory) throws IOException {

    Path directory;//w w  w .j a va  2s  . c o m
    if (!baseDirectory.isEmpty()) {
        String path = FilenameUtils.normalize(baseDirectory);
        try {
            directory = Paths.get(path, DEFAULT_CONTENT_REPOSITORY, DEFAULT_CONTENT_STORE);
        } catch (InvalidPathException e) {
            path = System.getProperty(KARAF_HOME);
            directory = Paths.get(path, DEFAULT_CONTENT_REPOSITORY, DEFAULT_CONTENT_STORE);
        }
    } else {
        String path = System.getProperty("karaf.home");
        directory = Paths.get(path, DEFAULT_CONTENT_REPOSITORY, DEFAULT_CONTENT_STORE);
    }

    Path directories;
    if (!Files.exists(directory)) {
        directories = Files.createDirectories(directory);
        LOGGER.debug("Setting base content directory to: {}", directories.toAbsolutePath().toString());
    } else {
        directories = directory;
    }

    Path tmpDirectories;
    Path tmpDirectory = Paths.get(directories.toAbsolutePath().toString(), DEFAULT_TMP);
    if (!Files.exists(tmpDirectory)) {
        tmpDirectories = Files.createDirectories(tmpDirectory);
        LOGGER.debug("Setting base content directory to: {}", tmpDirectory.toAbsolutePath().toString());
    } else {
        tmpDirectories = tmpDirectory;
    }

    this.baseContentDirectory = directories;
    this.baseContentTmpDirectory = tmpDirectories;
}

From source file:org.craftercms.studio.impl.v1.service.clipboard.ClipboardServiceImpl.java

/**
 * Cut/Paste calls the Rename service <link>WcmRenameService</link>
 *//*w w w  .  j a va2s  . c o m*/
protected List<String> cutPaste(final String site, List<Map<String, String>> pasteItems,
        final String destination) throws ServiceException {
    for (final Map<String, String> pasteItem : pasteItems) {
        String path = pasteItem.get("uri");
        path = FilenameUtils.normalize(path);
        String fullPath = contentService.expandRelativeSitePath(site, path);
        objectStateService.setSystemProcessing(site, path, true);
        String destinationUri = destination;
        if (destination.endsWith(DmConstants.INDEX_FILE)) {
            destinationUri = ContentUtils.getParentUrl(destinationUri);
        }
        destinationUri = destinationUri + "/"
                + ContentUtils.getPageName(path.replace("/" + DmConstants.INDEX_FILE, ""));
        String destinationFinalUri = destinationUri;
        String lockKey = site + ":" + path;
        generalLockService.lock(lockKey);
        String lockKeyDest = site + ":" + destinationUri;
        generalLockService.lock(lockKeyDest);
        try {
            if (contentService.contentExists(site, destinationUri)) {
                throw new ServiceException("Content already exists [" + site + ":" + destinationUri + "]");
            } else {
                logger.error("Destination URI: " + destinationUri);
                dmRenameService.rename(site, path, destinationUri, false);
                updateFileWithNewNavOrder(site, destinationUri);//only for cut/paste will need to provide new navorder value right here since it doesnt go through FormContentProcessor
                ContentItemTO itemTO = contentService.getContentItem(site, destinationUri);
                destinationFinalUri = itemTO.getUri();
                objectStateService.transition(site, itemTO,
                        org.craftercms.studio.api.v1.service.objectstate.TransitionEvent.SAVE);
            }
        } finally {
            objectStateService.setSystemProcessing(site, path, false);
            generalLockService.unlock(lockKey);
            generalLockService.unlock(lockKeyDest);
        }
    }
    return null;
}