Example usage for java.util.regex Matcher appendReplacement

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

Introduction

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

Prototype

public Matcher appendReplacement(StringBuilder sb, String replacement) 

Source Link

Document

Implements a non-terminal append-and-replace step.

Usage

From source file:disko.flow.analyzers.RegexpAnalyzer.java

/** Replaces HTML tags with same number of whitespaces */
private String cleanText(String docText) {
    StringBuffer cleanText = new StringBuffer();
    Matcher tagMatcher = TAG_PATTERN.matcher(docText);
    while (tagMatcher.find()) {
        String found = tagMatcher.group();
        tagMatcher.appendReplacement(cleanText, getWhiteSpace(found.length()));
    }//from   www. j av a 2 s  .  c  o  m
    return cleanText.toString();
}

From source file:es.itg.sensorweb.model.swecommon.DataArray.java

@Override
@JsonIgnore//from   w w w  .ja v  a 2s .com
public String getTextEncodedValue(String blockSeparator, String tokenSeparator) {

    Map<String, String> separators = new HashMap<String, String>();
    separators.put(this.blockSeparator, blockSeparator);
    separators.put(this.tokenSeparator, tokenSeparator);

    Pattern pattern = Pattern.compile("(" + this.blockSeparator + "|" + this.tokenSeparator + ")");
    Matcher matcher = pattern.matcher(this.textEncodedResult);

    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, separators.get(matcher.group(1)));
    }
    int last_index = this.textEncodedResult.lastIndexOf(this.tokenSeparator);
    sb.append(this.textEncodedResult.substring(last_index + 1));
    return sb.toString();
}

From source file:org.dthume.couchdb.maven.ExpandIncludesMojo.java

private String expandIncludeReferences(final String js) throws IOException {
    if (null == js)
        return js;

    final StringBuffer sb = new StringBuffer();

    final Matcher matcher = INCLUDES_PATTERN.matcher(js);
    while (matcher.find()) {
        final String replacement = expandIncludeReferences(readInclude(matcher.group(1)));
        matcher.appendReplacement(sb, replacement);
        sb.append("\n");
    }//w  w  w .j  a v  a2 s  . co m
    matcher.appendTail(sb);

    return sb.toString();
}

From source file:io.hops.hopsworks.api.admin.llap.LlapMonitorProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    // Check if the user is logged in
    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;/*from   w  w w.  j  ava2s . co  m*/
    }

    // Check that the user is an admin
    boolean isAdmin = servletRequest.isUserInRole("HOPS_ADMIN");
    if (!isAdmin) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this application");
        return;
    }

    // The path we will receive is [host]/llapmonitor/llaphost/
    // We need to extract the llaphost to redirect the request
    String[] pathInfoSplits = servletRequest.getPathInfo().split("/");
    String llapHost = pathInfoSplits[1];

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    if (matcher.find()) {
        matcher.appendReplacement(urlBuf, llapHost);
    }

    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    super.service(servletRequest, servletResponse);
}

From source file:com.buaa.cfs.utils.StringUtils.java

/**
 * Matches a template string against a pattern, replaces matched tokens with the supplied replacements, and returns
 * the result.  The regular expression must use a capturing group.  The value of the first capturing group is used
 * to look up the replacement.  If no replacement is found for the token, then it is replaced with the empty
 * string./*from  w  ww . j av a 2s  . co  m*/
 * <p>
 * For example, assume template is "%foo%_%bar%_%baz%", pattern is "%(.*?)%", and replacements contains 2 entries,
 * mapping "foo" to "zoo" and "baz" to "zaz".  The result returned would be "zoo__zaz".
 *
 * @param template     String template to receive replacements
 * @param pattern      Pattern to match for identifying tokens, must use a capturing group
 * @param replacements Map<String, String> mapping tokens identified by the capturing group to their replacement
 *                     values
 *
 * @return String template with replacements
 */
