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:it.tidalwave.northernwind.core.model.spi.ParameterLanguageOverrideLinkPostProcessor.java

/*******************************************************************************************************************
 *
 * {@inheritDoc}//from   w  w w.j av  a  2  s.c  o  m
 *
 ******************************************************************************************************************/
@Nonnull
public String postProcess(final @Nonnull String link, final @Nonnull String parameterValue) {
    final String parameterName = parameterLanguageOverrideRequestProcessor.getParameterName();
    final String regexp = "([\\?&])(" + parameterName + "=[a-z,0-9]*)";

    final Matcher matcher = Pattern.compile(regexp).matcher(link);

    if (matcher.find()) // replace a parameter already present
    {
        final StringBuffer buffer = new StringBuffer();
        matcher.appendReplacement(buffer, matcher.group(1) + parameterName + "=" + parameterValue);
        matcher.appendTail(buffer);

        return buffer.toString();
    }

    final StringBuilder builder = new StringBuilder(link);

    if (link.contains("?")) {
        builder.append("&");
    } else {
        if (!builder.toString().endsWith("/") && !builder.toString().contains(".")) // FIXME: check . only in trailing
        {
            builder.append("/");
        }

        builder.append("?");
    }

    builder.append(parameterName).append("=").append(parameterValue);

    return builder.toString();
}

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

/**
 * Removes watermarks from title attributes and replaces some strings
 *///from   w ww.  j av a 2s  .co  m
private String removeWatermark2(final String html) {
    final Matcher matcher = WATERMARK_PAT_2.matcher(html);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        LOG.debug("Watermark = [{}]", matcher.group());
        matcher.appendReplacement(sb, "title=\"Possible watermark removed\""); //you can put any text here
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:info.magnolia.link.LinkUtil.java

/**
 * Converts provided html with links in UUID pattern format to any other kind of links based on provided link transformer.
 * @param str Html with UUID links//from ww  w.  j a  v  a 2  s  .com
 * @param transformer Link transformer
 * @return converted html with links as created by provided transformer.
 * @see LinkTransformerManager
 */
public static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer) throws LinkException {
    Matcher matcher = UUID_PATTERN.matcher(str);
    StringBuffer res = new StringBuffer();
    while (matcher.find()) {
        Link link = createLinkInstance(matcher.group(1), matcher.group(2), matcher.group(5), matcher.group(7),
                matcher.group(8), matcher.group(10), matcher.group(12));
        String replacement = transformer.transform(link);
        // Replace "\" with "\\" and "$" with "\$" since Matcher.appendReplacement treats these characters specially
        replacement = StringUtils.replace(replacement, "\\", "\\\\");
        replacement = StringUtils.replace(replacement, "$", "\\$");
        matcher.appendReplacement(res, replacement);
    }
    matcher.appendTail(res);
    return res.toString();
}

From source file:org.pentaho.cdf.context.autoinclude.DashboardMatchRule.java

private Pattern replaceTokens(Matcher cdaMatcher, String regex) {
    // replace $1 for group 1 in regex etc
    Matcher token = REPLACE_TOKEN.matcher(regex);
    StringBuffer sb = new StringBuffer();
    while (token.find()) {
        int group = Integer.parseInt(token.group(1));
        if (group < cdaMatcher.groupCount()) {
            token.appendReplacement(sb, Matcher.quoteReplacement(Pattern.quote(cdaMatcher.group(group))));
        } else {//from w  w  w  . j av a  2 s . c  om
            log.error(String.format("Error processing rule '%s', group %d does not exist.", regex, group));
        }
    }
    token.appendTail(sb);
    return Pattern.compile(sb.toString());
}

From source file:com.github.jramos.snowplow.RedshiftSink.java

