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.ajax.gwt.helper.NavigationHelper.java

public List<GWTJahiaNode> retrieveRoot(List<String> paths, List<String> nodeTypes, List<String> mimeTypes,
        List<String> filters, List<String> fields, List<String> selectedNodes, List<String> openPaths,
        final JCRSiteNode site, JCRSessionWrapper currentUserSession, Locale uiLocale, boolean checkSubChild,
        boolean displayHiddenTypes, List<String> hiddenTypes, String hiddenRegex)
        throws GWTJahiaServiceException {
    try {/* w ww  .j a  v  a2 s.c o m*/
        if (logger.isDebugEnabled()) {
            logger.debug("open paths for getRoot : " + openPaths);
        }

        final List<GWTJahiaNode> userNodes = retrieveRoot(paths, nodeTypes, mimeTypes, filters, fields, site,
                uiLocale, currentUserSession, checkSubChild, displayHiddenTypes, hiddenTypes, hiddenRegex);
        List<GWTJahiaNode> allNodes = new ArrayList<GWTJahiaNode>(userNodes);
        if (selectedNodes != null) {
            if (openPaths == null) {
                openPaths = selectedNodes;
            } else {
                // copy the list to avoid ConcurrentModificationException, see QA-5200
                openPaths = new ArrayList<String>(openPaths);
                openPaths.addAll(selectedNodes);
            }
        }
        if (openPaths != null) {
            for (String openPath : new HashSet<String>(openPaths)) {
                try {
                    for (int i = 0; i < allNodes.size(); i++) {
                        GWTJahiaNode node = allNodes.get(i);
                        if (!node.isExpandOnLoad()) {
                            boolean matchPath;
                            if (openPath.endsWith("*")) {
                                String p = StringUtils.substringBeforeLast(openPath, "*");
                                matchPath = node.getPath().startsWith(p) || p.startsWith(node.getPath());
                            } else {
                                matchPath = openPath.startsWith(node.getPath());
                            }
                            if (matchPath) {
                                node.setExpandOnLoad(true);
                                List<GWTJahiaNode> list = ls(node.getPath(), nodeTypes, mimeTypes, filters,
                                        fields, checkSubChild, displayHiddenTypes, hiddenTypes, hiddenRegex,
                                        currentUserSession, false, uiLocale);
                                for (int j = 0; j < list.size(); j++) {
                                    node.insert(list.get(j), j);
                                    allNodes.add(list.get(j));
                                }
                            }
                        }
                        if (selectedNodes != null && selectedNodes.contains(node.getPath())) {
                            node.setSelectedOnLoad(true);
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        for (GWTJahiaNode userNode : userNodes) {
            userNode.set("isRootNode", Boolean.TRUE);
        }
        return userNodes;
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
        throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                "label.gwt.error.cannot.retrieve.root.nodes", uiLocale, paths, e.getLocalizedMessage()));
    }
}

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

public List<GWTJahiaNode> retrieveRoot(List<String> paths, List<String> nodeTypes, List<String> mimeTypes,
        List<String> filters, final List<String> fields, final JCRSiteNode site, Locale uiLocale,
        JCRSessionWrapper currentUserSession, boolean checkSubChild, boolean displayHiddenTypes,
        List<String> hiddenTypes, String hiddenRegex) throws RepositoryException, GWTJahiaServiceException {
    final List<GWTJahiaNode> userNodes = new ArrayList<GWTJahiaNode>();
    final boolean checkLicense = haveToCheckLicense(fields);

    for (String path : paths) {
        // replace $user and $site by the right values
        String displayName = null;
        if (site != null) {
            if (path.contains("$site/") || path.endsWith("$site")) {
                String sitePath = site.getPath();
                if (StringUtils.startsWith(sitePath, "/modules/")) {
                    String moduleName = sitePath.indexOf('/', "/modules/".length()) != -1
                            ? StringUtils.substringBetween(sitePath, "/modules/", "/")
                            : StringUtils.substringAfter(sitePath, "/modules/");
                    JahiaTemplatesPackage module = ServicesRegistry.getInstance()
                            .getJahiaTemplateManagerService().getTemplatePackageById(moduleName);
                    if (module == null) {
                        return userNodes;
                    }/*from   w  w w .  ja  va 2  s .  com*/
                    path = StringUtils.replace(path, "$site", sitePath + "/" + module.getVersion().toString());
                } else {
                    path = StringUtils.replace(path, "$site", sitePath);
                }
            }
            if (path.contains("$siteKey/")) {
                path = path.replace("$siteKey", site.getSiteKey());
            }
        }
        if (path.contains("$moduleversion")) {
            String moduleName = StringUtils.split(path, '/')[1];
            if (ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                    .getTemplatePackageById(moduleName) != null) {
                path = path.replace("$moduleversion",
                        ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                                .getTemplatePackageById(moduleName).getVersion().toString());
            } else {
                logger.warn("read version - Unable to get bundle " + moduleName + " from registry");
                continue;
            }
        }
        if (path.contains("$systemsite")) {
            String systemSiteKey = JCRContentUtils.getSystemSitePath();
            path = path.replace("$systemsite", systemSiteKey);
        }
        if (site != null && path.contains("$sites")) {
            JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Object>() {
                public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                    final JCRNodeWrapper parent = site.getParent();
                    NodeIterator nodes = parent.getNodes();
                    while (nodes.hasNext()) {
                        JCRNodeWrapper nodeWrapper = (JCRNodeWrapper) nodes.next();
                        if (!checkLicense || isAllowedByLicense(nodeWrapper)) {
                            userNodes.add(getGWTJahiaNode(nodeWrapper, fields));
                        }
                    }
                    return null;
                }
            });
        }
        if (path.contains("$user")) {
            final JCRNodeWrapper userFolder = JCRContentUtils.getInstance()
                    .getDefaultUserFolder(currentUserSession, StringUtils.substringAfter(path, "$user"));

            path = userFolder.getPath();
            displayName = Messages.getInternal("label.personalFolder", uiLocale, "label.personalFolder");
        }
        if (path.startsWith("/")) {
            try {
                if (path.endsWith("/*")) {
                    getMatchingChildNodes(nodeTypes, mimeTypes, filters, fields,
                            currentUserSession.getNode(StringUtils.substringBeforeLast(path, "/*")), userNodes,
                            checkSubChild, displayHiddenTypes, hiddenTypes, hiddenRegex, false, uiLocale);
                } else {
                    GWTJahiaNode root = getNode(path, fields, currentUserSession, uiLocale);
                    if (root != null) {
                        if (displayName != null) {
                            root.setDisplayName(JCRContentUtils.unescapeLocalNodeName(displayName));
                        }
                        userNodes.add(root);
                    }
                }
            } catch (PathNotFoundException e) {
                // do nothing is the path is not found
            }
        }
    }
    return userNodes;
}

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

private GWTJahiaPublicationInfo convert(Map<String, GWTJahiaPublicationInfo> all, PublicationInfoNode root,
        List<String> mainPaths, WorkflowRule lastRule, PublicationInfoNode node,
        List<PublicationInfo> references, JCRSessionWrapper currentUserSession, String language,
        String workflowAction) {/*from  w  ww  .j ava 2s  . c o  m*/
    GWTJahiaPublicationInfo gwtInfo = new GWTJahiaPublicationInfo(node.getUuid(), node.getStatus());
    try {
        JCRNodeWrapper jcrNode;
        if (node.getStatus() == PublicationInfo.DELETED) {
            JCRSessionWrapper liveSession = JCRTemplate.getInstance().getSessionFactory().getCurrentUserSession(
                    "live", currentUserSession.getLocale(), currentUserSession.getFallbackLocale());
            jcrNode = liveSession.getNodeByUUID(node.getUuid());
        } else {
            jcrNode = currentUserSession.getNodeByUUID(node.getUuid());
            if (lastRule == null || jcrNode.hasNode(WorkflowService.WORKFLOWRULES_NODE_NAME)) {
                WorkflowRule rule = workflowService.getWorkflowRuleForAction(jcrNode, false, workflowAction);
                if (rule != null) {
                    if (!rule.equals(lastRule)) {
                        if (workflowService.getWorkflowRuleForAction(jcrNode, true, workflowAction) != null) {
                            lastRule = rule;
                        } else {
                            lastRule = null;
                        }
                    }
                }
            }
        }
        if (jcrNode.hasProperty("jcr:title")) {
            gwtInfo.setTitle(jcrNode.getProperty("jcr:title").getString());
        } else {
            gwtInfo.setTitle(jcrNode.getName());
        }
        gwtInfo.setPath(jcrNode.getPath());
        gwtInfo.setNodetype(jcrNode.getPrimaryNodeType().getLabel(currentUserSession.getLocale()));
        gwtInfo.setIsAllowedToPublishWithoutWorkflow(jcrNode.hasPermission("publish"));
        gwtInfo.setIsNonRootMarkedForDeletion(jcrNode.isNodeType("jmix:markedForDeletion")
                && !jcrNode.isNodeType("jmix:markedForDeletionRoot"));
    } catch (RepositoryException e1) {
        logger.warn("Issue when reading workflow and delete status of node " + node.getPath(), e1);
        gwtInfo.setTitle(node.getPath());
    }

    gwtInfo.setWorkInProgress(node.isWorkInProgress());
    String mainPath = root.getPath();
    gwtInfo.setMainPath(mainPath);
    gwtInfo.setMainUUID(root.getUuid());
    gwtInfo.setLanguage(language);
    if (!mainPaths.contains(mainPath)) {
        mainPaths.add(mainPath);
    }
    gwtInfo.setMainPathIndex(mainPaths.indexOf(mainPath));
    Map<String, GWTJahiaPublicationInfo> gwtInfos = new HashMap<String, GWTJahiaPublicationInfo>();
    gwtInfos.put(node.getPath(), gwtInfo);
    List<String> refUuids = new ArrayList<String>();
    //        if (node.isLocked()  ) {
    //            gwtInfo.setLocked(true);
    //        }

    all.put(node.getUuid(), gwtInfo);

    if (lastRule != null) {
        gwtInfo.setWorkflowGroup(language + lastRule.getDefinitionPath());
        gwtInfo.setWorkflowDefinition(lastRule.getProviderKey() + ":" + lastRule.getWorkflowDefinitionKey());
    } else {
        gwtInfo.setWorkflowGroup(language + " no-workflow");
    }

    String translationNodeName = node.getChildren().size() > 0 ? "/j:translation_" + language : null;
    for (PublicationInfoNode sub : node.getChildren()) {
        if (sub.getPath().contains(translationNodeName)) {
            String key = StringUtils.substringBeforeLast(sub.getPath(), "/j:translation");
            GWTJahiaPublicationInfo lastPub = gwtInfos.get(key);
            if (lastPub != null) {
                if (sub.getStatus() > lastPub.getStatus()) {
                    lastPub.setStatus(sub.getStatus());
                }
                if (lastPub.getStatus() == GWTJahiaPublicationInfo.UNPUBLISHED
                        && sub.getStatus() != GWTJahiaPublicationInfo.UNPUBLISHED) {
                    lastPub.setStatus(sub.getStatus());
                }
                if (sub.isLocked()) {
                    gwtInfo.setLocked(true);
                }
                if (sub.isWorkInProgress()) {
                    gwtInfo.setWorkInProgress(true);
                }
                lastPub.setI18NUuid(sub.getUuid());
            }
            //                references.addAll(sub.getReferences());
            for (PublicationInfo pi : sub.getReferences()) {
                if (!refUuids.contains(pi.getRoot().getUuid()) && !all.containsKey(pi.getRoot().getUuid())) {
                    refUuids.add(pi.getRoot().getUuid());
                    all.putAll(convert(pi, pi.getRoot(), mainPaths, currentUserSession, language, all,
                            workflowAction));
                }
            }

        } else if (sub.getPath().contains("/j:translation")
                && (node.getStatus() == GWTJahiaPublicationInfo.MARKED_FOR_DELETION
                        || node.getStatus() == GWTJahiaPublicationInfo.DELETED)) {
            String key = StringUtils.substringBeforeLast(sub.getPath(), "/j:translation");
            GWTJahiaPublicationInfo lastPub = gwtInfos.get(key);
            if (lastPub.getDeletedI18nUuid() != null) {
                lastPub.setDeletedI18nUuid(lastPub.getDeletedI18nUuid() + " " + sub.getUuid());
            } else {
                lastPub.setDeletedI18nUuid(sub.getUuid());
            }
        }
    }
    references.addAll(node.getReferences());

    for (PublicationInfo pi : node.getReferences()) {
        if (!refUuids.contains(pi.getRoot().getUuid())) {
            refUuids.add(pi.getRoot().getUuid());
            if (!mainPaths.contains(pi.getRoot().getPath()) && !all.containsKey(pi.getRoot().getUuid())) {
                all.putAll(convert(pi, pi.getRoot(), mainPaths, currentUserSession, language, all,
                        workflowAction));
            }
        }
    }

    // Move node after references
    all.remove(node.getUuid());
    all.put(node.getUuid(), gwtInfo);

    for (PublicationInfoNode sub : node.getChildren()) {
        if (sub.getPath().indexOf("/j:translation") == -1) {
            convert(all, root, mainPaths, lastRule, sub, references, currentUserSession, language,
                    workflowAction);
        }
    }

    return gwtInfo;
}

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

/**
 * Returns the localized display label template.
 * //  w w w .j a v  a  2  s  .  c o m
 * @param fileType
 *            the type of the file
 * @param snippetType
 *            the snippet type
 * @param fileName
 *            a file name
 * @param locale
 *            locale to be used for the label
 * @return the localized display label template
 */
private String getLabelTemplate(String fileType, String snippetType, String fileName, Locale locale) {
    String fileNameWithoutExtension = StringUtils.substringBeforeLast(fileName, ".");
    return Messages.getInternal(
            "label.codesnippets." + fileType + "." + snippetType + "." + fileNameWithoutExtension, locale,
            fileNameWithoutExtension);
}

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

private String getResourceViewNodeType(String resourceName) {
    int dotPosition = resourceName.indexOf('.');
    if (dotPosition == -1 || dotPosition >= resourceName.length() - 1
            || resourceName.indexOf('.', dotPosition + 1) == -1) {
        return null;
    }/*w  w w  . ja  v  a  2s. com*/
    String viewKey = StringUtils.substringAfter(StringUtils.substringBeforeLast(resourceName, "."), ".");
    return nodeTypeView.get(viewKey);
}

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

public String getName() {
    return name != null ? name
            : StringUtils.uncapitalize(StringUtils.substringBeforeLast(getClass().getSimpleName(), "Action"));
}

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

private ModelAndView handleGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String workspace = null;//  w  w  w .ja  va 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.Render.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp, RenderContext renderContext,
        URLResolver urlResolver) throws Exception {
    if (req.getParameter(JahiaPortalURLParserImpl.PORTLET_INFO) != null) {
        Resource resource = urlResolver.getResource();
        renderContext.setMainResource(resource);
        JCRSiteNode site = resource.getNode().getResolveSite();
        renderContext.setSite(site);//from   w  ww . j  av  a2 s  .c  o  m
        doGet(req, resp, renderContext, resource, System.currentTimeMillis());
        return;
    }
    Map<String, List<String>> parameters = new HashMap<String, List<String>>();
    if (checkForUploadedFiles(req, resp, urlResolver.getWorkspace(), urlResolver.getLocale(), parameters,
            urlResolver)) {
        if (parameters.isEmpty()) {
            return;
        }
    }
    if (parameters.isEmpty()) {
        parameters = toParameterMapOfListOfString(req);
    }

    Action action;
    Resource resource = null;
    if (urlResolver.getPath().endsWith(".do") || isWebflowRequest(req)) {
        resource = urlResolver.getResource();
        renderContext.setMainResource(resource);
        try {
            JCRSiteNode site = resource.getNode().getResolveSite();
            renderContext.setSite(site);
        } catch (RepositoryException e) {
            logger.warn("Cannot get site for action context", e);
        }

        if (isWebflowRequest(req)) {
            action = webflowAction;
        } else {
            action = templateService.getActions().get(resource.getResolvedTemplate());
        }
    } else {
        final String path = urlResolver.getPath();

        String resourcePath = JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(null,
                urlResolver.getWorkspace(), urlResolver.getLocale(), new JCRCallback<String>() {
                    public String doInJCR(JCRSessionWrapper session) throws RepositoryException {
                        String resourcePath = path.endsWith("*") ? StringUtils.substringBeforeLast(path, "/")
                                : path;
                        do {
                            try {
                                session.getNode(resourcePath);
                                break;
                            } catch (PathNotFoundException e) {
                                resourcePath = StringUtils.substringBeforeLast(resourcePath, "/");
                            }
                        } while (resourcePath.contains("/"));
                        return resourcePath;
                    }
                });

        resource = urlResolver.getResource(resourcePath + ".html");
        renderContext.setMainResource(resource);
        try {
            JCRSiteNode site = resource.getNode().getResolveSite();
            renderContext.setSite(site);
        } catch (RepositoryException e) {
        }
        action = defaultPostAction;
    }
    if (action == null) {
        if (urlResolver.getPath().endsWith(".do")) {
            logger.error("Couldn't resolve action named [" + resource.getResolvedTemplate() + "]");
        }
        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
    } else {
        doAction(req, resp, urlResolver, renderContext, resource, action, parameters);
    }
}

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

