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:cec.easyshop.storefront.filters.CommonResourcesAddOnFilterTest.java

@Override
protected void prepareRequest(final String remotePath) {
    final String normalized = FilenameUtils.normalize(new File(webTargetResource, remotePath).getPath(), true);
    Mockito.doReturn(normalized).when(filter).getFullPathNameFromRequest(request);
}

From source file:com.redhat.victims.VictimsService.java

/**
 * /*from w  ww  .j a  va2  s.  co  m*/
 * Work horse method that provides a {@link RecordStream} wraped from a
 * response received from the server.
 * 
 * @param since
 *            The date from when removed records are required for.
 * @param type
 *            The service type. To be used as ${base-uri}/${service}/%{type}
 * @return
 * @throws IOException
 */
protected RecordStream fetch(Date since, String type) throws IOException {
    SimpleDateFormat fmt = new SimpleDateFormat(VictimsRecord.DATE_FORMAT);
    String spec = FileUtils.getFile(serviceEntry, type, fmt.format(since)).toString();
    spec = FilenameUtils.normalize(spec, true);
    URL merged = new URL(new URL(baseURI), spec);
    return new RecordStream(merged.toString());
}

From source file:com.orange.ocara.model.export.docx.DocxWriter.java

/**
 * To zip a directory./*from   w w  w. j a v  a2  s.c o  m*/
 *
 * @param rootPath  root path
 * @param directory directory
 * @param zos       ZipOutputStream
 * @throws IOException
 */
private void zipDirectory(String rootPath, File directory, ZipOutputStream zos) throws IOException {
    //get a listing of the directory content
    File[] files = directory.listFiles();

    //loop through dirList, and zip the files
    for (File file : files) {
        if (file.isDirectory()) {
            zipDirectory(rootPath, file, zos);
            continue;
        }

        String filePath = FilenameUtils.normalize(file.getPath(), true);
        String fileName = StringUtils.difference(rootPath, filePath);

        fileName = fileName.replaceAll("\\[_\\]", "_").replaceAll("\\[.\\]", ".");

        //create a FileInputStream on top of file
        ZipEntry anEntry = new ZipEntry(fileName);
        zos.putNextEntry(anEntry);

        FileUtils.copyFile(file, zos);
    }
}

From source file:com.astamuse.asta4d.web.builtin.AbstractGenericPathHandler.java

private boolean fileNameSecurityCheck(String path) {
    // we do not allow any unnormalized path for security reason
    String normalizedPath = FilenameUtils.normalize(path, true);
    return path.equals(normalizedPath);
}

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

private void assertDefaultSound(Sound sound) {
    assertThat(sound.getType(), is(MediaType.Sound));
    assertThat(sound.getWorkspaceSubFolderName(), is("soundmediaId"));
    assertThat(sound.getBitrate(), is(2048L));
    assertThat(sound.getDuration(), is(72000000L));
    assertThat(sound.getApplicationOriginalUrl(),
            is(GALLERY_REST_WEB_SERVICE_BASE_URI + "sounds/mediaId/content?_t=1393628400000"));
    assertThat(FilenameUtils.normalize(sound.getFile(MediaResolution.ORIGINAL).getPath(), true),
            endsWith("/instanceId/soundmediaId/soundFile.mp3"));
}

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

private void assertDefaultVideo(Video video) {
    assertThat(video.getType(), is(MediaType.Video));
    assertThat(video.getWorkspaceSubFolderName(), is("videomediaId"));
    assertThat(video.getDefinition().getWidth(), is(800));
    assertThat(video.getDefinition().getHeight(), is(600));
    assertThat(video.getBitrate(), is(1024L));
    assertThat(video.getDuration(), is(36000000L));
    assertThat(video.getApplicationOriginalUrl(),
            is(GALLERY_REST_WEB_SERVICE_BASE_URI + "videos/mediaId/content?_t=1393628400000"));
    assertThat(FilenameUtils.normalize(video.getFile(MediaResolution.ORIGINAL).getPath(), true),
            endsWith("/instanceId/videomediaId/videoFile.mp4"));
}

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

