Example usage for org.apache.commons.lang StringUtils substringBeforeLast

List of usage examples for org.apache.commons.lang StringUtils substringBeforeLast

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBeforeLast.

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:org.jahia.modules.wiki.errors.NewWikiPageHandler.java

public boolean handle(Throwable e, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {/*  w ww.ja  v a  2  s .  co  m*/
        if (!(e instanceof PathNotFoundException)) {
            return false;
        }
        URLResolver urlResolver = urlResolverFactory.createURLResolver(request.getPathInfo(),
                request.getServerName(), request);
        JCRNodeWrapper pageNode;
        String parentPath = StringUtils.substringBeforeLast(urlResolver.getPath(), "/");
        String newName = StringUtils.substringAfterLast(urlResolver.getPath(), "/");
        newName = StringUtils.substringBefore(newName, ".html");
        JCRSessionWrapper session = JCRSessionFactory.getInstance()
                .getCurrentUserSession(urlResolver.getWorkspace(), urlResolver.getLocale());
        try {
            JCRNodeWrapper parent = session.getNode(parentPath);
            if (parent.isNodeType("jnt:page")) {
                pageNode = parent;
            } else {
                pageNode = JCRContentUtils.getParentOfType(parent, "jnt:page");
            }
            // test if pageNode is wiki
            boolean isWiki = false;
            if (pageNode != null && pageNode.hasProperty("j:templateName")) {
                String query = "select * from [jnt:pageTemplate] where [j:nodename]='"
                        + pageNode.getPropertyAsString("j:templateName") + "'";
                QueryWrapper q = session.getWorkspace().getQueryManager().createQuery(query, Query.JCR_SQL2);
                QueryResultWrapper result = q.execute();
                if (result.getNodes().hasNext()
                        && JCRContentUtils.getDescendantNodes((JCRNodeWrapper) result.getNodes().next(),
                                "jnt:wikiPageFormCreation").hasNext()) {
                    isWiki = true;
                }

            }
            if (pageNode == null || !isWiki) {
                return false;
            }
            try {
                JCRNodeWrapper node = pageNode.getNode(newName);
                String link = request.getContextPath() + request.getServletPath() + "/"
                        + StringUtils.substringBefore(request.getPathInfo().substring(1), "/") + "/"
                        + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + node.getPath();

                link += ".html";
                response.sendRedirect(link);
            } catch (PathNotFoundException e1) {
                if (null != pageNode) {
                    String link = request.getContextPath() + request.getServletPath() + "/"
                            + StringUtils.substringBefore(request.getPathInfo().substring(1), "/") + "/"
                            + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + pageNode.getPath();
                    String wikiTitle = request.getParameter("wikiTitle") != null
                            ? request.getParameter("wikiTitle")
                            : URLEncoder.encode(newName, "UTF-8");
                    link += ".html?displayTab=create-new-page&newPageName="
                            + URLEncoder.encode(newName, "UTF-8") + "&wikiTitle="
                            + URLEncoder.encode(wikiTitle, "UTF-8");
                    response.sendRedirect(link);
                    return true;
                }
                logger.debug("Wiki page not found ask for creation", e1);
            }
        } catch (PathNotFoundException e1) {
            return false;
        }
    } catch (Exception e1) {
        logger.error(e1.getMessage(), e1);
    }
    return false;
}

From source file:org.jahia.services.content.AclListener.java

