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.ejisto.event.listener.SessionRecorderManager.java

void startSessionRecording(WebApplicationDescriptor webApplicationDescriptor) {
    try {// w  w  w.  jav a 2 s.  c  o  m
        log.debug("start listening for collected data...");
        File outputDir = selectOutputDirectory(application,
                settingsRepository.getSettingValue(LAST_OUTPUT_PATH), true, settingsRepository);
        if (outputDir == null) {
            return;
        }
        final WebApplicationDescriptor descriptor = createTempWebApplicationDescriptor(
                webApplicationDescriptor);
        zipDirectory(new File(descriptor.getDeployablePath()),
                FilenameUtils.normalize(outputDir.getAbsolutePath() + descriptor.getContextPath() + ".war"));
        applicationEventDispatcher
                .registerApplicationEventListener(new ApplicationListener<CollectedDataReceived>() {
                    @Override
                    public void onApplicationEvent(CollectedDataReceived event) {
                        try {
                            CollectedData collectedData = event.getData();
                            String contextPath = collectedData.getContextPath();
                            Set<MockedField> fields = putIfAbsent(contextPath, RECORDED_FIELDS);
                            Set<CollectedData> data = putIfAbsent(contextPath, RECORDED_DATA);
                            fields.addAll(flattenAttributes(collectedData.getRequestAttributes()));
                            fields.addAll(flattenAttributes(collectedData.getSessionAttributes()));
                            replace(contextPath, RECORDED_FIELDS, fields);
                            data.add(collectedData);
                            replace(contextPath, RECORDED_DATA, data);
                        } catch (Exception e) {
                            SessionRecorderManager.log.error("got exception while collecting fields", e);
                        }
                    }

                    @Override
                    public Class<CollectedDataReceived> getTargetEventType() {
                        return CollectedDataReceived.class;
                    }
                });
    } catch (IOException | JDOMException e) {
        eventManager.publishEvent(new ApplicationError(this, ApplicationError.Priority.HIGH, e));
    }
}

From source file:com.ariht.maven.plugins.config.ConfigProcessorMojo.java

/**
 * Prepare output directory: base-path/filter-sub-dir/template-dir/template.name
 *//*from w  ww  . j av  a2  s .  c om*/
private String createOutputDirectory(final FileInfo template, final FileInfo filter,
        final String outputBasePath) throws IOException {
    final String outputDirectory = getOutputPath(template, filter, outputBasePath);
    final File outputDir = new File(outputDirectory);
    if (!outputDir.exists()) {
        getLog().debug("Creating : " + outputDir);
        FileUtils.forceMkdir(outputDir);
    }
    return FilenameUtils.normalize(outputDirectory);
}

From source file:ddf.catalog.cache.impl.ResourceCache.java

public void setProductCacheDirectory(final String productCacheDirectory) {
    String newProductCacheDirectoryDir = "";

    if (!StringUtils.isEmpty(productCacheDirectory)) {
        String path = FilenameUtils.normalize(productCacheDirectory);
        File directory = new File(path);

        // Create the directory if it doesn't exist
        if ((!directory.exists() && directory.mkdirs())
                || (directory.isDirectory() && directory.canRead() && directory.canWrite())) {
            LOGGER.debug("Setting product cache directory to: {}", path);
            newProductCacheDirectoryDir = path;
        }/*from  www  .j a  va 2 s.  co m*/
    }

    // if productCacheDirectory is invalid or productCacheDirectory is
    // an empty string, default to the DEFAULT_PRODUCT_CACHE_DIRECTORY in <karaf.home>
    if (newProductCacheDirectoryDir.isEmpty()) {
        try {
            final File karafHomeDir = new File(System.getProperty(KARAF_HOME));

            if (karafHomeDir.isDirectory()) {
                final File fspDir = new File(karafHomeDir + File.separator + DEFAULT_PRODUCT_CACHE_DIRECTORY);

                // if directory does not exist, try to create it
                if (fspDir.isDirectory() || fspDir.mkdirs()) {
                    LOGGER.debug("Setting product cache directory to: {}", fspDir.getAbsolutePath());
                    newProductCacheDirectoryDir = fspDir.getAbsolutePath();
                } else {
                    LOGGER.warn(
                            "Unable to create directory: {}. Please check for proper permissions to create this folder. Instead using default folder.",
                            fspDir.getAbsolutePath());
                }
            } else {
                LOGGER.warn(
                        "Karaf home folder defined by system property {} is not a directory.  Using default folder.",
                        KARAF_HOME);
            }
        } catch (NullPointerException npe) {
            LOGGER.warn(
                    "Unable to create FileSystemProvider folder - {} system property not defined. Using default folder.",
                    KARAF_HOME);
        }
    }

    this.productCacheDirectory = newProductCacheDirectoryDir;

    LOGGER.debug("Set product cache directory to: {}", this.productCacheDirectory);
}

