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:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param input//  ww  w.j  a v a  2 s .  c o m
 * @return String
 */
public static String transform(String input) {
    String result = input;

    Pattern jspDeclarationPattern = Pattern.compile(JSP_DECL_PATTERN, Pattern.DOTALL);
    Matcher jspDeclarationMatcher = jspDeclarationPattern.matcher(result);
    if (!jspDeclarationMatcher.find()) {
        //no JSP declarations, must be a JSP Document, not a page
        return (preprocessJspDocument(result));
    }

    result = performStaticInclude(STATIC_INCLUDE_PATTERN, input);

    result = toLowerHTML(result);

    Pattern jspTaglibPattern = Pattern.compile(JSP_TAGLIB_PATTERN, Pattern.DOTALL);
    Pattern openTagPattern = Pattern.compile(OPEN_TAG_PATTERN, Pattern.DOTALL);
    Pattern attributePattern = Pattern.compile(ATTRIBUTE_PATTERN, Pattern.DOTALL);
    Pattern prefixPattern = Pattern.compile(PREFIX_PATTERN, Pattern.DOTALL);
    Pattern uriPattern = Pattern.compile(URI_PATTERN, Pattern.DOTALL);

    Hashtable declarationsTable = new Hashtable();
    Matcher jspTaglibMatcher = jspTaglibPattern.matcher(result);
    declarationsTable.put("xmlns:jsp", "jsp");
    declarationsTable.put("xmlns:icefaces", "http://www.icesoft.com/icefaces");

    while (jspTaglibMatcher.find()) {
        String attributes = jspTaglibMatcher.group(1);
        Matcher prefixMatcher = prefixPattern.matcher(attributes);
        Matcher uriMatcher = uriPattern.matcher(attributes);
        prefixMatcher.find();
        uriMatcher.find();
        String prefix = prefixMatcher.group(1);
        String url = uriMatcher.group(1);
        declarationsTable.put("xmlns:" + prefix, url);
    }

    Matcher openTagMatcher = openTagPattern.matcher(result);
    openTagMatcher.find();
    String tag = openTagMatcher.group(1);
    String attributes = openTagMatcher.group(2);

    Matcher attributeMatcher = attributePattern.matcher(attributes);
    while (attributeMatcher.find()) {
        String name = attributeMatcher.group(1);
        String value = attributeMatcher.group(2);
        declarationsTable.put(name, value);
    }

    Enumeration declarations = declarationsTable.keys();
    String namespaceDeclarations = "";
    while (declarations.hasMoreElements()) {
        String prefix = (String) declarations.nextElement();
        String url = (String) declarationsTable.get(prefix);
        namespaceDeclarations += prefix + "=\"" + url + "\" ";
    }

    jspDeclarationMatcher = jspDeclarationPattern.matcher(result);
    result = jspDeclarationMatcher.replaceAll("");

    //ensure single root tag for all JSPs as per bug 361
    result = "<icefaces:root " + namespaceDeclarations + ">" + result + "</icefaces:root>";

    Pattern jspIncludePattern = Pattern.compile(JSP_INCLUDE_PATTERN);
    Matcher jspIncludeMatcher = jspIncludePattern.matcher(result);
    StringBuffer jspIncludeBuf = new StringBuffer();
    while (jspIncludeMatcher.find()) {
        String args = jspIncludeMatcher.group(1);
        jspIncludeMatcher.appendReplacement(jspIncludeBuf,
                "<icefaces:include" + args + " isDynamic=\"#{true}\" />");
    }
    jspIncludeMatcher.appendTail(jspIncludeBuf);
    result = jspIncludeBuf.toString();

    //Fix HTML
    result = toSingletonTag(P_TAG_PATTERN, result);
    result = toSingletonTag(LINK_TAG_PATTERN, result);
    result = toSingletonTag(META_TAG_PATTERN, result);
    result = toSingletonTag(IMG_TAG_PATTERN, result);
    result = toSingletonTag(INPUT_TAG_PATTERN, result);

    Pattern brTagPattern = Pattern.compile(BR_TAG_PATTERN);
    Matcher brTagMatcher = brTagPattern.matcher(result);
    result = brTagMatcher.replaceAll("<br/>");

    Pattern hrTagPattern = Pattern.compile(HR_TAG_PATTERN);
    Matcher hrTagMatcher = hrTagPattern.matcher(result);
    result = hrTagMatcher.replaceAll("<hr/>");

    Pattern nbspEntityPattern = Pattern.compile(NBSP_ENTITY_PATTERN);
    Matcher nbspEntityMatcher = nbspEntityPattern.matcher(result);
    //  result = nbspEntityMatcher.replaceAll("&nbsp;");
    result = nbspEntityMatcher.replaceAll("&amp;nbsp");

    Pattern copyEntityPattern = Pattern.compile(COPY_ENTITY_PATTERN);
    Matcher copyEntityMatcher = copyEntityPattern.matcher(result);
    result = copyEntityMatcher.replaceAll("&#169;");

    Pattern docDeclPattern = Pattern.compile(DOC_DECL_PATTERN);
    Matcher docDeclMatcher = docDeclPattern.matcher(result);
    result = docDeclMatcher.replaceAll("");

    result = unescapeBackslash(result);

    return result;
}

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

