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.modules.googleAnalytics.GoogleAnalyticsFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//w w  w .jav  a2  s. c  o  m
    String webPropertyID = renderContext.getSite().hasProperty("webPropertyID")
            ? renderContext.getSite().getProperty("webPropertyID").getString()
            : null;
    if (StringUtils.isNotEmpty(webPropertyID)) {
        String script = getResolvedTemplate();
        if (script != null) {
            Source source = new Source(previousOut);
            OutputDocument outputDocument = new OutputDocument(source);
            List<Element> headElementList = source.getAllElements(HTMLElementName.HEAD);
            for (Element element : headElementList) {
                final EndTag headEndTag = element.getEndTag();
                String extension = StringUtils.substringAfterLast(template, ".");
                ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
                ScriptContext scriptContext = new GoogleScriptContext();
                final Bindings bindings = scriptEngine.createBindings();
                bindings.put("webPropertyID", webPropertyID);
                String url = resource.getNode().getUrl();
                if (renderContext.getRequest().getAttribute("analytics-path") != null) {
                    url = (String) renderContext.getRequest().getAttribute("analytics-path");
                }
                bindings.put("resourceUrl", url);
                bindings.put("resource", resource);
                bindings.put("gaMap", renderContext.getRequest().getAttribute("gaMap"));
                scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
                // The following binding is necessary for Javascript, which doesn't offer a console by default.
                bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                scriptEngine.eval(script, scriptContext);
                StringWriter writer = (StringWriter) scriptContext.getWriter();
                final String googleAnalyticsScript = writer.toString();
                if (StringUtils.isNotBlank(googleAnalyticsScript)) {
                    outputDocument.replace(headEndTag.getBegin(), headEndTag.getBegin() + 1,
                            "\n" + AggregateCacheFilter.removeEsiTags(googleAnalyticsScript) + "\n<");
                }
                break; // avoid to loop if for any reasons multiple body in the page
            }
            out = outputDocument.toString().trim();
        }
    }

    return out;
}

From source file:org.jahia.modules.irclogs.filters.IRCLogPageTitleFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//w w  w . j a v  a 2s . co m
    String script = getResolvedTemplate();
    if (script != null) {
        Source source = new Source(previousOut);
        OutputDocument outputDocument = new OutputDocument(source);
        List<Element> headElementList = source.getAllElements(HTMLElementName.TITLE);
        for (Element element : headElementList) {
            final EndTag bodyEndTag = element.getEndTag();
            final StartTag bodyStartTag = element.getStartTag();
            String extension = StringUtils.substringAfterLast(template, ".");
            ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
            ScriptContext scriptContext = new irclogsScriptContext();
            final Bindings bindings = scriptEngine.createBindings();
            bindings.put("resource", resource);
            scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);

            // The following binding is necessary for Javascript, which doesn't offer a console by default.
            bindings.put("out", new PrintWriter(scriptContext.getWriter()));

            // Parameters needed for title replacing
            bindings.put("orgTitle",
                    outputDocument.toString().substring(bodyStartTag.getEnd(), bodyEndTag.getBegin()));
            bindings.put("dateFormatter", dateFormatter);
            bindings.put("title", getTitle());
            bindings.put("renderContext", renderContext);

            scriptEngine.eval(script, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            final String irclogsScript = writer.toString();
            if (StringUtils.isNotBlank(irclogsScript)) {
                outputDocument.replace(bodyStartTag.getEnd(), bodyEndTag.getBegin() + 1,
                        AggregateCacheFilter.removeEsiTags(irclogsScript) + "<");
            }
            break; // avoid to loop if for any reasons multiple body in the page
        }
        out = outputDocument.toString().trim();
    }

    return out;
}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