From source file:com.kegare.caveworld.world.WorldProviderDeepCaveworld.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.getDeepDimension()) {
            target.add(CaveUtils.respawnPlayer((EntityPlayerMP) obj, 0));
        }/*from  ww w  .  j a  v  a2s  .  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.getDeepDimension();
                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.getDeepDimension());
            }
        }
    }
}

From source file:de.uzk.hki.da.cb.ScanAction.java

protected TreeSet<String> neverConverted() {
    TreeSet<String> ret = new TreeSet<String>();
    ret.add(C.PREMIS_XML);//w  w  w .  j a  v  a  2  s .co m
    ret.add(C.PUBLIC_METS);

    if (o.getMetadata_file() != null) {
        ret.add(o.getMetadata_file());
        String packageType = o.getPackage_type();

        if ("EAD".equals(packageType)) {
            String mfPathSrc = o.getLatest(o.getMetadata_file()).getPath().toString();
            EadMetsMetadataStructure emms = null;
            try {
                emms = new EadMetsMetadataStructure(wa.dataPath(), new File(mfPathSrc), o.getDocuments());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (emms != null) {
                List<String> metse = emms.getMetsRefsInEad();
                for (int mmm = 0; mmm < metse.size(); mmm++) {
                    String mets = metse.get(mmm);
                    String normMets = FilenameUtils.normalize(mets);
                    if (normMets != null) {
                        mets = normMets;
                    }
                    ret.add(mets);
                }
            }
        }
    }

    return ret;
}

From source file:com.ariht.maven.plugins.config.ConfigProcessorMojo.java

/**
 * Concatenate together the filter's directory with the template's - 'deploy' templates just go into the
 * base path so only have the filter (i.e. the environment they are intended for).
 */// w  w w. java  2s.co m
private String getOutputPath(final FileInfo template, final FileInfo filter, final String outputBasePath) {
    final String outputPath = outputBasePath + PATH_SEPARATOR + filter.getRelativeSubDirectory()
            + filter.getNameWithoutExtension() + PATH_SEPARATOR + template.getRelativeSubDirectory()
            + PATH_SEPARATOR;
    return FilenameUtils.normalize(outputPath);
}

From source file:de.uzk.hki.da.cb.ScanForPresentationAction.java

