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:edu.umn.msi.tropix.storage.core.monitor.StorageMonitorClosureImplTest.java

@Test(groups = "unit")
public void testApplyNew() {
    final Credential mockCredential = Credentials.getMock("mockid");
    final TropixObjectService tropixObjectService = EasyMock.createMock(TropixObjectService.class);
    final FolderService folderService = EasyMock.createMock(FolderService.class);
    final FileService fileService = EasyMock.createMock(FileService.class);
    final PersistentFileMapperService mapperService = EasyMock.createMock(PersistentFileMapperService.class);
    final MonitorConfig monitorConfig = EasyMock.createMock(MonitorConfig.class);
    final StorageMonitorClosureImpl closure = new StorageMonitorClosureImpl(tropixObjectService, folderService,
            mapperService, monitorConfig,

            fileService, Suppliers.ofInstance(mockCredential));
    closure.setStorageServiceUrl("http://storage");
    final File directory = FILE_UTILS.createTempDirectory();
    try {//  w ww  .  jav a2s.c  om
        final File current = directory;
        final File other = new File(new File(".."), "someother");
        final File newFile = new File(new File(new File(directory, "moo"), "submoo"), "filename.txt");
        FILE_UTILS.writeStringToFile(newFile, "moo cow");
        EasyMock.expect(mapperService.pathHasMapping(FilenameUtils.normalize(newFile.getAbsolutePath())))
                .andStubReturn(false);
        EasyMock.expect(monitorConfig.getDirectories()).andStubReturn(Lists.newArrayList(other, current));
        EasyMock.expect(monitorConfig.getSharedFolderName(current)).andStubReturn("foo");
        final Capture<TropixFile> fileCapture = EasyMockUtils.newCapture();
        final String rootSharedFolderId = UUID.randomUUID().toString(),
                childSharedFolderId = UUID.randomUUID().toString();
        final VirtualFolder rootSharedFolder = new VirtualFolder();
        rootSharedFolder.setId(rootSharedFolderId);
        EasyMock.expect(folderService.getOrCreateRootVirtualFolderWithName("mockid", "foo"))
                .andStubReturn(rootSharedFolder);
        final VirtualFolder childSharedFolder = new VirtualFolder();
        childSharedFolder.setId(childSharedFolderId);
        EasyMock.expect(folderService.getOrCreateVirtualPath(EasyMock.eq("mockid"),
                EasyMock.eq(rootSharedFolderId), EasyMock.aryEq(new String[] { "moo", "submoo" })))
                .andReturn(childSharedFolder);
        final TropixFile returnedFile = new TropixFile();
        returnedFile.setId(UUID.randomUUID().toString());
        EasyMock.expect(tropixObjectService.createFile(EasyMock.eq("mockid"), EasyMock.eq(childSharedFolderId),
                EasyMock.capture(fileCapture), EasyMock.<String>isNull())).andReturn(returnedFile);
        final Capture<String> fileIdCapture = EasyMockUtils.newCapture();
        final Capture<String> fileIdCapture2 = EasyMockUtils.newCapture();
        mapperService.registerMapping(EasyMock.capture(fileIdCapture),
                EasyMock.eq(FilenameUtils.normalize(newFile.getAbsolutePath())));
        tropixObjectService.addToSharedFolder("mockid", returnedFile.getId(), childSharedFolderId, false);
        fileService.recordLength(EasyMock.capture(fileIdCapture2), EasyMock.eq(newFile.length()));
        EasyMock.replay(folderService, fileService, tropixObjectService, mapperService, monitorConfig);
        closure.apply(newFile);
        EasyMock.verify(folderService, fileService, tropixObjectService, mapperService, monitorConfig);
        TropixFile tropixFile = fileCapture.getValue();
        assert tropixFile.getFileId().equals(fileIdCapture.getValue());
        assert tropixFile.getName().equals("filename.txt");
        assert tropixFile.getCommitted();
        assert tropixFile.getStorageServiceUrl().equals("http://storage");
        assert fileIdCapture.getValue().equals(fileIdCapture2.getValue());
    } finally {
        FILE_UTILS.deleteDirectoryQuietly(directory);
    }
}

From source file:com.hpe.caf.worker.testing.preparation.PreparationResultProcessor.java

