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

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

Introduction

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

Prototype

public static String[] substringsBetween(String str, String open, String close) 

Source Link

Document

Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.

Usage

From source file:org.b3log.symphony.service.UserQueryService.java

/**
 * Gets user names from the specified text.
 *
 * <p>//from w  w  w . ja  va2 s  .co m
 * A user name is between &#64; and a punctuation, a blank or a line break (\n). For example, the specified text is
 * <pre>&#64;88250 It is a nice day. &#64;Vanessa, we are on the way.</pre> There are two user names in the text,
 * 88250 and Vanessa.
 * </p>
 *
 * @param text the specified text
 * @return user names, returns an empty set if not found
 * @throws ServiceException service exception
 */
public Set<String> getUserNames(final String text) throws ServiceException {
    final Set<String> ret = new HashSet<String>();

    int idx = text.indexOf('@');

    if (-1 == idx) {
        return ret;
    }

    String copy = text.trim();
    copy = copy.replaceAll("\\n", " ");
    copy = copy.replaceAll("(?=\\pP)[^@]", " ");
    String[] uNames = StringUtils.substringsBetween(copy, "@", " ");
    String tail = StringUtils.substringAfterLast(copy, "@");

    if (tail.contains(" ")) {
        tail = null;
    }

    if (null != tail) {
        if (null == uNames) {
            uNames = new String[1];
            uNames[0] = tail;
        } else {
            uNames = Arrays.copyOf(uNames, uNames.length + 1);
            uNames[uNames.length - 1] = tail;
        }
    }

    if (null == uNames) {
        return ret;
    }

    for (int i = 0; i < uNames.length; i++) {
        final String maybeUserName = uNames[i];

        if (!UserRegisterValidation.invalidUserName(maybeUserName)) { // A string match the user name pattern
            if (null != getUserByName(maybeUserName)) { // Found a user
                ret.add(maybeUserName);

                copy = copy.replaceFirst("@" + maybeUserName, "");
                idx = copy.indexOf('@');
                if (-1 == idx) {
                    return ret;
                }
            }
        }
    }

    return ret;
}

From source file:org.codice.ddf.commands.solr.BackupCommandTest.java

private String getRequestStatus(String consoleOutput) {
    return StringUtils.trim(StringUtils
            .substringsBetween(ASCII_COLOR_CODES_REGEX.matcher(consoleOutput).replaceAll(""), "[", "]")[1]);
}

From source file:org.codice.ddf.commands.solr.BackupCommandTest.java

private String getBackupName(String consoleOutput) {
    return StringUtils.trim(StringUtils
            .substringsBetween(ASCII_COLOR_CODES_REGEX.matcher(consoleOutput).replaceAll(""), "[", "]")[2]);
}

From source file:org.devproof.portal.core.module.common.component.ExtendedLabel.java

private IModel<String> createConvertedContentModel() {
    return new LoadableDetachableModel<String>() {
        private static final long serialVersionUID = -3507047529867991441L;

        @Override/*from  w  w  w .  j  a v  a 2s  . c o m*/
        protected String load() {
            cleanupExpiredImages();
            String modifiedContent = contentModel.getObject();
            String tagParts[] = StringUtils.substringsBetween(modifiedContent, PRETAG, POSTTAG);
            if (tagParts != null) {
                for (String tagPart : tagParts) {
                    String fullTag = PRETAG + tagPart + POSTTAG;
                    String splittedAttribute[] = StringUtils
                            .split(StringUtils.substringBefore(fullTag, CLOSE_SEP), "= ");
                    int fontSize = getFontSize(splittedAttribute);
                    List<String> str2ImgLines = getTextLines(tagPart);
                    Font font = getFont(fontSize);
                    ImgResourceReference imgResource = getImageResourceAndCache(str2ImgLines, font);
                    modifiedContent = replaceTagWithImage(modifiedContent, fullTag, imgResource);
                }
            }
            return modifiedContent;
        }
    };
}

From source file:org.ebayopensource.turmeric.eclipse.resources.util.SOAConsumerUtil.java

/**
 * This function returns the mapped value. Lets say the client config folder
 * name is "a" and if a has an entry in the the properties file map,then
 * that entry is returned otherwise a. the format of the String in the props
 * file is {[a,b],[d,e]}//from   ww  w . ja  v  a  2  s  . c om
 *
 * @param project the project
 * @param clientNames the client names
 * @return the mapped service names from props file
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws CoreException the core exception
 */
