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

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

Introduction

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

Prototype

public static String substringAfterLast(String str, String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:org.jahia.bin.DocumentConverter.java

private ModelAndView handleGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String workspace = null;//from  w ww. j  av  a  2s  .c om
    String nodePath = null;
    String targetFileExtension = null;

    String pathInfo = request.getPathInfo();
    // we expect the format:
    // /<workspace>/<file-node-path>.<target-file-extension>
    if (pathInfo != null && pathInfo.length() > 1) {
        pathInfo = StringUtils.substringAfter(pathInfo.substring(1), "/");
        workspace = StringUtils.substringBefore(pathInfo, "/");
        nodePath = StringUtils.substringAfter(pathInfo, workspace);
        if (nodePath.contains(".")) {
            targetFileExtension = StringUtils.substringAfterLast(nodePath, ".");
            nodePath = StringUtils.substringBeforeLast(nodePath, ".");
        } else {
            nodePath = null;
        }
    }
    // check required parameters
    if (!JCRContentUtils.isValidWorkspace(workspace) || StringUtils.isEmpty(nodePath)
            || StringUtils.isEmpty(targetFileExtension)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Expected data not found in the request."
                + " Please check the documentation of the Jahia Document Converter Service for more details.");
        return null;
    }
    // check target format
    String targetFormat = converterService.getMimeType(targetFileExtension);
    if (targetFormat == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Cannot lookup MIME type that corresponds to file extension '" + targetFileExtension + "'");
        return null;
    }

    InputStream is = null;
    try {
        JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession(workspace);
        JCRNodeWrapper node = session.getNode(nodePath);
        if (node.isNodeType("nt:file")) {
            response.setContentType(targetFormat);
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + StringUtils.substringBeforeLast(node.getName(), ".") + "." + targetFileExtension + "\"");
            is = node.getFileContent().downloadFile();
            converterService.convert(is,
                    converterService.getMimeType(FilenameUtils.getExtension(node.getName())),
                    response.getOutputStream(), targetFormat);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Path should correspond to a file node");
        }
    } catch (PathNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        IOUtils.closeQuietly(is);
    }

    return null;
}

From source file:org.jahia.bin.Logout.java

