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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:org.jahia.ajax.gwt.helper.WorkflowHelper.java

public GWTJahiaWorkflowDefinition getGWTJahiaWorkflowDefinition(String key, Locale uiLocale) {
    return getGWTJahiaWorkflowDefinition(service.getWorkflowDefinition(StringUtils.substringBefore(key, ":"),
            StringUtils.substringAfter(key, ":"), uiLocale));
}

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

private ModelAndView handleGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String workspace = null;//w  w w. j  a  v a  2s.c o m
    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.Initializers.java

private String[] parseParameters(HttpServletRequest request) {
    String workspace = null;/*from  ww  w .  j av a2 s .c  o m*/
    String lang = null;
    String path = request.getPathInfo();
    if (path != null && path.startsWith(CONTROLLER_MAPPING + "/")) {
        path = path.substring(CONTROLLER_MAPPING.length() + 1);
        if (path.contains("/")) {
            workspace = StringUtils.substringBefore(path, "/");
            lang = StringUtils.substringAfter(path, "/");
            if (lang.contains("/")) {
                lang = StringUtils.substringBefore(lang, "/");
            }
        }
    }
    if (!JCRContentUtils.isValidWorkspace(workspace, true)) {
        // unknown workspace
        throw new JahiaBadRequestException("Unknown workspace '" + workspace + "'");
    }

    return new String[] { StringUtils.defaultIfEmpty(workspace, defaultWorkspace),
            StringUtils.defaultIfEmpty(lang, defaultLocale) };
}

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 {//from   ww w. ja  v  a2s .  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.bin.WelcomeServlet.java

protected void redirect(String url, HttpServletResponse response) throws IOException {
    String targetUrl = response.encodeRedirectURL(url);
    String jsessionIdParameterName = SettingsBean.getInstance().getJsessionIdParameterName();
    if (targetUrl.contains(";" + jsessionIdParameterName)) {
        if (targetUrl.contains("?")) {
            targetUrl = StringUtils.substringBefore(targetUrl, ";" + jsessionIdParameterName + "=") + "?"
                    + StringUtils.substringAfter(targetUrl, "?");
        } else {//from   www .j  av  a  2  s .  c o  m
            targetUrl = StringUtils.substringBefore(targetUrl, ";" + jsessionIdParameterName + "=");
        }
    }
    WebUtils.setNoCacheHeaders(response);
    response.sendRedirect(targetUrl);
}

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

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String wfKey = request.getParameter("workflowKey");
    String basePath = "/" + StringUtils.substringBefore(wfKey, ":").replaceAll("\\.", "/") + "/";
    wfKey = StringUtils.substringAfter(wfKey, ":");
    WorklowTypeRegistration workflowRegistration = workflowService.getWorkflowRegistration(wfKey);
    JahiaTemplatesPackage module = workflowRegistration.getModule();

    String language = request.getParameter("language");

    Resource resource = module.getResource(basePath + wfKey + "_" + language + ".png");
    if (resource == null) {
        resource = module.getResource(basePath + wfKey + ".png");
    }/*from   w  w w  . jav  a 2 s. co  m*/
    if (resource != null) {
        response.setContentType("image/png");

        ServletOutputStream out = response.getOutputStream();

        IOUtils.copy(resource.getInputStream(), out);
        out.flush();
    }
    response.setStatus(HttpServletResponse.SC_OK);
    return null;
}

From source file:org.jahia.modules.defaultmodule.CommentTaskAction.java

public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource,
        JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {
    String task = parameters.get("task").get(0);
    String taskId = StringUtils.substringAfter(task, ":");
    String providerKey = StringUtils.substringBefore(task, ":");
    String comment = parameters.get("comment").get(0);

    workflowService.addComment(taskId, providerKey, comment, renderContext.getUser().getUserKey());

    return ActionResult.OK;
}

From source file:org.jahia.modules.defaultmodule.ExecuteTaskAction.java

public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource,
        JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {
    String action = parameters.get("action").get(0);
    String actionId = StringUtils.substringAfter(action, ":");
    String providerKey = StringUtils.substringBefore(action, ":");
    String outcome = parameters.get("outcome").get(0);

    workflowService.assignAndCompleteTask(actionId, providerKey, outcome, getVariablesMap(parameters),
            renderContext.getUser());//from  www.  jav a  2s  . com

    return ActionResult.OK_JSON;
}