public static String serverHTMLStripper(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, "");
        }//from w  w  w . ja  v a2s. c  o m
        m.appendTail(sb);
        stripTags = sb.toString();
    }
    return stripTags.trim();
}

From source file:autocorrelator.apps.SDFGroovy.java

/**
 * Parse groovyStrng for input and output variables marked by $&lt;&gt;
 *    and create {@link Script} object./*  w ww .  j av a  2s . c  o  m*/
 * @param groovyStrg string containing groovy script
 * @param initArgs arguments to be passed to init() method if exists
 * @param outFields Set to be filled with output variable names
 * @return pre compiled groovy script
 */
private static Script getGroovyScript(String groovyStrg, Set<String> inFields, Set<String> outFields) {
    StringBuffer sb = new StringBuffer(groovyStrg.length());
    Matcher varMatch = VARIABLEPat.matcher(groovyStrg);

    // Identify in and out variables in script by looking for
    // $(>|<>)?[a-zA-Z_][a-zA-Z_0-9]*
    while (varMatch.find()) {
        String var = varMatch.group();

        /*Remove the prefix $(>|<>)? to get correct variable names.*/
        String varName = var.replaceAll(TASK_VAR_FLAG, "");

        if (INVariablePat.matcher(var).find()) //input
            inFields.add(varName);
        else if (OUTVariablePat.matcher(var).find()) //output
            outFields.add(varName);
        else //input & output
        {
            inFields.add(varName);
            outFields.add(varName);
        }
        varMatch.appendReplacement(sb, varName);
    }
    varMatch.appendTail(sb);

    groovyStrg = "import static autocorrelator.apps.SDFGroovyHelper.*;\n " + sb.toString();
    GroovyShell shell = new GroovyShell();
    Script script;
    try {
        script = shell.parse(groovyStrg);
    } catch (CompilationFailedException e) {
        System.err.println(groovyStrg);
        throw e;
    }
    return script;
}

From source file:io.wcm.devops.conga.generator.util.VariableStringResolver.java

private static String resolve(String value, Map<String, Object> variables, int iterationCount) {
    if (iterationCount >= REPLACEMENT_MAX_ITERATIONS) {
        throw new IllegalArgumentException("Cyclic dependencies in variable string detected: " + value);
    }/* www .  j a  v a2s.  c  o m*/

    Matcher matcher = VARIABLE_PATTERN.matcher(value);
    StringBuffer sb = new StringBuffer();
    boolean replacedAny = false;
    while (matcher.find()) {
        boolean escapedVariable = StringUtils.equals(matcher.group(1), "\\$");
        String variable = matcher.group(2);
        if (escapedVariable) {
            // keep escaped variables intact
            matcher.appendReplacement(sb, Matcher.quoteReplacement("\\${" + variable + "}"));
        } else {
            Object valueObject = MapExpander.getDeep(variables, variable);
            if (valueObject != null) {
                String variableValue = valueToString(valueObject);
                matcher.appendReplacement(sb, Matcher.quoteReplacement(variableValue.toString()));
                replacedAny = true;
            } else {
                throw new IllegalArgumentException("Unknown variable: " + variable);
            }
        }
    }
    matcher.appendTail(sb);
    if (replacedAny) {
        // try again until all nested references are resolved
        return resolve(sb.toString(), variables, iterationCount + 1);
    } else {
        return sb.toString();
    }
}