private String resolveEnvVars(String input) {
    if (null == input) {
        return null;
    }//ww w  .  ja v a  2s  .  c  o m
    Pattern p = Pattern.compile("\\$\\{(\\w+)\\}|\\$(\\w+)"); // match ${ENV_VAR_NAME} or $ENV_VAR_NAME
    Matcher m = p.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String envVarName = null == m.group(1) ? m.group(2) : m.group(1);
        String envVarValue = System.getenv(envVarName);
        m.appendReplacement(sb, null == envVarValue ? "" : envVarValue);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:cc.aileron.workflow.util.WorkflowUriTemplate.java

/**
 * @param accessor//  w ww . j  ava2  s.com
 * @return ????
 * @throws PojoPropertiesNotFoundException
 * @throws PojoAccessorValueNotFoundException
 */
public String replace(final PojoAccessor<?> accessor)
        throws PojoAccessorValueNotFoundException, PojoPropertiesNotFoundException {
    final Matcher matcher = pattern.matcher(uriTemplate);
    final StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        final String key = matcher.group(1);
        final String val = accessor.to(key).value(String.class);
        matcher.appendReplacement(buffer, val != null ? val : "");
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:org.opencms.search.galleries.CmsGalleryNameMacroResolver.java

/**
 * @see org.opencms.util.CmsMacroResolver#resolveMacros(java.lang.String)
 *//*from  w  w  w  . j a  va 2 s .  com*/
@Override
public String resolveMacros(String input) {

    // We are overriding this method to implement the no_prefix macro. This is because
    // we only know what the no_prefix macro should expand to after resolving all other
    // macros (there could be an arbitrary number of macros before it which might potentially
    // all expand to the empty string).
    String result = super.resolveMacros(input);
    Matcher matcher = NO_PREFIX_PATTERN.matcher(result);
    if (matcher.find()) {
        StringBuffer resultBuffer = new StringBuffer();
        matcher.appendReplacement(resultBuffer,
                matcher.start() == 0 ? "" : result.substring(matcher.start(1), matcher.end(1)));
        matcher.appendTail(resultBuffer);
        result = resultBuffer.toString();
    }
    return result;
}

From source file:com.gh4a.utils.HtmlUtils.java

/**
 * Rewrite relative URLs in HTML fetched e.g. from markdown files.
 *
 * @param html//from w ww . ja v a2s.c om
 * @param repoUser
 * @param repoName
 * @param branch
 * @return
 */
public static String rewriteRelativeUrls(final String html, final String repoUser, final String repoName,
        final String branch) {
    final String baseUrl = "https://raw.github.com/" + repoUser + "/" + repoName + "/" + branch;
    final StringBuffer sb = new StringBuffer();
    final Pattern p = Pattern.compile("(href|src)=\"(\\S+)\"");
    final Matcher m = p.matcher(html);

    while (m.find()) {
        String url = m.group(2);
        if (!url.contains("://") && !url.startsWith("#")) {
            if (url.startsWith("/")) {
                url = baseUrl + url;
            } else {
                url = baseUrl + "/" + url;
            }
        }
        m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + url + "\""));
    }
    m.appendTail(sb);

    return sb.toString();
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseQueryHandler.java

/**
 * Returns an HQL query without the fetch part
 *///from ww  w .  ja va2s  .c o m
private static String stripFetch(String hql) {
    // This is done so we don't confuse the matcher, i.e.: from X x left join fetch x.a *left* join fetch ... -> that *left* could be an alias
    hql = hql.replaceAll("left join", "^left join");

    Matcher matcher = LEFT_JOIN_FETCH.matcher(hql);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String path = StringUtils.trimToEmpty(matcher.group(1));
        String alias = StringUtils.trimToEmpty(matcher.group(2));
        boolean nextIsLeft = "left".equalsIgnoreCase(alias);
        boolean safeToRemove = alias.isEmpty() || nextIsLeft || "where".equalsIgnoreCase(alias)
                || "order".equalsIgnoreCase(alias) || "group".equalsIgnoreCase(alias);
        String replacement;
        if (safeToRemove) {
            // No alias - we can just remove the entire left join fetch
            replacement = nextIsLeft ? "" : " " + alias;
        } else {
            // Just remove the 'fetch'
            replacement = " left join " + path + " " + alias;
        }
        matcher.appendReplacement(sb, replacement);
    }
    matcher.appendTail(sb);
    return sb.toString().replaceAll("\\^left join", "left join");
}

From source file:com.yukthitech.persistence.NativeQueryFactory.java

/**
 * Fetches the query template with specified "name" and builds the query using specified "context".
 * If the query uses "param" directive, corresponding values will be collected into "paramValues".
 * //from w  ww  .  j  a va  2  s  . c om
 * @param name Name of the query to be fetched
 * @param outputParamValues Collected param values that needs to be passed to query as prepared statement params
 * @param context Context to be used to parse template into query
 * @return Built query
 */
public String buildQuery(String name, List<Object> outputParamValues, Object context) {
    String rawQuery = queryMap.get(name);

    //if no query found with specified name
    if (rawQuery == null) {
        throw new InvalidArgumentException("No query found with specified name - {}", name);
    }

    try {
        //build the final query (replacing the param expressions)
        String query = freeMarkerEngine.processTemplate(name, rawQuery, context);
        StringBuffer finalQuery = new StringBuffer();
        Matcher matcher = QUERY_PARAM_PATTERN.matcher(query);
        String property = null;

        while (matcher.find()) {
            property = matcher.group(1);
            matcher.appendReplacement(finalQuery, "?");

            outputParamValues.add(PropertyUtils.getProperty(context, property));
        }

        matcher.appendTail(finalQuery);

        return finalQuery.toString();
    } catch (Exception ex) {
        throw new InvalidStateException(ex, "An exception occurred while building query: " + name);
    }
}