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:pt.webdetails.cdv.api.CdvApi.java

private JSONObject createTest(String origin, String newPath) throws JSONException {
    JSONObject result = new JSONObject();
    if (!newPath.endsWith(".cdv")) {
        newPath = newPath + ".cdv";
    }/*from ww w  .j a va  2s . c  o m*/
    String newFileName = Util.joinPath(CdvEnvironment.getPluginRepositoryDir(),
            CdvConstants.SolutionFolders.TESTS, newPath);

    IRWAccess pluginRepo = CdvEnvironment.getPluginRepositoryWriter("tests");
    IReadAccess systemRepo = CdvEnvironment.getPluginSystemReader();
    IReadAccess contentRepo = CdvEnvironment.getUserContentAccess();

    try {
        if (pluginRepo.fileExists(newPath)) {
            logger.error("New File already exists, aborting creation of new test");
            result.put("success", "false");
            return result;
        }

        InputStream inputStream;

        if (StringUtils.isEmpty(origin)) {
            inputStream = systemRepo.getFileInputStream("validationTemplate.cdv");
        } else {
            inputStream = contentRepo.getFileInputStream(origin);
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, CharsetHelper.getEncoding());
        String originalTest = writer.toString();

        originalTest = Pattern.compile("path:\\s*['\"].*['\"]\\s*,").matcher(originalTest)
                .replaceFirst("path: '" + newFileName + "',");
        originalTest = Pattern.compile("name:\\s*['\"].*['\"]\\s*,").matcher(originalTest)
                .replaceFirst("name: '" + newFileName.substring(newFileName.lastIndexOf("/") + 1)
                        .replaceAll(Matcher.quoteReplacement(".cdv"), "") + "',");
        originalTest = Pattern.compile("createdBy:\\s*['\"].*['\"]\\s*,").matcher(originalTest)
                .replaceFirst("createdBy: '" + PentahoSessionHolder.getSession().getName() + "',");

        inputStream = new ByteArrayInputStream(originalTest.getBytes(CharsetHelper.getEncoding()));

        pluginRepo.saveFile(newPath, inputStream);
        result.put("success", "true");
        result.put("path", newFileName);
        InterPluginCall pluginCall = new InterPluginCall(InterPluginCall.CDV, "refreshTests");
        pluginCall.call();
    } catch (IOException ioe) {
        logger.error("Error while creating test file", ioe);
        result.put("success", "false");
    }

    return result;
}

From source file:alluxio.Configuration.java

/**
 * Actual recursive lookup replacement./*from   ww  w  .  j  a  v a 2  s  .  c o m*/
 *
 * @param base the String to look for
 * @param found {@link Map} of String that already seen in this path
 * @return resolved String value
 */
private String lookupRecursively(final String base, Map<String, String> found) {
    // check argument
    if (base == null) {
        return null;
    }

    String resolved = base;
    // Lets find pattern match to ${key}.
    // TODO(hsaputra): Consider using Apache Commons StrSubstitutor.
    Matcher matcher = CONF_REGEX.matcher(base);
    while (matcher.find()) {
        String match = matcher.group(2).trim();
        String value;
        if (!found.containsKey(match)) {
            value = lookupRecursively(mProperties.getProperty(match), found);
            found.put(match, value);
        } else {
            value = found.get(match);
        }
        if (value != null) {
            LOG.debug("Replacing {} with {}", matcher.group(1), value);
            resolved = resolved.replaceFirst(REGEX_STRING, Matcher.quoteReplacement(value));
        }
    }
    return resolved;
}

From source file:org.olat.core.util.Formatter.java

License:asdf

/**
 * renders wiki markup like _italic_ to XHTML see also www.radeox.org
 * //w w  w  . ja va2  s  .  co m
 * @Deprecated The wiki markup area is no longer supported. In the legacy form infrastructure it's still there, but it won't be available in the new flexi forms. In
 *             flexi forms use the RichTextElement instead. tested during migration and expanded to prevent radeox failures
 * @param originalText
 * @return result (rendered originalText) or null if originalText was null
 */