protected void doRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String redirect = request.getParameter("redirect");
    if (redirect == null) {
        redirect = request.getHeader("referer");
        if (StringUtils.isNotEmpty(redirect) && Login.isAuthorizedRedirect(request, redirect, false)) {
            redirect = redirect.startsWith("http://") ? StringUtils.substringAfter(redirect, "http://")
                    : StringUtils.substringAfter(redirect, "https://");
            redirect = redirect.contains("/") ? "/" + StringUtils.substringAfter(redirect, "/") : null;
        } else {//  www.  ja v a  2  s  .  c  o  m
            redirect = null;
        }
    } else if (!Login.isAuthorizedRedirect(request, redirect, false)) {
        redirect = null;
    }
    if (StringUtils.isNotBlank(redirect)) {
        try {
            final String r = redirect;
            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                @Override
                public String getRequestURI() {
                    return r;
                }

                @Override
                public String getPathInfo() {
                    if (r.startsWith(getContextPath() + "/cms/")) {
                        return StringUtils.substringAfter(r, getContextPath() + "/cms");
                    }
                    return null;
                }
            };

            if (urlRewriteService.prepareInbound(wrapper, response)) {
                RewrittenUrl restored = urlRewriteService.rewriteInbound(wrapper, response);
                if (restored != null) {
                    redirect = request.getContextPath() + restored.getTarget();
                }
            }
        } catch (Exception e) {
            logger.error("Cannot rewrite redirection url", e);
        }

        String prefix = request.getContextPath() + "/cms/";
        if (redirect.startsWith(prefix)) {
            String url = "/" + StringUtils.substringAfter(redirect, prefix);
            String hash = StringUtils.substringAfterLast(url, "#");
            url = StringUtils.substringBefore(url,
                    ";" + SettingsBean.getInstance().getJsessionIdParameterName());
            url = StringUtils.substringBefore(url, "?");
            url = StringUtils.substringBefore(url, "#");
            if (hash != null && hash.startsWith("/sites/") && url.contains("/sites/")) {
                url = StringUtils.substringBefore(url, "/sites/") + StringUtils.substringBefore(hash, ":")
                        + ".html";
            }

            List<String> urls = new ArrayList<String>();
            urls.add(url);
            if (url.startsWith("/edit/")) {
                url = "/render/" + StringUtils.substringAfter(url, "/edit/");
                urls.add(url);
            } else if (url.startsWith("/editframe/default/")) {
                url = "/render/live/" + StringUtils.substringAfter(url, "/editframe/default/");
                urls.add(url);
            } else if (url.startsWith("/contribute/")) {
                url = "/render/" + StringUtils.substringAfter(url, "/contribute/");
                urls.add(url);
            } else if (url.startsWith("/contributeframe/default/")) {
                url = "/render/live/" + StringUtils.substringAfter(url, "/contributeframe/default/");
                urls.add(url);
            }
            if (url.startsWith("/render/default/")) {
                url = "/render/live/" + StringUtils.substringAfter(url, "/render/default/");
                urls.add(url);
            }
            for (String currentUrl : urls) {
                try {
                    URLResolver r = urlResolverFactory.createURLResolver(currentUrl, request.getServerName(),
                            request);
                    if (r.getPath().startsWith("/sites/")) {
                        JCRNodeWrapper n = r.getNode();
                        // test that we do not get the site node, in that case, redirect to homepage
                        if (n.isNodeType("jnt:virtualsite")) {
                            n = ((JCRSiteNode) n).getHome();
                        }
                        if (n == null) {
                            // this can occur if the homepage of the site is not set
                            redirect = request.getContextPath() + "/";
                        } else {
                            redirect = prefix + r.getServletPart() + "/" + r.getWorkspace() + "/"
                                    + resolveLanguage(request, n.getResolveSite()) + n.getPath() + ".html";
                        }
                    } else {
                        redirect = request.getContextPath() + "/";
                    }
                    redirect = urlRewriteService.rewriteOutbound(redirect, request, response);
                    response.sendRedirect(response.encodeRedirectURL(redirect));
                    return;
                } catch (Exception e) {
                    logger.debug("Cannot redirect to " + currentUrl, e);
                }
            }
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/"));
            return;
        }
    }

    response.sendRedirect(response
            .encodeRedirectURL(StringUtils.isNotEmpty(redirect) ? redirect : request.getContextPath() + "/"));
}

From source file:org.jahia.bundles.extender.jahiamodules.RulesBundleObserver.java

@Override
public void addingEntries(Bundle bundle, List<URL> urls) {
    if (urls.size() == 0) {
        return;//from   w  w  w  .  j  a  v a  2  s . co  m
    }
    String bundleName = BundleUtils.getDisplayName(bundle);
    for (URL url : urls) {
        BundleResource bundleResource = new BundleResource(url, bundle);
        try {

            JahiaTemplatesPackage module = templatePackageRegistry.lookupByBundle(bundle);

            if (url.toString().endsWith(".dsl")) {
                module.setRulesDescriptorFile(bundleResource.getURL().getPath().substring(1));

                for (RulesListener listener : RulesListener.getInstances()) {
                    listener.addRulesDescriptor(bundleResource, module);
                }
            }

            if (url.toString().endsWith(".drl")) {
                module.setRulesFile(bundleResource.getURL().getPath().substring(1));

                for (RulesListener listener : RulesListener.getInstances()) {
                    List<String> filesAccepted = listener.getFilesAccepted();
                    if (filesAccepted.contains(StringUtils.substringAfterLast(url.getPath(), "/"))) {
                        listener.addRules(bundleResource, module);
                    }
                }
            }

            logger.info("Registered rules from file {} for bundle {}", url, bundleName);
        } catch (Exception e) {
            logger.error("Error registering rules file " + url + " for bundle " + bundle, e);
        }
    }
}

From source file:org.jahia.bundles.jcrcommands.JCRNodeCompleter.java

