Example usage for java.util.regex Matcher appendTail

List of usage examples for java.util.regex Matcher appendTail

Introduction

In this page you can find the example usage for java.util.regex Matcher appendTail.

Prototype

public StringBuilder appendTail(StringBuilder sb) 

Source Link

Document

Implements a terminal append-and-replace step.

Usage

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

private String replaceHashTag(String statusText) {
    Pattern p = Pattern.compile("(\\s|\\A)#([^\\s]+)");
    Matcher m = p.matcher(statusText);

    // if we have a match anywhere in the string
    StringBuffer buf = new StringBuffer();
    while (m.find()) {
        //replace that portion that matched, with the link
        String matched = m.group();
        m.appendReplacement(buf,/*w  w  w.  j a  v  a 2s.c o  m*/
                String.format("<a target=\"_blank\" href=\"http://twitter.com/search?q=%%23%s\">%s</a>",
                        StringUtils.stripStart(matched.substring(1), "#"), matched));
    }
    m.appendTail(buf);
    return buf.toString();
}

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

/**
 * Processes tag short link (tag id).//from  w  ww  . j a va 2s .  com
 *
 * @param content the specified content
 * @return processed content
 */
public String linkTag(final String content) {
    final Matcher matcher = TAG_TITLE_PATTERN.matcher(content);
    final StringBuffer contentBuilder = new StringBuffer();

    try {
        while (matcher.find()) {
            final String linkTagTitle = StringUtils.substringBetween(matcher.group(), "[", "]");

            final Query query = new Query().addProjection(Tag.TAG_TITLE, String.class)
                    .setFilter(new PropertyFilter(Tag.TAG_TITLE, FilterOperator.EQUAL, linkTagTitle));
            final JSONArray results = tagRepository.get(query).optJSONArray(Keys.RESULTS);
            if (0 == results.length()) {
                continue;
            }

            final JSONObject linkTag = results.optJSONObject(0);

            final String linkTitle = linkTag.optString(Tag.TAG_TITLE);
            final String link = " [" + linkTitle + "](" + Latkes.getServePath() + "/tags/" + linkTitle + ") ";

            matcher.appendReplacement(contentBuilder, link);
        }
        matcher.appendTail(contentBuilder);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Generates tag link error", e);
    }

    return contentBuilder.toString();
}

From source file:org.glowroot.central.SyntheticMonitorService.java

@Instrumentation.Transaction(transactionType = "Background", transactionName = "Synthetic monitor", traceHeadline = "Synthetic monitor: {{0.id}}", timer = "synthetic monitor")
private void runJava(AgentRollup agentRollup, SyntheticMonitorConfig syntheticMonitorConfig,
        List<AlertConfig> alertConfigs) throws Exception {
    Matcher matcher = encryptedPattern.matcher(syntheticMonitorConfig.getJavaSource());
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String encryptedPassword = checkNotNull(matcher.group(1));
        matcher.appendReplacement(sb,/* ww w.jav  a  2  s  .  co  m*/
                "\"" + Encryption.decrypt(encryptedPassword, configRepository.getLazySecretKey()) + "\"");
    }
    matcher.appendTail(sb);
    runSyntheticMonitor(agentRollup, syntheticMonitorConfig, alertConfigs, () -> runJava(sb.toString()));
}

From source file:org.ejbca.core.model.ra.UsernameGenerator.java

/**
 * Interpolate the patterns that exists on the input on the form '${pattern}'.
 * @param input the input content to be interpolated
 * @return the interpolated content/*from www  . java 2  s  .  c o m*/
 */
