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:net.sf.jabref.bst.VM.java

private void addPeriodFunction() {
    if (stack.isEmpty()) {
        throw new VMException("Not enough operands on stack for operation add.period$");
    }/*from w  w w  .j  av a2s.  c  om*/
    Object o1 = stack.pop();

    if (!(o1 instanceof String)) {
        throw new VMException("Can only add a period to a string for add.period$");
    }

    String s = (String) o1;
    Matcher m = ADD_PERIOD_PATTERN.matcher(s);

    if (m.find()) {
        StringBuffer sb = new StringBuffer();
        m.appendReplacement(sb, m.group(1));
        sb.append('.');
        String group2 = m.group(2);
        if (group2 != null) {
            sb.append(m.group(2));
        }
        stack.push(sb.toString());
    } else {
        stack.push(s);
    }
}

From source file:com.networknt.light.rule.form.AbstractFormRule.java

protected String enrichForm(String json, Map<String, Object> inputMap) throws Exception {
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    Pattern pattern = Pattern.compile("\\[\\{\"label\":\"dynamic\",([^]]+)\\}\\]");
    Matcher m = pattern.matcher(json);
    StringBuffer sb = new StringBuffer(json.length());
    while (m.find()) {
        String text = m.group(1);
        // get the values from rules.
        logger.debug("text = {}", text);
        text = text.substring(8);// w  w  w .j ava2s.  c  om
        logger.debug("text = {}", text);
        Map<String, Object> jsonMap = mapper.readValue(text, new TypeReference<HashMap<String, Object>>() {
        });
        jsonMap.put("payload", inputMap.get("payload"));
        // inject host into data here.
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("host", data.get("host"));
        jsonMap.put("data", dataMap);
        RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap);
        String result = (String) jsonMap.get("result");
        logger.debug("result = {}", result);
        if (result != null && result.length() > 0) {
            m.appendReplacement(sb, Matcher.quoteReplacement(result));
        } else {
            m.appendReplacement(sb, Matcher.quoteReplacement("[ ]"));
        }
    }
    m.appendTail(sb);
    logger.debug("form = {}", sb.toString());
    return sb.toString();
}

From source file:org.alfresco.web.bean.NavigationBean.java

/**
 * @param helpUrl The helpUrl to set./*  w  ww  . j  ava 2 s.  c  o m*/
 */
public void setHelpUrl(String helpUrl) {
    if (this.helpUrl == null) {
        Descriptor serverDescriptor = Repository.getServiceRegistry(FacesContext.getCurrentInstance())
                .getDescriptorService().getServerDescriptor();
        // search / replace each available key occurrence in the template string
        // Note: server descriptor is looking for "version.major", "version.minor", etc.
        Pattern p = Pattern.compile("\\{(\\w+\\.?\\w+)\\}");
        Matcher m = p.matcher(helpUrl);
        boolean result = m.find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            String value = null;
            do {
                value = serverDescriptor.getDescriptor(m.group(1));
                m.appendReplacement(sb, value != null ? value : m.group(1));
                result = m.find();
            } while (result);
            m.appendTail(sb);
            helpUrl = sb.toString();
        }

        this.helpUrl = helpUrl;
    }
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Replace <code>url(&lt;<i>relative-path</i>&gt;)</code> references in the
 * input CSS with//from w ww  .  j a  v  a  2 s  .c o  m
 * <code>url(data:&lt;<i>mime-type</i>&gt;;&lt;<i>base64-encoded-data</i>&gt;</code>
 * ). The conversion is controlled by option settings as described in
 * {@link CSSModuleBuilder}.
 *
 * @param req
 *            The request associated with the call.
 * @param css
 *            The input CSS
 * @param res
 *            The resource for the CSS file
 * @return The transformed CSS with images in-lined as determined by option
 *         settings.
 */