protected Path saveContentFile(TestItem<TInput, TExpected> testItem, String baseFileName, String extension,
        InputStream dataStream) throws IOException {
    String outputFolder = getOutputFolder();
    if (configuration.isStoreTestCaseWithInput()) {

        Path path = Paths.get(testItem.getInputData().getInputFile()).getParent();
        outputFolder = Paths.get(configuration.getTestDataFolder(), path == null ? "" : path.toString())
                .toString();//w  ww. j a  v  a 2s .co  m
    }

    baseFileName = FilenameUtils.normalize(baseFileName);
    baseFileName = Paths.get(baseFileName).getFileName().toString();
    Path contentFile = Paths.get(outputFolder, baseFileName + "." + extension + ".content");
    Files.deleteIfExists(contentFile);
    Files.copy(dataStream, contentFile, REPLACE_EXISTING);

    return getRelativeLocation(contentFile);
}

From source file:com.izforge.izpack.util.LogUtils.java

public static void loadConfiguration(final Properties configuration) throws IOException {
    if (OVERRIDE) {
        LogManager manager = LogManager.getLogManager();

        // Merge global logging properties
        InputStream baseResourceStream = null;
        try {//from ww w  . java2s  . c  o m
            baseResourceStream = LogUtils.class.getResourceAsStream(LOGGING_BASE_CONFIGURATION);
            final Properties baseProps = new Properties();
            baseProps.load(baseResourceStream);
            mergeLoggingConfiguration(configuration, baseProps);
        } finally {
            IOUtils.closeQuietly(baseResourceStream);
        }

        boolean mkdirs = false;
        String pattern = null;
        if (configuration.getProperty("handlers") != null
                && configuration.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)
                && manager.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)) {
            // IzPack maintains just one log file, don't override the existing handler type of it.
            // Special use case: Command line argument -logfile "wins" over the <log-file> tag.
            // Assumption at the moment for optimization: Just FileHandler is used for configurations from install.xml.
            return;
        }
        for (String key : configuration.stringPropertyNames()) {
            if (key.equals(FILEHANDLER_CLASSNAME + ".pattern")) {
                // Workaround for not normalized file paths, for example ${INSTALL_PATH}/../install_log/name.log
                // to get them working before creating ${INSTALL_PATH} in the
                // com.izforge.izpack.installer.unpacker.UnpackerBase.preUnpack phase
                // otherwise the FileHandler will fail when opening files already in constructor and not recover from that.
                pattern = FilenameUtils.normalize(configuration.getProperty(key));
                configuration.setProperty(key, pattern);
            } else if (key.equals(FILEHANDLER_CLASSNAME + ".mkdirs")) {
                // This key goes beyond the capabilities of java.util.logging.FileHandler
                mkdirs = Boolean.parseBoolean(configuration.getProperty(key));
                configuration.remove(key);
            }
        }
        if (mkdirs && pattern != null) {
            FileUtils.forceMkdirParent(new File(pattern));
        }

        // Merge user settings compiled in
        final Properties userProps = new Properties();
        InputStream userPropsStream = LogUtils.class
                .getResourceAsStream(ResourceManager.getInstallLoggingConfigurationResourceName());
        try {
            if (userPropsStream != null) {
                userProps.load(userPropsStream);
                for (String userPropName : userProps.stringPropertyNames()) {
                    if (userPropName.endsWith(".level") && !userPropName.startsWith(FILEHANDLER_CLASSNAME)) {
                        String level = userProps.getProperty(userPropName);
                        if (level != null) {
                            configuration.setProperty(userPropName, level);
                        }
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(userPropsStream);
        }

        InputStream defaultResourceStream = null;
        try {
            defaultResourceStream = LogUtils.class.getResourceAsStream(LOGGING_CONFIGURATION);
            final Properties defaultProps = new Properties();
            defaultProps.load(defaultResourceStream);
            mergeLoggingConfiguration(configuration, defaultProps);
        } finally {
            IOUtils.closeQuietly(defaultResourceStream);
        }

        if (Debug.isDEBUG()) {
            configuration.setProperty(FILEHANDLER_CLASSNAME + ".level", Level.FINE.toString());
            configuration.setProperty(ConsoleHandler.class.getName() + ".level", Level.FINE.toString());
        }

        // Set general log level which acts as filter in front of all handlers
        String fileLevelName = configuration.getProperty(FILEHANDLER_CLASSNAME + ".level",
                Level.ALL.toString());
        Level fileLevel = Level.ALL;
        if (fileLevelName != null) {
            fileLevel = Level.parse(fileLevelName);
        }

        String consoleLevelName = configuration.getProperty(CONSOLEHANDLER_CLASSNAME + ".level",
                Level.INFO.toString());
        Level consoleLevel = Level.INFO;
        if (consoleLevelName != null) {
            consoleLevel = Level.parse(consoleLevelName);
        }

        configuration.setProperty(".level",
                (fileLevel.intValue() < consoleLevel.intValue()) ? fileLevelName : consoleLevelName);

        final PipedOutputStream out = new PipedOutputStream();
        final PipedInputStream in = new PipedInputStream(out);
        try {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        configuration.store(out, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
            }).start();

            manager.readConfiguration(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:de.uni_hildesheim.sse.ant.versionReplacement.PluginVersionReplacer.java

/**
 * Makes a file path relative to the given <code>basePath</code>.
 * //from ww w  . j  a va  2s  . c o  m
 * @param basePath the base path 
 * @param file the file to be made relative
 * @return the relative path (if <code>file</code> can be made relative)
 */
private static String makeRelative(String basePath, File file) {
    String filePath = FilenameUtils.normalize(file.getAbsolutePath());
    if (null != basePath && filePath.startsWith(basePath) && filePath.length() > basePath.length()) {
        filePath = filePath.substring(basePath.length());
    }

    filePath = filePath.replace('\\', '/');
    if (file.isDirectory() && !filePath.endsWith("/")) {
        filePath = filePath + "/";
    }

    return filePath;
}

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

/**
 * To file./*from   w w  w . j a  v  a2  s  .  c o  m*/
 * 
 * @param clazz
 *          the clazz
 * @return the file
 * @throws JBOPClassException
 *           the jBOP class exception
 */
static Path toPath(final Class<?> clazz) throws JBOPClassException {
    final CodeSource cs = clazz.getProtectionDomain().getCodeSource();
    final URL resource = cs.getLocation();
    if (resource == null) {
        throw new JBOPClassException("The Classfile for Class<" + clazz.getName() + "> couldn't be determined.",
                null);
    }
    String filename = FilenameUtils.normalize(FileUtils.toFile(resource).getAbsolutePath());
    final String path = toClassPath(clazz);
    if (filename.endsWith(".jar")) {
        filename = filename + "!" + path;
    } else {
        filename = filename + "/" + path;
    }
    return Paths.get(filename);
}

From source file:ch.unibas.fittingwizard.infrastructure.base.VmdRunner.java

private void setCommand(List<String> args, File outputFile) {

    ArrayList<String> list = new ArrayList<>();
    list.add(ExecutableName);/* w w  w . j  a va  2 s  .c o m*/

    if (!args.isEmpty()) {
        list.addAll(args);
    }

    pb.command(list);
    if (logger.isDebugEnabled()) {
        logger.debug("ProcessBuilder.command = " + StringUtils.join(pb.command(), " "));
    }

    if (outputFile != null) {
        logger.debug("redirectOutput set to " + FilenameUtils.normalize(outputFile.getAbsolutePath()));
        pb.redirectOutput(outputFile);
    } else {
        logger.debug("redirectOutput set to inheritIO");
        pb.inheritIO();
    }
}

From source file:de.iai.ilcd.xml.read.SourceReader.java

@Override
public Source parse(JXPathContext context, PrintWriter out) {

    context.registerNamespace("ilcd", "http://lca.jrc.it/ILCD/Source");

    Source source = new Source();

    // OK, now read in all fields common to all DataSet types
    readCommonFields(source, DataSetType.SOURCE, context);

    IMultiLangString shortName = parserHelper.getIMultiLanguageString("//common:shortName");
    IMultiLangString citation = parserHelper.getIMultiLanguageString("//ilcd:sourceCitation");
    String publicationType = parserHelper.getStringValue("//ilcd:publicationType");
    PublicationTypeValue publicationTypeValue = PublicationTypeValue.UNDEFINED;
    if (publicationType != null) {
        try {//  w w  w  .j av  a 2s .c  o m
            publicationTypeValue = PublicationTypeValue.fromValue(publicationType);
        } catch (Exception e) {
            if (out != null) {
                out.println("Warning: the field publicationType has an illegal value " + publicationType);
            }
        }
    }

    IMultiLangString description = parserHelper.getIMultiLanguageString("//ilcd:sourceDescriptionOrComment");

    source.setShortName(shortName);
    source.setName(shortName);
    source.setCitation(citation);
    source.setPublicationType(publicationTypeValue);
    source.setDescription(description);

    List<String> digitalFileReferences = parserHelper.getStringValues("//ilcd:referenceToDigitalFile", "uri");
    for (String digitalFileReference : digitalFileReferences) {
        logger.info("raw source data set file name is {}", getDataSetFileName());
        String baseDirectory = FilenameUtils.getFullPath(getDataSetFileName());
        // get rid of any leading/trailing white space
        digitalFileReference = digitalFileReference.trim();
        String absoluteFileName = FilenameUtils.concat(baseDirectory, digitalFileReference);
        absoluteFileName = FilenameUtils.normalize(absoluteFileName);
        logger.info("normalized form of digital file name is {}", absoluteFileName);
        logger.debug("reference to digital file: " + absoluteFileName);
        File file = new File(absoluteFileName);
        DigitalFile digitalFile = new DigitalFile();
        logger.debug("canread:" + (file.canRead()));
        String fileName = null;
        if (file.canRead()) {
            fileName = absoluteFileName; // file will be imported and Name
            // stripped after importing
        } else if (absoluteFileName.toLowerCase().endsWith(".jpg")
                || absoluteFileName.toLowerCase().endsWith(".jpeg")
                || absoluteFileName.toLowerCase().endsWith(".gif")
                || absoluteFileName.toLowerCase().endsWith(".pdf")) {
            // in case we're on a case sensitive filesystem and the case of the extension is not correct, we'll try
            // to fix this
            // TO DO this could be a little more elegant

            java.io.File parentDir = file.getParentFile();
            String fileNotFound = file.getName();
            String[] matches = parentDir.list(new CaseInsensitiveFilenameFilter(fileNotFound));
            if (matches != null && matches.length == 1) {
                fileName = parentDir + File.separator + matches[0];
                logger.debug(fileName);
            } else {
                fileName = digitalFileReference;
            }
        } else {
            logger.debug("file could not be read from " + file.getAbsolutePath());
            fileName = digitalFileReference; // Not a local filename, likely
            // be an URL to external
            // resource
        } // logger.debug("found reference to digital file: " + fileName);
        logger.info("set filename of digital file to {}", fileName);
        digitalFile.setFileName(fileName);
        source.addFile(digitalFile);
    }

    List<GlobalReference> contacts = commonReader.getGlobalReferences("//ilcd:referenceToContact", out);
    for (GlobalReference contact : contacts) {
        source.addContact(contact);
    }

    return source;
}

From source file:com.igormaznitsa.mindmap.model.ExtraFile.java

public boolean isSame(@Nonnull final File baseFolder, @Nonnull final MMapURI file) {
    final File theFile = this.fileUri.asFile(baseFolder);
    final File thatFile = file.asFile(baseFolder);

    final String theFilePath = FilenameUtils.normalize(theFile.getAbsolutePath());
    final String thatFilePath = FilenameUtils.normalize(thatFile.getAbsolutePath());

    return theFilePath.equals(thatFilePath);
}

From source file:ch.unibas.fittingwizard.infrastructure.base.PythonScriptRunner.java

private void setCommand(File scriptName, List<String> args, File outputFile) {
    if (scriptName != null && !scriptName.exists()) {
        throw new ScriptExecutionException("Could not find Python script " + scriptName);
    }/*from  w  w w .j a v  a 2s  .c o m*/

    ArrayList<String> list = new ArrayList<>();
    list.add(ExecutableName);
    if (scriptName != null) {
        list.add(FilenameUtils.normalize(scriptName.getAbsolutePath()));
    }
    if (!args.isEmpty()) {
        list.addAll(args);
    }

    pb.command(list);
    if (logger.isDebugEnabled()) {
        logger.debug("ProcessBuilder.command = " + StringUtils.join(pb.command(), " "));
    }

    if (outputFile != null) {
        logger.debug("redirectOutput an redirectError set to "
                + FilenameUtils.normalize(outputFile.getAbsolutePath()));
        pb.redirectOutput(outputFile);
        pb.redirectError(outputFile);
    } else {
        logger.debug("redirectOutput set to inheritIO");
        pb.inheritIO();
    }
}

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

/**
 * Attempts to create a temporary directory in the installer folder to
 * unpack the jar./*from   w w  w.  j  a v a  2  s  .  c  om*/
 *
 * @return
 * @throws IOException
 */
private static File getTempDir() throws IOException {
    Random rand = new Random();
    String hex = Integer.toHexString(rand.nextInt(Integer.MAX_VALUE));
    File tmp = new File(FilenameUtils.concat(InstallerConfig.getInstallerDir(), hex + "/"));
    int t = 0;
    while (tmp.exists() && t < 10) {
        hex = Integer.toHexString(rand.nextInt(Integer.MAX_VALUE));
        tmp = new File(FilenameUtils.normalize("./" + hex + "/"));
        t++;
    }
    if (tmp.exists()) {
        throw new IOException("Error creating temporary folder. Too many failures.");
    }
    return tmp;
}