protected TreeSet<String> neverConverted() {
    TreeSet<String> ret = new TreeSet<String>();
    ret.add(PREMIS_XML);/*  w  w w.j  a  va2s .c  om*/
    ret.add(C.PUBLIC_METS);

    if (o.getMetadata_file() != null) {
        ret.add(o.getMetadata_file());
        String packageType = o.getPackage_type();

        if ("EAD".equals(packageType)) {
            String mfPathSrc = o.getLatest(o.getMetadata_file()).getPath().toString();
            EadMetsMetadataStructure emms = null;
            try {
                emms = new EadMetsMetadataStructure(wa.dataPath(), new File(mfPathSrc), o.getDocuments());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (emms != null) {
                List<String> metse = emms.getMetsRefsInEad();
                for (int mmm = 0; mmm < metse.size(); mmm++) {
                    String mets = metse.get(mmm);
                    String normMets = FilenameUtils.normalize(mets);
                    if (normMets != null) {
                        mets = normMets;
                    }
                    ret.add(mets);
                }
            }
        }
    }

    return ret;
}

From source file:com.silverpeas.attachment.servlets.DragAndDrop.java

/**
 * Method declaration//from w ww  .j a  v  a  2  s  .  c  o  m
 * @param req
 * @param res
 * @throws IOException
 * @throws ServletException
 * @see
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    if (!FileUploadUtil.isRequestMultipart(req)) {
        res.getOutputStream().println("SUCCESS");
        return;
    }
    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false);
    try {
        req.setCharacterEncoding("UTF-8");
        String componentId = req.getParameter("ComponentId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId);
        String id = req.getParameter("PubId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id);
        String userId = req.getParameter("UserId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId);
        String context = req.getParameter("Context");
        boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt"));

        List<FileItem> items = FileUploadUtil.parseRequest(req);
        for (FileItem item : items) {
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getFieldName());
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getName() + "; " + item.getString("UTF-8"));

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null) {
                    String physicalName = saveFileOnDisk(item, componentId, context);
                    String mimeType = AttachmentController.getMimeType(fileName);
                    long size = item.getSize();
                    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item size = " + size);
                    // create AttachmentDetail Object
                    AttachmentDetail attachment = new AttachmentDetail(
                            new AttachmentPK(null, "useless", componentId), physicalName, fileName, null,
                            mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId));
                    attachment.setAuthor(userId);
                    try {
                        AttachmentController.createAttachment(attachment, bIndexIt);
                    } catch (Exception e) {
                        // storing data into DB failed, delete file just added on disk
                        deleteFileOnDisk(physicalName, componentId, context);
                        throw e;
                    }
                    // Specific case: 3d file to convert by Actify Publisher
                    if (actifyPublisherEnable) {
                        String extensions = settings.getString("Actify3dFiles");
                        StringTokenizer tokenizer = new StringTokenizer(extensions, ",");
                        // 3d native file ?
                        boolean fileForActify = false;
                        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                                "nb tokenizer =" + tokenizer.countTokens());
                        String type = FileRepositoryManager.getFileExtension(fileName);
                        while (tokenizer.hasMoreTokens() && !fileForActify) {
                            String extension = tokenizer.nextToken();
                            fileForActify = type.equalsIgnoreCase(extension);
                        }
                        if (fileForActify) {
                            String dirDestName = "a_" + componentId + "_" + id;
                            String actifyWorkingPath = settings.getString("ActifyPathSource")
                                    + File.separatorChar + dirDestName;

                            String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath;
                            if (!new File(destPath).exists()) {
                                FileRepositoryManager.createGlobalTempPath(actifyWorkingPath);
                            }
                            String normalizedFileName = FilenameUtils.normalize(fileName);
                            if (normalizedFileName == null) {
                                normalizedFileName = FilenameUtils.getName(fileName);
                            }
                            String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath
                                    + File.separatorChar + normalizedFileName;
                            FileRepositoryManager
                                    .copyFile(AttachmentController.createPath(componentId, "Images")
                                            + File.separatorChar + physicalName, destFile);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
        res.getOutputStream().println("ERROR");
        return;
    }
    res.getOutputStream().println("SUCCESS");
}

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

/**
 * Installs the specified list of mods, updating the gui as it goes.
 *
 * @param mods The list of mods to install.
 * @param text The text area to update with logging statements.
 * @param progressBar The progress bar to update.
 *//*from  www .  j av  a2  s .  c  om*/
public static void guiInstall(List<String> mods, JTextArea text, JProgressBar progressBar) {

    //Create backups to restore if the install fails.
    try {
        createBackup();
    } catch (IOException e) {
        text.append("Failed to create backup copies of minecraft.jar and mods folder");
        LOGGER.error("Failed to create backup copies of minecraft.jar and mods folder", e);
        return;
    }

    //Create a temp directory where we can unpack the jar and install mods.
    File tmp;
    try {
        tmp = getTempDir();
    } catch (IOException e) {
        text.append("Error creating temp directory!");
        LOGGER.error("Install Error", e);
        return;
    }
    if (!tmp.mkdirs()) {
        text.append("Error creating temp directory!");
        return;
    }

    File mcDir = new File(InstallerConfig.getMinecraftFolder());
    File mcJar = new File(InstallerConfig.getMinecraftJar());
    File reqDir = new File(InstallerConfig.getRequiredModsFolder());

    //Calculate the number of "tasks" for the progress bar.
    int reqMods = 0;
    for (File f : reqDir.listFiles()) {
        if (f.isDirectory()) {
            reqMods++;
        }
    }
    //3 "other" steps: unpack, repack, delete temp
    int baseTasks = 3;
    int taskSize = reqMods + mods.size() + baseTasks;
    progressBar.setMinimum(0);
    progressBar.setMaximum(taskSize);
    int task = 1;

    try {
        text.append("Unpacking minecraft.jar\n");
        unpackMCJar(tmp, mcJar);
        progressBar.setValue(task++);

        text.append("Installing Core mods\n");
        //TODO specific ordering required!
        for (File mod : reqDir.listFiles()) {
            if (!mod.isDirectory()) {
                continue;
            }
            String name = mod.getName();
            text.append("...Installing " + name + "\n");
            installMod(mod, tmp, mcDir);
            progressBar.setValue(task++);
        }

        if (!mods.isEmpty()) {
            text.append("Installing Extra mods\n");
            //TODO specific ordering required!
            for (String name : mods) {
                File mod = new File(FilenameUtils
                        .normalize(FilenameUtils.concat(InstallerConfig.getExtraModsFolder(), name)));
                text.append("...Installing " + name + "\n");
                installMod(mod, tmp, mcDir);
                progressBar.setValue(task++);
            }
        }

        text.append("Repacking minecraft.jar\n");
        repackMCJar(tmp, mcJar);
        progressBar.setValue(task++);
    } catch (Exception e) {
        text.append("!!!Error installing mods!!!");
        LOGGER.error("Installation error", e);
        try {
            restoreBackup();
        } catch (IOException ioe) {
            text.append("Error while restoring backup files minecraft.jar.backup and mods_backup folder\n!");
            LOGGER.error("Error while restoring backup files minecraft.jar.backup and mods_backup folder!",
                    ioe);
        }
    }

    text.append("Deleting temporary files\n");
    try {
        FileUtils.deleteDirectory(tmp);
        progressBar.setValue(task++);
    } catch (IOException e) {
        text.append("Error deleting temporary files!\n");
        LOGGER.error("Install Error", e);
        return;
    }
    text.append("Finished!");

}

From source file:com.eincs.decanter.handler.StaticFileHandler.java

private static String sanitizeUri(File directory, String uri) {
    // Decode the path.
    try {/*  ww  w.ja  v  a2s .c om*/
        uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        try {
            uri = URLDecoder.decode(uri, "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            throw new Error();
        }
    }

    // Convert file separators.
    uri = uri.replace('/', File.separatorChar);

    // Simplistic dumb security check.
    // You will have to do something serious in the production environment.
    if (uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.startsWith(".")
            || uri.endsWith(".")) {
        return null;
    }

    // Convert to absolute path.
    String filePath = new File(directory, uri).getAbsolutePath();
    return FilenameUtils.normalize(filePath);
}