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:com.ewcms.publication.PublishService.java

@Override
public void afterPropertiesSet() throws Exception {

    if (tempRoot == null) {
        tempRoot = System.getProperty("java.io.tmpdir");
    }//from  w  w  w.jav a 2 s  .c o m
    tempRoot = FilenameUtils.normalize(tempRoot);
    try {
        testTempRoot(tempRoot);
    } catch (IOException e) {
        throw new IOException(tempRoot + " not write please check.", e);
    }

    if (pubRunner == null) {
        pubRunner = new SimplePublishRunner(publishDao);
    }
    pubRunner.start();
}

From source file:egovframework.com.utl.sys.fsm.service.FileSystemUtils.java

/**
 * Find free space on the Windows platform using the 'dir' command.
 *
 * @param path  the path to get free space for, including the colon
 * @return the amount of free drive space on the drive
 * @throws IOException if an error occurs
 *//*  w  ww . ja v  a 2 s .co  m*/
long freeSpaceWindows(String path) throws IOException {
    path = FilenameUtils.normalize(path);
    if (path.length() > 2 && path.charAt(1) == ':') {
        path = path.substring(0, 2); // seems to make it work
    }

    // build and run the 'dir' command
    String[] cmdAttribs = new String[] { "cmd.exe", "/C", "dir /-c " + path };

    // read in the output of the command to an ArrayList
    List lines = performCommand(cmdAttribs, Integer.MAX_VALUE);

    // now iterate over the lines we just read and find the LAST
    // non-empty line (the free space bytes should be in the last element
    // of the ArrayList anyway, but this will ensure it works even if it's
    // not, still assuming it is on the last non-blank line)
    for (int i = lines.size() - 1; i >= 0; i--) {
        String line = (String) lines.get(i);
        if (line.length() > 0) {
            return parseDir(line, path);
        }
    }
    // all lines are blank
    throw new IOException("Command line 'dir /-c' did not return any info " + "for path '" + path + "'");
}

From source file:com.ejisto.event.listener.SessionRecorderManager.java

private WebApplicationDescriptor createTempWebApplicationDescriptor(WebApplicationDescriptor original)
        throws IOException, JDOMException {
    Path path = Files.createTempDirectory(original.getContextPath().replaceAll("/", "_"));
    unzipFile(original.getWarFile(), path.toString());
    File targetDir = new File(FilenameUtils.normalize(path.toString() + "/WEB-INF/lib/"));
    copyEjistoLibs(true, targetDir.toPath());
    WebApplicationDescriptor temp = WebApplicationDescriptor.copyOf(original);
    temp.setDeployablePath(path.toString());
    modifyWebXml(temp);/* w  ww  . ja va 2s . c o m*/
    return temp;
}

From source file:com.sangupta.jerry.util.FileUtils.java

/**
 * List the files in the given path string with wild cards.
 * //w  w  w  .  j  av  a 2 s .c o m
 * @param baseDir
 *            the base directory to search for files in
 * 
 * @param filePathWithWildCards
 *            the file path to search in - can be absolute
 * 
 * @param recursive
 *            whether to look in sub-directories or not
 * 
 * @param additionalFilters
 *            additional file filters that need to be used when scanning for
 *            files
 * 
 * @return the list of files and directories that match the criteria
 */
