Example usage for org.apache.commons.lang3 StringUtils substringBefore

List of usage examples for org.apache.commons.lang3 StringUtils substringBefore

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils substringBefore.

Prototype

public static String substringBefore(final String str, final String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:org.wrml.runtime.rest.UriTemplate.java

public SortedSet<Parameter> getParameters(final URI uri) {

    if (uri == null) {
        throw new UriTemplateException("Null URI", null, this);
    }//from   www.j  av  a 2s  .  co m

    String uriString = uri.toString();
    uriString = StringUtils.substringBefore(uriString, "?");

    final Matcher matcher = _MatchPattern.matcher(uriString);

    if (!matcher.matches()) {
        return null;
    }

    final SortedSet<Parameter> parameterSet = new TreeSet<>();
    for (final String paramName : _ParamNames) {
        final String paramValue = matcher.group(paramName);
        final Parameter parameter = new Parameter(paramName, paramValue);
        parameterSet.add(parameter);
    }

    return parameterSet;
}

From source file:org.xlrnet.metadict.engines.leo.LeoEngine.java

/**
 * Extracts the domain information from a given representation string.
 * <p>//  w w w .ja v a  2s .  c o  m
 * Example:
 * If the input is "drive-in restaurant [cook.]", then the domain is "cook."
 *
 * @param representation
 *         The input string.
 * @return the domain string or null if none could be found
 */
@Nullable
private String extractDomainString(String representation) {
    String substring = StringUtils.substringAfterLast(representation, "[");
    if (substring != null)
        return StringUtils.substringBefore(substring, "]");
    return null;
}

From source file:org.xlrnet.metadict.engines.woxikon.WoxikonEngine.java

@NotNull
private DictionaryObject processSingleNode(@NotNull Element element, @NotNull Language language,
        String queryString) {//from   www .j  a va  2s .  com
    DictionaryObjectBuilder objectBuilder = ImmutableDictionaryObject.builder();
    objectBuilder.setLanguage(language);

    // Extract entry text:
    String context = StringUtils.substringBefore(element.text(), element.getElementsByTag("a").first().text());
    String generalForm = context + element.getElementsByTag("a").first().text();
    objectBuilder.setGeneralForm(StringUtils.strip(generalForm));

    // Extract description:
    extractDescription(element, queryString, objectBuilder);

    // Extract gender:
    extractGender(element, objectBuilder);

    return objectBuilder.build();
}

From source file:org.xwiki.contrib.jira.macro.internal.source.ListJIRADataSource.java

/**
 * @param macroContent the macro content listing JIRA issue ids and optional notes
 * @return the list of issue ids and optional notes specified in the macro content
 *///from ww  w .j  ava 2s.  c o m
public List<Pair<String, String>> parseIds(String macroContent) {
    List<Pair<String, String>> ids = new ArrayList<Pair<String, String>>();
    if (macroContent != null) {
        for (String issueLine : macroContent.split("\\r?\\n")) {
            // Split on pipe symbol
            String issue = StringUtils.substringBefore(issueLine, PIPE).trim();
            String note = StringUtils.substringAfter(issueLine, PIPE).trim();
            // Only add if the issue is not empty
            if (StringUtils.isNotBlank(issue)) {
                ids.add(new ImmutablePair<String, String>(issue, note));
            }
        }
    }
    return ids;
}

From source file:org.xwiki.contrib.mailarchive.utils.internal.MailUtils.java

@Override
public IMAUser parseUser(final String user, final boolean isMatchLdap) {
    logger.debug("parseUser {}, {}", user, isMatchLdap);

    MAUser maUser = new MAUser();
    maUser.setOriginalAddress(user);/*from w  w w . j  a  va 2 s  . c  o  m*/

    if (StringUtils.isBlank(user)) {
        return maUser;
    }

    String address = null;
    String personal = null;
    // Do our best to extract an address and a personal
    try {
        InternetAddress ia = null;
        InternetAddress[] result = InternetAddress.parse(user, true);
        if (result != null && result.length > 0) {
            ia = result[0];
            if (!StringUtils.isBlank(ia.getAddress())) {
                address = ia.getAddress();
            }
            if (!StringUtils.isBlank(ia.getPersonal())) {
                personal = ia.getPersonal();
            }
        }
    } catch (AddressException e) {
        logger.info("Email Address does not follow standards : " + user);
    }
    if (StringUtils.isBlank(address)) {
        String[] substrs = StringUtils.substringsBetween(user, "<", ">");
        if (substrs != null && substrs.length > 0) {
            address = substrs[0];
        } else {
            // nothing matches, we suppose recipient only contains email address
            address = user;
        }
    }
    if (StringUtils.isBlank(personal)) {
        if (user.contains("<")) {
            personal = StringUtils.substringBeforeLast(user, "<");
            if (StringUtils.isBlank(personal)) {
                personal = StringUtils.substringBefore(address, "@");
            }
        }

    }
    maUser.setAddress(address);
    maUser.setDisplayName(personal);

    // Now to match a wiki profile
    logger.debug("parseUser extracted email {}", address);
    String parsedUser = null;
    if (!StringUtils.isBlank(address)) {
        // to match "-external" emails and old mails with '@gemplus.com'...
        String pattern = address.toLowerCase();
        pattern = pattern.replace("-external", "").replaceAll("^(.*)@.*[.]com$", "$1%@%.com");
        logger.debug("parseUser pattern applied {}", pattern);
        // Try to find a wiki profile with this email as parameter.
        // TBD : do this in the loading phase, and only try to search db if it was not found ?
        String xwql = "select doc.fullName from Document doc, doc.object(XWiki.XWikiUsers) as user where LOWER(user.email) like :pattern";

        List<String> profiles = null;
        try {
            profiles = queryManager.createQuery(xwql, Query.XWQL).bindValue("pattern", pattern).execute();
        } catch (QueryException e) {
            logger.warn("parseUser Query threw exception", e);
            profiles = null;
        }
        if (profiles == null || profiles.size() == 0) {
            logger.debug("parseUser found no wiki profile from db");
            return maUser;
        } else {
            if (isMatchLdap) {
                logger.debug("parseUser Checking for LDAP authenticated profile(s) ...");
                // If there exists one, we prefer the user that's been authenticated through LDAP
                for (String usr : profiles) {
                    if (bridge.exists(usr, "XWiki.LDAPProfileClass")) {
                        parsedUser = usr;
                        logger.debug("parseUser Found LDAP authenticated profile {}", parsedUser);
                    }
                }
                if (parsedUser != null) {
                    maUser.setWikiProfile(parsedUser);
                    logger.debug("parseUser return {}", maUser);
                    return maUser;
                }
            }
        }

        // If none has authenticated from LDAP, we return the first user found
        maUser.setWikiProfile(profiles.get(0));
        logger.debug("parseUser return {}", maUser);
        return maUser;

    } else {
        logger.debug("parseUser No email found to match");
        return maUser;
    }

}

From source file:org.xwiki.editor.tool.autocomplete.internal.AutoCompletionResource.java

/**
 * Find hints for the passed content assuming that it's representing method calls.
 *
 * @param chars the content to parse//from   ww  w . j  ava 2s . com
 * @param currentPos the current position at which method calls are starting
 * @param variableName the name of the variable on which the first method is called
 * @return the list of autocompletion hints
 * @throws InvalidVelocityException if a parsing error occurs
 */
private Hints getHintsForMethodCall(char[] chars, int currentPos, String variableName)
        throws InvalidVelocityException {
    Hints results = new Hints();
    VelocityParserContext context = new VelocityParserContext();

    // Find the next method after the currentPos.
    int pos = currentPos;

    // Handle the case when the variable of the first method call does not exist, also avoiding a NPE here.
    // See http://jira.xwiki.org/browse/WIKIEDITOR-18
    Object contextVariable = getVelocityContext().get(variableName);
    if (contextVariable == null) {
        return results;
    }

    AutoCompletionMethodFinder methodFinder = getMethodFinder(variableName);
    List<Class> methodClasses = Arrays.asList((Class) contextVariable.getClass());

    do {
        // Handle the special case when the cursor is after the dot ('.')
        String methodName;
        if (pos == chars.length - 1) {
            methodName = "";
            pos++;
        } else {
            StringBuffer method = new StringBuffer();
            pos = this.parser.getMethodOrProperty(chars, pos, method, context);
            methodName = StringUtils.substringBefore(method.toString(), "(").substring(1);
        }

        if (pos == chars.length) {
            // Find all methods matching methodName in methodClasses
            for (Class methodClass : methodClasses) {
                results.withHints(methodFinder.findMethods(methodClass, methodName));
            }

            // Set the hints offset to be able to determine where the completion should be inserted.
            results = results.withStartOffset(methodName.length());

            break;
        } else {
            // Find the returned type for method "methodName".
            List<Class> returnTypes = new ArrayList<Class>();
            for (Class methodClass : methodClasses) {
                returnTypes.addAll(methodFinder.findMethodReturnTypes(methodClass, methodName));
            }
            methodClasses = returnTypes;

            // Reset the method finder since we use a specialized finder only for the first autocompletion method
            methodFinder = this.defaultAutoCompletionMethodFinder;
        }
    } while (true);

    return results;
}

From source file:org.xwiki.localization.internal.AbstractWikiBundle.java

/**
 * Loads translations from a document, in a specified language. If the requested language is not the same as the
 * default wiki language, then the translations in the default language are first loaded as a base translation.
 * Additionally, the document is added to the list of watched documents, so that changes in the document are
 * detected.// w ww.  j  a v a2s. co m
 * 
 * @param documentName The full name of the source document, including the wiki prefix.
 * @param language The translation to load.
 * @return A {@link Properties} object loaded from the translation, including as a base the default language values
 *         for the keys that are not defined in the requested translation.
 * @throws Exception if the document cannot be accessed.
 * @see #loadDocumentBundle(String, String, String)
 */
protected Properties loadDocumentBundle(String documentName, String language) throws Exception {
    String wiki;
    if (documentName.indexOf(WikiInformation.WIKI_PREFIX_SEPARATOR) > 0) {
        wiki = StringUtils.substringBefore(documentName, WikiInformation.WIKI_PREFIX_SEPARATOR);
    } else {
        wiki = this.wikiInfo.getCurrentWikiName();
    }
    return loadDocumentBundle(wiki, documentName, language);
}

From source file:org.xwiki.rendering.internal.renderer.MailtoURILabelGenerator.java

@Override
public String generateLabel(ResourceReference reference) {
    // Remove the query string (if any).
    return StringUtils.substringBefore(reference.getReference(), "?");
}

From source file:org.xwiki.test.xmlrpc.confluence.CommentsTest.java

/**
 * Compare two URLs, discarding any jsession id information in the URL.
 */// w  w  w .  ja v a  2s . c o  m
private void assertURLEquals(String expectedURL, String url) {
    assertEquals(StringUtils.substringBefore(expectedURL, ";jsessionid"),
            StringUtils.substringBefore(url, ";jsessionid"));
}

From source file:org.xwiki.url.internal.standard.DomainWikiReferenceExtractor.java

private String resolveDomainBasedWikiReference(String alias) {
    String wikiId;/*from w w  w .j a  v a 2s . c  o  m*/

    // Look for a Wiki Descriptor
    WikiDescriptor wikiDescriptor = getWikiDescriptorByAlias(alias);
    if (wikiDescriptor != null) {
        // Get the wiki id from the wiki descriptor
        wikiId = wikiDescriptor.getId();
    } else {
        // Fallback: No definition found based on the full domain name, consider the alias as a
        // domain name and try to use the first part of the domain name as the wiki name.
        String domainAlias = StringUtils.substringBefore(alias, ".");

        // As a convenience, we do not require the creation of an XWiki.XWikiServerXwiki page for the main
        // wiki and automatically go to the main wiki in certain cases:
        // - "www.<rest of domain name>"
        // - "localhost"
        // - IP address
        if ("www".equals(domainAlias) || "localhost".equals(alias)
                || alias.matches("[0-9]{1,3}(?:\\.[0-9]{1,3}){3}")) {
            wikiId = getMainWikiId();
        } else {
            wikiId = normalizeWikiIdForNonExistentWikiDescriptor(domainAlias);
        }

        // Create a virtual descriptor and save it so that next call will resolve to it directly without needing
        // to query the entity store.
        // this.wikiDescriptorCache.add(new WikiDescriptor(wikiId, alias));
        // TODO: uncomment theses lines, find a solution
    }

    return wikiId;
}