@Deprecated
public static String formatWikiMarkup(String oldValue) {
    if (oldValue != null) {
        String newValue = "";
        // oldValue = oldValue.replaceAll("<>", "&lt;&gt;");
        // oldValue = oldValue.replaceAll(Pattern.quote("[]"),
        // "&#91;&#93;");

        // prevent error with {$} interpreted as regexp
        String marker1 = "piYie6Eigh0phafeiTuk4dahwahvoh7eedoegee2egh8xuj9phah8eop8iuk";
        oldValue = oldValue.replaceAll(Pattern.quote("{$}"), marker1);

        // \{code} will result in an error => convert
        String marker2 = "RohbaeW7xahbohk8iewoo7thocaemaech2pahS8oe1UVohkohJiugaagaeco";
        oldValue = oldValue.replaceAll(Pattern.quote("\\{code}"), marker2);

        // radeox gets an error, if {code} is not a closed tag. prevent at
        // least the case with one single statement.
        int nrOfCodeStatements = countOccurrences(oldValue, "{code}");
        String marker3 = "shagheiph6enieNo0theph9aique0EihoChae6ve2edie4Pohwaok8thaoda";
        if (nrOfCodeStatements == 1) {
            oldValue = oldValue.replaceAll(Pattern.quote("{code}"), marker3);
        }
        if (nrOfCodeStatements % 2 != 0 && nrOfCodeStatements != 1) {
            Formatter fInst = Formatter.getInstance(new Locale("olat"));
            fInst.log(
                    "There will be a Warning/NPE from Radeox soon, as there are not enough {code} statements in a text.");
            fInst.log("Old value of text will be kept! " + oldValue);
        }

        // added for compatibility with wikimedia syntax used in the new wiki component. org.olat.core.gui.components.wiki.WikiMarkupComponent
        // filters " ''' " for bold and " ''''' " for bold/italic
        oldValue = oldValue.replaceAll(
                "(^|>|[\\p{Punct}\\p{Space}]+)'{3}(.*?)'{3}([\\p{Punct}\\p{Space}]+|<|$)", "$1*$2*$3");
        oldValue = oldValue.replaceAll(
                "(^|>|[\\p{Punct}\\p{Space}]+)'{5}(.*?)'{5}([\\p{Punct}\\p{Space}]+|<|$)", "$1_*$2*_$3");

        // try-catch not usable, as Radeox doesn't throw an exception,
        // it just prints warnings and returns unconverted value!
        newValue = engineWithContext.render(oldValue, baseRenderContext);

        // convert back
        newValue = newValue.replaceAll(marker1, Matcher.quoteReplacement("{$}"));
        newValue = newValue.replaceAll(marker2, Matcher.quoteReplacement("\\{code}"));
        newValue = newValue.replaceAll(marker3, Matcher.quoteReplacement("{code}"));

        return newValue;
    } else
        return null;
}

From source file:org.freeplane.view.swing.features.time.mindmapmode.nodelist.NodeList.java

private void replace(final HolderAccessor holderAccessor) {
    final String searchString = (String) mFilterTextSearchField.getSelectedItem();
    if (searchString == null)
        return;//from  w  ww . j  a v a 2 s . com
    final String replaceString = (String) mFilterTextReplaceField.getSelectedItem();
    Pattern p;
    try {
        p = Pattern.compile(useRegexInFind.isSelected() ? searchString : Pattern.quote(searchString),
                matchCase.isSelected() ? 0 : Pattern.CASE_INSENSITIVE);
    } catch (final PatternSyntaxException e) {
        UITools.errorMessage(TextUtils.format("wrong_regexp", searchString, e.getMessage()));
        return;
    }
    final String replacement = replaceString == null ? "" : replaceString;
    final int length = holderAccessor.getLength();
    for (int i = 0; i < length; i++) {
        TextHolder[] textHolders = holderAccessor.getNodeHoldersAt(i);
        for (final TextHolder textHolder : textHolders) {
            final String text = textHolder.getText();
            final String replaceResult;
            final String literalReplacement = useRegexInReplace.isSelected() ? replacement
                    : Matcher.quoteReplacement(replacement);
            try {
                if (HtmlUtils.isHtmlNode(text)) {
                    replaceResult = NodeList.replace(p, text, literalReplacement);
                } else {
                    replaceResult = p.matcher(text).replaceAll(literalReplacement);
                }
            } catch (Exception e) {
                UITools.errorMessage(TextUtils.format("wrong_regexp", replacement, e.getMessage()));
                return;
            }
            if (!StringUtils.equals(text, replaceResult)) {
                holderAccessor.changeString(textHolder, replaceResult);
            }
        }
    }
    tableModel.fireTableDataChanged();
    mFlatNodeTableFilterModel.resetFilter();
    mFilterTextSearchField.insertItemAt(mFilterTextSearchField.getSelectedItem(), 0);
    mFilterTextReplaceField.insertItemAt(mFilterTextReplaceField.getSelectedItem(), 0);
    mFilterTextSearchField.setSelectedItem("");
}

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

