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.opencastproject.execute.impl.ExecuteServiceImpl.java

/**
 * Does the actual processing/*from  w  w w.j a va2s.co m*/
 *
 * @param arguments
 *          The list containing the program and its arguments
 * @param mp
 *          MediaPackage used in the operation
 * @param outFileName
 *          The name of the resulting file
 * @param expectedType
 *          The expected element type
 * @return A {@code String} containing the command output
 * @throws ExecuteException
 *           if some internal error occurred
 */
protected String doProcess(List<String> arguments, MediaPackage mp, String outFileName, Type expectedType)
        throws ExecuteException {

    String params = arguments.remove(1);

    File outFile = null;
    MediaPackageElement[] elementsByFlavor = null;

    try {
        if (outFileName != null) {
            // FIXME : Find a better way to place the output File
            File firstElement = workspace.get(mp.getElements()[0].getURI());
            outFile = new File(firstElement.getParentFile(), outFileName);
        }

        // Get the substitution pattern.
        // The following pattern matches, any construct with the form
        // #{name}
        // , where 'name' is the value of a certain property. It is stored in the backreference group 1.
        // Optionally, expressions can take a parameter, like
        // #{name(parameter)}
        // , where 'parameter' is the name of a certain parameter.
        // If specified, 'parameter' is stored in the group 2. Otherwise it's null.
        // Both name and parameter match any character sequence that does not contain {, }, ( or ) .
        Pattern pat = Pattern.compile("#\\{([^\\{\\}\\(\\)]+)(?:\\(([^\\{\\}\\(\\)]+)\\))?\\}");

        // Substitute the appearances of the patterns with the actual absolute paths
        Matcher matcher = pat.matcher(params);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            // group(1) = property. group(2) = (optional) parameter
            if (matcher.group(1).equals("id")) {
                matcher.appendReplacement(sb, mp.getIdentifier().toString());
            } else if (matcher.group(1).equals("flavor")) {
                elementsByFlavor = mp
                        .getElementsByFlavor(MediaPackageElementFlavor.parseFlavor(matcher.group(2)));
                if (elementsByFlavor.length == 0)
                    throw new ExecuteException(
                            "No elements in the MediaPackage match the flavor '" + matcher.group(1) + "'.");

                if (elementsByFlavor.length > 1)
                    logger.warn("Found more than one element with flavor '{}'. Using {} by default...",
                            matcher.group(1), elementsByFlavor[0].getIdentifier());

                File elementFile = workspace.get(elementsByFlavor[0].getURI());
                matcher.appendReplacement(sb, elementFile.getAbsolutePath());
            } else if (matcher.group(1).equals("out")) {
                matcher.appendReplacement(sb, outFile.getAbsolutePath());
            } else if (properties.get(matcher.group(1)) != null) {
                matcher.appendReplacement(sb, (String) properties.get(matcher.group(1)));
            } else if (bundleContext.getProperty(matcher.group(1)) != null) {
                matcher.appendReplacement(sb, bundleContext.getProperty(matcher.group(1)));
            }
        }
        matcher.appendTail(sb);
        params = sb.toString();
    } catch (IllegalArgumentException e) {
        throw new ExecuteException("Tag 'flavor' must specify a valid MediaPackage element flavor.", e);
    } catch (NotFoundException e) {
        throw new ExecuteException("The element '" + elementsByFlavor[0].getURI().toString()
                + "' does not exist in the workspace.", e);
    } catch (IOException e) {
        throw new ExecuteException("Error retrieving MediaPackage element from workspace: '"
                + elementsByFlavor[0].getURI().toString() + "'.", e);
    }

    arguments.addAll(splitParameters(params));

    return runCommand(arguments, outFile, expectedType);
}

From source file:io.swagger.codegen.languages.ElixirClientCodegen.java

