Example usage for org.apache.commons.io FilenameUtils getPrefix

List of usage examples for org.apache.commons.io FilenameUtils getPrefix

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getPrefix.

Prototype

public static String getPrefix(String filename) 

Source Link

Document

Gets the prefix from a full filename, such as C:/ or ~/.

Usage

From source file:edu.ur.file.db.DefaultFileDatabase.java

/**
 * Set the path of the folder. This makes no changes to the children
 * folders. The path must be a full path and cannot be relative. The path
 * must also include the prefix i.e. C:/ (for windows) or / (for unix).
 * /*w w  w .  j a va  2s  .c o m*/
 * 
 * This converts the paths to the correct path immediately / for *NIX and \
 * for windows.
 * 
 * @param path
 */
void setPath(String path) {

    path = FilenameUtils.separatorsToSystem(path.trim());

    // add the end separator
    if (path.charAt(path.length() - 1) != IOUtils.DIR_SEPARATOR) {
        path = path + IOUtils.DIR_SEPARATOR;
    }

    // get the prefix
    prefix = FilenameUtils.getPrefix(path).trim();

    // the prefix cannot be null.
    if (prefix == null || prefix.equals("")) {
        throw new IllegalArgumentException("Path must have a prefix");
    }

    this.path = FilenameUtils.getPath(path);

}

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

/**
 * List the files in the given path string with wild cards.
 * //from ww w . j a v a 2s .  c  om
 * @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:ch.cyberduck.core.Local.java

/**
 * @param directory Parent directory/* www.java2  s  . c  o  m*/
 * @return True if this is a child in the path hierarchy of the argument passed
 */
public boolean isChild(final Local directory) {
    if (this.isRoot()) {
        // Root cannot be a child of any other path
        return false;
    }
    if (Objects.equals(this.parent(this.getAbsolute()), this.parent(directory.getAbsolute()))) {
        // Cannot be a child if the same parent
        return false;
    }
    final String prefix = FilenameUtils.getPrefix(this.getAbsolute());
    String parent = this.getAbsolute();
    while (!parent.equals(prefix)) {
        parent = this.parent(parent);
        if (directory.getAbsolute().equals(parent)) {
            return true;
        }
    }
    return false;
}

From source file:ch.cyberduck.core.Local.java

private String parent(final String absolute) {
    final String prefix = FilenameUtils.getPrefix(absolute);
    if (absolute.equals(prefix)) {
        return null;
    }//  w w  w. j  av a2 s  .  co m
    int index = absolute.length() - 1;
    if (absolute.charAt(index) == this.getDelimiter()) {
        if (index > 0) {
            index--;
        }
    }
    final int cut = absolute.lastIndexOf(this.getDelimiter(), index);
    if (cut > FilenameUtils.getPrefixLength(absolute)) {
        return absolute.substring(0, cut);
    }
    return String.valueOf(prefix);
}

From source file:com.cordys.coe.ac.emailio.storage.FileStorageProvider.java

/**
 * This method returns the log folder. It will check whether the folder is relative or not and
 * then it will create the folder if it is not there on the filesystem.
 *
 * @param   sLogFolder  The folder to create.
 * @param   ebEmailBox  The corresponding email box.
 *
 * @return  The folder.//  w ww . j av a  2 s .c om
 */
private File getProperFolder(String sLogFolder, IEmailBox ebEmailBox) {
    File fReturn = null;

    if (FilenameUtils.getPrefix(sLogFolder).length() == 0) {
        // Relative file
        fReturn = new File(EIBProperties.getInstallDir(), sLogFolder);
    } else {
        fReturn = new File(sLogFolder);
    }

    if (!fReturn.exists()) {
        fReturn.mkdirs();
    }

    // Now create the folder specific for this emailbox.
    fReturn = new File(fReturn, ebEmailBox.getName().replaceAll("[^a-zA-Z0-9]", ""));

    if (!fReturn.exists()) {
        fReturn.mkdirs();
    }

    return fReturn;
}

