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.services.content.JCRObservationManager.java

private static boolean checkNodeTypeNames(JCRSessionWrapper session, EventWrapper event,
        String[] requiredNodeTypes) throws RepositoryException {
    if (event.getNodeTypes() == null) {
        String nodePath = (event.getType() == Event.PROPERTY_REMOVED
                || event.getType() == Event.PROPERTY_CHANGED || event.getType() == Event.PROPERTY_ADDED
                        ? StringUtils.substringBeforeLast(event.getPath(), "/")
                        : event.getPath());
        try {//w  w  w .j  a va 2 s  .  co  m
            JCRNodeWrapper node = session.getNode(nodePath);
            event.setNodeTypes(node.getNodeTypes());
        } catch (RepositoryException e) {
            logger.debug("Could not retrieve node (type)", e);
            event.setNodeTypes(Collections.<String>emptyList());
        }
    }
    if (event.getNodeTypes() != null) {
        for (String requiredNodeType : requiredNodeTypes) {
            for (String nodeType : event.getNodeTypes()) {
                if (NodeTypeRegistry.getInstance().getNodeType(nodeType).isNodeType(requiredNodeType)) {
                    return true;
                }
            }
        }
    }
    return false;
}

From source file:org.jahia.services.content.JCRSessionWrapper.java

public JCRItemWrapper getItem(String path, final boolean checkVersion)
        throws PathNotFoundException, RepositoryException {
    if (sessionCacheByPath.containsKey(path)) {
        return sessionCacheByPath.get(path);
    }//  w w w .ja  v a 2 s .co  m
    if (path.contains(DEREF_SEPARATOR)) {
        JCRNodeWrapper parent = (JCRNodeWrapper) getItem(StringUtils.substringBeforeLast(path, DEREF_SEPARATOR),
                checkVersion);
        return dereference(parent, StringUtils.substringAfterLast(path, DEREF_SEPARATOR));
    }
    for (Map.Entry<String, JCRStoreProvider> mp : sessionFactory.getMountPoints().entrySet()) {
        String key = mp.getKey();
        JCRStoreProvider provider = mp.getValue();
        if (provider.isDefault() || path.equals(key) || path.startsWith(key + "/")) {
            String localPath = path;
            if (!key.equals("/")) {
                localPath = localPath.substring(key.length());
            }
            if (localPath.equals("")) {
                localPath = "/";
            }
            //                Item item = getProviderSession(provider).getItem(localPath);
            Session session = getProviderSession(provider);
            boolean isAliased = sessionFactory.checkAliasedStatusAndToggleSessionIfNeeded(session, getUser());
            Item item = session.getItem(provider.getRelativeRoot() + localPath);
            if (item.isNode()) {
                final Node node = (Node) item;
                JCRNodeWrapper wrapper = null;
                if (checkVersion && (versionDate != null || versionLabel != null)
                        && node.isNodeType("mix:versionable")) {
                    JCRNodeWrapper frozen = getFrozenVersionAsRegular(node, provider, false);
                    if (frozen != null) {
                        wrapper = frozen;
                    }
                }
                if (wrapper == null) {
                    wrapper = provider.getNodeWrapper(node, localPath, null, this);
                }

                if (!isAliased) {
                    sessionCacheByPath.put(path, wrapper);
                    sessionCacheByIdentifier.put(wrapper.getIdentifier(), wrapper);
                }

                return wrapper;
            } else {
                // because of https://jira.jahia.org/browse/QA-6810, we retrieve the property from the parent
                // node to make sure that we go through any filtering that is implemented at a node decorator level,
                // as it is the case for the JCRUserNode. A more complete solution would involve implementing
                // the same decorator system around properties but this is much more complex and risky to do
                // than this (simple) method.
                JCRPropertyWrapper jcrPropertyWrapper = provider.getPropertyWrapper((Property) item, this);
                return jcrPropertyWrapper.getParent().getProperty(jcrPropertyWrapper.getName());
            }
        }
    }
    throw new PathNotFoundException(path);
}

From source file:org.jahia.services.content.JCRStoreService.java

