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

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

Introduction

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

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

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

private synchronized void registerNamespace(ExternalData data) throws RepositoryException {
    String prefix = data.getProperties().get("j:prefix")[0];
    String uri = data.getProperties().get("j:uri")[0];

    String cndPath = getCndPath(data.getPath(), data.getPath().toLowerCase());
    NodeTypeRegistry ntRegistry = loadRegistry(cndPath);

    NamespaceRegistry nsRegistry = JCRSessionFactory.getInstance().getNamespaceRegistry();
    boolean exists = false;
    try {//from  w  w  w . j  a v a 2  s  . com
        nsRegistry.getURI(prefix);
        exists = true;
    } catch (NamespaceException e) {
        // the prefix is not registered yet
        try {
            nsRegistry.getPrefix(uri);
            exists = true;
        } catch (NamespaceException e2) {
            // the uri is not registered yet
        }
    }
    if (exists || ntRegistry.getNamespaces().containsKey(prefix)
            || ntRegistry.getNamespaces().containsValue(uri)) {
        throw new NamespaceException();
    }

    ntRegistry.getNamespaces().put(prefix, uri);
    namespaceDefinitions.get(ntRegistry).put(prefix, uri);

    nodeTypeRegistryMap.get(StringUtils.substringBeforeLast(data.getPath(), "/")).getNamespaces().put(prefix,
            uri);
    writeDefinitionFile(ntRegistry, cndPath);
}

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

public void updateImportFileNodes(final List<File> files, final String importFilesRootFolder,
        final String filesNodePath) {
    synchronized (syncObject) {
        try {/*w w  w  . ja v a 2s  . c om*/
            JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Object>() {
                @Override
                public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                    JCRNodeWrapper filesNode = session.getNode(filesNodePath);
                    for (File file : files) {
                        if (!file.exists()) {
                            String relPath = StringUtils.removeStart(file.getPath(), importFilesRootFolder);
                            if (relPath.endsWith(file.getName() + File.separator + file.getName())) {
                                relPath = StringUtils.substringBeforeLast(relPath, File.separator);
                            }
                            if (filesNode.hasNode(relPath)) {
                                JCRNodeWrapper node = filesNode.getNode(relPath);
                                boolean removeEmptyFolder = !node.hasNodes() && !node.equals(filesNode);
                                node.remove();
                                while (removeEmptyFolder) {
                                    JCRNodeWrapper parent = node.getParent();
                                    removeEmptyFolder = !node.hasNodes() && !node.equals(filesNode);
                                    node.remove();
                                    node = parent;
                                }
                            }
                        } else if (file.isFile()) {
                            JCRNodeWrapper node = filesNode;
                            String[] pathSegments = (File.separatorChar == '\\' ? Patterns.BACKSLASH
                                    : Patterns.SLASH).split(
                                            StringUtils.removeStart(file.getPath(), importFilesRootFolder));
                            int endIndex;
                            if (pathSegments.length >= 2 && pathSegments[pathSegments.length - 1]
                                    .equals(pathSegments[pathSegments.length - 2])) {
                                endIndex = pathSegments.length - 2;
                            } else {
                                endIndex = pathSegments.length - 1;
                            }

                            for (int i = 0; i < endIndex; i++) {
                                String pathSegment = pathSegments[i];
                                if (node.hasNode(pathSegment)) {
                                    node = node.getNode(pathSegment);
                                } else {
                                    node = node.addNode(pathSegment, Constants.JAHIANT_FOLDER);
                                }
                            }

                            InputStream is = null;
                            try {
                                is = new BufferedInputStream(new FileInputStream(file));
                                node.uploadFile(file.getName(), is,
                                        JCRContentUtils.getMimeType(file.getName()));
                            } catch (FileNotFoundException e) {
                                logger.error("Failed to upload import file", e);
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        }
                    }
                    session.save();
                    return null;
                }
            });
        } catch (RepositoryException e) {
            logger.error("Failed to update import files", e);
        }
    }
}

From source file:org.jahia.modules.external.vfs.VFSDataSource.java

@Override
public boolean itemExists(String path) {
    try {/*from   w w w.  j  a  v  a2 s.c om*/
        FileObject file = getFile(
                path.endsWith(JCR_CONTENT_SUFFIX) ? StringUtils.substringBeforeLast(path, JCR_CONTENT_SUFFIX)
                        : path);
        return file.exists();
    } catch (FileSystemException e) {
        logger.warn("Unable to check file existence for path " + path, e);
    }
    return false;
}