public static List<File> listFiles(File baseDir, String filePathWithWildCards, boolean recursive,
        List<IOFileFilter> additionalFilters) {
    if (filePathWithWildCards == null) {
        throw new IllegalArgumentException("Filepath cannot be null");
    }

    // change *.* to *
    filePathWithWildCards = filePathWithWildCards.replace("*.*", "*");

    // normalize
    filePathWithWildCards = FilenameUtils.normalize(filePathWithWildCards);

    if (filePathWithWildCards.endsWith(File.pathSeparator)) {
        filePathWithWildCards += "*";
    }

    // check if this is an absolute path or not
    String prefix = FilenameUtils.getPrefix(filePathWithWildCards);
    final boolean isAbsolute = !prefix.isEmpty();

    // change the base dir if absolute directory
    if (isAbsolute) {
        baseDir = new File(filePathWithWildCards);
        if (!baseDir.isDirectory()) {
            // not a directory - get the base directory
            filePathWithWildCards = baseDir.getName();
            if (filePathWithWildCards.equals("~")) {
                filePathWithWildCards = "*";
            }

            if (AssertUtils.isEmpty(filePathWithWildCards)) {
                filePathWithWildCards = "*";
            }

            baseDir = baseDir.getParentFile();
            if (baseDir == null) {
                baseDir = getUsersHomeDirectory();
            }
        }
    }

    // check if the provided argument is a directory
    File dir = new File(filePathWithWildCards);
    if (dir.isDirectory()) {
        baseDir = dir.getAbsoluteFile();
        filePathWithWildCards = "*";
    } else {
        // let's check for base directory
        File parent = dir.getParentFile();
        if (parent != null) {
            baseDir = parent.getAbsoluteFile();
            filePathWithWildCards = dir.getName();
        }
    }

    // check for user home
    String basePath = baseDir.getPath();
    if (basePath.startsWith("~")) {
        basePath = getUsersHomeDirectory().getAbsolutePath() + File.separator + basePath.substring(1);
        basePath = FilenameUtils.normalize(basePath);
        baseDir = new File(basePath);
    }

    // now read the files
    WildcardFileFilter wildcardFileFilter = new WildcardFileFilter(filePathWithWildCards, IOCase.SYSTEM);
    IOFileFilter finalFilter = wildcardFileFilter;
    if (AssertUtils.isNotEmpty(additionalFilters)) {
        additionalFilters.add(0, wildcardFileFilter);
        finalFilter = new AndFileFilter(additionalFilters);
    }

    Collection<File> files = org.apache.commons.io.FileUtils.listFiles(baseDir, finalFilter,
            recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE);

    return (List<File>) files;
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private void addManifestReferences(XMLSignatureFactory signatureFactory, Document document,
        List<Reference> manifestReferences)
        throws IOException, JAXBException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    CTTypes contentTypes = getContentTypes();
    List<String> relsEntryNames = getRelsEntryNames();
    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Set<String> digestedPartNames = new HashSet<String>();
    for (String relsEntryName : relsEntryNames) {
        CTRelationships relationships = getRelationships(relsEntryName);
        List<CTRelationship> relationshipList = relationships.getRelationship();
        RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();
        for (CTRelationship relationship : relationshipList) {
            String relationshipType = relationship.getType();
            STTargetMode targetMode = relationship.getTargetMode();
            if (null != targetMode) {
                LOG.debug("TargetMode: " + targetMode.name());
                if (targetMode == STTargetMode.EXTERNAL) {
                    /*// w w w .j a  v  a2  s . c  om
                     * ECMA-376 Part 2 - 3rd edition
                     * 
                     * 13.2.4.16 Manifest Element
                     * 
                     * "The producer shall not create a Manifest element that references any data outside of the package."
                     */
                    continue;
                }
            }
            if (false == OOXMLSignatureFacet.isSignedRelationship(relationshipType)) {
                continue;
            }
            String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/"));
            String relationshipTarget = relationship.getTarget();
            String partName = FilenameUtils
                    .separatorsToUnix(FilenameUtils.normalize(baseUri + relationshipTarget));
            LOG.debug("part name: " + partName);
            String relationshipId = relationship.getId();
            parameterSpec.addRelationshipReference(relationshipId);
            String contentType = getContentType(contentTypes, partName);
            if (relationshipType.endsWith("customXml")) {
                if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) {
                    LOG.debug("skipping customXml with content type: " + contentType);
                    continue;
                }
            }
            if (false == digestedPartNames.contains(partName)) {
                /*
                 * We only digest a part once.
                 */
                Reference reference = signatureFactory.newReference(partName + "?ContentType=" + contentType,
                        digestMethod);
                manifestReferences.add(reference);
                digestedPartNames.add(partName);
            }
        }
        if (false == parameterSpec.getSourceIds().isEmpty()) {
            List<Transform> transforms = new LinkedList<Transform>();
            transforms.add(
                    signatureFactory.newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));
            transforms.add(signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
                    (TransformParameterSpec) null));
            Reference reference = signatureFactory.newReference(
                    "/" + relsEntryName
                            + "?ContentType=application/vnd.openxmlformats-package.relationships+xml",
                    digestMethod, transforms, null, null);

            manifestReferences.add(reference);
        }
    }
}