private void assertDefaultPhoto(Photo photo) {
    assertThat(photo.getType(), is(MediaType.Photo));
    assertThat(photo.getWorkspaceSubFolderName(), is("imagemediaId"));
    assertThat(photo.getDefinition().getWidth(), is(800));
    assertThat(photo.getDefinition().getHeight(), is(600));
    assertThat(photo.getMetaDataProperties(), hasSize(1));
    assertThat(photo.getMetaData(photo.getMetaDataProperties().iterator().next()).getValue(), is("ok"));
    assertThat(photo.getApplicationThumbnailUrl(MediaResolution.PREVIEW), is(
            GALLERY_REST_WEB_SERVICE_BASE_URI + "photos/mediaId/content?_t=1393628400000&resolution=PREVIEW"));
    assertThat(photo.getApplicationOriginalUrl(),
            is(GALLERY_REST_WEB_SERVICE_BASE_URI + "photos/mediaId/content?_t=1393628400000"));
    assertThat(FilenameUtils.normalize(photo.getFile(MediaResolution.ORIGINAL).getPath(), true),
            endsWith("/instanceId/imagemediaId/photoFile.jpg"));
}

From source file:com.igormaznitsa.mvngolang.utils.UnpackUtils.java

public static int unpackFileToFolder(@Nonnull final Log logger, @Nullable final String folder,
        @Nonnull final File archiveFile, @Nonnull final File destinationFolder, final boolean makeAllExecutable)
        throws IOException {
    final String normalizedName = archiveFile.getName().toLowerCase(Locale.ENGLISH);

    final ArchEntryGetter entryGetter;

    boolean modeZipFile = false;

    final ZipFile theZipFile;
    final ArchiveInputStream archInputStream;
    if (normalizedName.endsWith(".zip")) {
        logger.debug("Detected ZIP archive");

        modeZipFile = true;//from w  ww . ja  va  2s. c  om

        theZipFile = new ZipFile(archiveFile);
        archInputStream = null;
        entryGetter = new ArchEntryGetter() {
            private final Enumeration<ZipArchiveEntry> iterator = theZipFile.getEntries();

            @Override
            @Nullable
            public ArchiveEntry getNextEntry() throws IOException {
                ArchiveEntry result = null;
                if (this.iterator.hasMoreElements()) {
                    result = this.iterator.nextElement();
                }
                return result;
            }
        };
    } else {
        theZipFile = null;
        final InputStream in = new BufferedInputStream(new FileInputStream(archiveFile));
        try {
            if (normalizedName.endsWith(".tar.gz")) {
                logger.debug("Detected TAR.GZ archive");
                archInputStream = new TarArchiveInputStream(new GZIPInputStream(in));

                entryGetter = new ArchEntryGetter() {
                    @Override
                    @Nullable
                    public ArchiveEntry getNextEntry() throws IOException {
                        return ((TarArchiveInputStream) archInputStream).getNextTarEntry();
                    }
                };

            } else {
                logger.debug("Detected OTHER archive");
                archInputStream = ARCHIVE_STREAM_FACTORY.createArchiveInputStream(in);
                logger.debug("Created archive stream : " + archInputStream.getClass().getName());

                entryGetter = new ArchEntryGetter() {
                    @Override
                    @Nullable
                    public ArchiveEntry getNextEntry() throws IOException {
                        return archInputStream.getNextEntry();
                    }
                };
            }

        } catch (ArchiveException ex) {
            IOUtils.closeQuietly(in);
            throw new IOException("Can't recognize or read archive file : " + archiveFile, ex);
        } catch (CantReadArchiveEntryException ex) {
            IOUtils.closeQuietly(in);
            throw new IOException("Can't read entry from archive file : " + archiveFile, ex);
        }
    }

    try {

        final String normalizedFolder = folder == null ? null : FilenameUtils.normalize(folder, true) + '/';

        int unpackedFilesCounter = 0;
        while (true) {
            final ArchiveEntry entry = entryGetter.getNextEntry();
            if (entry == null) {
                break;
            }
            final String normalizedPath = FilenameUtils.normalize(entry.getName(), true);

            logger.debug("Detected archive entry : " + normalizedPath);

            if (normalizedFolder == null || normalizedPath.startsWith(normalizedFolder)) {
                final File targetFile = new File(destinationFolder, normalizedFolder == null ? normalizedPath
                        : normalizedPath.substring(normalizedFolder.length()));
                if (entry.isDirectory()) {
                    logger.debug("Folder : " + normalizedPath);
                    if (!targetFile.exists() && !targetFile.mkdirs()) {
                        throw new IOException("Can't create folder " + targetFile);
                    }
                } else {
                    final File parent = targetFile.getParentFile();

                    if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
                        throw new IOException("Can't create folder : " + parent);
                    }

                    final FileOutputStream fos = new FileOutputStream(targetFile);

                    try {
                        if (modeZipFile) {
                            logger.debug("Unpacking ZIP entry : " + normalizedPath);

                            final InputStream zipEntryInStream = theZipFile
                                    .getInputStream((ZipArchiveEntry) entry);
                            try {
                                if (IOUtils.copy(zipEntryInStream, fos) != entry.getSize()) {
                                    throw new IOException(
                                            "Can't unpack file, illegal unpacked length : " + entry.getName());
                                }
                            } finally {
                                IOUtils.closeQuietly(zipEntryInStream);
                            }
                        } else {
                            logger.debug("Unpacking archive entry : " + normalizedPath);

                            if (!archInputStream.canReadEntryData(entry)) {
                                throw new IOException("Can't read archive entry data : " + normalizedPath);
                            }
                            if (IOUtils.copy(archInputStream, fos) != entry.getSize()) {
                                throw new IOException(
                                        "Can't unpack file, illegal unpacked length : " + entry.getName());
                            }
                        }
                    } finally {
                        fos.close();
                    }

                    if (makeAllExecutable) {
                        try {
                            targetFile.setExecutable(true, true);
                        } catch (SecurityException ex) {
                            throw new IOException("Can't make file executable : " + targetFile, ex);
                        }
                    }
                    unpackedFilesCounter++;
                }
            } else {
                logger.debug("Archive entry " + normalizedPath + " ignored");
            }
        }
        return unpackedFilesCounter;
    } finally {
        IOUtils.closeQuietly(theZipFile);
        IOUtils.closeQuietly(archInputStream);
    }
}

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