@Override
public int complete(final Session session, final CommandLine commandLine, final List<String> candidates) {
    try {/*from  w w w.  j a  v a 2s. co m*/
        JCRTemplate.getInstance().doExecuteWithSystemSession(null, getCurrentWorkspace(session), null,
                new JCRCallback<Object>() {
                    @Override
                    public Object doInJCR(JCRSessionWrapper jcrsession) throws RepositoryException {
                        String arg = commandLine.getCursorArgument();
                        if (arg == null) {
                            arg = "";
                        } else {
                            arg = arg.substring(0, commandLine.getArgumentPosition());
                        }

                        JCRNodeWrapper n = jcrsession.getNode(getCurrentPath(session));
                        String prefix = "";
                        if (arg.indexOf('/') > -1) {
                            prefix = StringUtils.substringBeforeLast(arg, "/") + "/";
                            if (prefix.startsWith("/")) {
                                n = jcrsession.getNode(prefix);
                            } else {
                                n = n.getNode(prefix);
                            }
                            arg = StringUtils.substringAfterLast(arg, "/");
                        }
                        JCRNodeIteratorWrapper nodes = n.getNodes();
                        while (nodes.hasNext()) {
                            JCRNodeWrapper next = (JCRNodeWrapper) nodes.nextNode();
                            if (next.getName().startsWith(arg)) {
                                candidates.add(prefix + next.getName() + "/");
                            }
                        }
                        return null;
                    }
                });
    } catch (RepositoryException e) {
        // ignore
    }
    return candidates.isEmpty() ? -1 : commandLine.getBufferPosition() - commandLine.getArgumentPosition();
}

From source file:org.jahia.izpack.ResourcesConverter.java

/**
 * Performs conversion of the property file into XML language pack.
 * /*from  ww  w  .j a v  a  2  s .  c  o m*/
 * @param bundleName
 *            the resource bundle name
 * @param locale
 *            locale to be used
 * @param targetFolder
 *            the target folder
 * @throws FileNotFoundException
 */
private static void convert(String bundleName, Locale locale, File targetFolder) throws FileNotFoundException {
    ResourceBundle enBundle = ResourceBundle.getBundle(bundleName, Locale.ENGLISH);
    ResourceBundle bundle = null;
    try {
        bundle = ResourceBundle.getBundle(bundleName, locale);
    } catch (MissingResourceException e) {
        bundle = enBundle;
    }
    PrintWriter out = new PrintWriter(new File(targetFolder,
            StringUtils.substringAfterLast(bundleName, ".") + "." + locale.getISO3Language() + ".xml"));
    Enumeration<String> keyEnum = enBundle.getKeys();
    List<String> keys = new LinkedList<String>();
    while (keyEnum.hasMoreElements()) {
        keys.add(keyEnum.nextElement());
    }
    Collections.sort(keys);
    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    out.println("<langpack>");
    for (String key : keys) {
        String value = null;
        try {
            value = bundle.getString(key);
        } catch (MissingResourceException e) {
            try {
                value = enBundle.getString(key);
            } catch (MissingResourceException e2) {
                value = key;
            }
        }
        out.append("    <str id=\"").append(key).append("\" txt=\"").append(StringEscapeUtils.escapeXml(value))
                .append("\"/>");
        out.println();
    }
    out.println("</langpack>");
    out.flush();
    out.close();
}

From source file:org.jahia.modules.external.ExternalContentStoreProvider.java

public PropertyIterator getWeakReferences(JCRNodeWrapper node, String propertyName, Session session)
        throws RepositoryException {
    if (dataSource instanceof ExternalDataSource.Referenceable && session instanceof ExternalSessionImpl) {
        String identifier = node.getIdentifier();
        if (this.equals(node.getProvider())) {
            identifier = ((ExternalNodeImpl) node.getRealNode()).getData().getId();
        }//from ww  w  .  j  av a2  s .  co m
        setCurrentSession((ExternalSessionImpl) session);
        List<String> referringProperties = null;
        try {
            referringProperties = ((ExternalDataSource.Referenceable) dataSource)
                    .getReferringProperties(identifier, propertyName);
        } finally {
            ExternalContentStoreProvider.removeCurrentSession();
        }
        if (referringProperties == null) {
            return null;
        }
        if (referringProperties.isEmpty()) {
            return PropertyIteratorAdapter.EMPTY;
        }
        List<Property> l = new ArrayList<Property>();
        for (String propertyPath : referringProperties) {
            String nodePath = StringUtils.substringBeforeLast(propertyPath, "/");
            if (nodePath.isEmpty()) {
                nodePath = "/";
            }
            ExternalNodeImpl referringNode = (ExternalNodeImpl) session.getNode(nodePath);
            if (referringNode != null) {
                l.add(new ExternalPropertyImpl(
                        new Name(StringUtils.substringAfterLast(propertyPath, "/"),
                                NodeTypeRegistry.getInstance().getNamespaces()),
                        referringNode, (ExternalSessionImpl) session));
            }
        }
        return new PropertyIteratorAdapter(l);
    }
    return null;
}

