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

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

Introduction

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

Prototype

public static int indexOfLastSeparator(String filename) 

Source Link

Document

Returns the index of the last directory separator character.

Usage

From source file:com.kamike.misc.FsNameUtils.java

public static String getIncomingName(String fileName) {
    String name = FilenameUtils.getFullPathNoEndSeparator(fileName);
    ///* w ww . j  a va 2s. c o  m*/
    int end = FilenameUtils.indexOfLastSeparator(name);
    String parent = name.substring(end);
    int lastEnd = FilenameUtils.indexOfLastSeparator(parent);
    return parent.substring(lastEnd, end);
}

From source file:hudson.gridmaven.MavenModuleSetBuild.java

private static String normalizePath(String relPath) {
    relPath = StringUtils.trimToEmpty(relPath);
    if (StringUtils.isEmpty(relPath)) {
        LOGGER.config("No need to normalize an empty path.");
    } else {/*from  www  .  java 2  s.  c  o  m*/
        if (FilenameUtils.indexOfLastSeparator(relPath) == -1) {
            LOGGER.config("No need to normalize " + relPath);
        } else {
            String tmp = FilenameUtils.normalize(relPath);
            if (tmp == null) {
                LOGGER.config(
                        "Path " + relPath + " can not be normalized (parent dir is unknown). Keeping as is.");
            } else {
                LOGGER.config("Normalized path " + relPath + " to " + tmp);
                relPath = tmp;
            }
            relPath = FilenameUtils.separatorsToUnix(relPath);
        }
    }
    LOGGER.fine("Returning path " + relPath);
    return relPath;
}

From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java

private ArrayList<File> getScmlFileImagesList(FileHandle fileHandle) {
    ArrayList<File> images = new ArrayList<File>();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;// w w w .  ja  v  a2s.  co  m
    try {
        db = dbf.newDocumentBuilder();
        org.w3c.dom.Document document = db.parse(fileHandle.file());
        NodeList nodeList = document.getElementsByTagName("file");
        for (int x = 0, size = nodeList.getLength(); x < size; x++) {
            String absolutePath = fileHandle.path();
            String path = absolutePath.substring(0, FilenameUtils.indexOfLastSeparator(fileHandle.path()))
                    + File.separator + nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue();
            File imgFile = new File(path);
            images.add(imgFile);
        }
    } catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
    }
    return images;
}

From source file:edu.ku.brc.specify.datamodel.SpAppResource.java

/**
 * Gets the contents with a possible existing session.
 * @param sessionArg the current session or null.
 * @return the contents as a string// w  ww .java 2 s .c om
 */
@Transient
public String getDataAsString(final DataProviderSessionIFace sessionArg) {
    SpAppResourceData appResData = null;
    DataProviderSessionIFace session = null;
    try {
        if (spAppResourceId != null) {
            session = sessionArg != null ? sessionArg : DataProviderFactory.getInstance().createSession();
            session.attach(this);
        }

        if (spAppResourceDatas.size() > 0) {
            appResData = spAppResourceDatas.iterator().next();
            if (appResData != null) {
                return new String(appResData.getData());
            }
        }

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpAppResource.class, ex);
        log.error(ex);
        ex.printStackTrace();

    } finally {
        if (sessionArg == null && session != null) {
            session.close();
        }
    }

    String fileNameToOpen = fileName;
    boolean doesFileExist = false;
    if (StringUtils.isNotEmpty(fileNameToOpen)) {
        File file = new File(fileNameToOpen);
        if (!file.exists()) {
            String fName = FilenameUtils.getName(fileNameToOpen);
            String path = FilenameUtils.getFullPathNoEndSeparator(fileNameToOpen);
            path = path.substring(0, FilenameUtils.indexOfLastSeparator(path));

            fileNameToOpen = path + File.separator + fName;

            doesFileExist = (new File(fileNameToOpen)).exists();
        } else {
            doesFileExist = true;
        }
    }

    String str = null;
    if (doesFileExist) {
        File file = new File(fileNameToOpen);
        str = XMLHelper.getContents(file);
        timestampCreated = new Timestamp(file.lastModified());
        //timestampModified = timestampCreated;
    } else {
        UIRegistry.showError("The file in the app_resources.xml [" + fileName + "] is missing.");
    }

    if (str != null && str.length() > 0) {
        return StringEscapeUtils.unescapeXml(str);
    }

    return null;
}

From source file:org.apache.torque.generator.file.Fileset.java

/**
 * Returns the largest position of a path separator within the path
 * which is smaller than endIndex. An endIndex of -1 means that
 * the largest separator pos should be given. -1 is returned if no
 * separator is present in the region./*from   w  ww  .j  a v a  2s. c  o m*/
 * <ul>
 *   <li>getBaseDir("/xml/xxxx", 5) returns 4</li>
 *   <li>getBaseDir("/xml/x/y", -1) returns 6</li>
 *   <li>getBaseDir("/xml/x/y/", -1) returns 8</li>
 * </ul>
 */