public boolean uploadModule(MultipartFile moduleFile, MessageContext context, boolean forceUpdate,
        boolean autoStart) {
    if (moduleFile == null) {
        context.addMessage(new MessageBuilder().error().source("moduleFile")
                .code("serverSettings.manageModules.install.moduleFileRequired").build());
        return false;
    }/*from w  ww  . ja va  2  s .  co  m*/
    String originalFilename = moduleFile.getOriginalFilename();
    if (!FilenameUtils.isExtension(StringUtils.lowerCase(originalFilename), "jar")) {
        context.addMessage(new MessageBuilder().error().source("moduleFile")
                .code("serverSettings.manageModules.install.wrongFormat").build());
        return false;
    }
    File file = null;
    try {
        file = File.createTempFile("module-", "." + StringUtils.substringAfterLast(originalFilename, "."));
        moduleFile.transferTo(file);
        installBundles(file, context, originalFilename, forceUpdate, autoStart);
        return true;
    } catch (Exception e) {
        context.addMessage(new MessageBuilder().source("moduleFile")
                .code("serverSettings.manageModules.install.failed").arg(e.getMessage()).error().build());
        logger.error(e.getMessage(), e);
    } finally {
        FileUtils.deleteQuietly(file);
    }
    return false;
}

From source file:org.jahia.modules.modulemanager.forge.ForgeService.java

public File downloadModuleFromForge(String forgeId, String url) {
    for (Forge forge : forges) {
        if (forgeId.equals(forge.getId())) {
            GetMethod httpMethod = new GetMethod(url);
            httpMethod.addRequestHeader("Authorization",
                    "Basic " + Base64.encode((forge.getUser() + ":" + forge.getPassword()).getBytes()));
            HttpClient httpClient = httpClientService.getHttpClient();
            try {
                int status = httpClient.executeMethod(httpMethod);
                if (status == HttpServletResponse.SC_OK) {
                    File f = File.createTempFile("module", "." + StringUtils.substringAfterLast(url, "."));
                    FileUtils.copyInputStreamToFile(httpMethod.getResponseBodyAsStream(), f);
                    return f;
                }//from   w  ww .j  a v  a  2  s  .co  m
            } catch (IOException e) {
                logger.error(e.getMessage(), e); //To change body of catch statement use File | Settings | File Templates.
            }

        }
    }
    return null;
}

From source file:org.jahia.modules.portal.action.MoveWidgetAction.java

public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource,
        JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {
    String area = req.getParameter("toArea");
    String widgetPath = req.getParameter("widget");
    String onTopOfWidgetPath = req.getParameter("onTopOfWidget");
    String colPath = resource.getNode().getPath() + "/" + area;

    JCRSessionWrapper jcrSessionWrapper = JCRSessionFactory.getInstance()
            .getCurrentUserSession(resource.getWorkspace(), resource.getLocale());

    if (StringUtils.isNotEmpty(onTopOfWidgetPath)) {
        contentManager.moveOnTopOf(widgetPath, onTopOfWidgetPath, jcrSessionWrapper);
    } else {/*from w  ww .  j av  a2s .c o m*/
        contentManager.moveAtEnd(widgetPath, portalService.getColumn(colPath, jcrSessionWrapper).getPath(),
                jcrSessionWrapper);
    }

    JSONObject result = new JSONObject();
    result.put("path", colPath + "/" + StringUtils.substringAfterLast(widgetPath, "/"));

    return new ActionResult(HttpServletResponse.SC_OK, null, result);
}