@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
    Map<String, Object> operations = (Map<String, Object>) super.postProcessOperations(objs).get("operations");
    List<CodegenOperation> os = (List<CodegenOperation>) operations.get("operation");
    List<ExtendedCodegenOperation> newOs = new ArrayList<ExtendedCodegenOperation>();
    Pattern pattern = Pattern.compile("\\{([^\\}]+)\\}([^\\{]*)");
    for (CodegenOperation o : os) {
        ArrayList<String> pathTemplateNames = new ArrayList<String>();
        Matcher matcher = pattern.matcher(o.path);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            String pathTemplateName = matcher.group(1);
            matcher.appendReplacement(buffer, "#{" + underscore(pathTemplateName) + "}" + "$2");
            pathTemplateNames.add(pathTemplateName);
        }/*from   w  w  w .  j  a  v  a  2s  .c om*/
        ExtendedCodegenOperation eco = new ExtendedCodegenOperation(o);
        if (buffer.toString().isEmpty()) {
            eco.setReplacedPathName(o.path);
        } else {
            eco.setReplacedPathName(buffer.toString());
        }
        eco.setPathTemplateNames(pathTemplateNames);

        // detect multipart form types
        if (eco.hasConsumes == Boolean.TRUE) {
            Map<String, String> firstType = eco.consumes.get(0);
            if (firstType != null) {
                if ("multipart/form-data".equals(firstType.get("mediaType"))) {
                    eco.isMultipart = Boolean.TRUE;
                }
            }
        }

        newOs.add(eco);
    }
    operations.put("operation", newOs);
    return objs;
}

From source file:com.ibm.jaggr.service.impl.transport.AbstractHttpTransport.java

/**
 *  Decode JSON object encoded for url transport.
 *  Enforces ordering of object keys and mangles JSON format to prevent encoding of frequently used characters.
 *  Assumes that keynames and values are valid filenames, and do not contain illegal filename chars.
 *  See http://www.w3.org/Addressing/rfc1738.txt for small set of safe chars.  
 *//* ww  w .ja  v a  2s.c o m*/
protected JSONObject decodeModules(String encstr) throws IOException {
    StringBuffer json = new StringBuffer(encstr.length() * 2);
    Matcher m = DECODE_JSON.matcher(encstr);
    while (m.find()) {
        String match = m.group(1);
        if (match.equals("!")) //$NON-NLS-1$
            m.appendReplacement(json, ":"); //$NON-NLS-1$
        else if (match.equals("(")) //$NON-NLS-1$
            m.appendReplacement(json, "{"); //$NON-NLS-1$
        else if (match.equals(")")) //$NON-NLS-1$
            m.appendReplacement(json, "}"); //$NON-NLS-1$
        else if (match.equals("|")) //$NON-NLS-1$
            m.appendReplacement(json, "!"); //$NON-NLS-1$
        else if (match.equals("*")) //$NON-NLS-1$
            m.appendReplacement(json, ","); //$NON-NLS-1$
        else if (match.equals("<")) //$NON-NLS-1$
            m.appendReplacement(json, "("); //$NON-NLS-1$
        else if (match.equals(">")) //$NON-NLS-1$
            m.appendReplacement(json, ")"); //$NON-NLS-1$
    }
    m.appendTail(json);
    JSONObject decoded = null;
    String jsonstr = json.toString();
    jsonstr = REQUOTE_JSON.matcher(jsonstr).replaceAll("$1\"$2\"$3"); // matches all keys //$NON-NLS-1$
    jsonstr = REQUOTE_JSON.matcher(jsonstr).replaceAll("$1\"$2\"$3"); // matches all values //$NON-NLS-1$
    try {
        decoded = new JSONObject(jsonstr);
    } catch (JSONException e) {
        throw new BadRequestException(e);
    }
    return decoded;
}

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

public Properties preprocessVars(Properties unprocessedVars) {
    Properties newVars = new Properties(unprocessedVars);
    boolean doneProcessing = false;
    int recursionLevel = 0;
    while (!doneProcessing) {
        doneProcessing = true;//w ww. j a va2 s  . c o  m
        @SuppressWarnings("rawtypes")
        Enumeration newVarsEnum = newVars.propertyNames();
        while (newVarsEnum.hasMoreElements()) {
            String newVarsKey = (String) newVarsEnum.nextElement();
            String newVarsValue = newVars.getProperty(newVarsKey);
            Matcher m = PATTERN.matcher(newVarsValue);
            StringBuffer sb = new StringBuffer();
            while (m.find()) {
                String embeddedVar = m.group(1);
                String value = newVars.getProperty(embeddedVar);
                if (value != null) {
                    if (trim) {
                        value = value.trim();
                    }
                    String escapedValue = Matcher.quoteReplacement(value);
                    m.appendReplacement(sb, escapedValue);
                }
            }
            m.appendTail(sb);
            String replacementValue = sb.toString();
            if (!replacementValue.equals(newVarsValue)) {
                doneProcessing = false;
                newVars.put(newVarsKey, replacementValue);
            }
        }
        recursionLevel++;
        // Avoid infinite replacement loops
        if ((!doneProcessing) && (recursionLevel > MAX_RECURSION_LEVEL)) {
            break;
        }
    }
    return unescape(newVars);
}