public Object getExpressionValue(Object expr) {
    if (expr != null) {
        String evalExpr = expr.toString();

        Matcher matcher = EL_PATTERN.matcher(evalExpr);
        if (!matcher.find()) {
            return expr;
        }//from w  ww  .  ja v  a2 s  .c  om

        boolean hasMoreGroup = false;
        StringBuffer exprBuffer = new StringBuffer();

        Object result = evaluateExpression(evalExpr.substring(matcher.start() + 2, matcher.end() - 1));
        matcher.appendReplacement(exprBuffer,
                result != null ? Matcher.quoteReplacement(result.toString()) : "null");

        while (matcher.find()) {
            hasMoreGroup = true;
            Object object = evaluateExpression(evalExpr.substring(matcher.start() + 2, matcher.end() - 1));
            matcher.appendReplacement(exprBuffer,
                    object != null ? Matcher.quoteReplacement(object.toString()) : "null");
        }

        if (hasMoreGroup || result instanceof String) {
            return matcher.appendTail(exprBuffer).toString();
        } else {
            return result;
        }
    }
    return null;
}

From source file:org.alfresco.web.site.servlet.CSRFFilter.java

private String resolve(String str, Map<String, String> propertyMap) {
    if (str == null) {
        return null;
    }/* w w w .j  a  v a2  s  . c  om*/
    Pattern pattern = Pattern.compile("\\{(.+?)\\}");
    Matcher matcher = pattern.matcher(str);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        if (propertyMap.containsKey(matcher.group(1))) {
            String replacement = resolve(propertyMap.get(matcher.group(1)), propertyMap);
            matcher.appendReplacement(buffer,
                    replacement != null ? Matcher.quoteReplacement(replacement) : "null");
        }
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:com.google.livingstories.server.dataservices.entities.BaseContentEntity.java

/**
 * Examines the content for anchor tags that look like they point to external pages
 *   (in general, any link that doesn't start with 'javascript:', and adds a
 *   target="_blank" attribute to them, if there isn't a target attribute already.
 * @param content Content to fix up.//  w w  w.j a  va  2s . co m
 * @return The modified content string, with links fixed to pop up new windows.
 */
private String fixLinks(String content) {
    Matcher matcher = EXTERNAL_LINK_PATTERN.matcher(content);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String link = matcher.group(0);
        if (!TARGET_ATTR_PATTERN.matcher(link).find()) {
            link = link.replace(">", DEFAULT_LINK_TARGET + ">");
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(link));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

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

private static String convertPointsToCm(String html) {
    StringBuffer sb = new StringBuffer();
    Pattern pTag = Pattern.compile("(<.+?style=\")(.+?)(\".*?>)", Pattern.DOTALL);
    Pattern pNumber = Pattern.compile("\\d+(?:\\.\\d*)");
    Matcher mTag = pTag.matcher(html);
    while (mTag.find()) {
        StringBuilder sbStyle = new StringBuilder(mTag.group(1));
        Map<String, String> mapStyle = DocumentUtil.styleToMap(mTag.group(2));
        for (Map.Entry<String, String> e : mapStyle.entrySet()) {
            String key = e.getKey();
            String value = e.getValue();
            if (pNumber.matcher(value).matches()) {
                value = LengthUnit.convertTo(Float.parseFloat(value), "cm");
            }//  ww w  .j av a 2 s  . c o m
            sbStyle.append(key + ": " + value + "; ");
        }
        sbStyle.append(mTag.group(3));
        mTag.appendReplacement(sb, Matcher.quoteReplacement(sbStyle.toString()));
    }
    mTag.appendTail(sb);
    return sb.toString();
}

From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java

@Test
public void noFlushAppend() throws Exception {
    File tempFolder = this.temp.newFolder();
    FileWritingMessageHandler handler = new FileWritingMessageHandler(tempFolder);
    handler.setFileExistsMode(FileExistsMode.APPEND_NO_FLUSH);
    handler.setFileNameGenerator(message -> "foo.txt");
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.afterPropertiesSet();/*from   ww w .j  av  a 2s.  com*/
    handler.setTaskScheduler(taskScheduler);
    handler.setOutputChannel(new NullChannel());
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.setFlushInterval(30000);
    handler.afterPropertiesSet();
    handler.start();
    File file = new File(tempFolder, "foo.txt");
    handler.handleMessage(new GenericMessage<String>("foo"));
    handler.handleMessage(new GenericMessage<String>("bar"));
    handler.handleMessage(new GenericMessage<String>("baz"));
    handler.handleMessage(new GenericMessage<byte[]>("qux".getBytes())); // change of payload type forces flush
    assertThat(file.length(), greaterThanOrEqualTo(9L));
    handler.stop(); // forces flush
    assertThat(file.length(), equalTo(12L));
    handler.setFlushInterval(100);
    handler.start();
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("fiz".getBytes())));
    int n = 0;
    while (n++ < 100 && file.length() < 15) {
        Thread.sleep(100);
    }
    assertThat(file.length(), equalTo(15L));
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("buz".getBytes())));
    handler.trigger(new GenericMessage<String>(Matcher.quoteReplacement(file.getAbsolutePath())));
    assertThat(file.length(), equalTo(18L));
    assertEquals(0, TestUtils.getPropertyValue(handler, "fileStates", Map.class).size());

    handler.setFlushInterval(30000);
    final AtomicBoolean called = new AtomicBoolean();
    handler.setFlushPredicate((fileAbsolutePath, firstWrite, lastWrite, triggerMessage) -> {
        called.set(true);
        return true;
    });
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("box".getBytes())));
    handler.trigger(new GenericMessage<String>("foo"));
    assertThat(file.length(), equalTo(21L));
    assertTrue(called.get());

    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("bux".getBytes())));
    called.set(false);
    handler.flushIfNeeded((fileAbsolutePath, firstWrite, lastWrite) -> {
        called.set(true);
        return true;
    });
    assertThat(file.length(), equalTo(24L));
    assertTrue(called.get());

    handler.stop();
    Log logger = spy(TestUtils.getPropertyValue(handler, "logger", Log.class));
    new DirectFieldAccessor(handler).setPropertyValue("logger", logger);
    when(logger.isDebugEnabled()).thenReturn(true);
    final AtomicInteger flushes = new AtomicInteger();
    doAnswer(i -> {
        flushes.incrementAndGet();
        return null;
    }).when(logger).debug(startsWith("Flushed:"));
    handler.setFlushInterval(50);
    handler.setFlushWhenIdle(false);
    handler.start();
    for (int i = 0; i < 40; i++) {
        handler.handleMessage(new GenericMessage<String>("foo"));
        Thread.sleep(5);
    }
    assertThat(flushes.get(), greaterThanOrEqualTo(2));
    handler.stop();
}