From source file:com.yahoo.glimmer.web.QueryController.java

/**
 * Replaces '{' + resourceString + '}' with '@' + resourceId.
 * /*from w w  w.  j  av a  2 s .c o  m*/
 * @param index
 * @param query
 * @return re-written query.
 * @throws IllegalArgumentException when a resource that is not in the data set is found in the given query.
 */
public static String encodeResources(RDFIndex index, String query) {
    Matcher resourceMatcher = RESOURCE_PATTERN.matcher(query);
    StringBuffer sb = new StringBuffer();
    while (resourceMatcher.find()) {
        String resource = resourceMatcher.group(0);
        // Remove { and }
        resource = resource.substring(1, resource.length() - 1);

        // TODO. Objects that are Resources aren't converted to lower case during indexing but predicates are!
        // (in PredicatePrefixTupleFilter)  Needs to be consistent.
        String resourceId = index.lookupIdByResourceId(resource);
        if (resourceId == null) {
            resourceId = index.lookupIdByResourceId(resource.toLowerCase());
            if (resourceId == null) {
                throw new IllegalArgumentException("The resource " + resource + " isn't in the data set.");
            }
        }
        resourceMatcher.appendReplacement(sb, resourceId);
    }
    resourceMatcher.appendTail(sb);

    return sb.toString();
}

From source file:forge.game.spellability.AbilityManaPart.java

/**
 * <p>/*from w  ww . j a  v  a 2 s  .com*/
 * applyManaReplacement.
 * </p>
 * @return a String
 */
public static String applyManaReplacement(final SpellAbility sa, final String original) {
    final HashMap<String, String> repMap = new HashMap<String, String>();
    final Player act = sa != null ? sa.getActivatingPlayer() : null;
    final String manaReplace = sa != null ? sa.getManaPart().getManaReplaceType() : "";
    if (manaReplace.isEmpty()) {
        if (act != null && act.getLandsPlayedThisTurn() > 0 && sa.hasParam("ReplaceIfLandPlayed")) {
            return sa.getParam("ReplaceIfLandPlayed");
        }
        return original;
    }
    if (manaReplace.startsWith("Any")) {
        // Replace any type and amount
        String replaced = manaReplace.split("->")[1];
        if (replaced.equals("Any")) {
            byte rs = MagicColor.GREEN;
            if (act != null) {
                rs = act.getController().chooseColor("Choose a color", sa, ColorSet.ALL_COLORS);
            }
            replaced = MagicColor.toShortString(rs);
        }
        return replaced;
    }
    final Pattern splitter = Pattern.compile("->");
    // Replace any type
    for (String part : manaReplace.split(" & ")) {
        final String[] v = splitter.split(part, 2);
        if (v[0].equals("Colorless")) {
            repMap.put("[0-9][0-9]?", v.length > 1 ? v[1].trim() : "");
        } else {
            repMap.put(v[0], v.length > 1 ? v[1].trim() : "");
        }
    }
    // Handle different replacement simultaneously
    Pattern pattern = Pattern.compile(StringUtils.join(repMap.keySet().iterator(), "|"));
    Matcher m = pattern.matcher(original);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        if (m.group().matches("[0-9][0-9]?")) {
            final String rep = StringUtils.repeat(repMap.get("[0-9][0-9]?") + " ", Integer.parseInt(m.group()))
                    .trim();
            m.appendReplacement(sb, rep);
        } else {
            m.appendReplacement(sb, repMap.get(m.group()));
        }
    }
    m.appendTail(sb);
    String replaced = sb.toString();
    while (replaced.contains("Any")) {
        byte rs = MagicColor.GREEN;
        if (act != null) {
            rs = act.getController().chooseColor("Choose a color", sa, ColorSet.ALL_COLORS);
        }
        replaced = replaced.replaceFirst("Any", MagicColor.toShortString(rs));
    }
    return replaced;
}

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

