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

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

Introduction

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

Prototype

public static String substringAfterLast(String str, String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:org.jahia.services.content.impl.external.ExternalSessionImpl.java

public Item getItem(String path) throws PathNotFoundException, RepositoryException {
    path = path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
    if (deletedData.containsKey(path)) {
        throw new PathNotFoundException("This node has been deleted");
    }//w  w  w  . jav  a  2s .c  o  m
    if (changedData.containsKey(path)) {
        return new ExternalNodeImpl(changedData.get(path), this);
    }
    if (StringUtils.substringAfterLast(path, "/").startsWith("j:translation_")) {
        String nodeName = StringUtils.substringAfterLast(path, "/");
        String lang = StringUtils.substringAfterLast(nodeName, "_");
        ExternalData parentObject = repository.getDataSource()
                .getItemByPath(StringUtils.substringBeforeLast(path, "/"));
        if (parentObject.getI18nProperties() == null || !parentObject.getI18nProperties().containsKey(lang)) {
            throw new PathNotFoundException(path);
        }
        Map<String, String[]> i18nProps = new HashMap<String, String[]>(
                parentObject.getI18nProperties().get(lang));
        i18nProps.put("jcr:language", new String[] { lang });
        ExternalData i18n = new ExternalData("translation:" + lang + ":" + parentObject.getId(), path,
                "jnt:translation", i18nProps);
        return new ExternalNodeImpl(i18n, this);
    }
    return new ExternalNodeImpl(repository.getDataSource().getItemByPath(path), this);
}

From source file:org.jahia.services.content.interceptor.URLInterceptor.java

/**
 * Transform user URL with servlet context and links placeholders for storage.
 * <p/>/*from  w ww  .  j  a v a  2s  .com*/
 * Only URLs starting with /<context>/cms or /<context>/files are recognized.
 * <p/>
 * CMS URLs can use mode and language placeholders : /<context>/cms/render/default/en/sites/ACME/home.html and
 * /<context>/cms/##mode##/##lang##/sites/ACME/home.html are both recognized.
 * <p/>
 * If any link is invalid, a ConstraintViolationException is thrown.
 * <p/>
 * Add jmix:referencesInField mixin type to the parent node and j:referenceInField with the list of references
 * contained in the value.
 *
 * @param node
 * @param name
 * @param definition
 * @param originalValue Original value  @return Value to set, or null   @return
 * @throws ValueFormatException
 * @throws VersionException
 * @throws LockException
 * @throws ConstraintViolationException
 * @throws RepositoryException
 */
public Value beforeSetValue(final JCRNodeWrapper node, String name, final ExtendedPropertyDefinition definition,
        Value originalValue) throws ValueFormatException, VersionException, LockException,
        ConstraintViolationException, RepositoryException {
    String content = originalValue.getString();

    // if the node is a translated node, then take the parent to have the references
    JCRNodeWrapper nodeWithReferences = node.isNodeType(Constants.JAHIANT_TRANSLATION) ? node.getParent()
            : node;

    if (definition.isInternationalized()) {
        Locale locale = node.getSession().getLocale();
        if (locale == null) {
            // This might happen under publication
            if (node.isNodeType(Constants.JAHIANT_TRANSLATION)) {
                name += "_" + node.getProperty("jcr:language").getString();
            }
        } else {
            name += "_" + locale;
        }
    }

    final Map<String, Long> refs = new HashMap<String, Long>();

    if (logger.isDebugEnabled()) {
        logger.debug("Intercept setValue for " + node.getPath() + "/" + name);
    }

    if (nodeWithReferences.isNodeType(JAHIAMIX_REFERENCES_IN_FIELD)) {
        NodeIterator ni = nodeWithReferences.getNodes(JAHIA_REFERENCE_IN_FIELD_PREFIX);
        while (ni.hasNext()) {
            JCRNodeWrapper ref = (JCRNodeWrapper) ni.next();
            if (name.equals(ref.getProperty("j:fieldName").getString()) && ref.hasProperty("j:reference")) {
                refs.put(ref.getProperty("j:reference").getString(),
                        Long.valueOf(StringUtils.substringAfterLast(ref.getName(), "_")));
            }
        }
    }

    final Map<String, Long> newRefs = new HashMap<String, Long>();

    String result;
    try {
        result = urlTraverser.traverse(content, new HtmlTagAttributeVisitor() {
            public String visit(String value, RenderContext context, String tagName, String attrName,
                    Resource resource) {
                if (StringUtils.isNotEmpty(value)) {
                    try {
                        value = replaceRefsByPlaceholders(value, newRefs, refs,
                                node.getSession().getWorkspace().getName(), node.getSession().getLocale(), node,
                                definition);
                    } catch (RepositoryException e) {
                        throw new RuntimeException(e);
                    }
                }
                return value;
            }
        });
    } catch (RuntimeException e) {
        if (e.getCause() instanceof RepositoryException) {
            throw (RepositoryException) e.getCause();
        } else {
            throw e;
        }
    }

    Set<String> refsToRemove = new HashSet<>(refs.size());
    if (!newRefs.equals(refs)) {
        if (!newRefs.isEmpty() && !nodeWithReferences.isNodeType(JAHIAMIX_REFERENCES_IN_FIELD)) {
            nodeWithReferences.addMixin(JAHIAMIX_REFERENCES_IN_FIELD);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("New references : " + newRefs);
        }

        NodeIterator ni = nodeWithReferences.getNodes(JAHIA_REFERENCE_IN_FIELD_PREFIX);
        while (ni.hasNext()) {
            JCRNodeWrapper ref = (JCRNodeWrapper) ni.next();
            if (name.equals(ref.getProperty("j:fieldName").getString()) && (!ref.hasProperty("j:reference")
                    || !newRefs.containsKey(ref.getProperty("j:reference").getString()))) {
                refsToRemove.add(ref.getName());
            }
        }

        for (Map.Entry<String, Long> entry : newRefs.entrySet()) {
            if (!refs.containsKey(entry.getKey())) {
                JCRNodeWrapper ref = nodeWithReferences.addNode(
                        "j:referenceInField_" + Text.escapeIllegalJcrChars(name) + "_" + entry.getValue(),
                        "jnt:referenceInField");
                ref.setProperty("j:fieldName", name);
                ref.setProperty("j:reference", entry.getKey());
            }
        }
    }

    for (String refToRemove : refsToRemove) {
        nodeWithReferences.getNode(refToRemove).remove();
    }

    if (!result.equals(content)) {
        return node.getSession().getValueFactory().createValue(result);
    }
    return originalValue;
}

From source file:org.jahia.services.content.interceptor.URLInterceptor.java

/**
 * Restore value by replace context ( ##doc-context## and ##cms-context## ) and references ( ##ref:link[0-9]+##
 * placeholders. Resolves reference node and put path instead to make a valid link. If referenced node is not found,
 * log an error and put # as a path./*from   w w w . j  ava2 s  . c  o m*/
 *
 * @param property
 * @param storedValue
 * @return
 * @throws ValueFormatException
 * @throws RepositoryException
 */
public Value afterGetValue(final JCRPropertyWrapper property, Value storedValue)
        throws ValueFormatException, RepositoryException {
    String content = storedValue.getString();
    if (content == null
            || !content.contains(DOC_CONTEXT_PLACEHOLDER) && !content.contains(CMS_CONTEXT_PLACEHOLDER)) {
        return storedValue;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Intercept getValue for " + property.getPath());
    }

    final Map<Long, String> refs = new HashMap<Long, String>();

    final ExtendedPropertyDefinition definition = (ExtendedPropertyDefinition) property.getDefinition();
    String name = definition.getName();
    JCRNodeWrapper parent = property.getParent();
    if (definition.isInternationalized()) {
        name += "_" + property.getLocale();
    }

    if (parent.isNodeType(Constants.JAHIANT_TRANSLATION)) {
        parent = parent.getParent();
    }
    if (parent.isNodeType(JAHIAMIX_REFERENCES_IN_FIELD)) {
        NodeIterator ni = parent.getNodes(JAHIA_REFERENCE_IN_FIELD_PREFIX);
        while (ni.hasNext()) {
            JCRNodeWrapper ref = (JCRNodeWrapper) ni.next();
            if (name.equals(ref.getProperty("j:fieldName").getString()) && ref.hasProperty("j:reference")) {
                try {
                    refs.put(Long.valueOf(StringUtils.substringAfterLast(ref.getName(), "_")),
                            ref.getProperty("j:reference").getString());
                } catch (PathNotFoundException e) {
                    logger.warn("Unable to get j:reference field on the node {}. Skipping reference.",
                            ref.getPath());
                }
            }
        }
    }

    String result;
    try {
        result = urlTraverser.traverse(content, new HtmlTagAttributeVisitor() {
            public String visit(String value, RenderContext context, String tagName, String attrName,
                    Resource resource) {
                if (StringUtils.isNotEmpty(value)) {
                    try {
                        value = replacePlaceholdersByRefs(value, refs,
                                property.getSession().getWorkspace().getName(),
                                property.getSession().getLocale(), property.getParent());
                        if ("#".equals(value) && attrName.toLowerCase().equals("src")
                                && tagName.toLowerCase().equals("img")) {
                            value = "/missing-image.png";
                        }
                    } catch (RepositoryException e) {
                        throw new RuntimeException(e);
                    }
                }
                return value;
            }
        });
    } catch (RuntimeException e) {
        if (e.getCause() instanceof RepositoryException) {
            throw (RepositoryException) e.getCause();
        } else {
            throw e;
        }
    }

    if (!result.equals(content)) {
        return property.getSession().getValueFactory().createValue(result);
    }
    return storedValue;
}

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

/**
 * Retrieves the default user folder found at the specified path, creating it (and all intermediate folders) if needed, saving the session if requested.
 * @param session the session with which to access the JCR data
 * @param path the path of the default user folder to retrieve, if path is empty or <code>null</code> the user's node is returned
 * @param saveIfCreate <code>true</code> if we want the session to be immediately saved, <code>false</code> if the client code will save the session to commit the changes
 * @return the JCR node associated with the requested default user folder
 * @throws RepositoryException/*from  www.  j  a va  2s .  c o m*/
 */
public JCRNodeWrapper getDefaultUserFolder(JCRSessionWrapper session, String path, boolean saveIfCreate)
        throws RepositoryException {
    // if path is null or empty, return the user's node
    if (StringUtils.isEmpty(path)) {
        return session.getUserNode();
    }

    // make it possible to use relative paths without '/' prefix
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    // first check that we know this default user folder
    final String primaryNodeTypeName = defaultUserFolderTypes.get(path);
    if (primaryNodeTypeName == null) {
        throw new IllegalArgumentException("Unknown default user folder: " + path
                + ". Known default user folders are: " + defaultUserFolderTypes);
    }

    final String userPath = session.getUserNode().getPath();
    if (!session.itemExists(userPath + path)) {
        final String name = StringUtils.substringAfterLast(path, "/");
        final JCRNodeWrapper parentUserFolder = getDefaultUserFolder(session,
                StringUtils.substringBeforeLast(path, "/"), false);
        final JCRNodeWrapper userFolder = parentUserFolder.addNode(name, primaryNodeTypeName);

        if (saveIfCreate) {
            session.save();
        }

        return userFolder;
    }

    return session.getNode(userPath + path);
}

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);
    }//from www.ja v  a 2 s. com
    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.JCRUserPropertyModificationListener.java

