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:com.brienwheeler.lib.validation.MessageSourceMessageInterpolator.java

@Override
public String interpolate(String messageTemplate, Context context, Locale locale) {
    String resolvedMessage = messageSource.getMessage(messageTemplate, null, locale);

    // replaceVariables
    Matcher matcher = messageParameterPattern.matcher(resolvedMessage);
    StringBuffer sb = new StringBuffer();
    String resolvedParameterValue;
    while (matcher.find()) {
        String parameterValue = removeCurlyBraces(matcher.group(1));

        // first check the annotation constraints
        Object constraintValue = context.getConstraintDescriptor().getAttributes().get(parameterValue);
        if (constraintValue != null)
            parameterValue = constraintValue.toString();

        // recurse back to MessageSource to find replacement value 
        resolvedParameterValue = interpolate(parameterValue, context, locale);
        matcher.appendReplacement(sb, escapeMetaCharacters(resolvedParameterValue));
    }//  ww w.ja va 2s. co  m
    matcher.appendTail(sb);
    resolvedMessage = sb.toString();

    // last but not least we have to take care of escaped literals
    resolvedMessage = resolvedMessage.replace("\\{", "{");
    resolvedMessage = resolvedMessage.replace("\\}", "}");
    resolvedMessage = resolvedMessage.replace("\\\\", "\\");
    return resolvedMessage;
}

From source file:org.projectforge.scripting.GroovyEngine.java

private String replaceIncludes(final String template) {
    if (template == null) {
        return null;
    }/*  w  ww  . j  a v a  2  s  .  c o m*/
    final Pattern p = Pattern.compile("#INCLUDE\\{([0-9\\.a-zA-Z/]*)\\}", Pattern.MULTILINE);
    final StringBuffer buf = new StringBuffer();
    final Matcher m = p.matcher(template);
    while (m.find()) {
        if (m.group(1) != null) {
            final String filename = m.group(1);
            final Object[] res = ConfigXml.getInstance().getContent(filename);
            String content = (String) res[0];
            if (content != null) {
                content = replaceIncludes(content).replaceAll("\\$", "#HURZ#");
                m.appendReplacement(buf, content); // Doesn't work with $ in content
            } else {
                m.appendReplacement(buf, "*** " + filename + " not found! ***");
            }
        }
    }
    m.appendTail(buf);
    return buf.toString();
}

From source file:com.google.code.simplestuff.bean.SimpleBeanTest.java

/**
 * Utility method for replace a pattern in a String.
 * /* w  ww . j  av  a 2  s  . c  om*/
 * @param source the source string.
 * @param pattern the pattern to match.
 * @param replacement The replacement.
 * @return the result string.
 */
private String replacePattern(String source, String pattern, String replacement) {
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(source);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, replacement);
    }
    m.appendTail(sb);

    return sb.toString();
}

From source file:org.ops4j.pax.scanner.file.internal.FileScanner.java

/**
 * Reads the bundles from the file specified by the urlSpec.
 * {@inheritDoc}//w  w  w .  ja  va 2s  .  co m
 */
public List<ScannedBundle> scan(final ProvisionSpec provisionSpec)
        throws MalformedSpecificationException, ScannerException {
    NullArgumentException.validateNotNull(provisionSpec, "Provision spec");

    LOGGER.debug("Scanning [" + provisionSpec.getPath() + "]");
    List<ScannedBundle> scannedBundles = new ArrayList<ScannedBundle>();
    ScannerConfiguration config = createConfiguration();
    BufferedReader bufferedReader = null;
    try {
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(
                    URLUtils.prepareInputStream(provisionSpec.getPathAsUrl(), !config.getCertificateCheck())));
            Integer defaultStartLevel = getDefaultStartLevel(provisionSpec, config);
            Boolean defaultStart = getDefaultStart(provisionSpec, config);
            Boolean defaultUpdate = getDefaultUpdate(provisionSpec, config);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String trimmedLine = line.trim();
                if (trimmedLine.length() > 0 && !trimmedLine.startsWith(COMMENT_SIGN)) {
                    if (trimmedLine.startsWith(PROPERTY_PREFIX)) {
                        Matcher matcher = PROPERTY_PATTERN.matcher(trimmedLine);
                        if (!matcher.matches() || matcher.groupCount() != 2) {
                            throw new ScannerException("Invalid property: " + line);
                        }
                        String key = matcher.group(1);
                        String value = matcher.group(2);
                        StringBuffer stringBuffer = new StringBuffer(value.length());
                        for (matcher = QUOTED_PROPERTY_VALUE_PATTERN.matcher(value); matcher.find(); matcher
                                .appendReplacement(stringBuffer, value)) {
                            String group = matcher.group();
                            value = group.substring(1, group.length() - 1).replace("\\\"", "\"").replace("$",
                                    "\\$");
                        }
                        int index = stringBuffer.length();
                        matcher.appendTail(stringBuffer);
                        if (index < stringBuffer.length() && !(stringBuffer.indexOf(" ", index) < 0
                                && stringBuffer.indexOf("\"", index) < 0)) {
                            throw new ScannerException("Invalid property: " + line);
                        }
                        value = SystemPropertyUtils.resolvePlaceholders(stringBuffer.toString());
                        System.setProperty(key, value);
                    } else {
                        line = SystemPropertyUtils.resolvePlaceholders(line);
                        final ScannedFileBundle scannedFileBundle = new ScannedFileBundle(line,
                                defaultStartLevel, defaultStart, defaultUpdate);
                        scannedBundles.add(scannedFileBundle);
                        LOGGER.debug("Installing bundle [" + scannedFileBundle + "]");
                    }
                }
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
    } catch (IOException e) {
        throw new ScannerException("Could not parse the provision file", e);
    }
    return scannedBundles;
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