public static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = pattern.matcher(template);
    while (matcher.find()) {
        String replacement = replacements.get(matcher.group(1));
        if (replacement == null) {
            replacement = "";
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:com.dinochiesa.edgecallouts.Base64.java

private String resolvePropertyValue(String spec, MessageContext msgCtxt) {
    Matcher matcher = variableReferencePattern.matcher(spec);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, "");
        sb.append(matcher.group(1));/*from  w w  w.j  a  v a2 s.  c  om*/
        sb.append((String) msgCtxt.getVariable(matcher.group(2)));
        sb.append(matcher.group(3));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:com.impetus.kundera.utils.KunderaCoreUtils.java

/**
 * Resolves variable in path given as string
 * //  www  .ja  v  a  2  s .  com
 * @param input
 *            String input url Code inspired by
 *            :http://stackoverflow.com/questions/2263929/
 *            regarding-application-properties-file-and-environment-variable
 */
public static String resolvePath(String input) {
    if (null == input) {
        return input;
    }

    // matching for 2 groups match ${VAR_NAME} or $VAR_NAME
    Pattern pathPattern = Pattern.compile("\\$\\{(.+?)\\}");
    Matcher matcherPattern = pathPattern.matcher(input); // get a matcher
                                                         // object
    StringBuffer sb = new StringBuffer();
    EnvironmentConfiguration config = new EnvironmentConfiguration();
    SystemConfiguration sysConfig = new SystemConfiguration();

    while (matcherPattern.find()) {

        String confVarName = matcherPattern.group(1) != null ? matcherPattern.group(1)
                : matcherPattern.group(2);
        String envConfVarValue = config.getString(confVarName);
        String sysVarValue = sysConfig.getString(confVarName);

        if (envConfVarValue != null) {

            matcherPattern.appendReplacement(sb, envConfVarValue);

        } else if (sysVarValue != null) {

            matcherPattern.appendReplacement(sb, sysVarValue);

        } else {
            matcherPattern.appendReplacement(sb, "");
        }
    }
    matcherPattern.appendTail(sb);
    return sb.toString();
}

From source file:com.ocpsoft.pretty.faces.config.dynaview.DynaviewEngine.java

/**
 * Given the string value of the Faces Servlet mapping, return a string that is guaranteed to match when a servlet
 * forward is issued. It doesn't matter which FacesServlet we get to, as long as we get to one.
 *//*from  w  w  w  .j  a  v a2  s. co  m*/
public String buildDynaViewId(final String facesServletMapping) {
    StringBuffer result = new StringBuffer();

    Map<Pattern, String> patterns = new HashMap<Pattern, String>();

    Pattern pathMapping = Pattern.compile("^(/.*/)\\*$");
    Pattern extensionMapping = Pattern.compile("^\\*(\\..*)$");
    Pattern defaultMapping = Pattern.compile("^/$");

    patterns.put(pathMapping, "$1" + DYNAVIEW + ".jsf");
    patterns.put(extensionMapping, "/" + DYNAVIEW + "$1");
    patterns.put(defaultMapping, "/" + DYNAVIEW + ".jsf");

    boolean matched = false;
    Iterator<Pattern> iterator = patterns.keySet().iterator();
    while ((matched == false) && iterator.hasNext()) {
        Pattern p = iterator.next();
        Matcher m = p.matcher(facesServletMapping);
        if (m.matches()) {
            String replacement = patterns.get(p);
            m.appendReplacement(result, replacement);
            matched = true;
        }
    }

    if (matched == false) {
        // This is an exact url-mapping, use it.
        result.append(facesServletMapping);
    }

    return result.toString();
}

From source file:it.tidalwave.northernwind.core.impl.filter.MacroFilter.java

@Override
@Nonnull/* w ww .j a  v  a  2 s .com*/
public String filter(final @Nonnull String text, final @Nonnull String mimeType) {
    final Matcher matcher = pattern.matcher(text);
    final StringBuffer buffer = new StringBuffer();

    while (matcher.find()) {
        final String filtered = doFilter(matcher);
        try {
            matcher.appendReplacement(buffer, filtered);
        } catch (IllegalArgumentException e) // better diagnostics
        {
            throw new IllegalArgumentException(
                    String.format("Pattern error: %s regexp: %s%n**** filtered: %s%n**** buffer: %s",
                            e.getMessage(), pattern.pattern(), filtered, buffer));
        }
    }

    matcher.appendTail(buffer);

    return buffer.toString();
}

From source file:nl.ivonet.epub.strategy.epub.DitigalWatermarkRemovalStrategy.java

/**
 * removes watermark from a simple page.
 *///from  ww  w. j  a  v a 2s.  c  o  m
private String removeWatermark1(final String html) {
    final Matcher matcher = WATERMARK_PAT.matcher(html);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        LOG.debug("Watermark = " + matcher.group());
        matcher.appendReplacement(sb, ">" + WAS_WATERMARK + "</p>");
    }
    matcher.appendTail(sb);
    return sb.toString();
}