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

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

Introduction

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

Prototype

public static String substringBetween(String str, String open, String close) 

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

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

private void extractPropertyFromJSON(HashMap<String, Object> propertiesResult, JSONObject jsonObject,
        JSONArray jsonArray, String pathToProperty, String propertyName) throws JSONException {
    if (StringUtils.startsWith(pathToProperty, "/")) {

        String key = StringUtils.substringAfter(pathToProperty, "/");
        String potentialKey1 = StringUtils.substringBefore(key, "[");
        String potentialKey2 = StringUtils.substringBefore(key, "/");

        if (potentialKey1.length() <= potentialKey2.length()) {
            key = potentialKey1;/*w ww.j ava2  s.  c  o  m*/
        } else if (potentialKey1.length() > potentialKey2.length()) {
            key = potentialKey2;
        }

        pathToProperty = StringUtils.substringAfter(pathToProperty, "/" + key);

        if (StringUtils.isBlank(pathToProperty) && jsonObject.has(key)) {
            propertiesResult.put(propertyName, jsonObject.get(key));
        } else {
            if (StringUtils.startsWith(pathToProperty, "/") && jsonObject.has(key)) {
                extractPropertyFromJSON(propertiesResult, jsonObject.getJSONObject(key), null, pathToProperty,
                        propertyName);
            } else if (jsonObject.has(key)) {
                extractPropertyFromJSON(propertiesResult, null, jsonObject.getJSONArray(key), pathToProperty,
                        propertyName);
            }
        }
    } else {
        int arrayIndex = new Integer(StringUtils.substringBetween(pathToProperty, "[", "]"));
        pathToProperty = StringUtils.substringAfter(pathToProperty, "]");
        if (StringUtils.isBlank(pathToProperty) && jsonArray.length() >= arrayIndex) {
            propertiesResult.put(propertyName, jsonArray.get(arrayIndex));
        } else {
            if (StringUtils.startsWith(pathToProperty, "/") && jsonArray.length() >= arrayIndex) {
                extractPropertyFromJSON(propertiesResult, jsonArray.getJSONObject(arrayIndex), null,
                        pathToProperty, propertyName);
            } else if (jsonArray.length() >= arrayIndex) {
                extractPropertyFromJSON(propertiesResult, null, jsonArray.getJSONArray(arrayIndex),
                        pathToProperty, propertyName);
            }
        }
    }
}

From source file:org.jahia.services.content.decorator.JCRGroupNode.java

public boolean isMember(String userPath) {
    if (JahiaGroupManagerService.GUEST_GROUPPATH.equals(getPath())
            || (JahiaGroupManagerService.USERS_GROUPPATH.equals(getPath())
                    && !JahiaUserManagerService.GUEST_USERPATH.equals(userPath))
            || (JahiaGroupManagerService.SITE_USERS_GROUPNAME.equals(getName())
                    && (!userPath.startsWith("/sites/") || userPath.startsWith(
                            "/sites/" + StringUtils.substringBetween(getPath(), "/sites/", "/"))))) {
        return true;
    }/*from   w  w w.  j av a2 s . co m*/
    List<String> membershipByPath = JahiaGroupManagerService.getInstance().getMembershipByPath(userPath);
    return membershipByPath != null && membershipByPath.contains(getPath());
}

From source file:org.jahia.services.content.decorator.JCRUserNode.java

public String getRealm() {
    return getPath().startsWith("/sites/") ? StringUtils.substringBetween(getPath(), "/sites/", "/") : null;
}

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

public static String getJCRName(String qualifiedName, NamespaceRegistry namespaceRegistry)
        throws RepositoryException {
    if (qualifiedName.startsWith("{")) {
        final String uri = StringUtils.substringBetween(qualifiedName, "{", "}");
        if (uri.isEmpty()) {
            qualifiedName = StringUtils.substringAfter(qualifiedName, "}");
        } else {/*w w  w . j av  a2s. co m*/
            qualifiedName = namespaceRegistry.getPrefix(uri) + ":"
                    + StringUtils.substringAfter(qualifiedName, "}");
        }
    }

    return qualifiedName;
}

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