static int getLargestSeparatorPos(String path, int maxIndex) {
    String baseString;
    if (maxIndex == -1) {
        baseString = path;
    } else {
        baseString = path.substring(0, maxIndex);
    }
    return FilenameUtils.indexOfLastSeparator(baseString);
}

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);
                }/* ww  w  .  j  a  v  a2  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.panbox.desktop.common.vfs.FuseUserFS.java

@Override
public int create(final String path, final ModeWrapper mode, final FileInfoWrapper info) {
    try {/*from ww  w  . j  a  v a2s . c  om*/
        if (FilenameUtils.indexOfLastSeparator(path) == 0) {
            // we're in the VFS root
            VFSErrorMessages.showErrorMessage(bundle.getString("FuseUserFS.creatingInRootDir"),
                    bundle.getString("FuseUserFS.illegalOperation"));
            return -ErrorCodes.ECANCELED();
        } else {
            // preparations
            boolean readonly = (info.openMode() == OpenMode.READONLY);
            long handle = handleCtr.incrementAndGet();
            panboxFS.create(path, handle, readonly);
            // if no exception was thrown, set handle for subsequent session
            info.fh(handle);
        }
    } catch (ObfuscationException e) {
        log_error(e);
        VFSErrorMessages.showErrorMessage(
                MessageFormat.format(bundle.getString("FuseUserFS.fileCouldNotBeObfuscated"), path),
                bundle.getString("error"));
        return -ErrorCodes.EIO();
    } catch (IOException e) {
        log_error(e);
        return -ErrorCodes.EIO();
    } catch (PanboxEncryptionException e) {
        log_error(e);
        VFSErrorMessages.showErrorMessage(
                MessageFormat.format(bundle.getString("FuseUserFS.fileCouldNotBeEncrypted"), path),
                bundle.getString("error"));
        return -ErrorCodes.EIO();
    }
    return 0;
}

From source file:org.panbox.desktop.common.vfs.FuseUserFS.java

@Override
public int mkdir(final String path, final ModeWrapper mode) {
    if (!UnconsequentialFiles.isUnconsequential(path)) {
        try {//from w w  w. j  a v  a2 s. com
            if (FilenameUtils.indexOfLastSeparator(path) == 0) {
                // we're in the VFS root
                VFSErrorMessages.showErrorMessage(bundle.getString("FuseUserFS.creatingInRootDir"),
                        bundle.getString("FuseUserFS.illegalOperation"));
                return -ErrorCodes.EACCES();
            } else {
                panboxFS.mkdir(path);
            }
        } catch (SecretKeyNotFoundException e) {
            log_error(e);
            return -ErrorCodes.ENOENT();
        } catch (FileNotFoundException e) {
            log_error(e);
            return -ErrorCodes.ENOENT();
        } catch (PanboxCreateFailedException e) {
            log_error(e);
            return -ErrorCodes.EACCES();
        } catch (ObfuscationException e) {
            log_error(e);
            VFSErrorMessages.showErrorMessage(
                    MessageFormat.format(bundle.getString("FuseUserFS.fileCouldNotBeObfuscated"), path),
                    bundle.getString("error"));
            return -ErrorCodes.EIO();
        }
    }
    return 0;
}

From source file:org.pentaho.platform.repository.RepositoryFilenameUtils.java

/**
 * Returns the index of the last directory separator character.
 * <p/>/* w  w  w . j a  va 2  s.  c o  m*/
 * The position of the last forward or backslash is returned.
 * <p/>
 * 
 * @param filename
 *          the filename to find the last path separator in, null returns -1
 * @return the index of the last separator character, or -1 if there is no such character
 */
public static int indexOfLastSeparator(final String filename) {
    return FilenameUtils.indexOfLastSeparator(filename);
}

From source file:pt.webdetails.cpf.repository.pentaho.unified.UnifiedRepositoryAccess.java

private RepositoryFile getOrCreateFolder(IUnifiedRepository repo, String path, boolean isHidden) {
    // full path, no slash at end
    String fullPath = StringUtils.chomp(getFullPath(path), "/");
    // backtrack path to get list of folders to create
    List<String> foldersToCreate = new ArrayList<String>();
    while (!rawPathExists(repo, fullPath)) {
        // "a / b / c"
        // path<-|^|-> to create
        // accepts '/'
        int sepIdx = FilenameUtils.indexOfLastSeparator(fullPath);
        if (sepIdx < 0) {
            break;
        }/* ww w .j  av a  2 s.  com*/
        foldersToCreate.add(fullPath.substring(sepIdx + 1));
        fullPath = fullPath.substring(0, sepIdx);
    }

    //in case we reached root
    if (StringUtils.isEmpty(fullPath)) {
        fullPath = RepositoryHelper.appendPath("/", fullPath);
    }

    RepositoryFile baseFolder = repo.getFile(fullPath);

    if (baseFolder == null) {
        logger.error("Path " + fullPath + " doesn't exist");
        return null;
    }
    // reverse iterate 
    if (foldersToCreate.size() > 0) {
        for (int i = foldersToCreate.size() - 1; i >= 0; i--) {
            String folder = foldersToCreate.get(i);
            baseFolder = repo.createFolder(baseFolder.getId(),
                    new RepositoryFile.Builder(folder).folder(true).hidden(isHidden).build(), null);
        }
    }
    return baseFolder;
}