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

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

Introduction

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

Prototype

public static String getFullPathNoEndSeparator(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path, and also excluding the final directory separator.

Usage

From source file:org.jahia.modules.serversettings.portlets.BasePortletHelper.java

/**
 * Returns a file descriptor for the modified (prepared) portlet WAR file.
 * /*w ww .jav a2s  .  c  om*/
 * @param sourcePortletWar
 *            the source portlet WAR file
 * @return a file descriptor for the modified (prepared) portlet WAR file
 * @throws IOException
 *             in case of processing error
 */
public File process(File sourcePortletWar) throws IOException {
    JarFile jar = new JarFile(sourcePortletWar);
    File dest = new File(FilenameUtils.getFullPathNoEndSeparator(sourcePortletWar.getPath()),
            FilenameUtils.getBaseName(sourcePortletWar.getName()) + ".war");
    try {
        boolean needsServerSpecificProcessing = needsProcessing(jar);
        if (portletTldsPresent(jar) && !needsServerSpecificProcessing) {
            return sourcePortletWar;
        }
        jar.close();
        final JarInputStream jarIn = new JarInputStream(new FileInputStream(sourcePortletWar));
        final Manifest manifest = jarIn.getManifest();
        final JarOutputStream jarOut;
        if (manifest != null) {
            jarOut = new JarOutputStream(new FileOutputStream(dest), manifest);
        } else {
            jarOut = new JarOutputStream(new FileOutputStream(dest));
        }

        try {
            copyEntries(jarIn, jarOut);

            process(jarIn, jarOut);

            if (!hasPortletTld) {
                addToJar("META-INF/portlet-resources/portlet.tld", "WEB-INF/portlet.tld", jarOut);
            }
            if (!hasPortlet2Tld) {
                addToJar("META-INF/portlet-resources/portlet_2_0.tld", "WEB-INF/portlet_2_0.tld", jarOut);
            }
        } finally {
            jarIn.close();
            jarOut.close();
            FileUtils.deleteQuietly(sourcePortletWar);
        }
        return dest;
    } finally {
        jar.close();
    }
}

From source file:org.jahia.services.search.FileHit.java

/**
 * Returns the folder path for this hit.
 * // w ww.  jav  a 2  s  .  co m
 * @return the folder path for this hit
 */
public String getFolderPath() {
    return isFolder() ? getPath() : FilenameUtils.getFullPathNoEndSeparator(getPath());
}

From source file:org.javabeanstack.io.IOUtil.java

/**
 * Devuelve el path de un archivo ejemplo c:/carpeta1/subcarpeta1/archivo.txt
 * retorna /carpeta1/subcarpeta1/*from  w w  w  . j  a v a2s.  c o  m*/
 * @param file nombre y path del archivo
 * @return el path del archivo
 */
public static String getFullPathNoEndSeparator(String file) {
    return FilenameUtils.getFullPathNoEndSeparator(file);
}

From source file:org.jboss.tools.openshift.common.core.utils.FileUtils.java

/**
 * Returns the given filepath with a suffix if the given filepath already
 * exists.//from   w ww.  j  av  a2s . co m
 * 
 * @param filepath
 * @return the filepath or filepath + numeric suffix if not available.
 * 
 * @see #NUMERIC_SUFFIX_FILENAME_PATTERN
 */
public static String getAvailableFilepath(String filepath) {
    if (StringUtils.isEmpty(filepath)) {
        return filepath;
    }
    String extension = getExtension(filepath);
    String dir = FilenameUtils.getFullPathNoEndSeparator(filepath);
    String filenameWithoutExtension = stripNumericSuffix(getBaseName(filepath));

    String newFilename = filepath;
    int i = 1;
    while (new File(newFilename).exists()) {
        newFilename = MessageFormat.format(NUMERIC_SUFFIX_FILENAME_PATTERN, dir, filenameWithoutExtension, i++,
                extension);
    }
    return newFilename;
}

From source file:org.locationtech.udig.project.ui.internal.actions.Delete.java

protected final void doDelete(Project project, boolean deleteProjectFiles, int returncode) {
    if (returncode != Window.CANCEL) {
        Resource resource = project.eResource();
        if (!deleteProjectFiles) {
            try {
                resource.save(null);//from ww w. j ava2s .c  o m
                resource.getContents().remove(project);
            } catch (IOException e) {
                ProjectUIPlugin.log(null, e);
            }
        }

        List<ProjectElement> toRemove = new ArrayList<ProjectElement>();
        toRemove.addAll(project.getElementsInternal());
        boolean oldrunSyn = runSync;

        this.runSync = true;
        for (ProjectElement element : toRemove) {
            doDelete(element, deleteProjectFiles, returncode);
        }
        runSync = oldrunSyn;

        resource.setModified(false);
        if (ApplicationGIS.getActiveProject() == project)
            ProjectPlugin.getPlugin().getProjectRegistry().setCurrentProject(null);

        ProjectPlugin.getPlugin().getProjectRegistry().getProjects().remove(project);
        resource.getContents().clear();
        ResourceSet resourceSet = resource.getResourceSet();
        String path = resource.getURI().toFileString();

        resource.unload();

        if (deleteProjectFiles) {
            try {
                resourceSet.getResources().remove(resource);
                resource.unload();
                /*
                int lastIndexOf = path.lastIndexOf('/');
                if (lastIndexOf == -1)
                lastIndexOf = path.length();
                path = path.substring(0, lastIndexOf);
                */
                final File file = new File(path);
                deleteFile(file);
                //also delete the directory containing the files
                String dirPath = FilenameUtils.getFullPathNoEndSeparator(path);
                if (dirPath.endsWith(".udig")) {
                    deleteFile(new File(dirPath));
                }
            } catch (Exception e) {
                ProjectUIPlugin.log("Error deleting project file", e); //$NON-NLS-1$
            }
        }
    }
}

From source file:org.meri.wro4j.nogroups.fix.FixedWildcardExpanderModelTransformer.java

public Function<Collection<File>, Void> createExpanderHandler(final Group group, final Resource resource,
        final String baseNameFolder) {
    LOG.debug("createExpanderHandler using baseNameFolder: {}\n for resource {}", baseNameFolder, resource);
    final Function<Collection<File>, Void> handler = new Function<Collection<File>, Void>() {
        public Void apply(final Collection<File> files) {
            if (baseNameFolder == null) {
                // replacing group with empty list since the original uri has no associated resources.
                //No BaseNameFolder found
                LOG.warn("The resource {} is probably invalid, removing it from the group.", resource);
                group.replace(resource, new ArrayList<Resource>());
            } else {
                final List<Resource> expandedResources = new ArrayList<Resource>();
                LOG.debug("baseNameFolder: {}", baseNameFolder);
                for (final File file : files) {
                    final String resourcePath = getFullPathNoEndSeparator(resource);
                    LOG.debug("\tresourcePath: {}", resourcePath);
                    LOG.debug("\tfile path: {}", file.getPath());
                    final String computedResourceUri = resourcePath
                            + StringUtils.removeStart(file.getPath(), baseNameFolder).replace('\\', '/');

                    final Resource expandedResource = Resource.create(computedResourceUri, resource.getType());
                    LOG.debug("\texpanded resource: {}", expandedResource);
                    expandedResources.add(expandedResource);
                }//from   w  w  w  . j  a v a 2  s . c  o  m
                LOG.debug("\treplace resource {}", resource);
                group.replace(resource, expandedResources);
            }
            return null;
        }

        private String getFullPathNoEndSeparator(final Resource resource) {
            String result = FilenameUtils.getFullPathNoEndSeparator(resource.getUri());
            if (result != null && 1 == result.length() && 0 == FilenameUtils.indexOfLastSeparator(result))
                return "";

            return result;
        }
    };
    return handler;
}

From source file:org.onexus.data.loader.file.internal.FileCallable.java

private List<URL> getUrls(Plugin plugin, Data data) {

    String location = plugin.getParameter("location");
    String mirror = plugin.getParameter("mirror");
    String basePath = data.getLoader().getParameter("base-path");

    if (basePath == null) {
        basePath = "";
    }//from  w  w  w.j av  a  2  s  .  c o m

    if (!basePath.isEmpty() && !basePath.endsWith(File.separator)) {
        basePath = basePath + File.separator;
    }

    List<String> paths = data.getLoader().getParameterList("path");

    List<URL> urls = new ArrayList<URL>();

    for (String templatePath : paths) {
        String path = templatePath;
        String fileName = FilenameUtils.getName(path);

        // Check if it is a wildcard filter
        if (path.contains("*") || path.contains("?")) {

            // Is recursive?
            IOFileFilter dirFilter = null;
            if (path.contains("**/")) {
                dirFilter = TrueFileFilter.INSTANCE;
                path = path.replace("**/", "");
            }

            String sourceContainer = location + File.separator + basePath
                    + FilenameUtils.getFullPathNoEndSeparator(path);
            File sourceFile = new File(sourceContainer);

            for (File file : (Collection<File>) FileUtils.listFiles(sourceFile,
                    new WildcardFileFilter(fileName), dirFilter)) {
                try {
                    urls.add(file.toURI().toURL());
                } catch (MalformedURLException e) {
                    throw new RuntimeException(e);
                }
            }

        } else {
            String sourcePath = location + File.separator + basePath + path;
            File sourceFile = new File(sourcePath);

            if (sourceFile.exists()) {
                try {
                    urls.add(sourceFile.toURI().toURL());
                } catch (MalformedURLException e) {
                    throw new RuntimeException(e);
                }
            } else {

                // Try mirror
                if (mirror != null) {

                    String remoteFile = mirror + '/' + path;

                    try {
                        URL url = new URL(remoteFile);
                        urls.add(url);
                    } catch (MalformedURLException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    return urls;
}

From source file:org.paxml.core.ResourceLocator.java

/**
 * Make an Spring resource string from relative path which contains
 * wildcards./*from w  w w . j  a v a 2s  .c  o  m*/
 * 
 * @param base
 *            the base Spring resource
 * @param relative
 *            the relative path
 * @return the absolute spring resource path
 */
public static String getRelativeResource(final Resource base, final String relative) {
    String result;
    // find from both class path and file system
    final boolean root = relative.startsWith("/") || relative.startsWith("\\");

    try {
        URL url = base.getURL();

        if (root) {
            result = url.getProtocol() + ":" + relative;
        } else {
            String path = FilenameUtils.getFullPathNoEndSeparator(url.getFile());
            result = url.getProtocol() + ":" + path + "/" + relative;
        }

    } catch (IOException e) {
        throw new PaxmlRuntimeException("Cannot get the relative path for plan file: " + base, e);
    }
    return result;
}

From source file:org.pentaho.platform.engine.services.actionsequence.SequenceDefinition.java

private int parseResourceDefinitions(final Node actionRootNode, final ILogger logger) {

    resourceDefinitions = new ListOrderedMap();

    try {/*from w ww .  j a  v  a2s.  c  om*/
        List resources = actionRootNode.selectNodes("resources/*"); //$NON-NLS-1$

        // TODO create objects to represent the types
        // TODO need source variable list
        Iterator resourcesIterator = resources.iterator();

        Node resourceNode;
        String resourceName;
        String resourceTypeName;
        String resourceMimeType;
        int resourceType;
        ActionSequenceResource resource;
        Node typeNode, mimeNode;
        while (resourcesIterator.hasNext()) {
            resourceNode = (Node) resourcesIterator.next();
            typeNode = resourceNode.selectSingleNode("./*"); //$NON-NLS-1$
            if (typeNode != null) {
                resourceName = resourceNode.getName();
                resourceTypeName = typeNode.getName();
                resourceType = ActionSequenceResource.getResourceType(resourceTypeName);
                String resourceLocation = XmlDom4JHelper.getNodeText("location", typeNode); //$NON-NLS-1$
                if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                        || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
                    if (resourceLocation == null) {
                        logger.error(Messages.getInstance().getErrorString(
                                "SequenceDefinition.ERROR_0008_RESOURCE_NO_LOCATION", resourceName)); //$NON-NLS-1$
                        continue;
                    }
                } else if (resourceType == IActionSequenceResource.STRING) {
                    resourceLocation = XmlDom4JHelper.getNodeText("string", resourceNode); //$NON-NLS-1$
                } else if (resourceType == IActionSequenceResource.XML) {
                    //resourceLocation = XmlHelper.getNodeText("xml", resourceNode); //$NON-NLS-1$
                    Node xmlNode = typeNode.selectSingleNode("./location/*"); //$NON-NLS-1$
                    // Danger, we have now lost the character encoding of the XML in this node
                    // see BISERVER-895
                    resourceLocation = (xmlNode == null) ? "" : xmlNode.asXML(); //$NON-NLS-1$
                }
                mimeNode = typeNode.selectSingleNode("mime-type"); //$NON-NLS-1$
                if (mimeNode != null) {
                    resourceMimeType = mimeNode.getText();
                    if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                            || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
                        resourceLocation = FilenameUtils.separatorsToUnix(resourceLocation);
                        if (!resourceLocation.startsWith("/")) { //$NON-NLS-1$
                            String parentDir = FilenameUtils.getFullPathNoEndSeparator(xactionPath);
                            if (parentDir.length() == 0) {
                                parentDir = RepositoryFile.SEPARATOR;
                            }
                            resourceLocation = FilenameUtils
                                    .separatorsToUnix(FilenameUtils.concat(parentDir, resourceLocation));
                        }
                    }
                    resource = new ActionSequenceResource(resourceName, resourceType, resourceMimeType,
                            resourceLocation);
                    resourceDefinitions.put(resourceName, resource);
                } else {
                    logger.error(Messages.getInstance().getErrorString(
                            "SequenceDefinition.ERROR_0007_RESOURCE_NO_MIME_TYPE", resourceName)); //$NON-NLS-1$
                }
            }
            // input = new ActionParameter( resourceName, resourceType, null
            // );
            // resourceDefinitions.put( inputName, input );
        }
        return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_OK;
    } catch (Exception e) {
        logger.error(Messages.getInstance().getErrorString("SequenceDefinition.ERROR_0006_PARSING_RESOURCE"), //$NON-NLS-1$
                e);
    }
    return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_INVALID_ACTION_DOC;

}

From source file:org.pentaho.platform.engine.services.ActionSequenceJCRHelper.java

protected String getLocaleString(final String key, String baseName, final RepositoryFile baseFile,
        boolean marchUpParents) {

    String parentPath = FilenameUtils.getFullPathNoEndSeparator(baseFile.getPath());

    RepositoryFile searchDir = repository.getFile(parentPath);
    if (baseFile.isFolder()) {
        searchDir = baseFile;/*w ww  .  j  a  va2s. c o m*/
    }
    try {
        boolean searching = true;
        while (searching) {

            RepositoryFile[] propertyFiles = listFiles(searchDir, new IFileFilter() {
                public boolean accept(RepositoryFile file) {
                    return file.getName().toLowerCase().endsWith(PROPERTIES_SUFFIX);
                }
            });
            RepositoryFile blcv = null;
            RepositoryFile blc = null;
            RepositoryFile bl = null;
            RepositoryFile b = null;
            for (RepositoryFile element : propertyFiles) {
                if (element.getName().equalsIgnoreCase(baseName + '_' + getLocale().getLanguage() + '_'
                        + getLocale().getCountry() + '_' + getLocale().getVariant() + PROPERTIES_SUFFIX)) {
                    blcv = element;
                }
                if (element.getName().equalsIgnoreCase(baseName + '_' + getLocale().getLanguage() + '_'
                        + getLocale().getCountry() + PROPERTIES_SUFFIX)) {
                    blc = element;
                }
                if (element.getName()
                        .equalsIgnoreCase(baseName + '_' + getLocale().getLanguage() + PROPERTIES_SUFFIX)) {
                    bl = element;
                }
                if (element.getName().equalsIgnoreCase(baseName + PROPERTIES_SUFFIX)) {
                    b = element;
                }
            }

            String localeText = getLocaleText(key, blcv);
            if (localeText == null) {
                localeText = getLocaleText(key, blc);
                if (localeText == null) {
                    localeText = getLocaleText(key, bl);
                    if (localeText == null) {
                        localeText = getLocaleText(key, b);
                    }
                }
            }
            if (localeText != null) {
                return localeText;
            }
            if (searching && marchUpParents) {
                if (!baseName.equals("messages")) { //$NON-NLS-1$
                    baseName = "messages"; //$NON-NLS-1$
                } else {
                    parentPath = FilenameUtils.getFullPathNoEndSeparator(searchDir.getPath());
                    // If the parent path is empty or the same as the parent's parent path (meaning root)
                    if (parentPath == null || parentPath.length() < 1
                            || parentPath.equals(searchDir.getPath())) {
                        searching = false;
                    } else {
                        searchDir = repository.getFile(parentPath);
                    }
                }
            } else if (!marchUpParents) {
                searching = false;
            }
        }
        return null;
    } catch (Exception e) {
        logger.error(Messages.getInstance().getErrorString(
                "ActionSequenceJCRHelper.ERROR_0007_COULD_NOT_READ_PROPERTIES", baseFile.getPath()), e); //$NON-NLS-1$
    }
    return null;
}