public static Map<String, String> getMappedServiceNamesFromPropsFile(IProject project, String... clientNames)
        throws IOException, CoreException {
    final Map<String, String> svcClientNameMap = new ConcurrentHashMap<String, String>();
    // This is a hot fix for consumers. Impls wont have this props file
    // This is not a very nice approach. Impls also should have
    // consumer properties if its a consumer.
    IFile consumerPropsFile = getConsumerPropertiesFile(project);
    if (consumerPropsFile != null && consumerPropsFile.isAccessible()) {
        //this should be a consumer project
        final Properties properties = loadConsumerProperties(project);
        Object objMapStr = properties.get(SOAProjectConstants.PROPS_KEY_CONSUMER_SVC_CLIENT_NAME_MAPPING);
        if (objMapStr != null && objMapStr instanceof String && StringUtils.isNotEmpty((String) objMapStr)) {
            String strMap = (String) objMapStr;
            strMap = StringUtils.substringBetween(strMap, "{", "}");
            for (String tempStr : StringUtils.substringsBetween(strMap, "[", "]")) {
                String[] tempArr = StringUtils.split(tempStr, SOAProjectConstants.DELIMITER_COMMA);
                svcClientNameMap.put(tempArr[0], tempArr[1]);
            }
        }
    }
    if (clientNames != null) {
        for (String clientName : clientNames) {
            String svcName = svcClientNameMap.get(clientName);
            if (StringUtils.isEmpty(svcName)) {
                svcClientNameMap.put(clientName, clientName);
            }
        }
    }
    return svcClientNameMap;
}

From source file:org.eclipse.leshan.server.demo.servlet.ClientServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];

    // /clients/endPoint/LWRequest/observe : cancel observation for the given resource.
    if (path.length >= 4 && "observe".equals(path[path.length - 1])) {
        try {/*w  w w  . java 2 s  . c  o  m*/
            String target = StringUtils.substringsBetween(req.getPathInfo(), clientEndpoint, "/observe")[0];
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                server.getObservationService().cancelObservations(registration, target);
                resp.setStatus(HttpServletResponse.SC_OK);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException e) {
            handleException(e, resp);
        }
        return;
    }

    // /clients/endPoint/LWRequest/ : delete instance
    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
        if (registration != null) {
            DeleteRequest request = new DeleteRequest(target);
            DeleteResponse cResponse = server.send(registration, request, TIMEOUT);
            processDeviceResponse(req, resp, cResponse);
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
        }
    } catch (RuntimeException | InterruptedException e) {
        handleException(e, resp);
    }
}

From source file:org.eclipse.leshan.standalone.servlet.ClientServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];

    // /clients/endPoint/LWRequest/observe : cancel observation for the given resource.
    if (path.length >= 4 && "observe".equals(path[path.length - 1])) {
        try {/*from   w  ww .  j  a v a2  s  . c  o  m*/
            String target = StringUtils.substringsBetween(req.getPathInfo(), clientEndpoint, "/observe")[0];
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                server.getObservationRegistry().cancelObservation(client, target);
                resp.setStatus(HttpServletResponse.SC_OK);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }

    // /clients/endPoint/LWRequest/ : delete instance
    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        Client client = server.getClientRegistry().get(clientEndpoint);
        if (client != null) {
            DeleteRequest request = new DeleteRequest(target);
            LwM2mResponse cResponse = server.send(client, request, TIMEOUT);
            processDeviceResponse(req, resp, cResponse);
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
        }
    } catch (IllegalArgumentException e) {
        LOG.warn("Invalid request", e);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().append(e.getMessage()).flush();
    } catch (ResourceAccessException | RequestFailedException e) {
        LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()), e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().append(e.getMessage()).flush();
    }
}

From source file:org.jtalks.jcommune.service.nontransactional.BBCodeService.java

/**
 * In case when bb code contains tag [user], text processing execute with help
 * this method because KefirrBB does not work properly
 * with eg "[user=/jcommune/users/16][user]user[/user][/user]" i.e user name contains tag [user]
 * @param bbEncodedText line with nested [user] bb-codes
 * @return formatted text with link//from   w  w  w .j  a  v  a 2s  . co m
 */
private String processUserbbCode(String bbEncodedText) {
    String openTag = "<a  href=\"";
    String closeTag = "</a>";
    String classInfo = "\" class=\"mentioned-user\" >";

    String[] array = StringUtils.substringsBetween(bbEncodedText, "[", "]");
    String userLink = array[0];
    String userName = bbEncodedText.substring(userLink.length() + 2, bbEncodedText.length() - 7);
    String result = openTag + userLink.substring(5, userLink.length()) + classInfo + userName + closeTag;

    return result;
}

From source file:org.kuali.rice.krad.datadictionary.MessageBeanProcessor.java