private static String replaceAll(String text, Pattern pattern, String replace) {
    Matcher m = pattern.matcher(text);
    StringBuffer sb = null;/*from  w  ww . j  a  va2s  .com*/
    while (m.find()) {
        if (sb == null)
            sb = new StringBuffer();
        m.appendReplacement(sb, replace);
    }
    if (sb != null)
        m.appendTail(sb);
    return sb == null ? text : sb.toString();
}

From source file:com.thinkbiganalytics.nifi.feedmgr.ConfigurationPropertyReplacer.java

/**
 * @param property         the NifiProperty to replace
 * @param configProperties a Map of properties which will be looked to to match against the property key
 *//*from   w w w . j av  a  2 s . c  om*/
public static boolean resolveStaticConfigurationProperty(NifiProperty property,
        Map<String, Object> configProperties) {
    String value = property.getValue();
    StringBuffer sb = null;

    if (configProperties != null && !configProperties.isEmpty()) {

        if (StringUtils.isNotBlank(value)) {
            Pattern variablePattern = Pattern.compile("\\$\\{(.*?)\\}");
            Matcher matchVariablePattern = variablePattern.matcher(value);
            while (matchVariablePattern.find()) {
                if (sb == null) {
                    sb = new StringBuffer();
                }
                String group = matchVariablePattern.group();
                int groupCount = matchVariablePattern.groupCount();
                if (groupCount == 1) {

                    String variable = matchVariablePattern.group(1);
                    //lookup the variable
                    //first look at configuration properties
                    Object resolvedValue = configProperties.get(variable);
                    if (resolvedValue != null) {
                        matchVariablePattern.appendReplacement(sb, resolvedValue.toString());
                    }
                }
            }
            if (sb != null) {
                matchVariablePattern.appendTail(sb);
            }
        }
    }

    if (sb == null) {

        String updatedValue = resolveValue(property, configProperties);
        if (StringUtils.isNotBlank(updatedValue)) {
            sb = new StringBuffer();
            sb.append(updatedValue);
        }

    }
    if (sb != null) {
        property.setValue(StringUtils.trim(sb.toString()));
    }

    return sb != null;
}

From source file:org.rhq.core.domain.server.PersistenceUtility.java

/**
 * Builds a count(*) version of the named query so we don't have duplicate all our queries to use two query
 * pagination model./*from www. j  av  a 2s . c om*/
 *
 * @param  entityManager the entity manager to build the query for
 * @param  queryName     the NamedQuery to transform
 * @param  countItem     the object or attribute that needs to be counted, when it's ambiguous
 *
 * @return a query that can be bound and executed to get the total count of results
 */
public static Query createCountQuery(EntityManager entityManager, String queryName, String countItem) {
    NamedQueryDefinition namedQueryDefinition = getNamedQueryDefinition(entityManager, queryName);
    String query = namedQueryDefinition.getQueryString();

    Matcher matcher = COUNT_QUERY_PATTERN.matcher(query);
    if (!matcher.find()) {
        throw new RuntimeException(
                "Unable to transform query into count query [" + queryName + " - " + query + "]");
    }

    String newQuery = matcher.group(1) + "COUNT(" + countItem + ")" + matcher.group(3);

    matcher = COUNT_QUERY_REMOVE_FETCH.matcher(newQuery);
    if (matcher.find()) {
        StringBuffer buffer = new StringBuffer();
        do {
            matcher.appendReplacement(buffer, "");
        } while (matcher.find());
        matcher.appendTail(buffer);
        newQuery = buffer.toString();
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("Transformed query to count query [" + queryName + "] resulting in [" + newQuery + "]");
    }

    return entityManager.createQuery(newQuery);
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Return the input with embedded property references expanded
 *
 * @param properties the properties to select form
 * @param input      the input//from   ww w .j a  va  2 s  . c  o  m
 *
 * @return string with references expanded
 */
public static String expandProperties(final Properties properties, final String input) {
    final Pattern pattern = Pattern.compile(PROPERTY_PATTERN);
    final Matcher matcher = pattern.matcher(input);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        final String match = matcher.group(1);
        if (null != properties.get(match)) {
            matcher.appendReplacement(sb, Matcher.quoteReplacement(properties.getProperty(match)));
        } else {
            matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group(0)));
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}