private void parseEvents(JCRSessionWrapper systemSession, List<Event> aclEvents, Set<String> aceIdentifiers,
        Set<String> addedAceIdentifiers, Set<String> removedAcePaths, Set<String> addedExtPermIds,
        Set<List<String>> removedExtPermissions, Set<String> removedRoles) throws RepositoryException {
    for (Event next : aclEvents) {
        if (next.getPath().contains("/j:acl/")) {
            if (next.getType() == Event.PROPERTY_ADDED || next.getType() == Event.PROPERTY_CHANGED) {
                try {
                    JCRNodeWrapper nodeByIdentifier = systemSession.getNodeByIdentifier(next.getIdentifier());
                    if (nodeByIdentifier.isNodeType("jnt:ace")
                            && !nodeByIdentifier.isNodeType("jnt:externalAce") && nodeByIdentifier
                                    .getProperty("j:aceType").getValue().getString().equals("GRANT")) {
                        String identifier = next.getIdentifier();
                        if (identifier != null) {
                            aceIdentifiers.add(identifier);
                            if (next.getType() == Event.PROPERTY_ADDED) {
                                addedAceIdentifiers.add(identifier);
                            }/* w ww. jav  a  2 s  .c  o m*/
                        }
                    }
                } catch (ItemNotFoundException e) {
                    logger.error("unable to read node " + next.getPath());
                }
            } else if (next.getType() == Event.NODE_REMOVED
                    && StringUtils.substringAfterLast(next.getPath(), "/").startsWith("GRANT_")) {
                String identifier = next.getIdentifier();
                if (identifier != null) {
                    aceIdentifiers.add(identifier);
                }
                removedAcePaths.add(next.getPath());
            }
        } else if (next.getPath().startsWith("/roles/")) {
            if (next.getType() == Event.NODE_ADDED) {
                String identifier = next.getIdentifier();
                JCRNodeWrapper nodeByIdentifier = systemSession.getNodeByIdentifier(identifier);
                if (nodeByIdentifier.isNodeType("jnt:externalPermissions")) {
                    addedExtPermIds.add(identifier);
                }
            } else if (next.getType() == Event.NODE_REMOVED) {
                String path = next.getPath();
                if (path.endsWith("-access")) {
                    removedExtPermissions.add(Arrays.asList(
                            StringUtils.substringAfterLast(StringUtils.substringBeforeLast(path, "/"), "/"),
                            StringUtils.substringAfterLast(path, "/")));
                } else {
                    removedRoles.add(StringUtils.substringAfterLast(path, "/"));
                }
            }
        }
    }
}

From source file:org.jahia.services.content.ConflictResolver.java

private JCRNodeWrapper getParentTarget(JCRNodeWrapper target, String path) throws RepositoryException {
    if (path.contains("/")) {
        return target.getNode(StringUtils.substringBeforeLast(path, "/"));
    } else {// ww  w  .  ja  va 2 s  . c o m
        return target;
    }
}

From source file:org.jahia.services.content.impl.external.ExternalNodeImpl.java

public Node getParent() throws ItemNotFoundException, AccessDeniedException, RepositoryException {
    if (data.getPath().equals("/")) {
        throw new ItemNotFoundException();
    }//w  w w  .  j  a  va 2 s.c  om
    String path = StringUtils.substringBeforeLast(data.getPath(), "/");
    return session.getNode(path.isEmpty() ? "/" : path);
}

From source file:org.jahia.services.content.impl.external.ExternalSessionImpl.java

public Item getItem(String path) throws PathNotFoundException, RepositoryException {
    path = path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
    if (deletedData.containsKey(path)) {
        throw new PathNotFoundException("This node has been deleted");
    }//from   w  w  w.  j av a 2  s  .co  m
    if (changedData.containsKey(path)) {
        return new ExternalNodeImpl(changedData.get(path), this);
    }
    if (StringUtils.substringAfterLast(path, "/").startsWith("j:translation_")) {
        String nodeName = StringUtils.substringAfterLast(path, "/");
        String lang = StringUtils.substringAfterLast(nodeName, "_");
        ExternalData parentObject = repository.getDataSource()
                .getItemByPath(StringUtils.substringBeforeLast(path, "/"));
        if (parentObject.getI18nProperties() == null || !parentObject.getI18nProperties().containsKey(lang)) {
            throw new PathNotFoundException(path);
        }
        Map<String, String[]> i18nProps = new HashMap<String, String[]>(
                parentObject.getI18nProperties().get(lang));
        i18nProps.put("jcr:language", new String[] { lang });
        ExternalData i18n = new ExternalData("translation:" + lang + ":" + parentObject.getId(), path,
                "jnt:translation", i18nProps);
        return new ExternalNodeImpl(i18n, this);
    }
    return new ExternalNodeImpl(repository.getDataSource().getItemByPath(path), this);
}

From source file:org.jahia.services.content.impl.external.vfs.VFSDataSource.java

public ExternalData getItemByPath(String path) throws PathNotFoundException {
    try {/* w ww . j av a  2 s .  c o  m*/
        if (path.endsWith("/" + Constants.JCR_CONTENT)) {
            FileContent content = getFile(StringUtils.substringBeforeLast(path, "/" + Constants.JCR_CONTENT))
                    .getContent();
            return getFileContent(content);
        } else {
            FileObject fileObject = getFile(path);
            if (!fileObject.exists()) {
                throw new PathNotFoundException(path);
            }
            return getFile(fileObject);
        }

    } catch (FileSystemException e) {
        throw new PathNotFoundException("File system exception while trying to retrieve " + path, e);
    }
}

From source file:org.jahia.services.content.JCRContentUtils.java