static String performStaticInclude(String includePatternString, String input) {
    String result = input;//w w w  . j  ava2  s . c  o  m
    boolean matchFound = true;

    Pattern staticIncludePattern = Pattern.compile(includePatternString);
    StringBuffer staticIncludeBuf;

    while (matchFound) {
        matchFound = false;
        staticIncludeBuf = new StringBuffer();
        Matcher staticIncludeMatcher = staticIncludePattern.matcher(result);
        while (staticIncludeMatcher.find()) {
            matchFound = true;
            String args = staticIncludeMatcher.group(1);
            try {
                if (!args.startsWith("/")) {
                    String servletPath = FacesContext.getCurrentInstance().getExternalContext()
                            .getRequestServletPath();
                    String workingDir = servletPath.substring(0, servletPath.lastIndexOf("/"));
                    args = workingDir + "/" + args;
                }
                String includeString = getInputAsString(new InputStreamReader(FacesContext.getCurrentInstance()
                        .getExternalContext().getResource(args).openConnection().getInputStream()));
                //Strip xml declarations from included files
                Pattern xmlDeclPattern = Pattern.compile(XML_DECL_PATTERN);
                Matcher xmlDeclMatcher = xmlDeclPattern.matcher(includeString);
                includeString = xmlDeclMatcher.replaceAll("");

                staticIncludeMatcher.appendReplacement(staticIncludeBuf, escapeBackreference(includeString));
            } catch (Exception e) {
                //an error occurred, just remove the include
                staticIncludeMatcher.appendReplacement(staticIncludeBuf, "");
                if (log.isErrorEnabled()) {
                    log.error("static include failed to include " + args, e);
                }
            }
        }
        staticIncludeMatcher.appendTail(staticIncludeBuf);
        result = staticIncludeBuf.toString();
    }
    return result;
}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * Decodes percent-encoded unreserved characters.<p>
 * <code>http://www.example.com/%7Eusername/ &rarr;
 *       http://www.example.com/~username/</code>
 * @return this instance//from   ww  w.j  ava 2s. c o m
 */
public URLNormalizer decodeUnreservedCharacters() {
    if (url.contains("%")) {
        StringBuffer sb = new StringBuffer();
        Matcher m = PATTERN_PERCENT_ENCODED_CHAR.matcher(url);
        try {
            while (m.find()) {
                String enc = m.group(1).toUpperCase();
                if (isEncodedUnreservedCharacter(enc)) {
                    m.appendReplacement(sb, URLDecoder.decode(enc, CharEncoding.UTF_8));
                }
            }
        } catch (UnsupportedEncodingException e) {
            LOG.debug("UTF-8 is not supported by your system. " + "URL will remain unchanged:" + url, e);
        }
        url = m.appendTail(sb).toString();
    }
    return this;
}

From source file:org.kuali.kfs.coa.batch.dataaccess.impl.AccountingPeriodFiscalYearMakerImpl.java

/**
 * this routine is provided to update string fields which contain two-digit years that need to be updated for display. it is
 * very specific, but it's necessary. "two-digit year" means the two numeric characters preceded by a non-numeric character.
 * //from   w w w  .  ja  v a2  s. c o  m
 * @param newYear
 * @param oldYear
 * @param currentString
 * @return the updated string for a two digit year
 */