public void reloadNodeTypeRegistry() throws RepositoryException {
    List<String> filesList = new ArrayList<>();
    List<String> remfiles;

    NodeTypeRegistry instance = NodeTypeRegistry.getInstance();

    logger.info("Loading all CNDs from DB ..");
    remfiles = new ArrayList<>(nodeTypesDBService.getFilesList());
    List<String> reloadedSystemIds = new ArrayList<>();
    while (!remfiles.isEmpty() && !remfiles.equals(filesList)) {
        filesList = new ArrayList<>(remfiles);
        remfiles.clear();/*from  w  ww  . j a v  a2  s . c  o  m*/
        for (final String file : filesList) {
            try {
                if (file.endsWith(".cnd")) {
                    final String cndFile = nodeTypesDBService.readFile(file);
                    final String systemId = StringUtils.substringBeforeLast(file, ".cnd");
                    if (!initializedSystemIds.contains(systemId)) {
                        logger.debug("Loading CND : {}", file);
                        instance.addDefinitionsFile(new ByteArrayResource(cndFile.getBytes("UTF-8"), file),
                                systemId);
                    }
                    reloadedSystemIds.add(systemId);
                }
            } catch (ParseException | NoSuchNodeTypeException e) {
                logger.debug(file + " cannot be parsed, reorder later");
                remfiles.add(file);
            } catch (IOException e) {
                logger.error("Cannot parse CND file from DB : " + file, e);
            }
        }
    }

    List<String> systemIds = NodeTypeRegistry.getInstance().getSystemIds();
    systemIds.removeAll(reloadedSystemIds);
    for (String systemId : systemIds) {
        NodeTypeRegistry.getInstance().unregisterNodeTypes(systemId);
    }
    if (!remfiles.isEmpty()) {
        logger.error("Cannot read CND from : " + remfiles);
    }

    registerNamespaces();
}

From source file:org.jahia.services.content.JCRUserPropertyModificationListener.java

/**
 * This method is called when a bundle of events is dispatched.
 *
 * @param events The event set received.
 *///from   ww  w  . j  a  v  a 2  s .c o m
