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.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;//  ww  w  .  j  a  v a2 s. c o m
        }

        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.mitre.dsmiley.httpproxy.URITemplateProxyServlet.java

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

    //First collect params
    /*//from  ww w  .j a v a 2  s  .c  o  m
     * 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:org.lockss.util.UrlUtil.java

/** Add a subdomain to the host part of a URL
 * @param url the URL string/* w w w.java 2 s . c  o 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;
}

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 ww  w .j  a v a2 s  . com
 * @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:com.agimatec.validation.jsr303.DefaultMessageInterpolator.java

private String replaceVariables(String message, ResourceBundle bundle, Locale locale, boolean recurse) {
    Matcher matcher = messageParameterPattern.matcher(message);
    StringBuffer sb = new StringBuffer();
    String resolvedParameterValue;
    while (matcher.find()) {
        String parameter = matcher.group(1);
        resolvedParameterValue = resolveParameter(parameter, bundle, locale, recurse);

        matcher.appendReplacement(sb, resolvedParameterValue);
    }/*w  w  w  .j  a  v a 2 s  .  com*/
    matcher.appendTail(sb);
    return sb.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  v a 2s . c om*/
    source.appendTail(sb);
    return sb.toString();
}

From source file:org.carewebframework.maven.plugin.processor.AbstractProcessor.java

/**
 * Adjust any url references in the line to use new root path.
 * /*from www. j a v a 2 s . c  o m*/
 * @param line String to modify
 * @return the modified string
 */
public String replaceURLs(String line) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = URL_PATTERN.matcher(line);
    String newPath = "~./" + getResourceBase() + "/";

    while (matcher.find()) {
        char dlm = line.charAt(matcher.start() - 1);
        int i = line.indexOf(dlm, matcher.end());
        String url = i > 0 ? line.substring(matcher.start(), i) : null;

        if (url == null || (!mojo.isExcluded(url) && getTransform(url) != null)) {
            matcher.appendReplacement(sb, newPath);
        }
    }

    matcher.appendTail(sb);
    return sb.toString();
}

From source file:com.bellman.bible.android.control.link.LinkControl.java

/**
 * IBT use _nn_ for punctuation chars in references to dictionaries e.g. _32_ represents a space so 'Holy_32_Spirit' should be converted to 'Holy Spirit'
 *
 * @param ref Key e.g. dictionary key/*from   ww w .ja va2s  .  c o m*/
 * @return ref with _nn_ replaced by punctuation
 */
private String replaceIBTSpecialCharacters(String ref) {
    Matcher refIBTSpecialCharMatcher = IBT_SPECIAL_CHAR_RE.matcher(ref);
    StringBuffer output = new StringBuffer();
    while (refIBTSpecialCharMatcher.find()) {
        String specialChar = Character.toString((char) Integer.parseInt(refIBTSpecialCharMatcher.group(1)));
        refIBTSpecialCharMatcher.appendReplacement(output, specialChar);
    }
    refIBTSpecialCharMatcher.appendTail(output);
    return output.toString();
}

From source file:com.meidusa.venus.validate.validator.ValidatorSupport.java

public String getMessage(Object value) {
    if (message == null) {
        return "";
    }/*from   w  w  w .  j  a v  a 2  s . co  m*/
    String result = null;
    if (messageParameters == null || messageParameters.length == 0) {
        result = message;
    } else {
        Object[] parsedParameters = new Object[messageParameters.length];
        for (int i = 0; i < this.messageParameters.length; i++) {
            if (STAND_FOR_NAME.equals(messageParameters[i])) {
                parsedParameters[i] = this.describeValidateName();
            } else if (STAND_FOR_VALUE.equals(messageParameters[i])) {
                if (value != null) {
                    parsedParameters[i] = value.toString();
                } else {
                    parsedParameters[i] = "null";

                }
            } else {
                parsedParameters[i] = holder.findString(messageParameters[i]);
            }
        }
        result = String.format(message, parsedParameters);
    }
    Matcher matcher = validatorPattern.matcher(result);
    StringBuffer sb = new StringBuffer();
    Object obj = null;
    while (matcher.find()) {
        try {
            obj = PropertyUtils.getProperty(this, matcher.group(1));
        } catch (Exception e) {
            obj = "null";
        }
        if (obj == null) {
            obj = "null";
        }
        matcher.appendReplacement(sb, obj.toString());
    }
    matcher.appendTail(sb);
    return sb.toString();
}