@Override
public String getApplicationThumbnailUrl(MediaResolution mediaResolution) {
    if (mediaResolution == null || mediaResolution == MediaResolution.ORIGINAL) {
        mediaResolution = MediaResolution.PREVIEW;
    }//from w ww .  j av a2s .  co m
    if (getType().isPhoto()) {
        if (MediaResolution.WATERMARK == mediaResolution) {
            SilverpeasFile fileWatermark = getFile(MediaResolution.WATERMARK);
            if (!fileWatermark.exists()) {
                return "";
            }
        }
        if (StringUtil.isDefined(getFileName()) && isPreviewable()) {
            return GalleryResourceURIs.buildMediaContentURI(this, mediaResolution).toString();
        } else {
            String thumbnailUrl = URLManager.getApplicationURL() + "/gallery/jsp/icons/notAvailable_"
                    + MessageManager.getLanguage() + mediaResolution.getThumbnailSuffix();
            return FilenameUtils.normalize(thumbnailUrl, true);
        }
    } else if (getType().isVideo()) {
        SilverpeasFile thumbFile = SilverpeasFileProvider.getFile(FileUtils.getFile(Media.BASE_PATH.getPath(),
                getComponentInstanceId(), getWorkspaceSubFolderName(), "img0.jpg").getPath());
        if (thumbFile != null && thumbFile.exists()) {
            return GalleryResourceURIs.buildVideoThumbnailURI(this, ThumbnailPeriod.Thumbnail0).toString();
        }
        return super.getApplicationThumbnailUrl(mediaResolution);
    } else {
        return super.getApplicationThumbnailUrl(mediaResolution);
    }
}

