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:org.opennms.netmgt.dao.support.DefaultResourceDao.java

/**
 * Fetch a specific resource by string ID.
 *
 * @return Resource or null if resource cannot be found.
 * @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
 * @throws ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
 *//*from  ww  w .j  av  a 2  s.  c o m*/
@Override
@Transactional(readOnly = true)
public OnmsResource getResourceById(String id) {
    OnmsResource resource = null;

    Matcher m = RESOURCE_ID_PATTERN.matcher(id);
    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        String resourceTypeName = DefaultResourceDao.decode(m.group(1));
        String resourceName = DefaultResourceDao.decode(m.group(2));

        try {
            resource = getChildResource(resource, resourceTypeName, resourceName);
        } catch (Throwable e) {
            LOG.warn("Could not get resource for resource ID \"{}\"", id, e);
            return null;
        }

        m.appendReplacement(sb, "");
    }

    m.appendTail(sb);

    if (sb.length() > 0) {
        LOG.warn("Resource ID '{}' does not match pattern '{}' at '{}'", id, RESOURCE_ID_PATTERN, sb);
        return null;
    } else {
        return resource;
    }
}

From source file:models.GroupSerializer.java

protected String parseReferencesInComment(Group group) {
    CarbonOntology ontology = CarbonOntology.getInstance();
    Pattern p = Pattern.compile("\\{[^}]*\\}");
    Matcher m = p.matcher(group.getComment());
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String refId = m.group().substring(1, m.group().length() - 1);
        try {/*from   w w w .j a v  a 2 s  .c  om*/
            Reference ref = ontology.getReference(refId);
            if (!group.getReferences().contains(ref)) {
                log.warn("The reference " + ref.getId() + " in the group " + group.getId()
                        + "comment is not in the group reference list");
            }
            m.appendReplacement(sb, "[" + ref.getShortName() + "]");
        } catch (NotFoundException e) {
            log.warn("Unable to replace a reference in the group " + group.getId() + " comment: "
                    + e.getMessage());
            m.appendReplacement(sb, "[" + refId + "]");
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:PropertiesHelper.java

/**
 * Adds new properties to an existing set of properties while
 * substituting variables. This function will allow value
 * substitutions based on other property values. Value substitutions
 * may not be nested. A value substitution will be ${property.key},
 * where the dollar-brace and close-brace are being stripped before
 * looking up the value to replace it with. Note that the ${..}
 * combination must be escaped from the shell.
 *
 * @param b is the set of properties to add to existing properties.
 * @return the combined set of properties.
 *//*from  w  w w. ja v  a2s.c  o m*/
protected Properties addProperties(Properties b) {
    // initial
    // Properties result = new Properties(this);
    Properties sys = System.getProperties();
    Pattern pattern = Pattern.compile("\\$\\{[-a-zA-Z0-9._]+\\}");

    for (Enumeration e = b.propertyNames(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        String value = b.getProperty(key);

        // unparse value ${prop.key} inside braces
        Matcher matcher = pattern.matcher(value);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            // extract name of properties from braces
            String newKey = value.substring(matcher.start() + 2, matcher.end() - 1);

            // try to find a matching value in result properties
            String newVal = getProperty(newKey);

            // if still not found, try system properties
            if (newVal == null) {
                newVal = sys.getProperty(newKey);
            }

            // replace braced string with the actual value or empty string
            matcher.appendReplacement(sb, newVal == null ? "" : newVal);
        }
        matcher.appendTail(sb);
        setProperty(key, sb.toString());
    }
    return this;
}

From source file:org.nuxeo.launcher.commons.text.TextTemplate.java

public Properties preprocessVars(Properties unprocessedVars) {
    Properties newVars = new Properties(unprocessedVars);
    boolean doneProcessing = false;
    int recursionLevel = 0;
    while (!doneProcessing) {
        doneProcessing = true;//ww w .j  a  v  a 2 s.c o  m
        @SuppressWarnings("rawtypes")
        Enumeration newVarsEnum = newVars.propertyNames();
        while (newVarsEnum.hasMoreElements()) {
            String newVarsKey = (String) newVarsEnum.nextElement();
            String newVarsValue = newVars.getProperty(newVarsKey);
            Matcher m = PATTERN.matcher(newVarsValue);
            StringBuffer sb = new StringBuffer();
            while (m.find()) {
                String embeddedVar = m.group(1);
                String value = newVars.getProperty(embeddedVar);
                if (value != null) {
                    if (trim) {
                        value = value.trim();
                    }
                    String escapedValue = Matcher.quoteReplacement(value);
                    m.appendReplacement(sb, escapedValue);
                }
            }
            m.appendTail(sb);
            String replacementValue = sb.toString();
            if (!replacementValue.equals(newVarsValue)) {
                doneProcessing = false;
                newVars.put(newVarsKey, replacementValue);
            }
        }
        recursionLevel++;
        // Avoid infinite replacement loops
        if ((!doneProcessing) && (recursionLevel > MAX_RECURSION_LEVEL)) {
            break;
        }
    }
    return unescape(newVars);
}

From source file:fr.smile.liferay.LiferayUrlRewriter.java

/**
 * Fix all resources urls and return the result.
 *
 * @param input        The original charSequence to be processed.
 * @param requestUrl   The request URL./* ww w  .  j a v  a2s  .  co  m*/
 * @param baseUrlParam The base URL selected for this request.
 * @return the result of this renderer.
 */
public CharSequence rewriteHtml(CharSequence input, String requestUrl, Pattern pattern, String baseUrlParam,
        String visibleBaseUrl) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("input=" + input);
        LOG.debug("rewriteHtml (requestUrl=" + requestUrl + ", pattern=" + pattern + ",baseUrlParam)"
                + baseUrlParam + ",strVisibleBaseUrl=" + visibleBaseUrl + ")");
    }

    StringBuffer result = new StringBuffer(input.length());
    Matcher m = pattern.matcher(input);
    while (m.find()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("found match: " + m);
        }
        String url = input.subSequence(m.start(3) + 1, m.end(3) - 1).toString();
        url = rewriteUrl(url, requestUrl, baseUrlParam, visibleBaseUrl);
        url = url.replaceAll("\\$", "\\\\\\$"); // replace '$' -> '\$' as it
        // denotes group
        StringBuffer tagReplacement = new StringBuffer("<$1$2=\"").append(url).append("\"");
        if (m.groupCount() > 3) {
            tagReplacement.append("$4");
        }
        tagReplacement.append('>');
        if (LOG.isTraceEnabled()) {
            LOG.trace("replacement: " + tagReplacement);
        }
        m.appendReplacement(result, tagReplacement.toString());
    }
    m.appendTail(result);

    return result;
}

