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.nuxeo.theme.html.CSSUtils.java

public static String expandPartialUrls(String text, String cssContextPath) {
    Matcher m = partialUrlPattern.matcher(text);
    if (!cssContextPath.endsWith("/")) {
        cssContextPath += "/";
    }/*from   w ww  .ja v  a2s  .  c  om*/
    String replacement = String.format("url(%s$1)", Matcher.quoteReplacement(cssContextPath));
    return m.replaceAll(replacement);
}

From source file:br.ufal.cideei.soot.instrument.FeatureModelInstrumentorTransformer.java

private void preTransform(Body body) {
    SootClass sootClass = body.getMethod().getDeclaringClass();
    if (!sootClass.hasTag("SourceFileTag")) {
        throw new IllegalArgumentException("the body cannot be traced to its source file");
    }//from   ww  w.j a  v  a2s  . c o  m
    /*
     * XXX: WARNING! tag.getAbsolutePath() returns an INCORRECT value for the absolute path AFTER the first body
     * transformation. In this workaround, since this method depends on the classpath , it is injected on this class
     * constructor. We will use tag.getSourceFile() in order to resolve the file name.
     * 
     * Yes, this is ugly.
     */
    SourceFileTag sourceFileTag = (SourceFileTag) body.getMethod().getDeclaringClass().getTag("SourceFileTag");

    /*
     * The String absolutePath will be transformed to the absolute path to the Class which body belongs to. See the
     * XXX above for the explanation.
     */
    String absolutePath = sootClass.getName();
    int lastIndexOf = absolutePath.lastIndexOf(".");
    if (lastIndexOf != -1) {
        absolutePath = absolutePath.substring(0, lastIndexOf);
    } else {
        absolutePath = "";
    }

    /*
     * XXX String#replaceAll does not work properly when replacing "special" chars like File.separator. The Matcher
     * and Pattern composes a workaround for that.
     */
    absolutePath = absolutePath.replaceAll(Pattern.quote("."), Matcher.quoteReplacement(File.separator));
    absolutePath = classPath + File.separator + absolutePath + File.separator + sourceFileTag.getSourceFile();
    sourceFileTag.setAbsolutePath(absolutePath);

    IPath path = new Path(sourceFileTag.getAbsolutePath());
    this.file = org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);

    // #ifdef METRICS
    long startCompilationUnitParser = System.nanoTime();
    // #endif
    CompilationUnit compilationUnit = cachedParser.parse(file);
    // #ifdef METRICS
    long parsingDelta = System.nanoTime() - startCompilationUnitParser;
    if (sink != null)
        sink.flow(body, FeatureModelInstrumentorTransformer.PARSING, parsingDelta);
    FeatureModelInstrumentorTransformer.parsingTime += parsingDelta;

    long startBuilderColorLookUpTable = System.nanoTime();
    // #endif
    this.currentColorMap = cachedLineColorMapper.makeAccept(compilationUnit, file, extracter, compilationUnit);
    // #ifdef METRICS
    long builderColorLookUpTableDelta = System.nanoTime() - startBuilderColorLookUpTable;
    if (sink != null)
        sink.flow(body, FeatureModelInstrumentorTransformer.COLOR_LOOKUP, builderColorLookUpTableDelta);
    FeatureModelInstrumentorTransformer.colorLookupTableBuildingTime += builderColorLookUpTableDelta;
    // #endif
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private String completeHeader(HttpServletRequest httpRequest, Matcher htmlMatcher, String html) {
    // Try to place the css as the first link in the head tag
    Matcher startHeadMatcher = START_HEAD_PATTERN.matcher(html);
    if (startHeadMatcher.find()) {
        html = startHeadMatcher.replaceFirst("$1" + Matcher.quoteReplacement(headerStyles.toString()));
    } else {/*from  www.jav a 2s .  co m*/
        Head head = new Head();
        head.addText(headerStyles);
        html = htmlMatcher.replaceFirst("$1" + Matcher.quoteReplacement(head.getHtml().toString()));
    }

    // Place the CSRF token as Meta tags
    String tokenName = (String) httpRequest.getAttribute(REQUEST_META_DATA_CSRF_TOKEN_NAME);
    if (tokenName != null) {
        String tokenValue = (String) httpRequest.getAttribute(REQUEST_META_DATA_CSRF_TOKEN_VALUE);
        startHeadMatcher = START_HEAD_PATTERN.matcher(html);

        Tag csrfName = new Meta().addAttribute("name", CSRF_TOKEN_NAME).addAttribute("content", tokenName);
        Tag csrfToken = new Meta().addAttribute("name", CSRF_TOKEN_VALUE).addAttribute("content", tokenValue);
        StringBuilder metaTags = csrfName.getHtml().append(csrfToken.getHtml());

        html = startHeadMatcher.replaceFirst("$1" + Matcher.quoteReplacement(metaTags.toString()));
    }
    return html;
}