From source file:org.apache.flex.compiler.internal.tree.mxml.MXMLNodeBase.java

/**
 * Resolves the path specified in an MXML tag's <code>source</code>
 * attribute./*w ww  .  j  a va2 s .c o  m*/
 * 
 * @param builder The {@code MXMLTreeBuilder} object which is building this
 * MXML tree.
 * @param attribute The <code>source</code> attribute.
 * @return A resolved and normalized path to the external file.
 */
public static String resolveSourceAttributePath(MXMLTreeBuilder builder, IMXMLTagAttributeData attribute,
        MXMLNodeInfo info) {
    if (info != null)
        info.hasSourceAttribute = true;

    String sourcePath = attribute.getMXMLDialect().trim(attribute.getRawValue());

    if (sourcePath.isEmpty() && builder != null) {
        ICompilerProblem problem = new MXMLEmptyAttributeProblem(attribute);
        builder.addProblem(problem);
        return null;
    }

    String resolvedPath;

    if ((new File(sourcePath)).isAbsolute()) {
        // If the source attribute specifies an absolute path,
        // it doesn't need to be resolved.
        resolvedPath = sourcePath;
    } else {
        // Otherwise, resolve it relative to the MXML file.
        String mxmlPath = attribute.getParent().getParent().getPath();
        resolvedPath = FilenameUtils.getPrefix(mxmlPath) + FilenameUtils.getPath(mxmlPath);
        resolvedPath = FilenameUtils.concat(resolvedPath, sourcePath);
    }

    String normalizedPath = FilenameNormalization.normalize(resolvedPath);

    // Make the compilation unit dependent on the external file.
    if (builder != null)
        builder.getFileScope().addSourceDependency(normalizedPath);

    return normalizedPath;
}

From source file:org.apache.solr.cloud.AbstractFullDistribZkTestBase.java

private File getRelativeSolrHomePath(File solrHome) {
    String path = SolrResourceLoader.normalizeDir(new File(".").getAbsolutePath());
    String base = new File(solrHome.getPath()).getAbsolutePath();

    if (base.startsWith("."))
        ;/* ww w  . ja v a  2  s. c o m*/
    base.replaceFirst("\\.", new File(".").getName());

    if (path.endsWith(File.separator + ".")) {
        path = path.substring(0, path.length() - 2);
    }

    int splits = path.split("\\" + File.separator).length;

    StringBuilder p = new StringBuilder();
    for (int i = 0; i < splits - 2; i++) {
        p.append(".." + File.separator);
    }

    String prefix = FilenameUtils.getPrefix(path);
    if (base.startsWith(prefix)) {
        base = base.substring(prefix.length());
    }

    solrHome = new File(p.toString() + base);
    return solrHome;
}

From source file:org.h819.commons.file.MyPDFUtilss.java

/**
 * ???/*from w ww.  java  2  s  . c o m*/
 *
 * @param srcPdfFileDir
 * @param descPdfFileDir
 * @return
 */