From source file:net.sf.j2ep.UrlRewritingOutputStream.java

/**
 * Processes the stream looking for links, all links found are rewritten.
 * After this the stream is written to the response.
 * //from ww  w  . jav a  2  s.  com
 * @param server
 *            The server that we are using for this request.
 * @throws IOException
 *             Is thrown when there is a problem with the streams
 */
public void rewrite(Server server) throws IOException {
    /*
     * Using regex can be quite harsh sometimes so here is how the regex
     * trying to find links works
     * 
     * \\b(href=|src=|action=|url\\()([\"\']) This part is the
     * identification of links, matching something like href=", href=' and
     * href=
     * 
     * (([^/]+://)([^/<>]+))? This is to identify absolute paths. A link
     * doesn't have to be absolute therefor there is a ?.
     * 
     * ([^\"\'>]*) This is the link
     * 
     * [\"\'] Ending " or '
     * 
     * $1 - link type, e.g. href= $2 - ", ' or whitespace $3 - The entire
     * http://www.server.com if present $4 - The protocol, e.g http:// or
     * ftp:// $5 - The host name, e.g. www.server.com $6 - The link
     */
    StringBuffer page = new StringBuffer();

    Matcher matcher = linkPattern.matcher(stream.toString());

    while (matcher.find()) {

        String link = matcher.group(6).replaceAll("\\$", "\\\\\\$");
        if (link.length() == 0) {
            link = "/";
        }

        String rewritten = null;
        if (matcher.group(4) != null) {
            rewritten = handleExternalLink(matcher, link);
        } else if (link.startsWith("/")) {
            rewritten = handleLocalLink(server, matcher, link);
        }

        if (rewritten != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found link " + link + " >> " + rewritten);
            }
            matcher.appendReplacement(page, rewritten);
        }
    }

    matcher.appendTail(page);
    originalStream.write(stream.toByteArray());
}