From source file:PropertiesHelper.java

/**
 * Adds new properties to an existing set of properties while
 * substituting variables. This function will allow value
 * substitutions based on other property values. Value substitutions
 * may not be nested. A value substitution will be ${property.key},
 * where the dollar-brace and close-brace are being stripped before
 * looking up the value to replace it with. Note that the ${..}
 * combination must be escaped from the shell.
 *
 * @param b is the set of properties to add to existing properties.
 * @return the combined set of properties.
 *//* w w  w .jav a  2 s  .  c  om*/
protected Properties addProperties(Properties b) {
    // initial
    // Properties result = new Properties(this);
    Properties sys = System.getProperties();
    Pattern pattern = Pattern.compile("\\$\\{[-a-zA-Z0-9._]+\\}");

    for (Enumeration e = b.propertyNames(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        String value = b.getProperty(key);

        // unparse value ${prop.key} inside braces
        Matcher matcher = pattern.matcher(value);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            // extract name of properties from braces
            String newKey = value.substring(matcher.start() + 2, matcher.end() - 1);

            // try to find a matching value in result properties
            String newVal = getProperty(newKey);

            // if still not found, try system properties
            if (newVal == null) {
                newVal = sys.getProperty(newKey);
            }

            // replace braced string with the actual value or empty string
            matcher.appendReplacement(sb, newVal == null ? "" : newVal);
        }
        matcher.appendTail(sb);
        setProperty(key, sb.toString());
    }
    return this;
}

From source file:org.gvnix.jpa.geo.hibernatespatial.util.EWKTReader.java

/**
 * Removes all whitespace between Geometry type and <code>M</code> as this
 * parser expects. </br> Example: POINT M (111.1 111.1 5) ==> POINTM (111.1
 * 111.1 5)//from w  ww.jav a  2  s  .c om
 * 
 * @param wkt
 * @return
 */
private String fixMNames(String wkt) {
    Pattern p = Pattern.compile("(\\s*M\\s*[(])");
    Matcher m = p.matcher(wkt);
    StringBuffer s = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(s, "M (");
    }
    m.appendTail(s);
    return s.toString();
}

From source file:net.canarymod.util.SysOutWriterThread.java

private String replaceColours(String toProcess) throws IOException {
    if (!reader.getTerminal().isAnsiSupported()) {
        return TextFormat.removeFormatting(toProcess);
    } else {/*from www.  j  a v  a  2 s  .  c om*/
        Matcher matcher = colourPattern.matcher(toProcess);
        boolean result = matcher.find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                String match = matcher.group();
                String replacement = "";
                if (colourMap.containsKey(match)) {
                    Ansi replace = Ansi.ansi().reset();
                    replace = colourMap.get(match).getRight() ? replace.fgBright(colourMap.get(match).getLeft())
                            : replace.fg(colourMap.get(match).getLeft());
                    replacement = replace.toString();
                } else if (attributeMap.containsKey(match)) {
                    replacement = Ansi.ansi().a(attributeMap.get(match)).toString();
                }

                matcher.appendReplacement(sb, replacement);
                result = matcher.find();
            } while (result);
            matcher.appendTail(sb);
            sb.append(Ansi.ansi().reset());

            return sb.toString();
        }
        return toProcess;
    }
}

From source file:org.apache.bval.jsr.DefaultMessageInterpolator.java

