Example usage for java.util.regex Matcher quoteReplacement

List of usage examples for java.util.regex Matcher quoteReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher quoteReplacement.

Prototype

public static String quoteReplacement(String s) 

Source Link

Document

Returns a literal replacement String for the specified String .

Usage

From source file:org.squale.squalix.configurationmanager.ConfigUtility.java

/**
 * This method parses the given String to replace any "${...}"-like variable by the corresponding system property.
 * If no property is found, then the variable is left as is.
 * /*  w w  w  .j av  a2 s .  c  om*/
 * @param originalString the string to filter
 * @return the filtered String
 */
public static String filterStringWithSystemProps(String originalString) {
    String result = originalString;

    // Defines a "${...}"-like variable
    Pattern pattern = Pattern.compile("\\$\\{(\\w||\\.)*\\}");
    Matcher matcher = pattern.matcher(result);
    // try to find occurrences
    int searchIndex = 0;
    while (matcher.find(searchIndex)) {
        String propVar = matcher.group();
        // retrieve the name of the variable
        String propName = matcher.group().substring(2, propVar.length() - 1);
        // and try to retrieve its value
        String propValue = System.getProperty(propName);
        if (propValue != null) {
            // need to quote the string to prevent "\" to be removed
            result = matcher.replaceFirst(Matcher.quoteReplacement(propValue));
            searchIndex = matcher.start() + propValue.length();
        } else {
            // do nothing but increase the search index
            searchIndex = matcher.end();
        }
        // keep on analyzing the string for other matches
        matcher = pattern.matcher(result);
    }

    return result;
}

From source file:com.jwebmp.core.FileTemplates.java

/**
 * Replaces all instances of the following
 *
 * @param templateName/*  w ww  . j  a v a  2s. c  o  m*/
 *       The name of the template being processed
 * @param template
 *       The physical string to process
 *
 * @return
 */
public static StringBuilder processTemplate(String templateName, String template) {
    String templateOutput = template;
    for (String templateVariable : getTemplateVariables().keySet()) {
        String templateScript = null;
        try {
            templateScript = Matcher.quoteReplacement(getTemplateVariables().get(templateVariable).toString());
            templateOutput = templateOutput.replaceAll(
                    StaticStrings.STRING_EMPTY + templateVariable + StaticStrings.STRING_EMPTY, templateScript);
        } catch (NullPointerException iae) {
            LOG.log(Level.WARNING,
                    "[Error]-[Unable to find specified template];[Script]-[" + templateVariable + "]", iae);
        } catch (IllegalArgumentException iae) {
            LOG.log(Level.WARNING, format(
                    "[Error]-[Invalid Variable Name for Regular Expression Search];[Variable]-[{0}];[Script]-[{1}]",
                    templateVariable, templateScript), iae);
        }
    }
    TemplateScripts.put(templateName, new StringBuilder(templateOutput.trim()));
    return TemplateScripts.get(templateName);
}

From source file:org.sablo.IndexPageEnhancer.java

/**
 * Enhance the provided index.html// ww w .  ja v  a  2  s .com
 * @param resource url to index.html
 * @param contextPath the path to express in base tag
 * @param cssContributions possible css contributions
 * @param jsContributions possible js contributions
 * @param variableSubstitution replace variables
 * @param writer the writer to write to
 * @throws IOException
 */
public static void enhance(URL resource, String contextPath, Collection<String> cssContributions,
        Collection<String> jsContributions, Map<String, String> variableSubstitution, Writer writer,
        IContributionFilter contributionFilter) throws IOException {
    String index_file = IOUtils.toString(resource);
    String lowercase_index_file = index_file.toLowerCase();
    int headstart = lowercase_index_file.indexOf("<head>");
    int headend = lowercase_index_file.indexOf(COMPONENT_CONTRIBUTIONS);

    //use real html parser here instead?
    if (variableSubstitution != null) {
        for (String variableName : variableSubstitution.keySet()) {
            String variableReplace = VAR_START + variableName + VAR_END;
            index_file = index_file.replaceAll(Matcher.quoteReplacement(variableReplace),
                    variableSubstitution.get(variableName));
        }
    }

    StringBuilder sb = new StringBuilder(index_file);
    if (headend < 0) {
        log.warn("Could not find marker for component contributions: " + COMPONENT_CONTRIBUTIONS
                + " for resource " + resource);
    } else {
        sb.insert(headend + COMPONENT_CONTRIBUTIONS.length(),
                getAllContributions(cssContributions, jsContributions, contributionFilter));
    }
    if (headstart < 0) {
        log.warn("Could not find empty head tag for base tag for resource " + resource);
    } else {
        sb.insert(headstart + 6, getBaseTag(contextPath));
    }
    writer.append(sb);
}

From source file:com.thoughtworks.go.utils.CommandUtils.java

/**
 * Surrounds a string with double quotes if it is not already surrounded by single or double quotes, or if it contains
 * unescaped spaces, single quotes, or double quotes. When surrounding with double quotes, this method will only escape
 * double quotes in the String.//from   ww  w  .j av a2  s .com
 *
 * This method assumes the argument is well-formed if it was already surrounded by either single or double quotes.
 *
 * @param argument String to quote
 * @return the quoted String, if not already quoted
 */