From source file:org.jahia.modules.defaultmodule.LockAction.java

public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource,
        JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {
    String type = req.getParameter("type");
    Map<String, String> res = new HashMap<String, String>();
    try {/* ww w.  j a  va  2  s .  co m*/
        // avoid to lock multiple times the same lock
        if (resource.getNode().hasProperty("j:lockTypes")) {
            for (Value v : resource.getNode().getProperty("j:lockTypes").getValues()) {
                String owner = StringUtils.substringBefore(v.getString(), ":");
                String currentType = StringUtils.substringAfter(v.getString(), ":");
                if (StringUtils.equals(owner, session.getUserID()) && StringUtils.equals(currentType, type)) {
                    // lock already set on this node
                    return new ActionResult(HttpServletResponse.SC_OK, null, new JSONObject(res));
                }
            }
        }
        resource.getNode().lockAndStoreToken(type);
    } catch (RepositoryException e) {
        res.put("error", e.getMessage());
    }
    return new ActionResult(HttpServletResponse.SC_OK, null, new JSONObject(res));
}

From source file:org.sonar.updatecenter.deprecated.UpdateCenter.java

private History<Plugin> resolvePluginHistory(String id) throws Exception {
    String groupId = StringUtils.substringBefore(id, ":");
    String artifactId = StringUtils.substringAfter(id, ":");

    Artifact artifact = artifactFactory.createArtifact(groupId, artifactId, Artifact.LATEST_VERSION,
            Artifact.SCOPE_COMPILE, ARTIFACT_JAR_TYPE);

    List<ArtifactVersion> versions = filterSnapshots(
            metadataSource.retrieveAvailableVersions(artifact, localRepository, remoteRepositories));

    History<Plugin> history = new History<Plugin>();
    for (ArtifactVersion version : versions) {
        Plugin plugin = org.sonar.updatecenter.deprecated.Plugin
                .extractMetadata(resolve(artifact.getGroupId(), artifact.getArtifactId(), version.toString()));
        history.addArtifact(version, plugin);

        MavenProject project = mavenProjectBuilder
                .buildFromRepository(//from   w w w  .j a va  2  s .co  m
                        artifactFactory.createArtifact(groupId, artifactId, version.toString(),
                                Artifact.SCOPE_COMPILE, ARTIFACT_POM_TYPE),
                        remoteRepositories, localRepository);

        if (plugin.getVersion() == null) {
            // Legacy plugin - set default values
            plugin.setKey(project.getArtifactId());
            plugin.setName(project.getName());
            plugin.setVersion(project.getVersion());

            String sonarVersion = "1.10"; // TODO Is it minimal version for all extension points ?
            for (Dependency dependency : project.getDependencies()) {
                if ("sonar-plugin-api".equals(dependency.getArtifactId())) { // TODO dirty hack
                    sonarVersion = dependency.getVersion();
                }
            }

            plugin.setRequiredSonarVersion(sonarVersion);
            plugin.setHomepage(project.getUrl());
        }
        plugin.setDownloadUrl(getPluginDownloadUrl(groupId, artifactId, plugin.getVersion()));
        // There is no equivalent for following properties in MANIFEST.MF
        if (project.getIssueManagement() != null) {
            plugin.setIssueTracker(project.getIssueManagement().getUrl());
        } else {
            System.out.println("Unknown Issue Management for " + plugin.getKey() + ":" + plugin.getVersion());
        }
        if (project.getScm() != null) {
            String scmUrl = project.getScm().getUrl();
            if (StringUtils.startsWith(scmUrl, "scm:")) {
                scmUrl = StringUtils.substringAfter(StringUtils.substringAfter(scmUrl, ":"), ":");
            }
            plugin.setSources(scmUrl);
        } else {
            System.out.println("Unknown SCM for " + plugin.getKey() + ":" + plugin.getVersion());
        }
        if (project.getLicenses() != null && project.getLicenses().size() > 0) {
            plugin.setLicense(project.getLicenses().get(0).getName());
        } else {
            System.out.println("Unknown License for " + plugin.getKey() + ":" + plugin.getVersion());
        }
        if (project.getDevelopers().size() > 0) {
            plugin.setDevelopers(project.getDevelopers());
        } else {
            System.out.println("Unknown Developers for " + plugin.getKey() + ":" + plugin.getVersion());
        }
    }
    return history;
}