From source file:eu.asterics.mw.services.TestResourceRegistry.java

@Test
public void testSetAREBaseURI() throws URISyntaxException {
    //Test getting and relative to absolute
    testGetAREBaseURI();//from   w ww . j  a  va2 s. co m
    testRelativeToAbsoluteToRelative();

    //change base URI
    String testURIString = "C:\\Program Files (x86)\\eclipse\\";
    if (!OSUtils.isWindows()) {
        testURIString = "/var/log/";
    }

    testURIString = FilenameUtils.normalize(testURIString);
    URI newURI;
    newURI = new File(testURIString).toURI();
    System.out.println("Setting new AREBaseURI to <" + newURI.getPath() + ">");
    URI oldURI = ResourceRegistry.getInstance().getAREBaseURI();
    ResourceRegistry.getInstance().setAREBaseURI(newURI);

    //Test getting and relative to absolute again
    testGetAREBaseURI();
    testRelativeToAbsoluteToRelative();

    //Set old URI again to don't influence other tests.
    ResourceRegistry.getInstance().setAREBaseURI(oldURI);
}

From source file:com.iyonger.apm.web.configuration.Config.java

/**
 * Resolve nGrinder home path./*from  w  ww.  j  ava 2 s .c o m*/
 *
 * @return resolved home
 */
protected Home resolveHome() {
    if (StringUtils.isNotBlank(System.getProperty("unit-test"))) {
        final String tempDir = System.getProperty("java.io.tmpdir");
        final File tmpHome = new File(tempDir, ".ngrinder");
        if (tmpHome.mkdirs()) {
            LOG.info("{} is created", tmpHome.getPath());
        }
        try {
            FileUtils.forceDeleteOnExit(tmpHome);
        } catch (IOException e) {
            LOG.error("Error while setting forceDeleteOnExit on {}", tmpHome);
        }
        return new Home(tmpHome);
    }
    String userHomeFromEnv = System.getenv("NGRINDER_HOME");
    String userHomeFromProperty = System.getProperty("ngrinder.home");
    if (!StringUtils.equals(userHomeFromEnv, userHomeFromProperty)) {
        CoreLogger.LOGGER.warn("The path to ngrinder-home is ambiguous:");
        CoreLogger.LOGGER.warn("    System Environment:  NGRINDER_HOME=" + userHomeFromEnv);
        CoreLogger.LOGGER.warn("    Java System Property:  ngrinder.home=" + userHomeFromProperty);
        CoreLogger.LOGGER.warn("    '" + userHomeFromProperty + "' is accepted.");
    }
    String userHome = StringUtils.defaultIfEmpty(userHomeFromProperty, userHomeFromEnv);
    if (StringUtils.isEmpty(userHome)) {
        userHome = System.getProperty("user.home") + File.separator + NGRINDER_DEFAULT_FOLDER;
    } else if (StringUtils.startsWith(userHome, "~" + File.separator)) {
        userHome = System.getProperty("user.home") + File.separator + userHome.substring(2);
    } else if (StringUtils.startsWith(userHome, "." + File.separator)) {
        userHome = System.getProperty("user.dir") + File.separator + userHome.substring(2);
    }

    userHome = FilenameUtils.normalize(userHome);
    File homeDirectory = new File(userHome);
    CoreLogger.LOGGER.info("nGrinder home directory:{}.", homeDirectory.getPath());

    return new Home(homeDirectory);
}

From source file:it.grid.storm.info.SpaceInfoManager.java

/**
 * Populate with DU tasks// w w  w.j  a v  a  2s  .co m
 */