From source file:de.uni_luebeck.inb.knowarc.usecases.invocation.local.LocalUseCaseInvocation.java

@Override
protected void submit_generate_job_inner() throws InvocationException {
    tags.put("uniqueID", "" + getSubmissionID());
    String command = usecase.getCommand();
    for (String cur : tags.keySet()) {
        command = command.replaceAll("\\Q%%" + cur + "%%\\E", Matcher.quoteReplacement(tags.get(cur)));
    }//  w ww .j a va2  s.  com

    List<String> cmds = new ArrayList<String>();
    if ((shellPrefix != null) && !shellPrefix.isEmpty()) {
        String[] prefixCmds = shellPrefix.split(" ");
        for (int i = 0; i < prefixCmds.length; i++) {
            cmds.add(prefixCmds[i]);
        }
        cmds.add(command);
    } else {
        String[] splitCmds = command.split(" ");
        for (int i = 0; i < splitCmds.length; i++) {
            cmds.add(splitCmds[i]);
        }
    }

    ProcessBuilder builder = new ProcessBuilder(cmds);
    builder.directory(tempDir);

    for (int i = 0; i < cmds.size(); i++) {
        logger.info("cmds[" + i + "] = " + cmds.get(i));
    }
    logger.info("Command is " + command + " in directory " + tempDir);
    try {
        running = builder.start();
        if (stdInReader != null) {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(running.getOutputStream()));
            IOUtils.copyLarge(stdInReader, writer);
            writer.close();
        }
    } catch (IOException e) {
        throw new InvocationException(e);
    }
}

From source file:org.springframework.aop.interceptor.CustomizableTraceInterceptor.java

/**
 * Replace the placeholders in the given message with the supplied values,
 * or values derived from those supplied.
 * @param message the message template containing the placeholders to be replaced
 * @param methodInvocation the {@code MethodInvocation} being logged.
 * Used to derive values for all placeholders except {@code $[exception]}
 * and {@code $[returnValue]}./*from   ww  w. j  a  va 2 s  .  c o m*/
 * @param returnValue any value returned by the invocation.
 * Used to replace the {@code $[returnValue]} placeholder. May be {@code null}.
 * @param throwable any {@code Throwable} raised during the invocation.
 * The value of {@code Throwable.toString()} is replaced for the
 * {@code $[exception]} placeholder. May be {@code null}.
 * @param invocationTime the value to write in place of the
 * {@code $[invocationTime]} placeholder
 * @return the formatted output to write to the log
 */
protected String replacePlaceholders(String message, MethodInvocation methodInvocation,
        @Nullable Object returnValue, @Nullable Throwable throwable, long invocationTime) {

    Matcher matcher = PATTERN.matcher(message);

    StringBuffer output = new StringBuffer();
    while (matcher.find()) {
        String match = matcher.group();
        if (PLACEHOLDER_METHOD_NAME.equals(match)) {
            matcher.appendReplacement(output, Matcher.quoteReplacement(methodInvocation.getMethod().getName()));
        } else if (PLACEHOLDER_TARGET_CLASS_NAME.equals(match)) {
            String className = getClassForLogging(methodInvocation.getThis()).getName();
            matcher.appendReplacement(output, Matcher.quoteReplacement(className));
        } else if (PLACEHOLDER_TARGET_CLASS_SHORT_NAME.equals(match)) {
            String shortName = ClassUtils.getShortName(getClassForLogging(methodInvocation.getThis()));
            matcher.appendReplacement(output, Matcher.quoteReplacement(shortName));
        } else if (PLACEHOLDER_ARGUMENTS.equals(match)) {
            matcher.appendReplacement(output, Matcher.quoteReplacement(
                    StringUtils.arrayToCommaDelimitedString(methodInvocation.getArguments())));
        } else if (PLACEHOLDER_ARGUMENT_TYPES.equals(match)) {
            appendArgumentTypes(methodInvocation, matcher, output);
        } else if (PLACEHOLDER_RETURN_VALUE.equals(match)) {
            appendReturnValue(methodInvocation, matcher, output, returnValue);
        } else if (throwable != null && PLACEHOLDER_EXCEPTION.equals(match)) {
            matcher.appendReplacement(output, Matcher.quoteReplacement(throwable.toString()));
        } else if (PLACEHOLDER_INVOCATION_TIME.equals(match)) {
            matcher.appendReplacement(output, Long.toString(invocationTime));
        } else {
            // Should not happen since placeholders are checked earlier.
            throw new IllegalArgumentException("Unknown placeholder [" + match + "]");
        }
    }
    matcher.appendTail(output);

    return output.toString();
}

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