From source file:net.sourceforge.jencrypt.FileEncrypter.java

/**
 * Encrypt file [inputFile] relative to [pathToEncrypt] into the archive
 * specified by [outputFile]./*from  ww  w.j  a v  a  2  s  . c  o m*/
 * 
 * @param pathToEncrypt
 * @param inputFile
 * @param outputFile
 * @throws Exception
 */
private void encryptAndArchivePath(String folderToEncryptString, String inputFileRelativePath, OutputStream os)
        throws Exception {

    // Full path to file to encrypt
    String fullSourcePath = folderToEncryptString + File.separator + inputFileRelativePath;

    // Path to encrypt is a folder if it ends with a file separator
    boolean pathIsFolder = (inputFileRelativePath
            .charAt(inputFileRelativePath.length() - 1) == File.separatorChar);

    // Use a Unix separator for storing file paths
    inputFileRelativePath = FilenameUtils.normalize(inputFileRelativePath, true);

    // To indicate a folder add a Unix file separator at the end
    if (pathIsFolder)
        inputFileRelativePath += Utils.UNIX_SEPARATOR;

    File inputFile = new File(fullSourcePath);
    Set<PosixFilePermission> perms = null;

    // Get the "Encrypting [file] ... " message
    String message = getCipherMessage(inputFile.getName(), commandline.getCipherMode());

    // Instantiate ProgressInfo
    ProgressInfo progress = new FileProgressInfo(message, inputFile.length(), config.getReadBufferSize());

    assert (inputFileRelativePath.length() > 0);

    byte[] pathLength = ByteBuffer.allocate(4).putInt(inputFileRelativePath.length()).array();
    byte[] pathLengthEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(pathLength, Cipher.ENCRYPT_MODE);
    // write 4 bytes path size
    os.write(pathLengthEnc);

    byte[] fullPath = inputFileRelativePath.getBytes();
    byte[] fullPathEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(fullPath, Cipher.ENCRYPT_MODE);
    // write full path of encrypted file
    os.write(fullPathEnc);

    // Retain file permissions on Unix flavours
    if (fileSystemIsPosixCompliant()) {
        perms = Files.getPosixFilePermissions(Paths.get(fullSourcePath), LinkOption.NOFOLLOW_LINKS);
    } else {
        /*
         * On non-POSIX file systems use default Unix (umask 022) file and
         * directory permissions
         */
        if (pathIsFolder)
            perms = PosixFilePermissions.fromString("rwxr-xr-x");
        else
            perms = PosixFilePermissions.fromString("rw-r--r--");
    }

    byte[] permBytes = Utils.permsToByte(perms);
    byte[] permBytesEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(permBytes, Cipher.ENCRYPT_MODE);
    // write 2 bytes with the file's permissions
    os.write(permBytesEnc);

    // Start file encryption if the supplied relative path is not a folder
    if (!pathIsFolder) {

        long l = inputFile.length();
        byte[] fileSize = ByteBuffer.allocate(8).putLong(l).array();
        byte[] fileSizeEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(fileSize, Cipher.ENCRYPT_MODE);
        // write 8 bytes filesize
        os.write(fileSizeEnc);

        cryptoWrapperFileContent.doCipherOperation(getInputFileStream(fullSourcePath), os,
                new File(fullSourcePath).length(), Cipher.ENCRYPT_MODE, progress);
    }
}