private void fakeSAtoAnalyze(List<String> absPaths) {

    // Create a list of SSD using the list of AbsPaths
    List<StorageSpaceData> toAnalyze = new ArrayList<StorageSpaceData>();
    for (String path : absPaths) {
        path = path + File.separator;
        String pathNorm = FilenameUtils.normalize(FilenameUtils.getFullPath(path));
        StorageSpaceData ssd = new StorageSpaceData();
        try {
            PFN spaceFN = PFN.make(pathNorm);
            log.trace("PFN : ", spaceFN);
            ssd.setSpaceToken(TSpaceToken.make(new it.grid.storm.common.GUID().toString()));

            ssd.setSpaceFileName(spaceFN);
            toAnalyze.add(ssd);
        } catch (InvalidTSpaceTokenAttributesException e) {
            log.error("Unable to create Space Token. {}", e.getMessage(), e);
        } catch (InvalidPFNAttributeException e) {
            log.error("Unable to create PFN. {}", e.getMessage(), e);
        }
    }

    for (StorageSpaceData ssd : toAnalyze) {
        TSpaceToken sT = ssd.getSpaceToken();
        String absPath = ssd.getSpaceFileNameString();
        try {
            bDUTasks.addTask(sT, absPath);
            log.debug("Added {} to the DU-Task Queue. (Task queue size: {})", absPath, bDUTasks.howManyTask());
        } catch (SAInfoException e) {
            log.error(e.getMessage(), e);
        }
    }
    log.info("Background DU tasks size: {}", bDUTasks.getTasks().size());
}

From source file:com.xpandit.fusionplugin.pentaho.content.FusionApi.java

@POST
@Path("/uploadFile")
@Consumes("multipart/form-data")
@Produces(MimeTypes.JSON)// ww w.j av  a 2  s.com
public String store(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("path") String path)
        throws JSONException {

    String fileName = checkRelativePathSanity(fileDetail.getFileName()),
            savePath = checkRelativePathSanity(path);
    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    byte[] contents;
    try {
        IOUtils.copy(uploadedInputStream, oStream);
        oStream.flush();
        contents = oStream.toByteArray();
        oStream.close();
    } catch (IOException e) {
        logger.error(e);
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }

    if (fileName == null) {
        logger.error("parameter fileName must not be null");
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }
    if (!fileName.endsWith(".zip")) {
        logger.error("parameter fileName must be zip file");
        return buildResponseJson(false, "You are only allowed to upload zip files");
    }
    if (savePath == null) {
        logger.error("parameter path must not be null");
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }
    if (contents == null) {
        logger.error("File content must not be null");
        return buildResponseJson(false, DEFAULT_STORE_ERROR_MESSAGE);
    }

    FusionPluginSettings fps = new FusionPluginSettings();
    String basePath = fps.getBasePath() + DEFAULT_STORE_UPLOAD_FOLDER;
    String fullPath = FilenameUtils.normalize(savePath + "/" + fileName);
    if (fileExists(checkRelativePathSanity(fullPath), basePath)) {
        return buildResponseJson(false, "File " + fileName + " already exists!");
    }

    File f;

    if (checkRelativePathSanity(fullPath).startsWith(File.separator)) {
        f = new File(basePath + checkRelativePathSanity(fullPath));
    } else {
        f = new File(basePath + File.separator + checkRelativePathSanity(fullPath));
    }

    FileOutputStream fos;

    try {
        fos = new FileOutputStream(f, false);
        fos.write(contents);
        fos.flush();
        fos.close();
        return buildResponseJson(true, "File " + fileName + " Saved!");
    } catch (FileNotFoundException fnfe) {
        logger.error("Unable to create file. Check permissions on folder " + fullPath, fnfe);
        return buildResponseJson(false, "File " + fileName + " not Saved!");
    } catch (IOException ioe) {
        logger.error("Error caught while writing file", ioe);
        return buildResponseJson(false, "File " + fileName + " not Saved!");
    }
}

From source file:com.kegare.caveworld.world.WorldProviderCaveworld.java