public void onEvent(final EventIterator events) {
    String userId = ((JCREventIterator) events).getSession().getUserID();
    if (userId.startsWith(JahiaLoginModule.SYSTEM)) {
        userId = userId.substring(JahiaLoginModule.SYSTEM.length());
    }
    try {
        JCRTemplate.getInstance().doExecuteWithSystemSession(userId, workspace, new JCRCallback<Object>() {
            public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                while (events.hasNext()) {
                    Event event = events.nextEvent();

                    if (isExternal(event)) {
                        continue;
                    }

                    String path = event.getPath();
                    if (path.startsWith("/jcr:system/")) {
                        continue;
                    }
                    if ((event.getType()
                            & Event.PROPERTY_CHANGED + Event.PROPERTY_ADDED + Event.PROPERTY_REMOVED) != 0) {
                        if (propertiesToIgnore.contains(StringUtils.substringAfterLast(path, "/"))) {
                            continue;
                        }
                    }
                    String username = StringUtils.substringAfterLast(StringUtils.substringBeforeLast(path, "/"),
                            "/");
                    JahiaUser jahiaUser = ServicesRegistry.getInstance().getJahiaUserManagerService()
                            .lookupUser(username);
                    if (jahiaUser != null) {
                        ServicesRegistry.getInstance().getJahiaUserManagerService().updateCache(jahiaUser);
                    }
                }
                return null;
            }
        });
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.jahia.services.content.JCRWorkspaceWrapper.java

void move(String source, String dest, final boolean sessionMove)
        throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException,
        ItemExistsException, LockException, RepositoryException {
    final JCRStoreProvider provider = service.getProvider(source);
    JCRStoreProvider destProvider = service.getProvider(dest);
    if (destProvider != provider) {
        try {/*from w  ww.  jav a  2s  .c o  m*/
            session.getItem(dest);
            throw new ItemExistsException(dest);
        } catch (RepositoryException e) {
        }
        if (sessionMove) {
            getSession().getNode(source).copy(StringUtils.substringBeforeLast(dest, "/"),
                    StringUtils.substringAfterLast(dest, "/"));
            session.getItem(source).remove();
        } else {
            throw new UnsupportedRepositoryOperationException();
        }
    } else {
        if (provider.getMountPoint().length() > 1) {
            dest = dest.substring(provider.getMountPoint().length());
            source = source.substring(provider.getMountPoint().length());
        }
        final String sourcePath = source;
        Node sourceNode = session.getProviderSession(provider).getNode(source);
        if (sourceNode.isNodeType("jmix:shareable")) {
            final String destination = dest;
            final JCRCallback<Object> callback = new JCRCallback<Object>() {
                public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                    JCRNodeWrapper sourceNode = session.getNode(sourcePath);
                    JCRNodeWrapper parentNode = session
                            .getNode(StringUtils.substringBeforeLast(destination, "/"));
                    String sourceParentPath = StringUtils.substringBeforeLast(sourcePath, "/");
                    if (parentNode.getPath().equals(sourceParentPath)) {
                        // rename case
                        JCRNodeWrapper userFolder = session.getUserNode();
                        if (!userFolder.hasNode("tmp")) {
                            if (!userFolder.isCheckedOut()) {
                                session.checkout(userFolder);
                            }
                            userFolder.addNode("tmp", "jnt:contentList");
                        }
                        JCRNodeWrapper newSourceNode = userFolder.getNode("tmp").clone(sourceNode,
                                sourceNode.getIdentifier());
                        sourceNode.removeShare();
                        sourceNode = newSourceNode;
                    }
                    parentNode.clone(sourceNode, StringUtils.substringAfterLast(destination, "/"));
                    List<Value> values = new ArrayList<Value>();
                    String v = sourcePath + ":::" + destination;
                    if (sourceNode.hasProperty("j:movedFrom")) {
                        values.addAll(Arrays.asList(sourceNode.getProperty("j:movedFrom").getValues()));
                        for (Value value : values) {
                            String s = value.getString();
                            if (s.endsWith(":::" + sourcePath)) {
                                v = StringUtils.substringBefore(s, ":::") + ":::" + destination;
                                values.remove(value);
                                break;
                            }
                        }
                    }
                    values.add(getSession().getValueFactory().createValue(v));
                    sourceNode.setProperty("j:movedFrom", values.toArray(new Value[values.size()]));
                    sourceNode.removeShare();
                    if (parentNode.isNodeType("mix:lastModified")) {
                        parentNode.setProperty(Constants.JCR_LASTMODIFIED, new GregorianCalendar());
                        parentNode.setProperty(Constants.JCR_LASTMODIFIEDBY, session.getUser().getName());
                    }

                    if (!sessionMove) {
                        session.save();
                    }
                    return null;
                }
            };
            if (sessionMove) {
                callback.doInJCR(session);
            } else {
                JCRCallback<Object> jcrCallback = new JCRCallback<Object>() {
                    public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                        return JCRObservationManager.doWorkspaceWriteCall(session,
                                JCRObservationManager.WORKSPACE_MOVE, callback);
                    }
                };
                if (session.isSystem()) {
                    JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(session.getUser(), getName(),
                            session.getLocale(), jcrCallback);
                } else {
                    JCRTemplate.getInstance().doExecute(session.getUser(), getName(), session.getLocale(),
                            jcrCallback);
                }
            }
        } else {
            if (sessionMove) {
                session.getProviderSession(provider).move(source, dest);
            } else {
                final String fSource = source;
                final String fDest = dest;
                JCRObservationManager.doWorkspaceWriteCall(getSession(), JCRObservationManager.WORKSPACE_MOVE,
                        new JCRCallback<Object>() {
                            public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                                session.getProviderSession(provider).getWorkspace().move(fSource, fDest);
                                return null;
                            }
                        });
            }
        }
    }
}

From source file:org.jahia.services.content.LastModifiedListener.java