From source file:org.jahia.modules.external.ExternalData.java

public ExternalData(String id, String path, String type, Map<String, String[]> properties, boolean isNew) {
    this.id = id;
    this.path = path;
    this.name = StringUtils.substringAfterLast(path, "/");
    this.type = type;
    this.properties = properties;
    this.isNew = isNew;
    if (isNew) {//from   ww  w  .j  ava  2  s  .c o m
        this.tmpId = id;
    }
}

From source file:org.jahia.modules.external.ExternalNodeImpl.java

public Node getExtensionNode(boolean create) throws RepositoryException {

    Session extensionSession = getSession().getExtensionSession();
    if (extensionSession == null) {
        return null;
    }/*from   w ww  . jav  a2s .  c  o m*/
    List<String> extensionAllowedTypes = getSession().getExtensionAllowedTypes();
    boolean allowed = false;
    if (extensionAllowedTypes != null) {
        for (String type : extensionAllowedTypes) {
            if (isNodeType(type, false)) {
                allowed = true;
                break;
            }
        }
    }
    if (!allowed) {
        return null;
    }
    String path = getPath();
    boolean isRoot = path.equals("/");

    String mountPoint = getStoreProvider().getMountPoint();
    String globalPath = mountPoint + (isRoot ? "" : path);

    if (!extensionSession.itemExists(globalPath)) {
        if (!create) {
            return null;
        } else {
            // create extension nodes if needed
            String[] splittedPath = StringUtils.split(path, "/");
            StringBuilder currentExtensionPath = new StringBuilder(mountPoint);
            StringBuilder currentExternalPath = new StringBuilder();
            // create extension node on the mountpoint if needed
            if (!extensionSession.nodeExists(mountPoint)) {
                String parent = StringUtils.substringBeforeLast(mountPoint, "/");
                if (parent.equals("")) {
                    parent = "/";
                }
                final Node extParent = extensionSession.getNode(parent);
                takeLockToken(extParent);
                extParent.addMixin("jmix:hasExternalProviderExtension");
                Node n = extParent.addNode(StringUtils.substringAfterLast(mountPoint, "/"),
                        "jnt:externalProviderExtension");
                n.addMixin("jmix:externalProviderExtension");
                n.setProperty("j:isExternalProviderRoot", true);
                Node externalNode = (Node) session.getItemWithNoCheck("/");
                n.setProperty("j:externalNodeIdentifier", externalNode.getIdentifier());
                List<Value> values = ExtensionNode.createNodeTypeValues(session.getValueFactory(),
                        externalNode.getPrimaryNodeType().getName());
                n.setProperty("j:extendedType", values.toArray(new Value[values.size()]));
            }
            for (String p : splittedPath) {
                currentExtensionPath.append("/").append(p);
                currentExternalPath.append("/").append(p);
                if (!extensionSession.nodeExists(currentExtensionPath.toString())) {
                    final Node extParent = extensionSession
                            .getNode(StringUtils.substringBeforeLast(currentExtensionPath.toString(), "/"));
                    takeLockToken(extParent);
                    Node n = extParent.addNode(p, "jnt:externalProviderExtension");
                    Node externalNode = (Node) session.getItemWithNoCheck(currentExternalPath.toString());
                    List<Value> values = ExtensionNode.createNodeTypeValues(session.getValueFactory(),
                            externalNode.getPrimaryNodeType().getName());
                    n.setProperty("j:extendedType", values.toArray(new Value[values.size()]));
                    n.addMixin("jmix:externalProviderExtension");
                    n.setProperty("j:isExternalProviderRoot", false);
                    n.setProperty("j:externalNodeIdentifier", externalNode.getIdentifier());
                }
            }
        }
    }

    Node node = extensionSession.getNode(globalPath);
    if (create && isRoot && !node.isNodeType("jmix:hasExternalProviderExtension")) {
        node.addMixin("jmix:hasExternalProviderExtension");
    }
    if (!node.isNodeType("jmix:externalProviderExtension")) {
        node.addMixin("jmix:externalProviderExtension");
    }
    return node;
}

