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:org.obm.push.protocol.data.HTMLBodyFormatter.java

public StringBuffer parseUrl(Matcher m) {
    StringBuffer result = new StringBuffer();

    Pattern pEmail = Pattern.compile(PATTERN_EMAIL);
    Pattern pUrl = Pattern.compile(PATTERN_URL);

    while (m.find()) {
        String href = m.group();//from w w  w  .j a  v  a 2 s.  c om
        Matcher mEmail = pEmail.matcher(href);
        Matcher mUrl = pUrl.matcher(href);

        if (mUrl.find()) {
            if (href.startsWith("http")) {
                m.appendReplacement(result, "<a href=\"" + href + "\" target=\"_blank\">" + href + "</a>");
            } else {
                m.appendReplacement(result,
                        "<a href=\"http://" + href + "\" target=\"_blank\">" + href + "</a>");
            }
        } else if (mEmail.find()) {
            m.appendReplacement(result, "<a href=mailto:" + href + ">" + href + "</a>");
        }
    }
    m.appendTail(result);
    return result;
}

From source file:com.confighub.core.utils.FileUtils.java

public static String resolveFile(final Context context, final RepoFile file,
        Map<PropertyKey, Property> resolved, Map<String, String> passwords) throws ConfigException {
    boolean encrypt = false;
    String pass = "";
    if (file.isEncrypted()) {
        pass = passwords.get(file.getSecurityProfile().getName());
        if (null == pass || !file.getSecurityProfile().isSecretValid(pass)) {
            pass = file.getSecurityProfile().getDecodedPassword();
            encrypt = true;/*from  w  w w . j a v a 2  s .c  om*/
        }

        file.decryptFile(pass);
    }

    Map<String, Property> propertyMap = new HashMap<>();
    Map<String, PropertyKey> keyMap = new HashMap<>();
    resolved.keySet().forEach(k -> {
        propertyMap.put(k.getKey(), resolved.get(k));
        keyMap.put(k.getKey(), k);
    });

    String fileContent = file.getContent();
    String patternString = "(?i)\\$\\{\\s*\\b(" + StringUtils.join(propertyMap.keySet(), "|") + ")\\b\\s*}";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(fileContent);

    StringBuffer sb = new StringBuffer();

    while (matcher.find()) {
        String key = matcher.group(1);
        Property property = propertyMap.get(key);

        // replace each key specification with the property value
        String value = "";

        if (null != property) {
            if (null != property.getAbsoluteFilePath() && PropertyKey.ValueDataType.FileEmbed
                    .equals(property.getPropertyKey().getValueDataType())) {
                RepoFile injectFile = context.resolveFullContextFilePath(property.getAbsoluteFilePath());
                if (null == injectFile)
                    value = "[ ERROR: No file resolved ]";
                else
                    value = resolveFile(context, injectFile, resolved, passwords);
            } else {
                if (property.isEncrypted()) {
                    String spName = keyMap.get(key).getSecurityProfile().getName();
                    if (passwords.containsKey(spName))
                        property.decryptValue(passwords.get(spName));
                }
                value = setValue(property);
            }
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
    }

    matcher.appendTail(sb);
    fileContent = sb.toString();

    // Remove all escapes \${...}
    fileContent = fileContent.replaceAll("\\\\\\$\\{", "\\$\\{");

    if (encrypt)
        fileContent = Encryption.encrypt(file.getSecurityProfile().getCipher(), fileContent, pass);

    return fileContent;
}

From source file:org.eclipse.virgo.kernel.osgi.provisioning.tools.DependencyLocator10.java

private static String expandProperties(String value) {
    Pattern regex = PROPERTY_PATTERN;
    StringBuffer buffer = new StringBuffer(value.length());
    Matcher matcher = regex.matcher(value);
    int propertyGroup = matcher.groupCount();
    String key, property = "";
    while (matcher.find()) {
        key = matcher.group(propertyGroup);
        property = "";
        if (key.contains("::")) {
            String[] keyDefault = key.split("::");
            property = System.getProperty(keyDefault[0]);
            if (property == null) {
                property = keyDefault[1];
            } else {
                property = property.replace('\\', '/');
            }//w ww  .  j a va  2s.  c  o  m
        } else {
            property = System.getProperty(matcher.group(propertyGroup)).replace('\\', '/');
        }
        matcher.appendReplacement(buffer, property);
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:org.obm.push.data.formatter.HTMLBodyFormatter.java

public StringBuffer parseUrl(Matcher m, StringBuilder input) {
    StringBuffer result = new StringBuffer();

    Pattern pEmail = Pattern.compile(PATTERN_EMAIL);
    Pattern pUrl = Pattern.compile(PATTERN_URL);

    while (m.find()) {
        String href = m.group();//from  w ww. jav  a  2s .  c  o m
        Matcher mEmail = pEmail.matcher(href);
        Matcher mUrl = pUrl.matcher(href);

        if (mUrl.find()) {
            if (href.startsWith("http")) {
                m.appendReplacement(result, "<a href=\"" + href + "\" target=\"_blank\">" + href + "</a>");
            } else {
                m.appendReplacement(result,
                        "<a href=\"http://" + href + "\" target=\"_blank\">" + href + "</a>");
            }
        } else if (mEmail.find()) {
            m.appendReplacement(result, "<a href=mailto:" + href + ">" + href + "</a>");
        }
    }
    m.appendTail(result);
    return result;
}

From source file:by.heap.remark.convert.TextCleaner.java

/**
 * Handles escaping special characters in URLs to avoid issues when they are rendered out
 * (ie: spaces, parentheses)/*from w w  w .  j  av a2 s .  c o m*/
 * @param input URL to process
 * @return Cleaned URL
 */
public String cleanUrl(String input) {
    StringBuffer output = new StringBuffer();

    Matcher m = URL_CLEANER.matcher(input);
    while (m.find()) {
        char c = m.group().charAt(0);
        m.appendReplacement(output, String.format("%%%02x", (int) c));
    }
    m.appendTail(output);
    return output.toString();
}

From source file:org.cosmo.common.util.Util.java

public static String replaceKeyword(String src, String keyword, String prefix, String suffix) {
    Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
    Matcher source = pattern.matcher(src);
    StringBuffer sb = new StringBuffer();
    while (source.find()) {
        source.appendReplacement(sb, prefix + source.toMatchResult().group() + suffix);
    }//from ww  w. j a  va 2s. co  m
    source.appendTail(sb);
    return sb.toString();
}

From source file:org.mitre.dsmiley.httpproxy.URITemplateProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    //First collect params
    /*//from   w ww.j ava  2 s  .c om
     * Do not use servletRequest.getParameter(arg) because that will
     * typically read and consume the servlet InputStream (where our
     * form data is stored for POST). We need the InputStream later on.
     * So we'll parse the query string ourselves. A side benefit is
     * we can keep the proxy parameters in the query string and not
     * have to add them to a URL encoded form attachment.
     */
    String queryString = "?" + servletRequest.getQueryString();//no "?" but might have "#"
    int hash = queryString.indexOf('#');
    if (hash >= 0) {
        queryString = queryString.substring(0, hash);
    }
    List<NameValuePair> pairs;
    try {
        //note: HttpClient 4.2 lets you parse the string without building the URI
        pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8");
    } catch (URISyntaxException e) {
        throw new ServletException("Unexpected URI parsing error on " + queryString, e);
    }
    LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
    for (NameValuePair pair : pairs) {
        params.put(pair.getName(), pair.getValue());
    }

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    while (matcher.find()) {
        String arg = matcher.group(1);
        String replacement = params.remove(arg);//note we remove
        if (replacement == null) {
            throw new ServletException("Missing HTTP parameter " + arg + " to fill the template");
        }
        matcher.appendReplacement(urlBuf, replacement);
    }
    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    //Determine the new query string based on removing the used names
    StringBuilder newQueryBuf = new StringBuilder(queryString.length());
    for (Map.Entry<String, String> nameVal : params.entrySet()) {
        if (newQueryBuf.length() > 0)
            newQueryBuf.append('&');
        newQueryBuf.append(nameVal.getKey()).append('=');
        if (nameVal.getValue() != null)
            newQueryBuf.append(nameVal.getValue());
    }
    servletRequest.setAttribute(ATTR_QUERY_STRING, newQueryBuf.toString());

    super.service(servletRequest, servletResponse);
}

From source file:fr.aliasource.webmail.formatting.HTMLBodyFormatter.java

private StringBuffer parseUrl(Matcher m, StringBuilder input) {
    StringBuffer result = new StringBuffer();

    Pattern pEmail = Pattern.compile(PATTERN_EMAIL);
    Pattern pUrl = Pattern.compile(PATTERN_URL);

    while (m.find()) {
        String href = m.group();//from   w  ww .j a v a 2  s  .  c  o m
        Matcher mEmail = pEmail.matcher(href);
        Matcher mUrl = pUrl.matcher(href);

        if (mUrl.find()) {
            if (href.startsWith("http")) {
                m.appendReplacement(result, "<a href=\"" + href + "\" target=\"_blank\">" + href + "</a>");
            } else {
                m.appendReplacement(result,
                        "<a href=\"http://" + href + "\" target=\"_blank\">" + href + "</a>");
            }
        } else if (mEmail.find()) {
            m.appendReplacement(result, "<a href=mailto:" + href + ">" + href + "</a>");
        }
    }
    m.appendTail(result);
    return result;
}

From source file:org.lockss.util.UrlUtil.java

/** Add a subdomain to the host part of a URL
 * @param url the URL string/*from www. j  a  va2  s . co  m*/
 * @param subdomain the subdomain to add (no trailing dot)
 * @return the URL string with the host prefixed with the subdomain
 */
public static String addSubDomain(String url, String subdomain) {
    Matcher m = SCHEME_HOST_PAT.matcher(url);
    if (m.find()) {
        String host = m.group(2);
        if (StringUtil.startsWithIgnoreCase(host, subdomain) && '.' == host.charAt(subdomain.length())) {
            // subdomain already present
            return url;
        }
        StringBuffer sb = new StringBuffer();
        m.appendReplacement(sb, "$1" + subdomain + ".$2");
        m.appendTail(sb);
        return sb.toString();
    }
    return url;
}