/**
 * Retrieves the default user folder found at the specified path, creating it (and all intermediate folders) if needed, saving the session if requested.
 * @param session the session with which to access the JCR data
 * @param path the path of the default user folder to retrieve, if path is empty or <code>null</code> the user's node is returned
 * @param saveIfCreate <code>true</code> if we want the session to be immediately saved, <code>false</code> if the client code will save the session to commit the changes
 * @return the JCR node associated with the requested default user folder
 * @throws RepositoryException// w ww  .  j a  va2 s.  com
 */
public JCRNodeWrapper getDefaultUserFolder(JCRSessionWrapper session, String path, boolean saveIfCreate)
        throws RepositoryException {
    // if path is null or empty, return the user's node
    if (StringUtils.isEmpty(path)) {
        return session.getUserNode();
    }

    // make it possible to use relative paths without '/' prefix
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    // first check that we know this default user folder
    final String primaryNodeTypeName = defaultUserFolderTypes.get(path);
    if (primaryNodeTypeName == null) {
        throw new IllegalArgumentException("Unknown default user folder: " + path
                + ". Known default user folders are: " + defaultUserFolderTypes);
    }

    final String userPath = session.getUserNode().getPath();
    if (!session.itemExists(userPath + path)) {
        final String name = StringUtils.substringAfterLast(path, "/");
        final JCRNodeWrapper parentUserFolder = getDefaultUserFolder(session,
                StringUtils.substringBeforeLast(path, "/"), false);
        final JCRNodeWrapper userFolder = parentUserFolder.addNode(name, primaryNodeTypeName);

        if (saveIfCreate) {
            session.save();
        }

        return userFolder;
    }

    return session.getNode(userPath + path);
}

From source file:org.jahia.services.content.JCRItemWrapperImpl.java

/**
 * {@inheritDoc}/*from  www .java  2s.c  om*/
 * <code>Item</code> at the specified <code>depth</code>. 
 */
public JCRItemWrapper getAncestor(int i)
        throws ItemNotFoundException, AccessDeniedException, RepositoryException {
    if (i >= provider.getDepth()) {
        return provider.getNodeWrapper((Node) item.getAncestor(i - provider.getDepth()), getSession());
    } else if (i < 0) {
        throw new ItemNotFoundException();
    }
    return session.getItem(StringUtils.substringBeforeLast(provider.getMountPoint(), "/")).getAncestor(i);
}

From source file:org.jahia.services.content.JCRNodeWrapperImpl.java

protected JCRNodeWrapperImpl(Node objectNode, String path, JCRNodeWrapper parent, JCRSessionWrapper session,
        JCRStoreProvider provider) {/*from w  w  w.j  av a  2  s  . c  o m*/
    super(session, provider);
    this.objectNode = objectNode;
    setItem(objectNode);
    if (path != null) {
        if (path.endsWith("/") && !path.equals("/")) {
            path = StringUtils.substringBeforeLast(path, "/");
        }
        try {
            this.localPath = objectNode.getPath();
            this.localPathInProvider = objectNode.getPath();
            if (path.contains(JCRSessionWrapper.DEREF_SEPARATOR)) {
                this.localPath = path;
            }
            // In case we are accessing versionned node, this ensure that localPath contain the expected localPath
            if (this.localPath.startsWith("/jcr:system")) {
                this.localPath = path;
                this.localPathInProvider = path;
            }
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    } else {
        try {
            this.localPath = objectNode.getPath();
            this.localPathInProvider = objectNode.getPath();
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
    if (parent != null) {
        parentAlreadyResolved = true;
        resolvedParentNode = parent;
    }
}

From source file:org.jahia.services.content.JCRNodeWrapperImpl.java

/**
 * {@inheritDoc}//  www  .  j av  a  2  s . c  om
 */
@Override
public JCRNodeWrapper getParent() throws ItemNotFoundException, AccessDeniedException, RepositoryException {
    if (parentAlreadyResolved) {
        return resolvedParentNode;
    }

    try {
        if (localPath.equals("/") || localPath.equals(provider.getRelativeRoot())) {
            if (provider.getMountPoint().equals("/")) {
                throw new ItemNotFoundException();
            }
            return (JCRNodeWrapper) session
                    .getItem(StringUtils.substringBeforeLast(provider.getMountPoint(), "/"));
        } else {
            return (JCRNodeWrapper) session.getItem(StringUtils.substringBeforeLast(getPath(), "/"));
        }
    } catch (PathNotFoundException e) {
        throw new ItemNotFoundException(e);
    }
}