public static void regenerate(final boolean backup) {
    final File dir = getDimDir();
    final String name = dir.getName().substring(4);
    final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
    Set<EntityPlayerMP> target = Sets.newHashSet();

    for (Object obj : server.getConfigurationManager().playerEntityList.toArray()) {
        if (obj != null && ((EntityPlayerMP) obj).dimension == CaveworldAPI.getDimension()) {
            target.add(CaveUtils.respawnPlayer((EntityPlayerMP) obj, 0));
        }//from   ww  w .ja  va  2  s .co m
    }

    boolean result = new ForkJoinPool().invoke(new RecursiveTask<Boolean>() {
        @Override
        protected Boolean compute() {
            IChatComponent component;

            try {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerating", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                if (server.isSinglePlayer()) {
                    Caveworld.network.sendToAll(new RegenerateMessage(backup));
                }

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(0));

                CaveBlocks.caveworld_portal.portalDisabled = true;

                int dim = CaveworldAPI.getDimension();
                WorldServer world = DimensionManager.getWorld(dim);

                if (world != null) {
                    world.saveAllChunks(true, null);
                    world.flush();

                    MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(world));

                    DimensionManager.setWorld(dim, null);
                }

                if (dir != null) {
                    if (backup) {
                        File parent = dir.getParentFile();
                        final Pattern pattern = Pattern.compile("^" + dir.getName() + "_bak-..*\\.zip$");
                        File[] files = parent.listFiles(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String name) {
                                return pattern.matcher(name).matches();
                            }
                        });

                        if (files != null && files.length >= 5) {
                            Arrays.sort(files, new Comparator<File>() {
                                @Override
                                public int compare(File o1, File o2) {
                                    int i = CaveUtils.compareWithNull(o1, o2);

                                    if (i == 0 && o1 != null && o2 != null) {
                                        try {
                                            i = Files.getLastModifiedTime(o1.toPath())
                                                    .compareTo(Files.getLastModifiedTime(o2.toPath()));
                                        } catch (IOException e) {
                                        }
                                    }

                                    return i;
                                }
                            });

                            FileUtils.forceDelete(files[0]);
                        }

                        Calendar calendar = Calendar.getInstance();
                        String year = Integer.toString(calendar.get(Calendar.YEAR));
                        String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
                        String day = String.format("%02d", calendar.get(Calendar.DATE));
                        String hour = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
                        String minute = String.format("%02d", calendar.get(Calendar.MINUTE));
                        String second = String.format("%02d", calendar.get(Calendar.SECOND));
                        File bak = new File(parent,
                                dir.getName() + "_bak-" + Joiner.on("").join(year, month, day) + "-"
                                        + Joiner.on("").join(hour, minute, second) + ".zip");

                        if (bak.exists()) {
                            FileUtils.deleteQuietly(bak);
                        }

                        component = new ChatComponentText(StatCollector
                                .translateToLocalFormatted("caveworld.regenerate.backingup", name));
                        component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                        server.getConfigurationManager().sendChatMsg(component);

                        Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(1));

                        if (CaveUtils.archiveDirZip(dir, bak)) {
                            ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_FILE,
                                    FilenameUtils.normalize(bak.getParentFile().getPath()));

                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backedup", name));
                            component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true)
                                    .setChatClickEvent(click);
                            server.getConfigurationManager().sendChatMsg(component);
                        } else {
                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backup.failed", name));
                            component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                            server.getConfigurationManager().sendChatMsg(component);
                        }
                    }

                    FileUtils.deleteDirectory(dir);
                }

                if (DimensionManager.shouldLoadSpawn(dim)) {
                    DimensionManager.initDimension(dim);

                    world = DimensionManager.getWorld(dim);

                    if (world != null) {
                        world.saveAllChunks(true, null);
                        world.flush();
                    }
                }

                CaveBlocks.caveworld_portal.portalDisabled = false;

                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerated", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(2));

                return true;
            } catch (Exception e) {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.failed", name));
                component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(3));

                CaveLog.log(Level.ERROR, e, component.getUnformattedText());
            }

            return false;
        }
    });

    if (result && (Config.hardcore || Config.caveborn)) {
        for (EntityPlayerMP player : target) {
            if (!CaveworldAPI.isEntityInCaveworld(player)) {
                CaveUtils.forceTeleport(player, CaveworldAPI.getDimension());
            }
        }
    }
}