/**
 * If the node path contains site information (i.e.
 * <code>/sites/&lt;siteKey&gt;/...</code>) this method returns the site key
 * part; otherwise <code>null</code> is returned.
 *
 * @param jcrNodePath the JCR node path/*from w w  w.  j a  v  a 2s. co  m*/
 * @return if the node path contains site information (i.e.
 *         <code>/sites/&lt;siteKey&gt;/...</code>) this method returns the
 *         site key part; otherwise <code>null</code> is returned
 */
public static String getSiteKey(String jcrNodePath) {
    return jcrNodePath != null
            ? (jcrNodePath.startsWith("/sites/") ? StringUtils.substringBetween(jcrNodePath, "/sites/", "/")
                    : null)
            : null;
}

From source file:org.jahia.services.content.nodetypes.Name.java

public Name(String qualifiedName, Map<String, String> namespaceMapping) {
    if (qualifiedName.startsWith("{")) {
        int endUri = qualifiedName.indexOf("}");
        if (endUri != -1 && qualifiedName.length() > endUri) {
            uri = StringUtils.substringBetween(qualifiedName, "{", "}");
            prefix = getPrefix(uri, namespaceMapping);
            localName = qualifiedName.substring(endUri + 1);
        } else {//w  w w. j a v a  2 s .c  o m
            localName = qualifiedName;
            uri = namespaceMapping.get("");
        }
    }
    if (localName == null) {
        String s[] = StringUtils.split(qualifiedName, ":");
        if (s.length == 2) {
            prefix = s[0];
            localName = s[1];
            uri = namespaceMapping.get(prefix);
        } else {
            localName = s[0];
            uri = namespaceMapping.get("");
        }
    }
    prefix = StringUtils.defaultString(prefix);
}

From source file:org.jahia.services.importexport.ReferencesHelper.java

private static void updateProperty(JCRSessionWrapper session, JCRNodeWrapper n, String pName, String value,
        boolean live) throws RepositoryException {
    if (pName.startsWith("[")) {
        int id = Integer.parseInt(StringUtils.substringBetween(pName, "[", "]"));
        pName = StringUtils.substringAfter(pName, "]");
        if (n.isNodeType("jnt:translation") && n.hasProperty("jcr:language")) {
            pName += "_" + n.getProperty("jcr:language").getString();
            n = n.getParent();/*from  w  w w  .  ja v a 2s  .  com*/
        }
        if (!n.isNodeType("jmix:referencesInField")) {
            n.addMixin("jmix:referencesInField");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("New references : " + value);
        }
        JCRNodeWrapper ref = n.addNode("j:referenceInField_" + Text.escapeIllegalJcrChars(pName) + "_" + id,
                "jnt:referenceInField");
        ref.setProperty("j:fieldName", pName);
        ref.setProperty("j:reference", value);
    } else if (pName.startsWith("@")) {
        JCRNodeWrapper ref = n.addNode(pName.substring(1), "jnt:contentReference");
        updateProperty(session, ref, Constants.NODE, value, false);
    } else {
        final ExtendedPropertyDefinition propertyDefinition = n.getApplicablePropertyDefinition(pName);
        if (propertyDefinition == null) {
            throw new ConstraintViolationException("Couldn't find definition for property " + pName);
        }
        String[] constraints = propertyDefinition.getValueConstraints();
        if (constraints != null && constraints.length > 0) {
            boolean b = false;
            JCRNodeWrapper target = session.getNodeByUUID(value);
            for (int i = 0; i < constraints.length; i++) {
                String constraint = constraints[i];
                b |= target.isNodeType(constraint);
            }
            if (!b) {
                logger.warn("Cannot set reference to " + target.getPath() + ", constraint on " + n.getPath());
                return;
            }
        }
        try {
            if (propertyDefinition.isMultiple()) {
                Value[] newValues;
                if (n.hasProperty(pName)) {
                    final Value[] oldValues = n.getProperty(pName).getValues();
                    newValues = new Value[oldValues.length + 1];
                    for (Value oldValue : oldValues) {
                        // value already set
                        if (oldValue.getString().equals(value)) {
                            return;
                        }
                    }
                    System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
                } else {
                    newValues = new Value[1];
                }
                newValues[newValues.length - 1] = session.getValueFactory().createValue(value,
                        propertyDefinition.getRequiredType());
                if (!n.hasProperty(pName) || !Arrays.equals(newValues, n.getProperty(pName).getValues())) {
                    session.checkout(n);
                    JCRPropertyWrapper property = n.setProperty(pName, newValues);

                    if (live) {
                        try {
                            property.getParent().getCorrespondingNodePath("live");
                            String key = property.getParent().getIdentifier() + "/" + property.getName();
                            if (!session.getResolvedReferences().containsKey(key)) {
                                session.getResolvedReferences().put(key, new HashSet<String>());
                            }
                            ((Set<String>) session.getResolvedReferences().get(key)).add(value);
                        } catch (ItemNotFoundException e) {
                            // Not in live
                        }
                    }
                }
            } else {
                if (!n.hasProperty(pName) || !value.equals(n.getProperty(pName).getString())) {
                    session.checkout(n);
                    JCRPropertyWrapper property = n.setProperty(pName,
                            session.getValueFactory().createValue(value, propertyDefinition.getRequiredType()));
                    String key = property.getParent().getIdentifier() + "/" + property.getName();
                    if (live) {
                        try {
                            property.getParent().getCorrespondingNodePath("live");
                            session.getResolvedReferences().put(key, property.getValue().getString());
                        } catch (ItemNotFoundException e) {
                            // Not in live
                        }
                    }
                }
            }
        } catch (RuntimeException e) {
            String msg = "Error setting property " + pName + " on node " + n.getPath() + " definition "
                    + propertyDefinition + " required type " + propertyDefinition.getRequiredType()
                    + ". Cause: " + e.getMessage();
            if (logger.isDebugEnabled()) {
                // in debug we log the full exception stacktrace
                logger.error(msg, e);
            } else {
                logger.error(msg);
            }
        }
    }
}