private String replaceAnnotationAttributes(final String message,
        final Map<String, Object> annotationParameters) {
    Matcher matcher = messageParameterPattern.matcher(message);
    StringBuffer sb = new StringBuffer(64);
    while (matcher.find()) {
        String resolvedParameterValue;
        String parameter = matcher.group(1);
        Object variable = annotationParameters.get(removeCurlyBrace(parameter));
        if (variable != null) {
            if (variable.getClass().isArray()) {
                resolvedParameterValue = ArrayUtils.toString(variable);
            } else {
                resolvedParameterValue = variable.toString();
            }/*from w ww . ja v a2s . com*/
        } else {
            resolvedParameterValue = parameter;
        }
        matcher.appendReplacement(sb, sanitizeForAppendReplacement(resolvedParameterValue));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:fr.smile.liferay.LiferayUrlRewriter.java

/**
 * Fix all resources urls and return the result.
 *
 * @param input        The original charSequence to be processed.
 * @param requestUrl   The request URL./*w w  w  .  j a  v a2s.  com*/
 * @param baseUrlParam The base URL selected for this request.
 * @return the result of this renderer.
 */
public CharSequence rewriteHtml(CharSequence input, String requestUrl, Pattern pattern, String baseUrlParam,
        String visibleBaseUrl) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("input=" + input);
        LOG.debug("rewriteHtml (requestUrl=" + requestUrl + ", pattern=" + pattern + ",baseUrlParam)"
                + baseUrlParam + ",strVisibleBaseUrl=" + visibleBaseUrl + ")");
    }

    StringBuffer result = new StringBuffer(input.length());
    Matcher m = pattern.matcher(input);
    while (m.find()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("found match: " + m);
        }
        String url = input.subSequence(m.start(3) + 1, m.end(3) - 1).toString();
        url = rewriteUrl(url, requestUrl, baseUrlParam, visibleBaseUrl);
        url = url.replaceAll("\\$", "\\\\\\$"); // replace '$' -> '\$' as it
        // denotes group
        StringBuffer tagReplacement = new StringBuffer("<$1$2=\"").append(url).append("\"");
        if (m.groupCount() > 3) {
            tagReplacement.append("$4");
        }
        tagReplacement.append('>');
        if (LOG.isTraceEnabled()) {
            LOG.trace("replacement: " + tagReplacement);
        }
        m.appendReplacement(result, tagReplacement.toString());
    }
    m.appendTail(result);

    return result;
}

From source file:net.sf.j2ep.UrlRewritingOutputStream.java

/**
 * Processes the stream looking for links, all links found are rewritten.
 * After this the stream is written to the response.
 * /*from  w  w  w  .j a  v a2 s.  c  om*/
 * @param server
 *            The server that we are using for this request.
 * @throws IOException
 *             Is thrown when there is a problem with the streams
 */
public void rewrite(Server server) throws IOException {
    /*
     * Using regex can be quite harsh sometimes so here is how the regex
     * trying to find links works
     * 
     * \\b(href=|src=|action=|url\\()([\"\']) This part is the
     * identification of links, matching something like href=", href=' and
     * href=
     * 
     * (([^/]+://)([^/<>]+))? This is to identify absolute paths. A link
     * doesn't have to be absolute therefor there is a ?.
     * 
     * ([^\"\'>]*) This is the link
     * 
     * [\"\'] Ending " or '
     * 
     * $1 - link type, e.g. href= $2 - ", ' or whitespace $3 - The entire
     * http://www.server.com if present $4 - The protocol, e.g http:// or
     * ftp:// $5 - The host name, e.g. www.server.com $6 - The link
     */
    StringBuffer page = new StringBuffer();

    Matcher matcher = linkPattern.matcher(stream.toString());

    while (matcher.find()) {

        String link = matcher.group(6).replaceAll("\\$", "\\\\\\$");
        if (link.length() == 0) {
            link = "/";
        }

        String rewritten = null;
        if (matcher.group(4) != null) {
            rewritten = handleExternalLink(matcher, link);
        } else if (link.startsWith("/")) {
            rewritten = handleLocalLink(server, matcher, link);
        }

        if (rewritten != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found link " + link + " >> " + rewritten);
            }
            matcher.appendReplacement(page, rewritten);
        }
    }

    matcher.appendTail(page);
    originalStream.write(stream.toByteArray());
}