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.alfresco.web.site.servlet.CSRFFilter.java

private String resolve(String str, Map<String, String> propertyMap) {
    if (str == null) {
        return null;
    }//www. ja v  a 2  s . c o m
    Pattern pattern = Pattern.compile("\\{(.+?)\\}");
    Matcher matcher = pattern.matcher(str);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        if (propertyMap.containsKey(matcher.group(1))) {
            String replacement = resolve(propertyMap.get(matcher.group(1)), propertyMap);
            matcher.appendReplacement(buffer,
                    replacement != null ? Matcher.quoteReplacement(replacement) : "null");
        }
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:com.jsmartframework.web.manager.ExpressionHandler.java

public Object getExpressionValue(Object expr) {
    if (expr != null) {
        String evalExpr = expr.toString();

        Matcher matcher = EL_PATTERN.matcher(evalExpr);
        if (!matcher.find()) {
            return expr;
        }//from w  ww  .j a  v  a 2s .  c o  m

        boolean hasMoreGroup = false;
        StringBuffer exprBuffer = new StringBuffer();

        Object result = evaluateExpression(evalExpr.substring(matcher.start() + 2, matcher.end() - 1));
        matcher.appendReplacement(exprBuffer,
                result != null ? Matcher.quoteReplacement(result.toString()) : "null");

        while (matcher.find()) {
            hasMoreGroup = true;
            Object object = evaluateExpression(evalExpr.substring(matcher.start() + 2, matcher.end() - 1));
            matcher.appendReplacement(exprBuffer,
                    object != null ? Matcher.quoteReplacement(object.toString()) : "null");
        }

        if (hasMoreGroup || result instanceof String) {
            return matcher.appendTail(exprBuffer).toString();
        } else {
            return result;
        }
    }
    return null;
}

From source file:com.axelor.studio.service.data.importer.FormImporter.java

private String[] getDomainContext(String domain) {

    if (domain == null) {
        return new String[] { null };
    }/*w ww .  j a va2 s.c o  m*/

    Matcher macher = DOMAIN_PATTERN.matcher(domain);

    StringBuffer sb = new StringBuffer(domain.length());
    List<String> context = new ArrayList<String>();
    int count = 0;
    while (macher.find()) {
        String replacement = ":_param" + count;
        context.add(replacement.substring(1) + ";eval" + macher.group().replace("= ", ""));
        macher.appendReplacement(sb, replacement);
        count++;
    }

    macher.appendTail(sb);

    if (context.isEmpty()) {
        return new String[] { domain };
    }

    return new String[] { sb.toString(), Joiner.on(",").join(context) };
}

From source file:org.azyva.dragom.cliutil.CliUtil.java

/**
 * Initializes the Java Util Logging framework by implementing replaceable
 * properties in the configuration file.
 *
 * <p>If the java.util.logging.config.file system property is defined, this method
 * does nothing, leaving the default initialization process be used.
 *
 * <p>If the java.util.logging.config.file system property is not defined and the
 * org.azyva.dragom.JavaUtilLoggingConfigFile system property is defined, this
 * method calls LogManager.readConfiguration with an InputStream which represents
 * the file but with property references replaced by the corresponding system
 * property./*from   w w  w  . java2 s.c om*/
 *
 * <p>If none of these two system properties are defined, this method does
 * nothing.
 */
public static void initJavaUtilLogging() {
    String javaUtilLoggingConfigFile;
    String javaUtilLoggingConfig;
    Matcher matcher;
    StringBuffer stringBufferNewJavaUtilLoggingConfig;

    Util.applyDragomSystemProperties();

    if ((System.getProperty("java.util.logging.config.file") == null) && ((javaUtilLoggingConfigFile = System
            .getProperty(CliUtil.SYS_PROPERTY_JAVA_UTIL_LOGGING_CONFIG_FILE)) != null)) {

        try {
            javaUtilLoggingConfig = new String(Files.readAllBytes(Paths.get(javaUtilLoggingConfigFile)));

            matcher = CliUtil.patternPropertyReference.matcher(javaUtilLoggingConfig);

            stringBufferNewJavaUtilLoggingConfig = new StringBuffer();

            while (matcher.find()) {
                String property;
                String value;

                property = matcher.group(1);
                value = System.getProperty(property);

                if (value == null) {
                    throw new RuntimeException("System property " + property + " referenced in "
                            + javaUtilLoggingConfigFile + " is not defined.");
                }

                // In a Properties file, \ must be escaped.
                value = value.replace("\\", "\\\\");

                matcher.appendReplacement(stringBufferNewJavaUtilLoggingConfig,
                        Matcher.quoteReplacement(value));
            }

            matcher.appendTail(stringBufferNewJavaUtilLoggingConfig);

            java.util.logging.LogManager.getLogManager().readConfiguration(
                    new ByteArrayInputStream(stringBufferNewJavaUtilLoggingConfig.toString().getBytes()));
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }
}

From source file:org.etudes.util.XrefHelper.java

/**
 * For email notifications, revise embedded media relative url to full url.
 * //from w  w w  . j a  v  a  2 s . c o  m
 * @param data
 *        The message data with relative urls.
 * @return data with full urls.
 */
public static String fullUrls(String data) {
    if (data == null)
        return data;

    Pattern p = getPattern();
    Matcher m = p.matcher(data);
    StringBuffer sb = new StringBuffer();
    String serverUrl = ServerConfigurationService.getServerUrl();

    // for the relative access check: matches /access/
    Pattern relAccessPattern = Pattern.compile("/access/.*");

    // process each "harvested" string (avoiding like strings that are not in src= or href= patterns)
    while (m.find()) {
        if (m.groupCount() == 3) {
            String ref = m.group(2);
            String terminator = m.group(3);

            // if this is an access to our own server, make it full URL (i.e. starting with "/access")
            Matcher relAccessMatcher = relAccessPattern.matcher(ref);
            if (relAccessMatcher.matches()) {
                m.appendReplacement(sb,
                        Matcher.quoteReplacement(m.group(1) + "=\"" + serverUrl + ref + terminator));
            }
        }
    }

    m.appendTail(sb);

    return sb.toString();
}

From source file:org.paxle.filter.robots.impl.RobotsTxtManager.java

void init(Map<String, Object> props) {
    // configure caching manager
    this.manager = CacheManager.getInstance();

    /* =================================================================================
     * init a new cache/* w w  w.  j  av a 2 s  .  c  o  m*/
     * ================================================================================= */
    Integer maxCacheSize = (Integer) props.get(PROP_MAX_CACHE_SIZE);
    if (maxCacheSize == null)
        maxCacheSize = Integer.valueOf(1000);
    this.cache = new Cache(CACHE_NAME, maxCacheSize.intValue(), false, false, 60 * 60, 30 * 60);
    this.manager.addCache(this.cache);

    /* =================================================================================
     * init threadpool
     * ================================================================================= */
    Integer maxIdle = (Integer) props.get(PROP_WORKER_MAX_IDLE);
    if (maxIdle == null)
        maxIdle = Integer.valueOf(20);

    Integer maxAlive = (Integer) props.get(PROP_WORKER_MAX_ALIVE);
    if (maxAlive == null)
        maxAlive = Integer.valueOf(20);
    if (maxAlive.compareTo(maxIdle) < 0)
        maxAlive = maxIdle;

    this.execService = new ThreadPoolExecutor(maxIdle.intValue(), maxAlive.intValue(), 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

    /* =================================================================================
     * init http-client
     * ================================================================================= */
    this.connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = this.connectionManager.getParams();

    final Integer connectionTimeout = (Integer) props.get(PROP_CONNECTION_TIMEOUT);
    if (connectionTimeout != null)
        params.setConnectionTimeout(connectionTimeout.intValue());
    final Integer socketTimeout = (Integer) props.get(PROP_SOCKET_TIMEOUT);
    if (socketTimeout != null)
        params.setSoTimeout(socketTimeout.intValue());
    final Integer maxConnections = (Integer) props.get(PROP_MAXCONNECTIONS_TOTAL);
    if (maxConnections != null)
        params.setMaxTotalConnections(maxConnections.intValue());

    this.httpClient = new HttpClient(this.connectionManager);

    /* =================================================================================
     * proxy configuration
     * ================================================================================= */
    final Boolean useProxyVal = (Boolean) props.get(PROP_PROXY_USE);
    final boolean useProxy = (useProxyVal == null) ? false : useProxyVal.booleanValue();
    final String host = (String) props.get(PROP_PROXY_HOST);
    final Integer portVal = (Integer) props.get(PROP_PROXY_PORT);

    if (useProxy && host != null && host.length() > 0 && portVal != null) {
        final int port = portVal.intValue();
        this.logger.info(String.format("Proxy is enabled: %s:%d", host, Integer.valueOf(port)));
        final ProxyHost proxyHost = new ProxyHost(host, port);
        this.httpClient.getHostConfiguration().setProxyHost(proxyHost);

        final String user = (String) props.get(PROP_PROXY_HOST);
        final String pwd = (String) props.get(PROP_PROXY_PASSWORD);

        if (user != null && user.length() > 0 && pwd != null && pwd.length() > 0)
            this.httpClient.getState().setProxyCredentials(new AuthScope(host, port),
                    new UsernamePasswordCredentials(user, pwd));
    } else {
        this.logger.info("Proxy is disabled");
        this.httpClient.getHostConfiguration().setProxyHost(null);
        this.httpClient.getState().clearCredentials();
    }

    /* =================================================================================
     * the user-agent name that should be used
     * ================================================================================= */
    final String userAgent = (String) props.get(PROP_USER_AGENT);
    if (userAgent != null) {
        final StringBuffer buf = new StringBuffer();
        Pattern pattern = Pattern.compile("\\$\\{[^\\}]*}");
        Matcher matcher = pattern.matcher(userAgent);

        // replacing property placeholders with system-properties
        while (matcher.find()) {
            String placeHolder = matcher.group();
            String propName = placeHolder.substring(2, placeHolder.length() - 1);
            String propValue = System.getProperty(propName);
            if (propValue != null)
                matcher.appendReplacement(buf, propValue);
        }
        matcher.appendTail(buf);

        this.userAgent = buf.toString();
    } else {
        // Fallback
        this.userAgent = "PaxleFramework";
    }

    this.logger
            .info(String.format("Robots.txt manager initialized. Using '%s' rule-store with %d stored entries.",
                    loader.getClass().getSimpleName(), Integer.valueOf(loader.size())));
}

From source file:org.opennms.ng.services.databaseschemaconfig.JdbcFilterDao.java

/**
 * Generic method to parse and translate a rule into SQL.
 *
 * Only columns listed in database-schema.xml may be used in a filter
 * (explicit "table.column" specification is not supported in filters)
 *
 * To differentiate column names from SQL key words (operators, functions, typecasts, etc)
 * SQL_KEYWORD_REGEX must match any SQL key words that may be used in filters,
 * and must not match any column names or prefixed values
 *
 * To make filter syntax more simple and intuitive than SQL
 * - Filters support some aliases for common SQL key words / operators
 *    "&amp;" or "&amp;&amp;" = "AND"
 *    "|" or "||" = "OR"/*w ww  .  j a  v  a 2 s  . c  o  m*/
 *    "!" = "NOT"
 *    "==" = "="
 * - "IPLIKE" may be used as an operator instead of a function in filters ("ipAddr IPLIKE '*.*.*.*'")
 *   When using "IPLIKE" as an operator, the value does not have to be quoted ("ipAddr IPLIKE *.*.*.*" is ok)
 * - Some common SQL expressions may be generated by adding a (lower-case) prefix to an unquoted value in the filter
 *    "isVALUE" = "serviceName = VALUE"
 *    "notisVALUE" = interface does not support the specified service
 *    "catincVALUE" = node is in the specified category
 * - Double-quoted (") strings in filters are converted to single-quoted (') strings in SQL
 *   SQL treats single-quoted strings as constants (values) and double-quoted strings as identifiers (columns, tables, etc)
 *   So, all quoted strings in filters are treated as constants, and filters don't support quoted identifiers
 *
 * This function does not do complete syntax/grammar checking - that is left to the database itself - do not assume the output is valid SQL
 *
 * @param tables
 *            a list to be populated with any tables referenced by the returned SQL
 * @param rule
 *            the rule to parse
 *
 * @return an SQL WHERE clause
 *
 * @throws org.opennms.ng.services.databaseschemaconfig.FilterParseException
 *             if any errors occur during parsing
 */
private String parseRule(final List<Table> tables, final String rule) throws FilterParseException {
    if (rule != null && rule.length() > 0) {
        final List<String> extractedStrings = new ArrayList<String>();

        String sqlRule = rule;

        // Extract quoted strings from rule and convert double-quoted strings to single-quoted strings
        // Quoted strings need to be extracted first to avoid accidentally matching/modifying anything within them
        // As in SQL, pairs of quotes within a quoted string are treated as an escaped quote character:
        //  'a''b' = a'b ; "a""b" = a"b ; 'a"b' = a"b ; "a'b" = a'b
        Matcher regex = SQL_QUOTE_PATTERN.matcher(sqlRule);
        StringBuffer tempStringBuff = new StringBuffer();
        while (regex.find()) {
            final String tempString = regex.group();
            if (tempString.charAt(0) == '"') {
                extractedStrings.add("'" + tempString.substring(1, tempString.length() - 1)
                        .replaceAll("\"\"", "\"").replaceAll("'", "''") + "'");
            } else {
                extractedStrings.add(regex.group());
            }
            regex.appendReplacement(tempStringBuff, "###@" + (extractedStrings.size() - 1) + "@###");
        }
        final int tempIndex = tempStringBuff.length();
        regex.appendTail(tempStringBuff);
        if (tempStringBuff.substring(tempIndex).indexOf('\'') > -1) {
            final String message = "Unmatched ' in filter rule '" + rule + "'";
            LOG.error(message);
            throw new FilterParseException(message);
        }
        if (tempStringBuff.substring(tempIndex).indexOf('"') > -1) {
            final String message = "Unmatched \" in filter rule '" + rule + "'";
            LOG.error(message);
            throw new FilterParseException(message);
        }
        sqlRule = tempStringBuff.toString();

        // Translate filter-specific operators to SQL operators
        sqlRule = sqlRule.replaceAll("\\s*(?:&|&&)\\s*", " AND ");
        sqlRule = sqlRule.replaceAll("\\s*(?:\\||\\|\\|)\\s*", " OR ");
        sqlRule = sqlRule.replaceAll("\\s*!(?!=)\\s*", " NOT ");
        sqlRule = sqlRule.replaceAll("==", "=");

        // Translate IPLIKE operators to IPLIKE() functions
        // If IPLIKE is already used as a function in the filter, this regex should not match it
        regex = SQL_IPLIKE_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            // Is the second argument already a quoted string?
            if (regex.group().charAt(0) == '#') {
                regex.appendReplacement(tempStringBuff, "IPLIKE($1, $2)");
            } else {
                regex.appendReplacement(tempStringBuff, "IPLIKE($1, '$2')");
            }
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Extract SQL key words to avoid identifying them as columns or prefixed values
        regex = SQL_KEYWORD_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            extractedStrings.add(regex.group().toUpperCase());
            regex.appendReplacement(tempStringBuff, "###@" + (extractedStrings.size() - 1) + "@###");
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Identify prefixed values and columns
        regex = SQL_VALUE_COLUMN_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            // Convert prefixed values to SQL expressions
            if (regex.group().startsWith("is")) {
                regex.appendReplacement(tempStringBuff,
                        addColumn(tables, "serviceName") + " = '" + regex.group().substring(2) + "'");
            } else if (regex.group().startsWith("notis")) {
                regex.appendReplacement(tempStringBuff, addColumn(tables, "ipAddr")
                        + " NOT IN (SELECT ifServices.ipAddr FROM ifServices, service WHERE service.serviceName ='"
                        + regex.group().substring(5) + "' AND service.serviceID = ifServices.serviceID)");
            } else if (regex.group().startsWith("catinc")) {
                regex.appendReplacement(tempStringBuff, addColumn(tables, "nodeID")
                        + " IN (SELECT category_node.nodeID FROM category_node, categories WHERE categories.categoryID = category_node.categoryID AND categories.categoryName = '"
                        + regex.group().substring(6) + "')");
            } else {
                // Call addColumn() on each column
                regex.appendReplacement(tempStringBuff, addColumn(tables, regex.group()));
            }
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Merge extracted strings back into expression
        regex = SQL_ESCAPED_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            regex.appendReplacement(tempStringBuff,
                    Matcher.quoteReplacement(extractedStrings.get(Integer.parseInt(regex.group(1)))));
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();
        return "WHERE " + sqlRule;
    }
    return "";
}

From source file:mergedoc.core.Comment.java

/**
 * ??? HTML ???/* w ww  .  j a v  a 2 s .co  m*/
 * <p>
 * @param comment 
 * @return HTML ?
 */
private String formatHTML(String comment) {

    // HTML ?????????
    boolean hasHtmlTag = comment.contains("<");

    // HTML ??
    if (hasHtmlTag) {
        Pattern pat = PatternCache.getPattern("</?\\w+");
        Matcher mat = pat.matcher(comment);
        StringBuffer sb = new StringBuffer();
        while (mat.find()) {
            String tag = mat.group().toLowerCase();
            mat.appendReplacement(sb, tag);
        }
        mat.appendTail(sb);
        comment = sb.toString();
    }

    comment = FastStringUtils.replaceAll(comment, "\\*/", "*&#47;");
    comment = FastStringUtils.replaceAll(comment, "\\\\u", "&#92;u");

    // 
    comment = FastStringUtils.replaceAll(comment, "(?m)^ ", "");

    // HTML ?
    if (hasHtmlTag) {

        // </p> 
        comment = FastStringUtils.replace(comment, "</p>", "");

        // <blockquote> 
        comment = FastStringUtils.replaceAll(comment, "\\s*(</?blockquote>)\\s*", "\n$1\n");

        // <pre> 
        if (comment.contains("<pre>")) {
            comment = FastStringUtils.replaceAll(comment, "\\s*(</?pre>)\\s*", "\n$1\n");
            comment = FastStringUtils.replaceAll(comment, "(<blockquote>)\n(<pre>)", "$1$2");
            comment = FastStringUtils.replaceAll(comment, "(</pre>)\n(</blockquote>)", "$1$2");
        }

        // <table> 
        if (comment.contains("<table")) {
            comment = FastStringUtils.replaceAll(comment, "\\s*(</?table|</?tr>)", "\n$1");
            comment = FastStringUtils.replaceAll(comment, "\\s*(<(th|td))", "\n  $1");
            comment = FastStringUtils.replaceAll(comment, "\\s*(<blockquote>)\n(<table)", "\n\n$1$2");
            comment = FastStringUtils.replaceAll(comment, "(</table>)\n(</blockquote>)", "$1$2");
        }

        // <ol> <ul> <li> 
        comment = FastStringUtils.replaceAll(comment, "\\s*(</?(ol|ul|li)>)", "\n$1");

        // <p> 
        if (comment.contains("<p>")) {
            comment = FastStringUtils.replaceAll(comment, "\\s*(<p>)\\s*", "\n\n$1");
            comment = FastStringUtils.replaceAll(comment, "(\\s*<p>)+$", "");
        }

        // <br/> 
        if (comment.contains("<br")) {
            comment = FastStringUtils.replaceAll(comment, "<br\\s*/>", "<br>");
        }
    }

    // ????
    comment = comment.trim();

    return comment;
}

From source file:com.g3net.tool.StringUtils.java

/**
 * src?regex????????(handler)/*from w w w.  ja  v a2 s  . com*/
 * ?????regex?
 * 
 * @param src
 * @param regex
 *            ???? saa(\\d+)bb
 * @param handleGroupIndex
 *            regex?
 * @param hander
 *            ?
 * @return
 */
public static String replaceAll(String src, String regex, int[] handleGroupIndex, GroupsHandler hander) {

    if (src == null || src.trim().length() == 0) {
        return "";
    }
    Matcher m = Pattern.compile(regex).matcher(src);

    StringBuffer sbuf = new StringBuffer();

    String[] groupStrs = new String[handleGroupIndex.length];
    // perform the replacements:
    while (m.find()) {
        for (int i = 0; i < handleGroupIndex.length; i++) {
            String value = m.group(handleGroupIndex[i]);
            // int l = Integer.valueOf(value, 16).intValue();
            // char c=(char)(0x0ffff&l);
            // log.info(m.group(0));
            groupStrs[i] = value;
            // m.appendReplacement(sbuf, handledStr);
        }
        String handledStr = hander.handler(groupStrs);
        m.appendReplacement(sbuf, handledStr);
    }
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    return sbuf.toString();

    // return null;
}

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

public String processText(CharSequence text) {
    Matcher m = PATTERN.matcher(text);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String var = m.group(1);
        String value = getVariable(var);
        if (value != null) {
            if (trim) {
                value = value.trim();//from   ww w  . j  a v a2s . co m
            }

            // process again the value if it still contains variable
            // to replace
            String oldValue = value;
            int recursionLevel = 0;
            while (!(value = processText(oldValue)).equals(oldValue)) {
                oldValue = value;
                recursionLevel++;
                // Avoid infinite replacement loops
                if (recursionLevel > MAX_RECURSION_LEVEL) {
                    break;
                }
            }

            // Allow use of backslash and dollars characters
            String valueL = Matcher.quoteReplacement(value);
            m.appendReplacement(sb, valueL);
        }
    }
    m.appendTail(sb);
    return unescape(sb.toString());
}