public void onEvent(final EventIterator eventIterator) {
    try {/*from   w  w w .  jav  a 2 s. c  om*/
        final JahiaUser user = ((JCREventIterator) eventIterator).getSession().getUser();
        final int type = ((JCREventIterator) eventIterator).getOperationType();

        if (type == JCRObservationManager.NODE_CHECKOUT || type == JCRObservationManager.NODE_CHECKIN) {
            return;
        }

        final Set<Session> sessions = new HashSet<Session>();
        final Set<String> nodes = new HashSet<String>();
        final Set<String> addedNodes = new HashSet<String>();
        final Set<String> reorderedNodes = new HashSet<String>();
        final List<String> autoPublishedIds;

        if (workspace.equals("default")) {
            autoPublishedIds = new ArrayList<String>();
        } else {
            autoPublishedIds = null;
        }

        JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(user, workspace, null,
                new JCRCallback<Object>() {
                    public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                        Calendar c = GregorianCalendar.getInstance();
                        while (eventIterator.hasNext()) {
                            final Event event = eventIterator.nextEvent();
                            if (event.getType() == Event.NODE_REMOVED && event.getIdentifier() != null) {
                                try {
                                    session.getNodeByIdentifier(event.getIdentifier());
                                } catch (ItemNotFoundException infe) {
                                    try {
                                        final JCRNodeWrapper parent = session
                                                .getNode(StringUtils.substringBeforeLast(event.getPath(), "/"));
                                        if (!session.getWorkspace().getName().equals(Constants.LIVE_WORKSPACE)
                                                && parent.getProvider().getMountPoint().equals("/")) {
                                            // Test if published and has lastPublished property
                                            boolean lastPublished = JCRTemplate.getInstance()
                                                    .doExecuteWithSystemSessionAsUser(user,
                                                            Constants.LIVE_WORKSPACE, null,
                                                            new JCRCallback<Boolean>() {
                                                                public Boolean doInJCR(
                                                                        JCRSessionWrapper session)
                                                                        throws RepositoryException {
                                                                    JCRNodeWrapper nodeByIdentifier = session
                                                                            .getNodeByIdentifier(
                                                                                    event.getIdentifier());
                                                                    boolean lastPublished = nodeByIdentifier
                                                                            .hasProperty(
                                                                                    Constants.LASTPUBLISHED);
                                                                    if (lastPublished && !parent
                                                                            .isNodeType("jmix:autoPublish")) {
                                                                        List<String> nodeTypes = (event instanceof JCRObservationManager.EventWrapper)
                                                                                ? ((JCRObservationManager.EventWrapper) event)
                                                                                        .getNodeTypes()
                                                                                : null;
                                                                        if (nodeTypes != null) {
                                                                            for (String nodeType : nodeTypes) {
                                                                                ExtendedNodeType eventNodeType = NodeTypeRegistry
                                                                                        .getInstance()
                                                                                        .getNodeType(nodeType);
                                                                                if (eventNodeType != null
                                                                                        && eventNodeType
                                                                                                .isNodeType(
                                                                                                        "jmix:autoPublish")) {
                                                                                    nodeByIdentifier.remove();
                                                                                    session.save();
                                                                                    return false;
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    return lastPublished;
                                                                }
                                                            });

                                            if (lastPublished) {
                                                if (!parent.isNodeType("jmix:deletedChildren")) {
                                                    parent.addMixin("jmix:deletedChildren");
                                                    parent.setProperty("j:deletedChildren",
                                                            new String[] { event.getIdentifier() });
                                                } else if (!parent.hasProperty("j:deletedChildren")) {
                                                    parent.setProperty("j:deletedChildren",
                                                            new String[] { event.getIdentifier() });
                                                } else {
                                                    parent.getProperty("j:deletedChildren")
                                                            .addValue(event.getIdentifier());
                                                }
                                                sessions.add(parent.getRealNode().getSession());
                                            }
                                        }
                                    } catch (PathNotFoundException e) {
                                        // no parent
                                    } catch (ItemNotFoundException e) {
                                        // no live
                                    }
                                }
                            }

                            if (isExternal(event)) {
                                continue;
                            }

                            String path = event.getPath();
                            if (path.startsWith("/jcr:system/")) {
                                continue;
                            }
                            if ((event.getType() & Event.PROPERTY_CHANGED + Event.PROPERTY_ADDED
                                    + Event.PROPERTY_REMOVED) != 0) {
                                if (propertiesToIgnore.contains(StringUtils.substringAfterLast(path, "/"))) {
                                    continue;
                                }
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Receiving event for lastModified date for : " + path);
                            }
                            if (event.getType() == Event.NODE_ADDED) {
                                addedNodes.add(path);
                                //                            if(!path.contains("j:translation")) {
                                //                                nodes.add(StringUtils.substringBeforeLast(path,"/"));
                                //                            }
                            } else if (Event.NODE_MOVED == event.getType()) {
                                // in the case of a real node move, we won't track this as we want to have last modification
                                // properties on moved nodes so we only handle the reordering case.
                                if (event.getInfo().get("srcChildRelPath") != null) {
                                    // this case is a node reordering in it's parent
                                    reorderedNodes.add(path);
                                }
                                nodes.add(StringUtils.substringBeforeLast(path, "/"));
                            } else {
                                nodes.add(StringUtils.substringBeforeLast(path, "/"));
                            }
                        }
                        if (reorderedNodes.size() > 0) {
                            addedNodes.removeAll(reorderedNodes);
                        }
                        if (addedNodes.size() > 0) {
                            nodes.removeAll(addedNodes);
                        }
                        if (!nodes.isEmpty() || !addedNodes.isEmpty()) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Updating lastModified date for existing nodes : "
                                        + Arrays.deepToString(nodes.toArray(new String[nodes.size()])));
                                logger.debug("Updating lastModified date for added nodes : " + Arrays
                                        .deepToString(addedNodes.toArray(new String[addedNodes.size()])));
                            }
                            for (String node : nodes) {
                                try {
                                    JCRNodeWrapper n = session.getNode(node);
                                    sessions.add(n.getRealNode().getSession());
                                    updateProperty(n, c, user, autoPublishedIds, type);
                                } catch (UnsupportedRepositoryOperationException e) {
                                    // Cannot write property
                                } catch (PathNotFoundException e) {
                                    // node has been removed
                                }
                            }
                            for (String addedNode : addedNodes) {
                                try {
                                    JCRNodeWrapper n = session.getNode(addedNode);
                                    sessions.add(n.getRealNode().getSession());
                                    if (!n.hasProperty("j:originWS") && n.isNodeType("jmix:originWS")) {
                                        n.setProperty("j:originWS", workspace);
                                    }
                                    updateProperty(n, c, user, autoPublishedIds, type);
                                } catch (UnsupportedRepositoryOperationException e) {
                                    // Cannot write property
                                } catch (PathNotFoundException e) {
                                    // node has been removed
                                }
                            }
                            for (Session jcrsession : sessions) {
                                try {
                                    jcrsession.save();
                                } catch (RepositoryException e) {
                                    logger.debug("Cannot update lastModification properties");
                                }
                            }
                        }
                        return null;
                    }
                });

        if (autoPublishedIds != null && !autoPublishedIds.isEmpty()) {
            synchronized (this) {
                publicationService.publish(autoPublishedIds, "default", "live", false, null);
            }
        }

    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:org.jahia.services.content.nodetypes.initializers.NodesChoiceListInitializerImpl.java

public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition epd, String param,
        List<ChoiceListValue> values, Locale locale, Map<String, Object> context) {
    final ArrayList<ChoiceListValue> listValues = new ArrayList<ChoiceListValue>();
    if (CollectionUtils.isNotEmpty(values))
        listValues.addAll(values);/*from  w ww .  j a va  2 s  .  c o m*/
    if (param != null) {
        for (String subParam : Patterns.PIPE.split(param)) {
            String[] s = Patterns.SEMICOLON.split(subParam);
            String nodetype = null;
            if (s.length > 1) {
                nodetype = s[1];
            }
            try {
                JCRSiteNode site;
                JCRNodeWrapper contextNode = (JCRNodeWrapper) context.get("contextParent");
                if (contextNode == null) {
                    contextNode = (JCRNodeWrapper) context.get("contextNode");
                }
                if (contextNode != null) {
                    site = contextNode.getResolveSite();
                } else {
                    final JahiaSite defaultSite = JahiaSitesService.getInstance().getDefaultSite();
                    if (defaultSite != null) {
                        site = (JCRSiteNode) sessionFactory.getCurrentUserSession()
                                .getNode("/sites/" + defaultSite.getSiteKey());
                    } else {
                        site = (JCRSiteNode) sessionFactory.getCurrentUserSession()
                                .getNode(JCRContentUtils.getSystemSitePath());
                    }
                    contextNode = site;
                }
                String path = s[0];
                String returnType = "";
                if (s.length > 2) {
                    returnType = s[2];
                }
                path = StringUtils.replace(path, "$currentSiteTemplatesSet",
                        "/modules/" + site.getTemplatePackage().getIdWithVersion());
                if (StringUtils.contains(path, "$currentSite/templates/")) {
                    path = StringUtils.replace(path, "$currentSite",
                            "/modules/" + site.getTemplatePackage().getIdWithVersion());
                } else {
                    path = StringUtils.replace(path, "$currentSite", site.getPath());
                }
                boolean subTree = false;
                if (path.endsWith("//*")) {
                    path = StringUtils.substringBeforeLast(path, "//*");
                    subTree = true;
                }
                JCRSessionWrapper jcrSessionWrapper = contextNode.getSession();
                JCRNodeWrapper node;
                if (path.equals(".")) {
                    node = contextNode;
                } else if (path.startsWith("./")) {
                    node = contextNode.getNode(path.substring(2));
                } else {
                    node = jcrSessionWrapper.getNode(path);
                }
                addSubnodes(listValues, nodetype, node, subTree, returnType);
            } catch (PathNotFoundException e) {
                logger.debug("Cannot find node " + e.getMessage(), e);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return listValues;
}

From source file:org.jahia.services.content.RBACUtils.java

/**
 * Creates the specified permission if it does not exist yet. Also creates all intermediate permission nodes if not present yet. The
 * {@link Session#save()} is not called by this method; it is the responsibility of the caller.
 * /*ww w  .ja v a 2  s  .c om*/
 * @param path
 *            the path of the permission to get/create
 * @param session
 *            current JCR session
 * @return the permission node
 * @throws RepositoryException
 *             in case of an error
 */
public static JCRNodeWrapper getOrCreatePermission(String path, JCRSessionWrapper session)
        throws RepositoryException {
    if (path == null || !path.startsWith("/permissions/")) {
        throw new IllegalArgumentException("Illegal value for the permission path: " + path);
    }
    String basePath = StringUtils.substringBeforeLast(path, "/");
    String name = StringUtils.substringAfterLast(path, "/");

    JCRNodeWrapper permission = null;

    JCRNodeWrapper base = null;
    try {
        base = session.getNode(basePath);
    } catch (PathNotFoundException e) {
        base = getOrCreatePermission(basePath, session);
    }
    if (!base.hasNode(name)) {
        session.checkout(base);
        permission = base.addNode(name, "jnt:permission");
        logger.info("Added permission node {}", permission.getPath());
    } else {
        permission = base.getNode(name);
    }

    return permission;
}

From source file:org.jahia.services.content.RBACUtils.java

/**
 * Creates the specified role if it does not exist yet. The {@link Session#save()} is not called by this method; it is the
 * responsibility of the caller.//from  w  ww  . j ava 2  s  .  c om
 * 
 * @param path
 *            the path of the role to get/create
 * @param session
 *            current JCR session
 * @return the role node
 * @throws RepositoryException
 *             in case of an error
 */
public static JCRNodeWrapper getOrCreateRole(String path, JCRSessionWrapper session)
        throws RepositoryException {
    if (path == null || !path.startsWith("/roles/")) {
        throw new IllegalArgumentException("Illegal value for the role path: " + path);
    }
    String name = StringUtils.substringAfterLast(path, "/");
    JCRNodeWrapper role = null;
    JCRNodeWrapper base = session.getNode(StringUtils.substringBeforeLast(path, "/"));
    if (!base.hasNode(name)) {
        session.checkout(base);
        role = base.addNode(name, "jnt:role");
        logger.info("Added role node {}", role.getPath());
    } else {
        role = base.getNode(name);
    }

    return role;
}

From source file:org.jahia.services.content.rules.FlushCacheOnNodeBackgroundAction.java

public void executeBackgroundAction(JCRNodeWrapper node) {
    String workspace = Constants.LIVE_WORKSPACE;
    boolean log = logger.isDebugEnabled();
    try {/*from   ww w  . j av a  2 s  .c  o  m*/
        JCRNodeWrapper currentNode = node;
        workspace = node.getSession().getWorkspace().getName();
        for (int level = 0; level <= (startLevel + levelsUp); level++) {
            if (level >= startLevel) {
                String path = currentNode.getPath();
                cacheProvider.invalidate(path);
                cacheProvider.invalidate(currentNode.getIdentifier());
                if (log) {
                    logger.debug("Flushed output caches for node {}", path);
                }
                if (currentNode.isFile()) {
                    fileCacheManager.invalidate(workspace, path);
                    if (log) {
                        logger.debug("Flushed file cache for node {}", path);
                    }
                }
                cacheProvider.flushRegexpDependenciesOfPath(path, true);
                if (log) {
                    logger.debug("Flushed regexp dependencies for node {}", path);
                }
            }
            currentNode = currentNode.getParent();
        }
    } catch (RepositoryException e) {
        //Flush by path directly as node might not be visible anymore
        String currentNodePath = node.getPath();
        for (int level = 0; level <= (startLevel + levelsUp); level++) {
            if (level >= startLevel) {
                cacheProvider.invalidate(currentNodePath);
                fileCacheManager.invalidate(workspace, currentNodePath);
                if (log) {
                    logger.debug("Flushed output and file caches for node {}", currentNodePath);
                }
                cacheProvider.flushRegexpDependenciesOfPath(currentNodePath, true);
                if (log) {
                    logger.debug("Flushed regexp dependencies for node {}", currentNodePath);
                }
            }
            currentNodePath = StringUtils.substringBeforeLast(currentNodePath, "/");
        }
    }
}