From source file:org.jahia.modules.portal.filter.JCRRestJavaScriptLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//from  w ww.java2s  .  c o m
    String context = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath()
            : "";

    // add lib
    String path = context + "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JCR_REST_JS_FILE;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JCR_REST_JS_FILE + "'/>");

    // instance JavaScript object
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(JCR_REST_SCRIPT_TEMPLATE, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new JCRRestUtilsScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("options", getBindingMap(renderContext, resource, context));
        scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
        // The following binding is necessary for Javascript, which doesn't offer a console by default.
        bindings.put("out", new PrintWriter(scriptContext.getWriter()));
        scriptEngine.eval(script, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String resultScript = writer.toString();
        if (StringUtils.isNotBlank(resultScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(resultScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}

From source file:org.jahia.modules.portal.filter.PortalLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/*w ww.  j a  v a2 s  .  c  o  m*/

    // add portal API lib
    String path = "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JS_API_FILE;
    path = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath() + path
            : path;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JS_API_FILE + "'/>");

    // add portal instance
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(template, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new PortalScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("portalContext", serializePortal(renderContext));
        scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
        // The following binding is necessary for Javascript, which doesn't offer a console by default.
        bindings.put("out", new PrintWriter(scriptContext.getWriter()));
        scriptEngine.eval(script, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String portalScript = writer.toString();
        if (StringUtils.isNotBlank(portalScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(portalScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}

From source file:org.jahia.modules.portal.service.PortalService.java

public JCRNodeWrapper getColumn(String path, JCRSessionWrapper sessionWrapper) {
    JCRNodeWrapper columnNode;//from w  ww  . j a v a  2  s.  com
    try {
        columnNode = sessionWrapper.getNode(path);
    } catch (RepositoryException e) {
        try {
            JCRNodeWrapper portalTabNode = sessionWrapper.getNode(StringUtils.substringBeforeLast(path, "/"));
            columnNode = portalTabNode.addNode(
                    JCRContentUtils.generateNodeName(StringUtils.substringAfterLast(path, "/"), 32),
                    PortalConstants.JNT_PORTAL_COLUMN);
            sessionWrapper.save();
        } catch (RepositoryException e1) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    return columnNode;
}

From source file:org.jahia.modules.rolesmanager.RolesAndPermissionsHandler.java

private void addPermissionsForScope(RoleBean roleBean, String scope, Map<String, List<String>> permIdsMap,
        Map<String, List<String>> inheritedPermIdsMap) throws RepositoryException {
    final Map<String, Map<String, Map<String, PermissionBean>>> permissions = roleBean.getPermissions();
    if (!permissions.containsKey(scope)) {
        permissions.put(scope, new LinkedHashMap<String, Map<String, PermissionBean>>());
    }/*from  w  w  w  .  j a v a 2  s  .c om*/
    List<JCRNodeWrapper> allPermissions = getAllPermissions();

    String type = null;
    final Map<String, List<String>> globalPermissionsGroups = roleTypes.getPermissionsGroups();
    final Map<String, List<String>> permissionsGroupsForRoleType = roleBean.getRoleType()
            .getPermissionsGroups();

    if (scope.equals("current")) {
        if (roleBean.getRoleType().getDefaultNodeTypes() != null
                && roleBean.getRoleType().getDefaultNodeTypes().size() == 1) {
            type = roleBean.getRoleType().getDefaultNodeTypes().get(0);
        }
    } else {
        if (scope.equals("currentSite")) {
            type = "jnt:virtualsite";
        } else if (scope.startsWith("/")) {
            try {
                type = getSession().getNode(scope).getPrimaryNodeTypeName();
            } catch (PathNotFoundException e) {
                logger.debug("Error retrieving scope", e);
            } catch (RepositoryException e) {
                logger.error("Error retrieving scope", e);
            }
        }
    }
    if (type == null || (!globalPermissionsGroups.containsKey(type)
            && (permissionsGroupsForRoleType == null || !permissionsGroupsForRoleType.containsKey(type)))) {
        type = "nt:base";
    }
    if (permissionsGroupsForRoleType != null && permissionsGroupsForRoleType.containsKey(type)) {
        for (String s : permissionsGroupsForRoleType.get(type)) {
            permissions.get(scope).put(s, new TreeMap<String, PermissionBean>());
        }
    } else {
        for (String s : globalPermissionsGroups.get(type)) {
            permissions.get(scope).put(s, new TreeMap<String, PermissionBean>());
        }
    }

    Map<String, PermissionBean> mappedPermissions = new HashMap<String, PermissionBean>();

    Map<String, String> allGroups = new HashMap<String, String>();
    for (String s : permissions.get(scope).keySet()) {
        for (String s1 : Arrays.asList(s.split(","))) {
            allGroups.put(s1, s);
        }
    }

    // Create mapped permissions
    for (Map.Entry<String, List<String>> entry : roleTypes.getPermissionsMapping().entrySet()) {
        String[] splitPath = entry.getKey().split("/");
        String permissionGroup = splitPath[2];
        if (allGroups.containsKey(permissionGroup)) {
            Map<String, PermissionBean> p = permissions.get(scope).get(allGroups.get(permissionGroup));
            PermissionBean bean = new PermissionBean();
            bean.setUuid(null);
            bean.setParentPath(StringUtils.substringBeforeLast(entry.getKey(), "/"));
            bean.setName(StringUtils.substringAfterLast(entry.getKey(), "/"));
            String localName = StringUtils.substringAfterLast(entry.getKey(), "/");
            if (localName.contains(":")) {
                localName = StringUtils.substringAfter(localName, ":");
            }
            String title = StringUtils
                    .capitalize(localName.replaceAll("([A-Z])", " $0").replaceAll("[_-]", " ").toLowerCase());
            final String rbName = localName.replaceAll("-", "_");
            bean.setTitle(
                    Messages.getInternal("label.permission." + rbName, LocaleContextHolder.getLocale(), title));
            bean.setDescription(Messages.getInternal("label.permission." + rbName + ".description",
                    LocaleContextHolder.getLocale(), ""));
            bean.setPath(entry.getKey());
            bean.setDepth(splitPath.length - 1);
            bean.setMappedPermissions(new TreeMap<String, PermissionBean>());
            if (p.containsKey(bean.getParentPath())) {
                p.get(bean.getParentPath()).setHasChildren(true);
            }

            p.put(entry.getKey(), bean);

            for (String s : entry.getValue()) {
                createMappedPermission(s, bean, mappedPermissions);
            }
        }
    }

    // Create standard permissions
    for (JCRNodeWrapper permissionNode : allPermissions) {
        JCRNodeWrapper permissionGroup = getPermissionGroupNode(permissionNode);
        final String permissionPath = getPermissionPath(permissionNode);

        if (!mappedPermissions.containsKey(permissionPath)
                && mappedPermissions.containsKey(getPermissionPath(permissionNode.getParent()))) {
            final PermissionBean bean = mappedPermissions.get(getPermissionPath(permissionNode.getParent()));
            createMappedPermission(permissionPath, bean, mappedPermissions);
        }

        if (allGroups.containsKey(permissionGroup.getName())
                && !mappedPermissions.containsKey(permissionPath)) {
            Map<String, PermissionBean> p = permissions.get(scope)
                    .get(allGroups.get(permissionGroup.getName()));
            if (!p.containsKey(permissionPath) || permissionNode.getPath().startsWith("/permissions")) {
                PermissionBean bean = new PermissionBean();
                setPermissionBeanProperties(permissionNode, bean);
                if (p.containsKey(bean.getParentPath())) {
                    p.get(bean.getParentPath()).setHasChildren(true);
                }
                p.put(permissionPath, bean);
                setPermissionFlags(permissionNode, p, bean, permIdsMap.get(scope),
                        inheritedPermIdsMap.get(scope), p.get(bean.getParentPath()));
            }
        }
        if (mappedPermissions.containsKey(permissionPath)) {
            PermissionBean bean = mappedPermissions.get(permissionPath);

            Map<String, PermissionBean> p = permissions.get(scope)
                    .get(allGroups.get(bean.getPath().split("/")[2]));
            setPermissionFlags(permissionNode, p, bean, permIdsMap.get(scope), inheritedPermIdsMap.get(scope),
                    p.get(bean.getParentPath()));
        }
    }

    // Auto expand permissions where mapped permissions are partially set
    for (Map<String, Map<String, PermissionBean>> map : roleBean.getPermissions().values()) {
        for (Map<String, PermissionBean> map2 : map.values()) {
            final Collection<PermissionBean> values = new ArrayList<PermissionBean>(map2.values());
            for (PermissionBean bean : values) {
                if (bean.getMappedPermissions() != null) {
                    Boolean lastValue = null;
                    for (PermissionBean value : bean.getMappedPermissions().values()) {
                        if (lastValue == null) {
                            lastValue = value.isSuperSet() || value.isSet();
                        }
                        if (!lastValue.equals(value.isSuperSet() || value.isSet())) {
                            bean.setMappedPermissionsExpanded(true);
                            bean.setSet(false);
                            bean.setSuperSet(false);
                            bean.setPartialSet(true);
                            break;
                        }
                    }
                    if (bean.isMappedPermissionsExpanded()) {
                        for (PermissionBean mapped : bean.getMappedPermissions().values()) {
                            map2.put(mapped.getPath(), mapped);
                        }
                    }
                }
            }
        }
    }
}

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

public boolean handle(Throwable e, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {//w w  w.ja  v  a2  s.c o  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;
}