/**
 * Checks a string property value for a message placeholder and if found the message is retrieved and updated
 * in the property value//from w  ww  . j  a v  a 2s .c om
 *
 * @param propertyValue string value to process for message placeholders
 * @param nestedBeanStack stack of bean definitions that contain the property, used to determine the namespace
 * and component for the message retrieval
 * @return String new value for the property (possibly modified from an external message)
 */
protected String processMessagePlaceholders(String propertyValue, Stack<BeanDefinitionHolder> nestedBeanStack) {
    String trimmedPropertyValue = StringUtils.stripStart(propertyValue, " ");
    if (StringUtils.isBlank(trimmedPropertyValue)) {
        return propertyValue;
    }

    String newPropertyValue = propertyValue;

    // first check for a replacement message key
    if (trimmedPropertyValue.startsWith(KRADConstants.MESSAGE_KEY_PLACEHOLDER_PREFIX)
            && StringUtils.contains(trimmedPropertyValue, KRADConstants.MESSAGE_KEY_PLACEHOLDER_SUFFIX)) {
        String messageKeyStr = StringUtils.substringBetween(trimmedPropertyValue,
                KRADConstants.MESSAGE_KEY_PLACEHOLDER_PREFIX, KRADConstants.MESSAGE_KEY_PLACEHOLDER_SUFFIX);

        // get any default specified value (given after the message key)
        String messageKeyWithPlaceholder = KRADConstants.MESSAGE_KEY_PLACEHOLDER_PREFIX + messageKeyStr
                + KRADConstants.MESSAGE_KEY_PLACEHOLDER_SUFFIX;

        String defaultPropertyValue = StringUtils.substringAfter(trimmedPropertyValue,
                messageKeyWithPlaceholder);

        // set the new property value to the message text (if found), or the default value if a message was not found
        // note the message text could be an empty string, in which case it will override the default
        String messageText = getMessageTextForKey(messageKeyStr, nestedBeanStack);
        if (messageText != null) {
            // if default value set then we need to merge any expressions
            if (StringUtils.isNotBlank(defaultPropertyValue)) {
                newPropertyValue = getMergedMessageText(messageText, defaultPropertyValue);
            } else {
                newPropertyValue = messageText;
            }
        } else {
            newPropertyValue = defaultPropertyValue;
        }
    }
    // now check for message keys within an expression
    else if (StringUtils.contains(trimmedPropertyValue, KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_PREFIX)) {
        String[] expressionMessageKeys = StringUtils.substringsBetween(newPropertyValue,
                KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_PREFIX,
                KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_SUFFIX);

        for (String expressionMessageKey : expressionMessageKeys) {
            String expressionMessageText = getMessageTextForKey(expressionMessageKey, nestedBeanStack);
            newPropertyValue = StringUtils
                    .replace(newPropertyValue,
                            KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_PREFIX + expressionMessageKey
                                    + KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_SUFFIX,
                            expressionMessageText);
        }
    }

    return newPropertyValue;
}

From source file:org.kuali.rice.krad.datadictionary.MessageBeanProcessor.java

/**
 * Prepares the message text that will replace the property value checking for any expression placeholders
 *
 * <p>/*from w  w  w  .j ava 2s  . c  o m*/
 * The message text may contain placeholders (using brace delimiters) for expression placement. It is
 * expected when these placeholders are given the property value contains the expressions (using the
 * expression placeholders) that will be inserted into the message text
 * </p>
 *
 * @param messageText - raw text of the message
 * @param propertyValue - current value for the property
 * @return String the message text with expressions inserted (if any expressions were found)
 */
protected String getMergedMessageText(String messageText, String propertyValue) {
    String mergedText = messageText;

    String[] expressions = StringUtils.substringsBetween(propertyValue, UifConstants.EL_PLACEHOLDER_PREFIX,
            UifConstants.EL_PLACEHOLDER_SUFFIX);
    if ((expressions != null) && expressions.length > 0) {
        // add expression placeholders back on
        String[] messageParameters = new String[expressions.length];
        for (int i = 0; i < expressions.length; i++) {
            String expression = expressions[i];

            expression = UifConstants.EL_PLACEHOLDER_PREFIX + expression + UifConstants.EL_PLACEHOLDER_SUFFIX;
            messageParameters[i] = expression;
        }

        // escape single quotes for message format process
        messageText = messageText.replace("'", "''");
        try {
            mergedText = MessageFormat.format(messageText, messageParameters);
        } catch (IllegalArgumentException e) {
            throw new RiceRuntimeException(
                    "Unable to merge expressions with message text. Expression count is: " + expressions.length,
                    e);
        }
    }

    return mergedText;
}