public static String quoteArgument(String argument) {
    if (QUOTED_STRING.matcher(argument).matches() || !UNESCAPED_SPACE_OR_QUOTES.matcher(argument).find()) {
        // assume the argument is well-formed if it's already quoted or if there are no unescaped spaces or quotes
        return argument;
    }

    return String.format("\"%s\"",
            DOUBLE_QUOTE.matcher(argument).replaceAll(Matcher.quoteReplacement("\\") + "$1"));
}

From source file:com.hexidec.ekit.component.HTMLTableUtilities.java

public static String separaTabelasDeParagrafos(String str) {

    Matcher m = pTabelaEmParagrafo.matcher(str);
    if (!m.find()) {
        return str;
    }//from   ww  w. j a v  a 2  s .  com

    StringBuffer sb = new StringBuffer();
    StringBuffer trecho;
    String pOpen, strBefore, tOpen, tBody, strAfter;
    do {
        trecho = new StringBuffer();
        pOpen = m.group(1);
        strBefore = m.group(2);
        tOpen = m.group(3);
        tBody = m.group(4);
        strAfter = m.group(5);

        if (!StringUtils.isEmpty(strBefore.trim())) {
            trecho.append(pOpen);
            trecho.append(strBefore);
            trecho.append("</p>");
        }
        trecho.append(tOpen);
        trecho.append(tBody);
        trecho.append("</table>");
        if (!StringUtils.isEmpty(strAfter.trim())) {
            trecho.append(pOpen);
            trecho.append(strAfter);
            trecho.append("</p>");
        }

        m.appendReplacement(sb, Matcher.quoteReplacement(trecho.toString()));

    } while (m.find());

    m.appendTail(sb);

    return sb.toString();
}

From source file:br.gov.frameworkdemoiselle.util.contrib.Strings.java

public static String getString(final String string, final Object... params) {
    String result = null;/*www  .  j a  va2  s  . c  om*/

    if (string != null) {
        result = new String(string);
    }

    if (params != null && string != null) {
        for (int i = 0; i < params.length; i++) {
            if (params[i] != null) {
                result = result.replaceAll("\\{" + i + "\\}", Matcher.quoteReplacement(params[i].toString()));
            }
        }
    }

    return result;
}

From source file:pt.webdetails.cdf.dd.model.inst.writer.cdfrunjs.dashboard.CdfRunJsDashboardWriteResult.java

public String getContent(String contextConfiguration) {
    return this._content.replaceFirst(CdeConstants.DASHBOARD_CONTEXT_CONFIGURATION_TAG,
            StringUtils.defaultIfEmpty(Matcher.quoteReplacement(contextConfiguration), "{}"));
}

From source file:org.entando.edo.model.EdoBuilder.java

public String getJavaFolder() {
    String pojoPath = this.getBaseDir() + FolderConstants.getJavaFolder()
            + this.getPackageName().replaceAll("\\.", Matcher.quoteReplacement(File.separator))
            + File.separator;//  w w  w.  j  a  va  2  s .c  om
    return pojoPath;
}

From source file:net.triptech.metahive.CalculationParser.java

/**
 * Builds the calculation.// w w w .  j a va2 s  . c o m
 *
 * @param calculation the calculation
 * @param values the values
 * @return the string
 */
public static String buildCalculation(String calculation, Map<Long, Double> values) {

    String parsedCalculation = "";

    logger.debug("Calculation: " + calculation);
    logger.debug("Values: " + values);

    if (StringUtils.isNotBlank(calculation) && values != null) {
        try {
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(calculation);
            StringBuffer sb = new StringBuffer();
            logger.debug("Regular expression: " + regEx);
            while (m.find()) {
                logger.info("Variable instance found: " + m.group());
                try {
                    String text = m.group();
                    Long id = Long.parseLong(StringUtils.substring(text, 1));
                    logger.info("Variable id: " + id);

                    if (values.containsKey(id)) {
                        logger.debug("Contains variable " + id);
                        double value = values.get(id);
                        logger.debug("Value: " + value);
                        text = String.valueOf(value);
                    }
                    logger.debug("Replacement text: " + text);
                    m.appendReplacement(sb, Matcher.quoteReplacement(text));

                } catch (NumberFormatException nfe) {
                    logger.error("Error parsing variable id");
                }
            }
            m.appendTail(sb);

            parsedCalculation = sb.toString();
            logger.info("Parsed calculation: " + parsedCalculation);

        } catch (PatternSyntaxException pe) {
            logger.error("Regex syntax error ('" + pe.getPattern() + "') " + pe.getMessage());
        }
    }
    return parsedCalculation;
}

From source file:io.apigee.buildTools.enterprise4g.utils.ZipUtils.java

static void addDir(File dirObj, ZipOutputStream out, File root, String prefix) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDir(files[i], out, root, prefix);
            continue;
        }/* ww w  .j av  a 2 s  .co  m*/
        FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
        log.debug(" Adding: " + files[i].getAbsolutePath());

        String relativePath = files[i].getCanonicalPath().substring(root.getCanonicalPath().length());
        while (relativePath.startsWith("/")) {
            relativePath = relativePath.substring(1);
        }
        while (relativePath.startsWith("\\")) {
            relativePath = relativePath.substring(1);
        }

        String left = Matcher.quoteReplacement("\\");
        String right = Matcher.quoteReplacement("/");

        relativePath = relativePath.replaceAll(left, right);
        relativePath = (prefix == null) ? relativePath : prefix + "/" + relativePath;
        out.putNextEntry(new ZipEntry(relativePath));
        int len;
        while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
}