protected String updateTwoDigitYear(String newYear, String oldYear, String currentString) {
    // group 1 is the bounded by the outermost set of parentheses
    // group 2 is the first inner set
    // group 3 is the second inner set--a two-digit year at the beginning of the line
    String regExpString = "(([^0-9]{1}" + oldYear + ")|^(" + oldYear + "))";
    Pattern pattern = Pattern.compile(regExpString);
    Matcher matcher = pattern.matcher(currentString);

    // start looking for a match
    boolean matched = matcher.find();
    if (!matched) {
        // just return if nothing is found
        return currentString;
    }

    // we found something
    // we have to process it
    String returnString = currentString;
    StringBuffer outString = new StringBuffer();
    // is there a match at the beginning of the line (a match with group 3)?
    if (matcher.group(3) != null) {
        // there is a two-digit-year string at the beginning of the line
        // we want to replace it
        matcher.appendReplacement(outString, newYear);
        // find the next match if there is one
        matched = matcher.find();
    }

    while (matched) {
        // the new string will no longer match with group 3
        // if there is still a match, it will be with group 2
        // now we have to prefix the new year string with the same
        // non-numeric character as the next match (hyphen, space, whatever)
        String newYearString = matcher.group(2).substring(0, 1) + newYear;
        matcher.appendReplacement(outString, newYearString);
        matched = matcher.find();
    }

    // dump whatever detritus is left into the new string
    matcher.appendTail(outString);

    return outString.toString();
}

From source file:com.haulmont.cuba.gui.data.impl.AbstractCollectionDatasource.java

protected String getJPQLQuery(Map<String, Object> parameterValues) {
    String query;// w w w. j  a  v a  2  s .co m
    if (filter == null)
        query = this.query;
    else
        query = filter.processQuery(this.query, parameterValues);

    for (ParameterInfo info : queryParameters) {
        final String paramName = info.getName();
        final String jpaParamName = info.getFlatName();

        Pattern p = Pattern.compile(paramName.replace("$", "\\$") + "([^\\.]|$)"); // not ending with "."
        Matcher m = p.matcher(query);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, jpaParamName + "$1");
        }
        m.appendTail(sb);
        query = sb.toString();

        Object value = parameterValues.get(paramName);
        if (value != null) {
            parameterValues.put(jpaParamName, value);
        }
    }
    query = query.replace(":" + ParametersHelper.CASE_INSENSITIVE_MARKER, ":");

    query = TemplateHelper.processTemplate(query, parameterValues);

    return query;
}

From source file:com.krawler.common.util.StringUtil.java

public static String serverHTMLStripperWithoutQuoteReplacement(String stripTags)
        throws IllegalStateException, IndexOutOfBoundsException {
    Pattern p = Pattern.compile("<[^>]*>");
    Matcher m = p.matcher(stripTags);
    StringBuffer sb = new StringBuffer();
    if (!isNullOrEmpty(stripTags)) {
        while (m.find()) {
            m.appendReplacement(sb, "");
        }/*  www .j  ava 2  s .c  o m*/
        m.appendTail(sb);
        stripTags = sb.toString();
        stripTags = stripTags.replaceAll("\r", "<br/>");
        stripTags = stripTags.replaceAll("\n", " ");
        stripTags = stripTags.replaceAll("&nbsp;", " ");
    }
    return stripTags.trim();
}

From source file:com.yangtsaosoftware.pebblemessenger.services.MessageProcessingService.java

private String process_RTL_ASCStr(String ascStr) {
    Constants.log(TAG_NAME, "set msg:[" + ascStr + "]");
    String[] stringLines = ascStr.split("\n");
    StringBuilder sbResult = new StringBuilder();
    Pattern p = Pattern.compile("\\w+");
    for (String oneStr : stringLines) {
        oneStr = reverseString(reformString(oneStr, fChars));
        StringBuffer oneResult = new StringBuffer();
        Constants.log(TAG_NAME, "oneStr before:[" + oneStr + "]");
        Matcher m = p.matcher(oneStr);
        while (m.find()) {
            m.appendReplacement(oneResult, reverseString(m.group()));
        }//from w  ww  .  j  a  v a2 s. co  m
        Constants.log(TAG_NAME, "oneStr after:[" + oneResult.toString() + "]");
        sbResult.append(oneResult);
        sbResult.append('\n');
    }
    return sbResult.toString();
}