private static boolean isEnoughtSpace(File srcPdfFileDir, File descPdfFileDir) {

    if (!srcPdfFileDir.exists() && !srcPdfFileDir.isDirectory()) {
        logger.info(srcPdfFileDir.getAbsolutePath() + " not exist.");
        return false;
    }

    try {
        FileUtils.forceMkdir(descPdfFileDir);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // ??

    // 
    long prefixDiskFreeSize = descPdfFileDir.getFreeSpace();
    // ??
    long srcSize = FileUtils.sizeOfDirectory(srcPdfFileDir);

    // logger.info(descPdfFileDir.getAbsolutePath() + " "
    // + prefixDiskFreeSize / 1000000.00 + " M");
    // logger.info(srcPdfFileDir.getAbsolutePath() + " ? :" + srcSize
    // / 1000000.00 + " M");

    if (prefixDiskFreeSize < srcSize) {
        logger.info(FilenameUtils.getPrefix(descPdfFileDir.getAbsolutePath()) + " has not enoght disk size .");
        return false;
    }

    return true;

}

From source file:org.h819.commons.file.MyPDFUtilss.java

/**
 * http://www.javabeat.net/javascript-in-pdf-documents-using-itext/
 * http://www.javabeat.net/javascript-communication-between-html-and-pdf-in-itext/
 *  PDF  field  javaScript//from  w ww .ja v a  2 s . c  o  m
 * <p>
 * pdf ? javaScript?????
 * <p>
 * javaScript ?? filed  filed javaScript ???
 * <p>
 * ?? javaScript 
 * <p>
 *  itext  reader.getJavaScript()? pdf  JavaScript??(adobe pro
 * ????)
 * <p>
 * ??? field ??
 *
 * @param srcPdfFileDir   ?
 * @param descPdfFileDir  
 * @param removeFieldName  javaScript ???
 * @throws java.io.IOException
 */
public static void removeFieldJavaScript(File srcPdfFileDir, File descPdfFileDir, String removeFieldName)
        throws IOException {

    if (!srcPdfFileDir.isDirectory()) {
        logger.info("srcPdfFileDir is not a Directory: " + srcPdfFileDir.getAbsolutePath());
        return;
    }

    File listFiles[] = srcPdfFileDir.listFiles();

    if (listFiles.length == 0) {
        logger.info("srcPdfFileDir has not file. " + srcPdfFileDir.getAbsolutePath());
        return;
    }

    FileUtils.forceMkdir(descPdfFileDir);

    // ??

    // 
    long prefixDiskFreeSize = descPdfFileDir.getFreeSpace();
    // ??
    long srcSize = FileUtils.sizeOf(srcPdfFileDir);

    logger.info(descPdfFileDir.getAbsolutePath() + " " + prefixDiskFreeSize / 1000000.00
            + " M");
    logger.info(srcPdfFileDir.getAbsolutePath() + " ? :" + srcSize / 1000000.00 + " M");

    if (prefixDiskFreeSize < srcSize) {

        logger.info(FilenameUtils.getPrefix(descPdfFileDir.getAbsolutePath()) + " has not enoght disk size .");

        return;
    }

    // logger.info(descPdfFileDir.getAbsolutePath());

    for (File f : listFiles) {
        String fileName = f.getName();
        String extensiion = FilenameUtils.getExtension(fileName).toLowerCase();

        PdfReader reader = null;

        PdfStamper stamper = null;

        if (f.isFile()) {
            if (extensiion.equals("pdf")) {

                reader = getPdfReader(f);

                File fileDesc = new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName);

                try {
                    stamper = new PdfStamper(reader, FileUtils.openOutputStream(fileDesc));

                    /**
                     * ???
                     * **/
                    // reader.removeFields();

                    /**
                     * ??? javaScript ?
                     * **/
                    AcroFields form = stamper.getAcroFields();
                    form.removeField(removeFieldName);

                    stamper.close();
                    reader.close();

                } catch (DocumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else
                continue;

        } // end if f.isFile

        else if (f.isDirectory()) {
            removeFieldJavaScript(f, new File(descPdfFileDir.getAbsolutePath() + File.separator + fileName),
                    removeFieldName);
        } // end if f.isDirectory
        else
            continue;

    } // end for

    logger.info("finished !");
}

From source file:org.openmicroscopy.shoola.agents.treeviewer.view.ToolBar.java

/**
 * Brings up the <code>Available Scripts</code> on top of the specified
 * component at the specified location./*from  w w  w.j  av a 2  s  .c o m*/
 * 
 * @param c The component that requested the pop-pup menu.
 * @param p The point at which to display the menu, relative to the
 *          <code>component</code>'s coordinates.
 */
void showAvailableScriptsMenu(Component c, Point p) {
    if (p == null)
        return;
    if (c == null) {
        c = scriptButton;
    }
    IconManager icons = IconManager.getInstance();
    Collection<ScriptObject> scripts = model.getAvailableScripts();
    if (CollectionUtils.isEmpty(scripts))
        return;
    if (scriptsMenu == null) {
        scriptsMenu = new JPopupMenu();
        JMenuItem refresh = new JMenuItem(icons.getIcon(IconManager.REFRESH));
        refresh.setText("Reload Scripts");
        refresh.setToolTipText("Reloads the existing scripts.");
        refresh.addMouseListener(new MouseAdapter() {

            /**
             * Launches the dialog when the user releases the mouse.
             * MouseAdapter#mouseReleased(MouseEvent)
             */
            public void mouseReleased(MouseEvent e) {
                model.setAvailableScripts(null);
                scriptsMenu = null;
                controller.reloadAvailableScripts(e.getPoint());
            }
        });
        scriptsMenu.add(refresh);
        scriptsMenu.add(new JSeparator());

        ScriptObject so;
        Map<String, JMenu> menus = new HashMap<String, JMenu>();
        String path;

        Icon icon = icons.getIcon(IconManager.ANALYSIS);
        Icon largeIcon = icons.getIcon(IconManager.ANALYSIS_48);
        ActionListener listener = new ActionListener() {

            /** 
             * Listens to the selection of a script.
             * @see ActionListener#actionPerformed(ActionEvent)
             */
            public void actionPerformed(ActionEvent e) {
                ScriptMenuItem item = (ScriptMenuItem) e.getSource();
                controller.handleScriptSelection(item.getScript());
            }
        };
        String name = "";
        //loop twice to check if we need to add the first element
        String refString = null;
        int count = 0;
        Iterator<ScriptObject> i = scripts.iterator();
        String sep;
        String[] values;
        String value;
        while (i.hasNext()) {
            so = i.next();
            value = "";
            path = so.getPath();
            if (path != null) {
                sep = FilenameUtils.getPrefix(path);
                if (path.startsWith(sep))
                    path = path.substring(1, path.length());
                values = UIUtilities.splitString(path);
                if (values != null && values.length > 0)
                    value = values[0];
            }

            if (refString == null) {
                refString = value;
                count++;
            } else if (refString.equals(value))
                count++;
        }
        int index = 0;
        if (scripts.size() == count)
            index++;
        i = scripts.iterator();
        List<JMenuItem> topMenus = new ArrayList<JMenuItem>();
        JMenu ref = null;
        while (i.hasNext()) {
            so = i.next();
            path = so.getPath();
            if (path != null) {
                sep = FilenameUtils.getPrefix(path);
                if (path.startsWith(sep))
                    path = path.substring(1, path.length());
                values = UIUtilities.splitString(path);
                if (values != null) {
                    for (int j = index; j < values.length; j++) {
                        value = values[j];
                        JMenu v;
                        String text = name + value;
                        if (menus.containsKey(text)) {
                            v = menus.get(text);
                        } else {
                            value = value.replace(ScriptObject.PARAMETER_SEPARATOR,
                                    ScriptObject.PARAMETER_UI_SEPARATOR);
                            v = new JMenu(value);
                        }
                        if (ref == null)
                            topMenus.add(v);
                        else
                            ref.add(v);
                        ref = v;
                        name += values[j];
                        menus.put(name, v);
                    }
                }
            }
            ScriptMenuItem item = new ScriptMenuItem(so);
            item.addActionListener(listener);
            if (ref != null)
                ref.add(item);
            else
                topMenus.add(item);
            name = "";
            ref = null;
            if (so.getIcon() == null) {
                so.setIcon(icon);
                so.setIconLarge(largeIcon);
            }
        }
        Iterator<JMenuItem> j = topMenus.iterator();
        while (j.hasNext()) {
            scriptsMenu.add(j.next());
        }
    }
    scriptsMenu.show(c, p.x, p.y);
}