/**
 * This method is called when a bundle of events is dispatched.
 *
 * @param events The event set received.
 *///from ww w  .  j a va 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  w w .j a  va 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 {//ww w  . j  av a  2 s .c  o  m
        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.MountPointListener.java

@Override
public void onEvent(EventIterator events) {
    if (inListener.get()) {
        return;//  ww w .ja v a2  s  .  c  o m
    }
    try {
        inListener.set(true);
        boolean isExternal = false;
        Map<String, MountPointEventValue> changeLog = new LinkedHashMap<String, MountPointEventValue>(1);
        while (events.hasNext()) {
            try {
                final Event evt = events.nextEvent();
                final int evtType = evt.getType();
                if ((evtType & (Event.PROPERTY_CHANGED + Event.PROPERTY_ADDED + Event.PROPERTY_REMOVED)) != 0) {
                    // if property-level event -> check ignored properties
                    String propertyName = StringUtils.substringAfterLast(evt.getPath(), "/");
                    if (propertiesToIgnore.contains(propertyName)) {
                        continue;
                    }
                }
                setStatus(changeLog, evt.getIdentifier(), evtType, isExternal(evt));
                isExternal = isExternal(evt);
            } catch (RepositoryException e) {
                logger.error(e.getMessage(), e);
            }
        }
        if (!isExternal) {
            processEvents(changeLog);
        } else {
            // If event is external, trigger a parallel job to do mountpoint operations in background
            try {
                JobDetail jobDetail = BackgroundJob.createJahiaJob("Mount point job", MountPointJob.class);
                jobDetail.setDurability(false);
                JobDataMap jobDataMap = jobDetail.getJobDataMap();
                jobDataMap.put("changeLog", changeLog);

                schedulerService.scheduleJobNow(jobDetail, true);
            } catch (SchedulerException e) {
                logger.error(e.getMessage(), e);
            }
        }
    } finally {
        inListener.set(false);
    }
}