From source file:org.jahia.modules.external.vfs.VFSDataSource.java

public ExternalData getItemByPath(String path) throws PathNotFoundException {
    try {/*from w  w w .j a  va  2 s .co m*/
        if (path.endsWith(JCR_CONTENT_SUFFIX)) {
            FileObject fileObject = getFile(StringUtils.substringBeforeLast(path, JCR_CONTENT_SUFFIX));
            FileContent content = fileObject.getContent();
            if (!fileObject.exists()) {
                throw new PathNotFoundException(path);
            }
            return getFileContent(content);
        } else {
            FileObject fileObject = getFile(path);
            if (!fileObject.exists()) {
                throw new PathNotFoundException(path);
            }
            return getFile(fileObject);
        }

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

From source file:org.jahia.modules.jahiaoauth.impl.JahiaOAuthServiceImpl.java

@Override
public String getResultUrl(String siteUrl, Boolean isAuthenticate) {
    return StringUtils.substringBeforeLast(siteUrl, ".html") + "/oauth-result.html?isAuthenticate="
            + isAuthenticate;/* w ww. jav a  2s  .  c  om*/
}

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

public JCRNodeWrapper getColumn(String path, JCRSessionWrapper sessionWrapper) {
    JCRNodeWrapper columnNode;/*from   ww  w  . j a  v a 2  s  .  c om*/
    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 RoleBean createRoleBean(JCRNodeWrapper role, boolean getPermissions, boolean getSubRoles)
        throws RepositoryException {
    RoleBean roleBean = new RoleBean();
    JCRNodeWrapper parentRole = JCRContentUtils.getParentOfType(role, "jnt:role");
    final String uuid = role.getIdentifier();
    roleBean.setUuid(uuid);//from  w w  w.ja v a2s.c  o m
    roleBean.setParentUuid(parentRole != null ? parentRole.getIdentifier() : null);
    roleBean.setName(role.getName());
    roleBean.setPath(role.getPath());
    roleBean.setDepth(role.getDepth());

    JCRNodeWrapper n;
    Map<String, I18nRoleProperties> i18nRoleProperties = new TreeMap<String, I18nRoleProperties>();
    for (Locale l : role.getExistingLocales()) {
        n = getSession(l).getNodeByIdentifier(uuid);
        if (!n.hasProperty(Constants.JCR_TITLE) && !n.hasProperty(Constants.JCR_DESCRIPTION)) {
            i18nRoleProperties.put(l.getLanguage(), null);
            continue;
        }
        I18nRoleProperties properties = new I18nRoleProperties();
        properties.setLanguage(l.getDisplayName(LocaleContextHolder.getLocale()));
        if (n.hasProperty(Constants.JCR_TITLE)) {
            properties.setTitle(n.getProperty(Constants.JCR_TITLE).getString());
        }
        if (n.hasProperty(Constants.JCR_DESCRIPTION)) {
            properties.setDescription(n.getProperty(Constants.JCR_DESCRIPTION).getString());
        }
        i18nRoleProperties.put(l.getLanguage(), properties);
    }
    roleBean.setI18nProperties(i18nRoleProperties);

    if (role.hasProperty("j:hidden")) {
        roleBean.setHidden(role.getProperty("j:hidden").getBoolean());
    }

    String roleGroup = "edit-role";
    if (role.hasProperty("j:roleGroup")) {
        roleGroup = role.getProperty("j:roleGroup").getString();
    }

    RoleType roleType = roleTypes.get(roleGroup);
    roleBean.setRoleType(roleType);
    if (getPermissions) {
        List<String> tabs = new ArrayList<String>(roleBean.getRoleType().getScopes());

        Map<String, List<String>> permIdsMap = new HashMap<String, List<String>>();
        fillPermIds(role, tabs, permIdsMap, false);

        Map<String, List<String>> inheritedPermIdsMap = new HashMap<String, List<String>>();
        fillPermIds(role.getParent(), tabs, inheritedPermIdsMap, true);

        Map<String, Map<String, Map<String, PermissionBean>>> permsForRole = new LinkedHashMap<String, Map<String, Map<String, PermissionBean>>>();
        roleBean.setPermissions(permsForRole);

        for (String tab : tabs) {
            addPermissionsForScope(roleBean, tab, permIdsMap, inheritedPermIdsMap);
        }

        if (roleType.getAvailableNodeTypes() != null) {
            List<String> nodeTypesOnRole = new ArrayList<String>();
            if (role.hasProperty("j:nodeTypes")) {
                for (Value value : role.getProperty("j:nodeTypes").getValues()) {
                    nodeTypesOnRole.add(value.getString());
                }
            }

            SortedSet<NodeType> nodeTypes = new TreeSet<NodeType>();
            for (String s : roleType.getAvailableNodeTypes()) {
                boolean includeSubtypes = false;
                if (s.endsWith("/*")) {
                    s = StringUtils.substringBeforeLast(s, "/*");
                    includeSubtypes = true;
                }
                ExtendedNodeType t = NodeTypeRegistry.getInstance().getNodeType(s);
                nodeTypes.add(new NodeType(t.getName(), t.getLabel(LocaleContextHolder.getLocale()),
                        nodeTypesOnRole.contains(t.getName())));
                if (includeSubtypes) {
                    for (ExtendedNodeType sub : t.getSubtypesAsList()) {
                        nodeTypes.add(new NodeType(sub.getName(), sub.getLabel(LocaleContextHolder.getLocale()),
                                nodeTypesOnRole.contains(sub.getName())));
                    }
                }
            }
            roleBean.setNodeTypes(nodeTypes);
        }
    }

    // sub-roles
    if (getSubRoles) {
        final List<JCRNodeWrapper> subRoles = JCRContentUtils.getNodes(role, "jnt:role");
        final List<RoleBean> subRoleBeans = new ArrayList<RoleBean>(subRoles.size());
        for (JCRNodeWrapper subRole : subRoles) {
            subRoleBeans.add(createRoleBean(subRole, false, false));
        }
        roleBean.setSubRoles(subRoleBeans);
    }

    return roleBean;
}

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 a2s .  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.tools.taglibs.GroovyConsoleHelper.java

/**
 * Returns a generated HTML with form elements for the script parameters.
 * /*from   w ww  . j av a 2 s  . c  om*/
 * @param scriptURI
 * @param request
 * @return
 */
public static String getScriptCustomFormElements(String scriptURI, HttpServletRequest request) {
    if (StringUtils.isBlank(scriptURI)) {
        return StringUtils.EMPTY;
    }
    final StringBuilder sb = new StringBuilder();
    try {
        final UrlResource resource = new UrlResource(
                StringUtils.substringBeforeLast(scriptURI, ".groovy") + ".properties");
        if (resource.exists()) {
            final Properties confs = new Properties();
            confs.load(resource.getInputStream());
            final String[] paramNames = StringUtils
                    .split(confs.getProperty("script.parameters.names", "").replaceAll("\\s", ""), ",");
            for (String paramName : paramNames) {
                generateFormElement(paramName.trim(), sb, confs, request);
            }

        }
    } catch (IOException e) {
        logger.error("An error occured while reading the configurations for the script " + scriptURI, e);
        return StringUtils.EMPTY;
    }
    final String formElements = sb.toString();
    if (StringUtils.isBlank(formElements)) {
        return StringUtils.EMPTY;
    }
    return sb.delete(0, sb.length()).append("<fieldset><legend>Script configuration</legend>")
            .append(formElements).append("</fieldset>").toString();
}

From source file:org.jahia.modules.tools.taglibs.GroovyConsoleHelper.java

/**
 * Returns an array of parameter names for the specified script or <code>null</code> if the script has no parameters.
 * //from  www .j av a  2  s . com
 * @param scriptURI the script URI to get parameter names for
 * @return an array of parameter names for the specified script or <code>null</code> if the script has no parameters
 */
public static String[] getScriptParamNames(String scriptURI) {
    try {
        final UrlResource resource = new UrlResource(
                StringUtils.substringBeforeLast(scriptURI, ".groovy") + ".properties");
        if (resource.exists()) {
            final Properties confs = new Properties();
            confs.load(resource.getInputStream());
            return StringUtils.split(confs.getProperty("script.parameters.names", "").replaceAll("\\s", ""),
                    ",");
        }
    } catch (IOException e) {
        logger.error("An error occured while reading the configurations for the script " + scriptURI, e);
    }
    return null;
}