From source file:org.jahia.services.mail.MailSettings.java

public Map<String, String> getOptions() {
    String uri = getUri();/* w ww.  j a v a2  s.  co m*/
    Map<String, String> options = new HashMap<String, String>();
    if (uri.contains("@")) {
        uri = StringUtils.substringAfterLast(uri, "@");
    }
    if (uri.contains(":")) {
        String portPart = StringUtils.substringAfterLast(uri, ":");
        // check if there are any custom options, e.g.
        // [mail.smtp.starttls.enable=true,mail.debug=true]
        String optionsPart = StringUtils.substringBetween(portPart, "[", "]");
        if (optionsPart != null && optionsPart.length() > 0) {
            String props[] = StringUtils.split(optionsPart, ",");
            for (String theProperty : props) {
                String keyValue[] = StringUtils.split(theProperty, "=");
                options.put(keyValue[0].trim(), keyValue[1].trim());
            }
        }
    }
    if (getUser() != null) {
        options.put("mail.smtp.auth", "true");
    }

    return options;
}

From source file:org.jahia.services.notification.SubscriptionService.java

/**
 * Checks if the provided user is subscribed to the specified node.
 *
 * @param target  the path of the target subscribable node
 * @param user    the user key for the registered users or an e-mail for
 *                non-registered users//from   w  ww  . j a  v a2 s .co  m
 * @param session the JCR session
 * @return <code>true</code> if the provided user is subscribed to the
 *         specified node
 * @throws RepositoryException   in case of a JCR error
 * @throws InvalidQueryException if the query syntax is invalid
 */