public String toSrcPath(String packageName, String basePath) {
    packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
    if (basePath != null && basePath.length() > 0) {
        basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
    }// ww w  .  j  a va2 s .  c o  m

    String regFirstPathSeparator;
    if ("/".equals(File.separator)) { // for mac, linux
        regFirstPathSeparator = "^/";
    } else { // for windows
        regFirstPathSeparator = "^\\\\";
    }

    String regLastPathSeparator;
    if ("/".equals(File.separator)) { // for mac, linux
        regLastPathSeparator = "/$";
    } else { // for windows
        regLastPathSeparator = "\\\\$";
    }

    return (basePath
            // Replace period, backslash, forward slash with file separator in package name
            + packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement(File.separator))
                    // Trim prefix file separators from package path
                    .replaceAll(regFirstPathSeparator, ""))
                            // Trim trailing file separators from the overall path
                            .replaceAll(regLastPathSeparator + "$", "");
}

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

@Test
public void test_Controller_Jsp_Model_Assets() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/sandbox/apsadmin/jsp/common/layouts/assets-more"
            .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(3, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.nuxeo.theme.html.CSSUtils.java

public static String expandVariables(String text, String basePath, String collectionName,
        ThemeDescriptor themeDescriptor) {

    String themeName = themeDescriptor.getName();

    if (basePath != null) {
        text = text.replaceAll("\\$\\{basePath\\}", Matcher.quoteReplacement(basePath));
        text = text.replaceAll("\\$\\{org.nuxeo.ecm.contextPath\\}", Matcher.quoteReplacement(basePath));
    }/*from  w w  w  .j a v  a  2  s  .c o m*/

    String contextPath = VirtualHostHelper.getContextPathProperty();

    // Replace global presets
    for (PresetType preset : PresetManager.getGlobalPresets(null, null)) {
        text = text.replaceAll(Pattern.quote(String.format("\"%s\"", preset.getTypeName())),
                Matcher.quoteReplacement(preset.getValue()));
    }

    // Replace custom presets
    for (PresetType preset : PresetManager.getCustomPresets(themeName)) {
        text = text.replaceAll(Pattern.quote(String.format("\"%s\"", preset.getTypeName())),
                Matcher.quoteReplacement(preset.getValue()));
    }

    // Replace presets from the current collection
    if (collectionName != null) {
        for (PresetType preset : PresetManager.getGlobalPresets(collectionName, null)) {
            text = text.replaceAll(Pattern.quote(String.format("\"%s\"", preset.getTypeName())),
                    Matcher.quoteReplacement(PresetManager.resolvePresets(themeName, preset.getValue())));
        }
    }

    // Replace presets and images from resource banks
    String resourceBankName = themeDescriptor.getResourceBankName();
    if (resourceBankName != null) {
        ResourceBank resourceBank;
        try {
            resourceBank = ThemeManager.getResourceBank(resourceBankName);

            for (PresetInfo preset : resourceBank.getPresets()) {
                text = text.replaceAll(Pattern.quote(String.format("\"%s\"", preset.getTypeName())),
                        Matcher.quoteReplacement(PresetManager.resolvePresets(themeName, preset.getValue())));
            }

            for (ImageInfo image : resourceBank.getImages()) {
                String path = image.getPath();
                text = text.replaceAll(path, Matcher.quoteReplacement(String.format("%s/nxthemes-images/%s/%s",
                        contextPath, resourceBankName, path.replace(" ", "%20"))));
            }

        } catch (ThemeException e) {
            log.warn("Could not get resources from theme bank: " + resourceBankName);
        }
    }

    return text;
}

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

@Test
public void test_Controller_Jsp_Model_Assets() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/plugins/jppet/apsadmin/jsp/common/layouts/assets-more"
            .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(3, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:edu.vt.middleware.ldap.search.SearchExecutor.java

/**
 * This returns a ldap search string for the supply list of query parameters.
 * count represents the number of queries which have been attempted, thus far.
 *
 * @param  queryParams  <code>String[]</code> to search for
 * @param  count  <code>int</code> number of queries performed
 *
 * @return  <code>String</code> - ldap search string
 */// w w  w .  j a  v  a  2 s.  c o  m
private String getQueryTemplate(final String[] queryParams, final int count) {
    String query = null;

    if (queryParams != null && queryParams.length > 0 && count <= this.queryTemplates.size()) {
        query = this.queryTemplates.get(new Integer(count));
        if (query != null) {

            // clone the params array, it may need to be changed for this search
            final String[] qp = (String[]) queryParams.clone();

            // replace all the initial parameters
            final String regexInitial = REGEX_INITIAL;
            final String[] qi = this.getInitials(qp);
            if (qi != null) {
                for (int i = 1; i <= qi.length; i++) {
                    if (qi[i - 1] != null) {
                        query = query.replaceAll(regexInitial.replaceAll("1", Integer.toString(i)),
                                Matcher.quoteReplacement(qi[i - 1]));
                    }
                }
            }

            // replace all the query parameters
            final String regexQuery = REGEX_QUERY;
            for (int i = 1; i <= qp.length; i++) {
                if (qp[i - 1] != null) {
                    query = query.replaceAll(regexQuery.replaceAll("1", Integer.toString(i)),
                            Matcher.quoteReplacement(qp[i - 1]));
                }
            }
        }
    }

    return query;
}