From source file:org.jahia.modules.external.ExternalPathWrapperImpl.java

@Override
public String getNodeName() throws NamespaceException {
    return StringUtils.substringAfterLast(jcrPath, "/");
}

From source file:org.jahia.modules.external.ExternalSessionImpl.java

protected Item getItemWithNoCheck(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   ww  w.j ava2s . com*/

    final Node fromCache = getFromCacheByPath(path);
    if (fromCache != null) {
        return fromCache;
    }

    String parentPath = StringUtils.substringBeforeLast(path, "/");
    if (parentPath.equals("")) {
        parentPath = "/";
    }
    try {
        if (StringUtils.substringAfterLast(parentPath, "/").startsWith(TRANSLATION_NODE_NAME_BASE)) {
            // Getting a translation property
            return getNode(parentPath).getProperty(StringUtils.substringAfterLast(path, "/"));
        } else if (StringUtils.substringAfterLast(path, "/").startsWith(TRANSLATION_NODE_NAME_BASE)) {
            // Getting translation node
            return handleI18nNode(parentPath, path);
        } else if (StringUtils.substringAfterLast(parentPath, "/").equals(ExternalDataAcl.ACL_NODE_NAME)
                && repository.getDataSource() instanceof ExternalDataSource.AccessControllable) {
            // Getting ace node or acl property
            String last = StringUtils.substringAfterLast(path, "/");
            if (last.startsWith(ExternalDataAce.Type.DENY.toString())
                    || last.startsWith(ExternalDataAce.Type.GRANT.toString())) {
                // get the ace node
                return handleAceNode(parentPath, path, last);
            } else {
                // get the property
                return getNode(parentPath).getProperty(last);
            }
        } else if (StringUtils.substringAfterLast(path, "/").equals(ExternalDataAcl.ACL_NODE_NAME)
                && repository.getDataSource() instanceof ExternalDataSource.AccessControllable) {
            // Getting acl node
            return handleAclNode(parentPath, path);
        } else if ((StringUtils.substringAfterLast(parentPath, "/")
                .startsWith(ExternalDataAce.Type.GRANT.toString())
                || StringUtils.substringAfterLast(path, "/").startsWith(ExternalDataAce.Type.DENY.toString()))
                && StringUtils.substringBeforeLast(parentPath, "/").endsWith("/j:acl")
                && repository.getDataSource() instanceof ExternalDataSource.AccessControllable) {
            // Getting ace node property
            return getNode(parentPath).getProperty(StringUtils.substringAfterLast(path, "/"));
        } else {
            String itemName = StringUtils.substringAfterLast(path, "/");
            if (getRepository().getStoreProvider().getReservedNodes().contains(itemName)) {
                throw new PathNotFoundException(path);
            }
            // Try to get the item as a node
            ExternalContentStoreProvider.setCurrentSession(this);
            try {
                ExternalData data = repository.getDataSource().getItemByPath(path);
                final ExternalNodeImpl node = new ExternalNodeImpl(data, this);
                registerNode(node);
                return node;
            } catch (PathNotFoundException e) {
                // Or a property in the parent node
                ExternalNodeImpl parentFromPath = getFromCacheByPath(parentPath);
                if (parentFromPath == null) {
                    ExternalData data = repository.getDataSource().getItemByPath(parentPath);
                    final ExternalNodeImpl node = new ExternalNodeImpl(data, this);
                    registerNode(node);
                    parentFromPath = node;
                }
                return parentFromPath.getProperty(itemName);
            } finally {
                ExternalContentStoreProvider.removeCurrentSession();
            }
        }
    } catch (PathNotFoundException e) {
        // In case item is not found in provider, lookup in extension provider if available
        if (getExtensionSession() != null && !StringUtils.equals("/", path)) {
            Item item = getExtensionSession().getItem(repository.getStoreProvider().getMountPoint() + path);
            if ((item.isNode() ? (Node) item : item.getParent()).isNodeType("jnt:externalProviderExtension")) {
                throw e;
            }
            return item.isNode() ? new ExtensionNode((Node) item, path, this)
                    : new ExtensionProperty((Property) item, path, this,
                            new ExtensionNode(item.getParent(), parentPath, this));
        } else {
            throw e;
        }
    }
}