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.entando.edo.builder.TestBuilderNoPlugin.java

@Test
public void test_Service_Init_Xml() throws IOException {

    String commonPath = "src/main/resources/component/sandbox".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.entando.edo.builder.TestBuilder.java

@Test
public void test_Service_Init_Xml() throws IOException {

    String commonPath = "src/main/resources/component/plugins/jppet".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.centralperf.sampler.driver.gatling.GatlingLauncher.java

/**
 * @see SamplerLauncher// w w  w . j  a v  a 2  s.  co m
 */
public SamplerRunJob launch(String simulation, Run run) {

    String fs = System.getProperty("file.separator");

    // Create temporary Gatling files
    String centralPerfDirectoryPath = System.getProperty("java.io.tmpdir") + fs + "centralperf";
    String simulationDirectoryPath = centralPerfDirectoryPath + fs + "simulations";
    String outputDirectoryPath = centralPerfDirectoryPath + fs + "output" + UUID.randomUUID();

    // Create folders for output
    new File(outputDirectoryPath).mkdirs();

    // Get class name and package name
    Pattern packagePattern = Pattern.compile("package (.*)");
    Matcher packageMatcher = packagePattern.matcher(simulation);
    String packageName = packageMatcher.find() ? packageMatcher.group(1) : null;
    Pattern classnamePattern = Pattern.compile("class (.*) extends.*");
    Matcher classnameMatcher = classnamePattern.matcher(simulation);
    String classname = classnameMatcher.find() ? classnameMatcher.group(1) : null;

    if (packageName == null || classname == null) {
        // TODO : manage this error
        return null;
    }

    // Create folder for package
    String simulationDirectoryPackagePath = simulationDirectoryPath + fs
            + packageName.replaceAll("\\\\.", Matcher.quoteReplacement(fs));
    new File(simulationDirectoryPackagePath).mkdirs();
    String simulationFileName = classname + ".scala";
    String simulationFilePath = simulationDirectoryPackagePath + fs + simulationFileName;

    // Put the simulation
    File simulationFile = new File(simulationFilePath);
    try {
        FileUtils.writeStringToFile(simulationFile, simulation);
    } catch (IOException e1) {
        log.error("IO Error on gatling launch:" + e1.getMessage(), e1);
    }
    // MEMO
    /*Usage: gatling [options]
            
      -nr | --no-reports
            Runs simulation but does not generate reports
      -ro <directoryName> | --reports-only <directoryName>
            Generates the reports for the simulation in <directoryName>
      -df <directoryPath> | --data-folder <directoryPath>
            Uses <directoryPath> as the absolute path of the directory where feeders are stored
      -rf <directoryPath> | --results-folder <directoryPath>
            Uses <directoryPath> as the absolute path of the directory where results are stored
      -bf <directoryPath> | --request-bodies-folder <directoryPath>
            Uses <directoryPath> as the absolute path of the directory where request bodies are stored
      -sf <directoryPath> | --simulations-folder <directoryPath>
            Uses <directoryPath> to discover simulations that could be run
      -sbf <directoryPath> | --simulations-binaries-folder <directoryPath>
            Uses <directoryPath> to discover already compiled simulations
      -s <className> | --simulation <className>
            Runs <className> simulation
      -on <name> | --output-name <name>
            Use <name> for the base name of the output directory
      -sd <description> | --simulation-description <description>
            A short <description> of the run to include in the report
    */

    String[] command = new String[] { gatlingLauncherPath + fs + gatlingLauncherScriptRelativePath, "-sf",
            simulationDirectoryPath, "-s", packageName + "." + classname, "-nr", "-rf", outputDirectoryPath,
            "-on", OUTPUT_PATTERN_PATH };
    GatlingRunJob job = new GatlingRunJob(command, run);
    job.setScriptLauncherService(scriptLauncherService);
    job.setRunResultService(runResultService);
    job.setSimulationFile(simulationFile);
    job.setResultFile(new File(outputDirectoryPath));
    job.setGatlingLauncherPath(gatlingLauncherPath);
    Thread jobThread = new Thread(job);
    jobThread.start();

    return job;
}

From source file:org.nuxeo.theme.styling.wro.FlavorResourceProcessor.java

protected void process(final Resource resource, final Reader reader, final Writer writer, String flavorName)
        throws IOException {
    final InputStream is = new ProxyInputStream(new ReaderInputStream(reader, getEncoding())) {
    };//from   ww w .  j a v a  2  s  . c  o  m
    final OutputStream os = new ProxyOutputStream(new WriterOutputStream(writer, getEncoding()));
    try {
        Map<String, String> presets = null;
        if (flavorName != null) {
            ThemeStylingService s = Framework.getService(ThemeStylingService.class);
            presets = s.getPresetVariables(flavorName);
        }
        if (presets == null || presets.isEmpty()) {
            IOUtils.copy(is, os);
        } else {
            String content = IOUtils.toString(reader);
            for (Map.Entry<String, String> preset : presets.entrySet()) {
                content = Pattern.compile(String.format("\"%s\"", preset.getKey()), Pattern.LITERAL)
                        .matcher(content).replaceAll(Matcher.quoteReplacement(preset.getValue()));
            }
            writer.write(content);
            writer.flush();
        }
        is.close();
        os.close();
    } catch (final Exception e) {
        throw WroRuntimeException.wrap(e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:com.asual.summer.core.util.StringUtils.java

public static String decorate(String str, Map<String, String> values, boolean preserve) {
    Matcher m = Pattern.compile("\\$\\{[^}]*\\}").matcher(str);
    while (m.find()) {
        String key = m.group().replaceAll("^\\$\\{|\\}$", "");
        String value = values.get(key);
        if (value == null) {
            if (preserve) {
                continue;
            } else {
                value = "";
            }/*w w  w  . j a  v  a  2 s. com*/
        }
        str = str.replaceAll("\\$\\{" + key + "\\}", Matcher.quoteReplacement(value));
    }
    return str;
}

From source file:org.sventon.util.KeywordHandler.java

/**
 * Substitutes keywords in content.//from   w w w  .  j av  a 2s  .c om
 *
 * @param content  The content
 * @param encoding Encoding to use.
 * @return Content with substituted keywords.
 * @throws UnsupportedEncodingException if given encoding is unsupported.
 */
public String substitute(final String content, final String encoding) throws UnsupportedEncodingException {
    String substitutedContent = content;
    for (String keyword : keywordsMap.keySet()) {
        logger.debug("Substituting keywords");
        final String value = new String(keywordsMap.get(keyword), encoding);
        logger.debug(keyword + "=" + value);
        final Pattern keywordPattern = Pattern.compile("\\$" + keyword + "\\$");
        substitutedContent = keywordPattern.matcher(substitutedContent)
                .replaceAll("\\$" + keyword + ": " + Matcher.quoteReplacement(value) + " \\$");
    }
    return substitutedContent;
}

From source file:org.perfcake.util.Utils.java

/**
 * Filters properties in the given string. Consider using {@link org.perfcake.util.StringTemplate} instead.
 *
 * @param text/*from   w  w  w.  j  a va 2  s  .com*/
 *       The string to be filtered.
 * @param matcher
 *       The matcher to find the properties, any user specified matcher can be provided.
 * @param pg
 *       The {@link org.perfcake.util.properties.PropertyGetter} to provide values of the properties.
 * @return The filtered text.
 */
public static String filterProperties(final String text, final Matcher matcher, final PropertyGetter pg) {
    String filteredString = text;

    matcher.reset();
    while (matcher.find()) {
        String pValue = null;
        final String pName = matcher.group(2);
        String defaultValue = null;
        if (matcher.groupCount() == 3 && matcher.group(3) != null) {
            defaultValue = (matcher.group(3)).substring(1);
        }
        pValue = pg.getProperty(pName, defaultValue);
        if (pValue != null) {
            filteredString = filteredString.replaceAll(Pattern.quote(matcher.group(1)),
                    Matcher.quoteReplacement(pValue));
        }
    }

    return filteredString;
}

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

/**
 * Marks up the calculation.//from  ww  w . j a  v a  2s . c  o m
 *
 * @param calculation the calculation
 * @return the string
 */
public static String maredUpCalculation(String calculation) {

    String markedUpCalculation = "";

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

    if (StringUtils.isNotBlank(calculation)) {
        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 = "<span class=\"variable\">" + m.group().toUpperCase() + "</span>";

                    m.appendReplacement(sb, Matcher.quoteReplacement(text));

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

            markedUpCalculation = sb.toString();
            logger.info("Marked up calculation: " + markedUpCalculation);

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

From source file:edu.kit.dama.staging.adapters.DefaultStorageVirtualizationAdapter.java

@Override
public boolean configure(Configuration pConfig) throws ConfigurationException {
    pathPattern = pConfig.getString("pathPattern");
    String archiveUrlProperty = pConfig.getString("archiveUrl");
    if (archiveUrlProperty == null) {
        throw new ConfigurationException("Property 'archiveUrl' is missing");
    }/*from ww w. j  a v  a  2s. c om*/

    //replace TMP_DIR_PATTERN in target URL
    LOGGER.debug("Looking for replacements in archive location");
    String tmp = System.getProperty("java.io.tmpdir");
    if (!tmp.startsWith("/")) {
        tmp = "/" + tmp;
    }
    archiveUrlProperty = archiveUrlProperty.replaceAll(Pattern.quote(TMP_DIR_PATTERN),
            Matcher.quoteReplacement(tmp));
    LOGGER.debug("Using archive Url {}", archiveUrlProperty);
    //set baseDestinationURL property

    try {
        archiveUrl = new URL(archiveUrlProperty);
    } catch (MalformedURLException mue) {
        throw new ConfigurationException("archiveUrl property (" + archiveUrlProperty + ") is not a valid URL",
                mue);
    }

    AbstractFile destination = new AbstractFile(archiveUrl);
    //if caching location is local, check accessibility
    if (destination.isLocal()) {
        LOGGER.debug("Archive URL is local. Checking accessibility.");
        URI uri = null;

        try {
            uri = destination.getUrl().toURI();
        } catch (IllegalArgumentException ex) {
            //provided archive URL is no URI (e.g. file://folder/ -> third slash is missing after file:)
            throw new StagingIntitializationException(
                    "Archive location " + destination.getUrl().toString() + " has an invalid URI syntax", ex);
        } catch (URISyntaxException ex) {
            LOGGER.warn("Failed to check local archive URL. URL " + destination.getUrl()
                    + " seems not to be a valid URI.", ex);
        }
        File localFile = null;
        try {
            localFile = new File(uri);
        } catch (IllegalArgumentException ex) {
            throw new ConfigurationException("Archive URI " + uri
                    + " seems not to be a supported file URI. This storage virtualization implementation only supports URLs in the format file:///<path>/",
                    ex);
        }

        if (!FileUtils.isAccessible(localFile)) {
            throw new StagingIntitializationException(
                    "Archive location seems to be offline: '" + destination.getUrl().toString() + "'");
        }
    }

    try {
        if (!destination.exists()) {
            LOGGER.debug("Archive location does not exists, trying to create it...");
            destination = AbstractFile.createDirectory(destination);
            LOGGER.debug("Archive location successfully created ");
        } else {
            LOGGER.debug("Archive location already exists");
        }
        //clear cached values, e.g. for isReadable() and isWriteable()
        destination.clearCachedValues();
        //check access
        if (destination.isReadable() && destination.isWriteable()) {
            LOGGER.debug("Archive location '{}' is valid", destination.getUrl());
        } else {
            throw new StagingIntitializationException(
                    "Archive location '" + destination.getUrl().toString() + "' is not accessible");
        }
    } catch (AdalapiException ae) {
        throw new StagingIntitializationException(
                "Failed to setup archive location '" + destination.getUrl().toString() + "'", ae);
    }
    return true;
}

From source file:com.threewks.thundr.route.Route.java

static String convertPathStringToRegex(String route) {
    String wildCardPlaceholder = "____placeholder____";
    route = route.replaceAll("\\*\\*", wildCardPlaceholder);
    route = route.replaceAll("\\*", Matcher.quoteReplacement("[" + AcceptablePathCharacters + "]*?"));
    route = PathParameterPattern.matcher(route)
            .replaceAll(Matcher.quoteReplacement("([" + AcceptablePathCharacters + "]+)"));
    route = route.replaceAll(wildCardPlaceholder,
            Matcher.quoteReplacement("[" + AcceptableMultiPathCharacters + "]*?"));
    return route + SemiColonDelimitedRequestParameters;
}