From source file:org.apache.bval.jsr.DefaultMessageInterpolator.java

private String replaceAnnotationAttributes(final String message,
        final Map<String, Object> annotationParameters) {
    Matcher matcher = messageParameterPattern.matcher(message);
    StringBuffer sb = new StringBuffer(64);
    while (matcher.find()) {
        String resolvedParameterValue;
        String parameter = matcher.group(1);
        Object variable = annotationParameters.get(removeCurlyBrace(parameter));
        if (variable != null) {
            if (variable.getClass().isArray()) {
                resolvedParameterValue = ArrayUtils.toString(variable);
            } else {
                resolvedParameterValue = variable.toString();
            }/*from w w w .ja  va2  s  . c  o m*/
        } else {
            resolvedParameterValue = parameter;
        }
        matcher.appendReplacement(sb, sanitizeForAppendReplacement(resolvedParameterValue));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.pentaho.osgi.platform.webjars.utils.RequireJsGenerator.java

private void requirejsFromJs(String moduleName, String moduleVersion, String jsScript)
        throws IOException, ScriptException, NoSuchMethodException, ParseException {
    moduleInfo = new ModuleInfo(moduleName, moduleVersion);

    Pattern pat = Pattern.compile("webjars!(.*).js");
    Matcher m = pat.matcher(jsScript);

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, m.group(1));
    }/*from  ww  w. j  a  v  a 2 s  .c o m*/
    m.appendTail(sb);

    jsScript = sb.toString();

    sb = new StringBuffer();

    pat = Pattern.compile("webjars\\.path\\(['\"]{1}(.*)['\"]{1}, (['\"]{0,1}[^\\)]+['\"]{0,1})\\)");
    m = pat.matcher(jsScript);
    while (m.find()) {
        m.appendReplacement(sb, m.group(2));
    }
    m.appendTail(sb);

    jsScript = sb.toString();

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    String script = IOUtils.toString(
            getClass().getResourceAsStream("/org/pentaho/osgi/platform/webjars/require-js-aggregator.js"));
    script = script.replace("{{EXTERNAL_CONFIG}}", jsScript);

    engine.eval(script);

    requireConfig = (Map<String, Object>) parser
            .parse(((Invocable) engine).invokeFunction("processConfig", "").toString());
}

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

private String replaceIncludes(final String template) {
    if (template == null) {
        return null;
    }/*from ww  w .  ja  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 = configurationService.getResourceContentAsString(filename);
            String content = (String) res[0];
            if (content != null) {
                content = replaceIncludes(content).replaceAll("\\\\", "#HURZ1#").replaceAll("\\$", "#HURZ2#");
                m.appendReplacement(buf, content); // Doesn't work with '$' or '\' in content
            } else {
                m.appendReplacement(buf, "*** " + filename + " not found! ***");
            }
        }
    }
    m.appendTail(buf);
    return buf.toString();
}

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

private String replaceUserReference(String statusText) {
    Pattern p = Pattern.compile("@[a-zA-Z0-9_]+");
    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 linkId = StringUtils.stripStart(m.group(), "@");
        m.appendReplacement(buf,/*from w w  w  . jav a2  s  .  com*/
                String.format("<a target=\"_blank\" href=\"http://twitter.com/%s\">%s</a>", linkId, m.group()));
    }
    m.appendTail(buf);
    return buf.toString();
}