private boolean checkForUploadedFiles(HttpServletRequest req, HttpServletResponse resp, String workspace,
        Locale locale, Map<String, List<String>> parameters, URLResolver urlResolver)
        throws RepositoryException, IOException {

    if (isMultipartRequest(req)) {
        // multipart is processed only if it's not a portlet request.
        // otherwise it's the task the portlet
        if (!isPortletRequest(req)) {
            final String savePath = getSettingsBean().getTmpContentDiskPath();
            final File tmp = new File(savePath);
            if (!tmp.exists()) {
                tmp.mkdirs();//from  ww  w .  j  a  v  a  2  s  .co m
            }
            try {
                final FileUpload fileUpload = new FileUpload(req, savePath, Integer.MAX_VALUE);
                req.setAttribute(FileUpload.FILEUPLOAD_ATTRIBUTE, fileUpload);
                if (fileUpload.getFileItems() != null && fileUpload.getFileItems().size() > 0) {
                    boolean isTargetDirectoryDefined = fileUpload.getParameterNames().contains(TARGETDIRECTORY);
                    boolean isAction = urlResolver.getPath().endsWith(".do");
                    boolean isContributePost = fileUpload.getParameterNames().contains(CONTRIBUTE_POST);
                    final String requestWith = req.getHeader("x-requested-with");
                    boolean isAjaxRequest = req.getHeader("accept") != null
                            && req.getHeader("accept").contains("application/json") && requestWith != null
                            && requestWith.equals("XMLHttpRequest") || fileUpload.getParameterMap().isEmpty();
                    List<String> uuids = new LinkedList<String>();
                    List<String> files = new ArrayList<String>();
                    List<String> urls = new LinkedList<String>();
                    // If target directory is defined or if it is an ajax request then save the file now
                    // otherwise we delay the save of the file to the node creation
                    if (!isAction && (isContributePost || isTargetDirectoryDefined || isAjaxRequest)) {
                        JCRSessionWrapper session = jcrSessionFactory.getCurrentUserSession(workspace, locale);
                        String target;
                        if (isTargetDirectoryDefined) {
                            target = (fileUpload.getParameterValues(TARGETDIRECTORY))[0];
                        } else if (isContributePost) {
                            String path = urlResolver.getPath();
                            path = (path.endsWith("*") ? StringUtils.substringBeforeLast(path, "/") : path);
                            JCRNodeWrapper sessionNode = session.getNode(path);
                            JCRSiteNode siteNode = sessionNode.getResolveSite();
                            if (siteNode != null) {
                                String s = sessionNode.getResolveSite().getPath() + "/files/contributed/";
                                String name = JCRContentUtils.replaceColon(sessionNode.getPrimaryNodeTypeName())
                                        + "_" + sessionNode.getName();
                                target = s + name;
                                try {
                                    session.getNode(target);
                                } catch (RepositoryException e) {
                                    JCRNodeWrapper node = session.getNode(s);
                                    session.checkout(node);
                                    node.addNode(name, "jnt:folder");
                                    session.save();
                                }
                            } else {
                                target = sessionNode.getPath() + "/files";
                                if (!sessionNode.hasNode("files")) {
                                    session.checkout(sessionNode);
                                    sessionNode.addNode("files", "jnt:folder");
                                    session.save();
                                }
                            }
                        } else {
                            String path = urlResolver.getPath();
                            target = (path.endsWith("*") ? StringUtils.substringBeforeLast(path, "/") : path);
                        }
                        final JCRNodeWrapper targetDirectory = session.getNode(target);

                        boolean isVersionActivated = fileUpload.getParameterNames().contains(VERSION)
                                ? (fileUpload.getParameterValues(VERSION))[0].equals("true")
                                : false;

                        final Map<String, DiskFileItem> stringDiskFileItemMap = fileUpload.getFileItems();
                        for (Map.Entry<String, DiskFileItem> itemEntry : stringDiskFileItemMap.entrySet()) {
                            //if node exists, do a checkout before
                            String name = itemEntry.getValue().getName();

                            if (fileUpload.getParameterNames().contains(TARGETNAME)) {
                                name = (fileUpload.getParameterValues(TARGETNAME))[0];
                            }

                            name = JCRContentUtils.escapeLocalNodeName(FilenameUtils.getName(name));

                            JCRNodeWrapper fileNode = targetDirectory.hasNode(name)
                                    ? targetDirectory.getNode(name)
                                    : null;
                            if (fileNode != null && isVersionActivated) {
                                session.checkout(fileNode);
                            }
                            // checkout parent directory
                            session.checkout(targetDirectory);
                            InputStream is = null;
                            JCRNodeWrapper wrapper = null;
                            try {
                                is = itemEntry.getValue().getInputStream();
                                wrapper = targetDirectory.uploadFile(name, is, JCRContentUtils.getMimeType(name,
                                        itemEntry.getValue().getContentType()));
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                            uuids.add(wrapper.getIdentifier());
                            urls.add(wrapper.getAbsoluteUrl(req));
                            files.add(itemEntry.getValue().getName());
                            if (isVersionActivated) {
                                if (!wrapper.isVersioned()) {
                                    wrapper.versionFile();
                                }
                                session.save();
                                // Handle potential move of the node after save
                                wrapper = session.getNodeByIdentifier(wrapper.getIdentifier());
                                wrapper.checkpoint();
                            }
                        }
                        fileUpload.disposeItems();
                        fileUpload.markFilesAsConsumed();
                        session.save();
                    }

                    if (isAction || (!isAjaxRequest && !isContributePost)) {
                        parameters.putAll(fileUpload.getParameterMap());
                        if (isTargetDirectoryDefined) {
                            parameters.put(NODE_NAME, files);
                        }
                        return true;
                    } else {
                        try {
                            resp.setStatus(HttpServletResponse.SC_CREATED);
                            Map<String, Object> map = new LinkedHashMap<String, Object>();
                            map.put("uuids", uuids);
                            map.put("urls", urls);
                            JSONObject nodeJSON = new JSONObject(map);
                            nodeJSON.write(resp.getWriter());
                            return true;
                        } catch (JSONException e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                if (fileUpload.getParameterMap() != null && !fileUpload.getParameterMap().isEmpty()) {
                    parameters.putAll(fileUpload.getParameterMap());
                }
            } catch (IOException e) {
                logger.error("Cannot parse multipart data !", e);
            }
        } else {
            logger.debug("Mulipart request is not processed. It's the task of the portlet");
        }
    }

    return false;
}

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

/**
 * This method allows you to define where you want to redirect the user after request.
 *
 * @param url/*from   www  .  j a v  a2s.  c  om*/
 * @param path
 * @param req
 * @param resp
 * @param parameters
 * @param bypassCache If true we will append a parameter to the URL that should match the id of the resource to refresh
 * @throws IOException
 */
public static void performRedirect(String url, String path, HttpServletRequest req, HttpServletResponse resp,
        Map<String, List<String>> parameters, boolean bypassCache) throws IOException {
    String renderedURL = null;

    List<String> stringList = parameters.get(NEW_NODE_OUTPUT_FORMAT);
    String outputFormat = !CollectionUtils.isEmpty(stringList) && stringList.get(0) != null ? stringList.get(0)
            : "html";

    stringList = parameters.get(REDIRECT_HTTP_RESPONSE_CODE);
    int responseCode = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? Integer.parseInt(stringList.get(0))
            : HttpServletResponse.SC_SEE_OTHER;

    stringList = parameters.get(REDIRECT_TO);
    String stayOnPage = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? StringUtils.substringBeforeLast(stringList.get(0), ";")
            : null;

    if (!Login.isAuthorizedRedirect(req, stayOnPage, true)) {
        logger.warn("Unauthorized attempt redirect to {}", stayOnPage);
        stayOnPage = null;
    }

    if (!StringUtils.isEmpty(stayOnPage)) {
        renderedURL = stayOnPage + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    } else if (!StringUtils.isEmpty(url)) {
        String requestedURL = req.getRequestURI();
        //            String encodedPath = URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
        String decodedURL = URLDecoder.decode(requestedURL, "UTF-8");

        int index = decodedURL.indexOf(path);

        renderedURL = decodedURL.substring(0, index) + url
                + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    }
    if (bypassCache) {
        stringList = parameters.get(RESOURCE_ID);
        String formuuid = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
                ? stringList.get(0)
                : null;
        if (formuuid != null) {
            renderedURL = renderedURL + "?ec=" + formuuid;
        }
    }
    if (!StringUtils.isEmpty(renderedURL)) {
        String redirect = resp.encodeRedirectURL(renderedURL);
        if (SettingsBean.getInstance().isDisableJsessionIdParameter()) {
            String s = ";" + SettingsBean.getInstance().getJsessionIdParameterName();
            if (redirect.contains(s)) {
                redirect = SessionidRemovalResponseWrapper.removeJsessionId(redirect);
            }
        }
        if (StringUtils.isEmpty(stayOnPage)) {
            resp.setHeader("Location", redirect);
        } else if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
            resp.setHeader("Location", redirect);
        }
        if (responseCode == HttpServletResponse.SC_FOUND) {
            resp.sendRedirect(redirect);
        } else {
            resp.setStatus(responseCode);
        }
    }
}