protected String inlineImageUrls(HttpServletRequest req, String css, IResource res) {
    if (imageSizeThreshold == 0 && inlinedImageIncludeList.size() == 0) {
        // nothing to do
        return css;
    }

    // In-lining of imports can be disabled by request parameter for debugging
    if (!TypeUtil.asBoolean(req.getParameter(INLINEIMAGES_REQPARAM_NAME), true)) {
        return css;
    }

    StringBuffer buf = new StringBuffer();
    Matcher m = urlPattern.matcher(css);
    while (m.find()) {
        String fullMatch = m.group(0);
        String urlMatch = m.group(1);

        // remove quotes.
        urlMatch = dequote(urlMatch);
        urlMatch = forwardSlashPattern.matcher(urlMatch).replaceAll("/"); //$NON-NLS-1$

        // Don't do anything with non-relative URLs
        if (urlMatch.startsWith("/") || urlMatch.startsWith("#") || protocolPattern.matcher(urlMatch).find()) { //$NON-NLS-1$ //$NON-NLS-2$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        URI imageUri = res.resolve(urlMatch).getURI();
        boolean exclude = false, include = false;

        // Determine if this image is in the include list
        for (Pattern regex : inlinedImageIncludeList) {
            if (regex.matcher(imageUri.getPath()).find()) {
                include = true;
                break;
            }
        }

        // Determine if this image is in the exclude list
        for (Pattern regex : inlinedImageExcludeList) {
            if (regex.matcher(imageUri.getPath()).find()) {
                exclude = true;
                break;
            }
        }
        // If there's an include list, then only the files in the include list
        // will be inlined
        if (inlinedImageIncludeList.size() > 0 && !include || exclude) {
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        boolean imageInlined = false;
        String type = URLConnection.getFileNameMap().getContentTypeFor(imageUri.getPath());
        String extension = PathUtil.getExtension(imageUri.getPath());
        if (type == null) {
            type = inlineableImageTypeMap.get(extension);
        }
        if (type == null) {
            type = "content/unknown"; //$NON-NLS-1$
        }
        if (include || inlineableImageTypes.contains(type) || inlineableImageTypeMap.containsKey(extension)) {
            InputStream in = null;
            try {
                // In-line the image.
                URLConnection connection = imageUri.toURL().openConnection();

                if (include || connection.getContentLength() <= imageSizeThreshold) {
                    in = connection.getInputStream();
                    String base64 = getBase64(connection);
                    m.appendReplacement(buf, ""); //$NON-NLS-1$
                    buf.append("url('data:" + type + //$NON-NLS-1$
                            ";base64," + base64 + "')"); //$NON-NLS-1$ //$NON-NLS-2$
                    imageInlined = true;
                }
            } catch (IOException ex) {
                if (log.isLoggable(Level.WARNING)) {
                    log.log(Level.WARNING,
                            MessageFormat.format(Messages.CSSModuleBuilder_0, new Object[] { imageUri }), ex);
                }
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
        if (!imageInlined) {
            // Image not in-lined.  Write the original URL
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
        }
    }
    m.appendTail(buf);
    return buf.toString();
}

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

/**
 * src?regex????????(handler)//from  w w w .j  a  va 2 s  .  c o  m
 * ?????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.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 ava 2 s  . c om*/
     * ================================================================================= */
    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.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   w ww  .  j  ava 2  s  .  c  o 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());
}

From source file:mergedoc.core.Comment.java

/**
 * ??? HTML ???//from w  w  w  . ja  va2s. c  o  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:mergedoc.core.Comment.java

/**
 * ???????//from   www  .  j  a v  a2  s .  co m
 * <p>
 * @param o 
 */
private void shrinkComment(OutputComment o) {

    // ? Java ????
    String emptyDescRegex = "(?s)\\s*/\\*\\*\\s*\\*\\s*@.*";
    if (FastStringUtils.matches(srcBody, emptyDescRegex)) {
        docBody = null;
        o.build();
        if (o.resultHeight() <= o.originHeight) {
            return;
        }
    }

    // ? Java ????
    // -> buildComment ?????????????????
    boolean b1 = shrinkTagList("@see", sees);
    boolean b2 = shrinkTagList("@throws", throwses);
    boolean b3 = shrinkTagList("@param", params);
    boolean b4 = shrinkTagList("@return", returns);
    if (b1 || b2 || b3 || b4) {
        o.build();
        if (o.resultHeight() <= o.originHeight) {
            return;
        }
    }

    // ?
    int height = o.resultHeight();

    // ? <p> ????
    Pattern pTagPat = PatternCache.getPattern("<p>\n\n(<p>)");
    if (o.comment.contains("<p>\n\n<p>")) {
        StringBuffer sb = new StringBuffer();
        Matcher pTagMat = pTagPat.matcher(o.comment);
        while (height > o.originHeight && pTagMat.find()) {
            pTagMat.appendReplacement(sb, "$1");
            height -= 2;
        }
        pTagMat.appendTail(sb);
        o.comment = sb.toString();
        if (height <= o.originHeight) {
            return;
        }
    }

    // <th?<td?</tr ???
    Pattern tdTagPat = PatternCache.getPattern("\\s+(<(t[hd]|/tr))");
    if (o.comment.contains("<table")) {
        StringBuffer sb = new StringBuffer();
        Matcher tdTagMat = tdTagPat.matcher(o.comment);
        while (height > o.originHeight && tdTagMat.find()) {
            tdTagMat.appendReplacement(sb, "$1");
            height--;
        }
        tdTagMat.appendTail(sb);
        o.comment = sb.toString();
        if (height <= o.originHeight) {
            return;
        }
    }

    // <li?</ul?</ol ???
    Pattern liTagPat = PatternCache.getPattern("\\s+(<(li|/[uo]l))");
    if (o.comment.contains("<li")) {
        StringBuffer sb = new StringBuffer();
        Matcher liTagMat = liTagPat.matcher(o.comment);
        while (height > o.originHeight && liTagMat.find()) {
            liTagMat.appendReplacement(sb, "$1");
            height--;
        }
        liTagMat.appendTail(sb);
        o.comment = sb.toString();
        if (height <= o.originHeight) {
            return;
        }
    }

    // 
    Pattern emptyLinePat = PatternCache.getPattern("(?m)^\\s*?\n");
    Matcher emptyLineMat = emptyLinePat.matcher(o.comment);
    StringBuffer sb = new StringBuffer();
    while (height > o.originHeight && emptyLineMat.find()) {
        emptyLineMat.appendReplacement(sb, "");
        height--;
    }
    emptyLineMat.appendTail(sb);
    o.comment = sb.toString();
    if (height <= o.originHeight) {
        return;
    }

    //  Java ? 1 ????
    String firstLineRegex = "(?s)\\s*/\\*\\*\\s*\n.*";
    if (!FastStringUtils.matches(srcBody, firstLineRegex)) {
        o.enabledFirstLine = true;
        if (o.resultHeight() <= o.originHeight) {
            return;
        }
    }

    // ???
    final int maxWidth = 160;
    while (o.resultHeight() > o.originHeight && o.width < maxWidth) {

        o.build();
        if (o.resultHeight() <= o.originHeight) {
            return;
        }

        if (o.comment.contains("<")) {

            o.comment = pTagPat.matcher(o.comment).replaceAll("$1");
            if (o.resultHeight() <= o.originHeight) {
                return;
            }

            o.comment = tdTagPat.matcher(o.comment).replaceAll("$1");
            if (o.resultHeight() <= o.originHeight) {
                return;
            }

            o.comment = liTagPat.matcher(o.comment).replaceAll("$1");
            if (o.resultHeight() <= o.originHeight) {
                return;
            }
        }

        o.comment = emptyLinePat.matcher(o.comment).replaceAll("");
        if (o.resultHeight() <= o.originHeight) {
            return;
        }

        if (o.width < 100) {
            o.width += 4;
        } else {
            o.width += 8;
        }
    }
}

From source file:com.ichi2.libanki.Media.java

private List<String> _expandClozes(String string) {
    Set<String> ords = new TreeSet<String>();
    Matcher m = Pattern.compile("\\{\\{c(\\d+)::.+?\\}\\}").matcher(string);
    while (m.find()) {
        ords.add(m.group(1));/*from ww  w.  j  a  va2s  .com*/
    }
    ArrayList<String> strings = new ArrayList<String>();
    String clozeReg = Template.clozeReg;

    for (String ord : ords) {
        StringBuffer buf = new StringBuffer();
        m = Pattern.compile(String.format(Locale.US, clozeReg, ord)).matcher(string);
        while (m.find()) {
            if (!TextUtils.isEmpty(m.group(3))) {
                m.appendReplacement(buf, "[$3]");
            } else {
                m.appendReplacement(buf, "[...]");
            }
        }
        m.appendTail(buf);
        String s = buf.toString().replaceAll(String.format(Locale.US, clozeReg, ".+?"), "$1");
        strings.add(s);
    }
    strings.add(string.replaceAll(String.format(Locale.US, clozeReg, ".+?"), "$1"));
    return strings;
}