public JCRNodeWrapper getSubscription(JCRNodeWrapper target, String user, JCRSessionWrapper session)
        throws InvalidQueryException, RepositoryException {
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    if (queryManager == null) {
        logger.error("Unable to obtain QueryManager instance");
        return null;
    }
    String subscriber = user;
    String provider = null;
    if (user.charAt(0) == '{') {
        // we deal with a registered user
        subscriber = StringUtils.substringAfter(user, "}");
        provider = StringUtils.substringBetween(user, "{", "}");
    }

    StringBuilder q = new StringBuilder(64);
    q.append("select * from [" + JNT_SUBSCRIPTION + "] where [" + J_SUBSCRIBER + "]='").append(subscriber)
            .append("'");
    if (provider != null) {
        q.append(" and [" + J_PROVIDER + "]='").append(provider).append("'");
    }
    q.append(" and").append(" isdescendantnode([").append(target.getPath()).append("])");
    Query query = queryManager.createQuery(q.toString(), Query.JCR_SQL2);
    query.setLimit(1);
    final NodeIterator nodeIterator = query.execute().getNodes();
    if (nodeIterator.hasNext()) {
        return (JCRNodeWrapper) nodeIterator.nextNode();
    }
    return null;
}

From source file:org.jahia.services.notification.SubscriptionService.java

/**
 * Creates subscription for the specified users and subscribable node
 *
 * @param subscribableIdentifier the UUID of the target subscribable node
 * @param subscribers            a map with subscriber information. The key is a subscriber ID,
 *                               the value is a map with additional properties that will be
 *                               stored for the subscription object. The subscriber ID is a a
 *                               user key in case of a registered Jahia user (the one, returned
 *                               by {@link org.jahia.services.usermanager.JahiaUser#getUserKey()}). In case of a
 *                               non-registered user this is an e-mail address of the
 * @param session/*from   w  w w  . j  a  v  a2  s . com*/
 */
public JCRNodeWrapper subscribe(final String subscribableIdentifier,
        final Map<String, Map<String, Object>> subscribers, JCRSessionWrapper session) {

    JCRNodeWrapper newSubscriptionNode = null;
    try {
        JCRNodeWrapper target = session.getNodeByIdentifier(subscribableIdentifier);
        if (!target.isNodeType(JMIX_SUBSCRIBABLE)) {
            logger.warn("The target node {} does not have the " + JMIX_SUBSCRIBABLE + " mixin."
                    + " No subscriptions can be created.", target.getPath());
            return null;
        }
        JCRNodeWrapper subscriptionsNode = target.getNode(J_SUBSCRIPTIONS);
        String targetPath = subscriptionsNode.getPath();
        if (target.isLocked() || subscriptionsNode.isLocked()) {
            logger.info("The target {} is locked and no subscriptions can be created. Skipping {} subscribers.",
                    targetPath, subscribers.size());
        }

        boolean allowUnregisteredUsers = target.hasProperty(J_ALLOW_UNREGISTERED_USERS)
                ? target.getProperty(J_ALLOW_UNREGISTERED_USERS).getBoolean()
                : true;

        for (Map.Entry<String, Map<String, Object>> subscriber : subscribers.entrySet()) {
            String username = subscriber.getKey();
            String provider = null;
            if (username.charAt(0) == '{') {
                // we deal with a registered user
                username = StringUtils.substringAfter(subscriber.getKey(), "}");
                provider = StringUtils.substringBetween(subscriber.getKey(), "{", "}");
            } else if (!allowUnregisteredUsers) {
                logger.info(
                        "The target {} does not allow unregistered users to be subscribed. Skipping subscription for {}.",
                        targetPath, subscriber.getKey());
                continue;
            }

            if (getSubscription(target, subscriber.getKey(), session) == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating subscription to the {} for {}.", targetPath, subscriber.getKey());
                }
                session.checkout(subscriptionsNode);
                newSubscriptionNode = subscriptionsNode.addNode(
                        JCRContentUtils.findAvailableNodeName(subscriptionsNode, "subscription"),
                        JNT_SUBSCRIPTION);
                newSubscriptionNode.setProperty(J_SUBSCRIBER, username);
                if (provider != null) {
                    newSubscriptionNode.setProperty(J_PROVIDER, provider);
                }
                storeProperties(newSubscriptionNode, subscriber.getValue(), session);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Subscription for the {} and {} is already present. Skipping ceraring new one.",
                            targetPath, subscriber.getKey());
                }
            }
        }
        session.save();
    } catch (RepositoryException e) {
        logger.error("Error creating subscriptions for node " + subscribableIdentifier, e);
    }
    return newSubscriptionNode;
}