From source file:org.kuali.rice.core.impl.config.property.JAXBConfigImpl.java

/**
 * This method is used when reading in new properties to check if there is a direct reference to
 * the key in the value. This emulates operating system environment variable setting behavior
 * and replaces the reference in the value with the current value of the property from the
 * rawProperties./*from w  ww.j  a  v a2  s  . co  m*/
 * 
 * <pre>
 * ex:
 * path=/usr/bin;${someVar}
 * path=${path};/some/other/path
 * 
 * resolves to:
 * path=/usr/bin;${someVar};/some/other/path
 * </pre>
 * 
 * It does not resolve the the value from rawProperties as it could contain nested properties
 * that might change later. If the property does not exist in the rawProperties it will check
 * for a default system property now to prevent a circular reference error.
 * 
 * @param name the property name
 * @param value the value to check for nested property of the same name
 * @return
 */
protected String replaceVariable(String name, String value) {
    String regex = "(?:\\$\\{" + name + "\\})";
    String temporary = null;

    // Look for a property in the map first and use that. If system override is true
    // then it will get overridden during the resolve phase. If the value is null
    // we need to check the system now so we don't throw an error.
    if (value.contains("${" + name + "}")) {
        if ((temporary = rawProperties.getProperty(name)) == null) {
            temporary = System.getProperty(name);
        }

        if (temporary != null) {
            return value.replaceAll(regex, Matcher.quoteReplacement(temporary));
        }
    }

    return value;
}