private String interpolate(String input) {
    if (input == null) {
        return null;
    }
    final Matcher m = PATTERN.matcher(input);
    final StringBuffer sb = new StringBuffer(input.length());
    while (m.find()) {
        // when the pattern is ${identifier}, group 0 is 'identifier'
        String key = m.group(1);
        String value = null;
        if (StringUtils.equals(key, "RANDOM")) {
            value = getRandomString(params.getRandomPrefixLength());
        }
        // if the pattern does exists, replace it by its value
        // otherwise keep the pattern ( it is group(0) )
        if (value != null) {
            m.appendReplacement(sb, value);
        } else {
            // I'm doing this to avoid the backreference problem as there will be a $
            // if I replace directly with the group 0 (which is also a pattern)
            m.appendReplacement(sb, "");
            String unknown = m.group(0);
            sb.append(unknown);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

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

/**
 * Processes article short link (article id).
 *
 * @param content the specified content/*from  www  . j  ava 2 s .c  o  m*/
 * @return processed content
 */
public String linkArticle(final String content) {
    final Matcher matcher = ID_PATTERN.matcher(content);
    final StringBuffer contentBuilder = new StringBuffer();

    try {
        while (matcher.find()) {
            final String linkId = StringUtils.substringBetween(matcher.group(), "[", "]");

            final Query query = new Query().addProjection(Article.ARTICLE_TITLE, String.class)
                    .setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, linkId));
            final JSONArray results = articleRepository.get(query).optJSONArray(Keys.RESULTS);
            if (0 == results.length()) {
                continue;
            }

            final JSONObject linkArticle = results.optJSONObject(0);

            final String linkTitle = linkArticle.optString(Article.ARTICLE_TITLE);
            final String link = " [" + linkTitle + "](" + Latkes.getServePath() + "/article/" + linkId + ") ";

            matcher.appendReplacement(contentBuilder, link);
        }
        matcher.appendTail(contentBuilder);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Generates article link error", e);
    }

    return contentBuilder.toString();
}

From source file:org.mule.transport.jdbc.JdbcConnector.java

/**
 * Parse the given statement filling the parameter list and return the ready to use statement.
 * /*  w  w w.j  a va2  s.  c  om*/
 * @param stmt
 * @param params
 */
public String parseStatement(String stmt, List params) {
    if (stmt == null) {
        return stmt;
    }
    Matcher m = STATEMENT_ARGS.matcher(stmt);
    StringBuffer sb = new StringBuffer(200);
    while (m.find()) {
        String key = m.group();
        m.appendReplacement(sb, "?");
        // Special legacy handling for #[payload]
        if (key.equals("#[payload]")) {
            // MULE-3597
            logger.error(
                    "invalid expression template #[payload]. It should be replaced with #[payload:] to conform with the correct expression syntax. Mule has replaced this for you, but may not in future versions.");
            key = "#[payload:]";
        }
        params.add(key);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.gewara.util.XSSFilter.java

protected String validateEntities(String s) {
    // validate entities throughout the string
    Pattern p = Pattern.compile("&([^&;]*)(?=(;|&|$))");
    Matcher m = p.matcher(s);
    if (m.find()) {
        String one = m.group(1); // ([^&;]*)
        String two = m.group(2); // (?=(;|&|$))
        s = checkEntity(one, two);/*from  w w w . ja v  a  2s  .com*/
    }

    // validate quotes outside of tags
    p = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);
    m = p.matcher(s);
    StringBuffer buf = new StringBuffer();
    if (m.find()) {
        String one = m.group(1); // (>|^)
        String two = m.group(2); // ([^<]+?)
        String three = m.group(3); // (<|$)
        m.appendReplacement(buf, one + two.replaceAll("\"", "&quot;") + three);
    }
    m.appendTail(buf);

    return s;
}

From source file:com.confighub.core.utils.FileUtils.java

private static String previewFile(final Context context, String fileContent, Map<String, Property> resolved,
        MultivaluedMap<String, String> passwords, Set<Long> breadcrumbs) {
    Collection<String> keyStrings = FileUtils.getKeys(fileContent);

    String patternString = "(?i)\\$\\{\\s*\\b(" + StringUtils.join(keyStrings, "|") + ")\\b\\s*}";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(fileContent);

    StringBuffer sb = new StringBuffer();

    while (matcher.find()) {
        String key = matcher.group(1);
        Property property = resolved.get(key);

        // replace each key specification with the property value
        String value = "";

        if (null != property) {
            if (null != property.getAbsoluteFilePath() && PropertyKey.ValueDataType.FileEmbed
                    .equals(property.getPropertyKey().getValueDataType())) {
                if (breadcrumbs.contains(property.getAbsoluteFilePath().getId())) {
                    JsonObject json = property.toJson();
                    json.addProperty("key", key);
                    throw new ConfigException(Error.Code.FILE_CIRCULAR_REFERENCE, json);
                }//from   www .  j a  v a  2s  .  co m

                breadcrumbs.add(property.getAbsoluteFilePath().getId());

                RepoFile injectFile = context.resolveFullContextFilePath(property.getAbsoluteFilePath());
                if (null == injectFile)
                    value = "[ ERROR: No file resolved ]";
                else
                    value = previewFile(context, injectFile.getContent(), resolved, passwords, breadcrumbs);
            } else {
                if (property.isEncrypted()) {
                    String spName = property.getPropertyKey().getSecurityProfile().getName();
                    if (null != passwords && passwords.containsKey(spName)) {
                        String password = passwords.get(spName).get(0);
                        if (!Utils.isBlank(password))
                            property.decryptValue(password);
                    }
                }
                value = setValue(property);
            }
        }

        matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
    }

    matcher.appendTail(sb);
    fileContent = sb.toString();

    // Remove all escapes \${...}
    fileContent = fileContent.replaceAll("\\\\\\$\\{", "\\$\\{");
    return fileContent;
}

From source file:org.encuestame.core.util.HTMLInputFilter.java

protected String validateEntities(String s) {
    // validate entities throughout the string
    Pattern pattern = Pattern.compile("&([^&;]*)(?=(;|&|$))");
    Matcher matcher = pattern.matcher(s);
    if (matcher.find()) {
        String one = matcher.group(1); // ([^&;]*)
        String two = matcher.group(2); // (?=(;|&|$))
        s = checkEntity(one, two);/*from   w  w  w .  j  av  a  2  s.c  o m*/
    }

    // validate quotes outside of tags
    pattern = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);
    matcher = pattern.matcher(s);
    StringBuffer buf = new StringBuffer();
    if (matcher.find()) {
        String one = matcher.group(1); // (>|^)
        String two = matcher.group(2); // ([^<]+?)
        String three = matcher.group(3); // (<|$)
        matcher.appendReplacement(buf, one + two.replaceAll("\"", "&quot;") + three);
    }
    matcher.appendTail(buf);

    return s;
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static String stripWhitespace(String str) {
    if (str == null)
        return null;
    Matcher matcher = WHITESPACE.matcher(str);
    StringBuffer buffer = new StringBuffer();
    for (; matcher.find(); matcher.appendReplacement(buffer, ""))
        ;//from   w w  w  .  ja v a2 s.c om
    matcher.appendTail(buffer);
    return buffer.toString();
}