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.apache.ivory.expression.ExpressionHelper.java

public static String substitute(String originalValue, Properties properties) {
    Matcher envVarMatcher = sysPropertyPattern.matcher(originalValue);
    while (envVarMatcher.find()) {
        String envVar = originalValue.substring(envVarMatcher.start() + 2, envVarMatcher.end() - 1);
        String envVal = properties.getProperty(envVar, System.getenv(envVar));

        envVar = "\\$\\{" + envVar + "\\}";
        if (envVal != null) {
            originalValue = originalValue.replaceAll(envVar, Matcher.quoteReplacement(envVal));
            envVarMatcher = sysPropertyPattern.matcher(originalValue);
        }//from   w  ww . ja  v  a2 s .  co m
    }
    return originalValue;
}

From source file:org.segrada.rendering.markup.DefaultMarkupFilter.java

/**
 * replace text parts with bibliographic annotations
 *
 * there are two://w  w  w. j a  v a2s .  co m
 *
 * [[haebler:rott]] => bibliographic reference -> replace with link to bib, but this will be done in the view
 *   so we do not have to replace this at all here...
 * [13:] => means page 13 in cited text => just decorated
 *
 * @param text input text
 * @return output text
 */
protected String annotateBibliographies(String text) {
    // check identity, if injector has been set
    Identity identity = injector != null ? injector.getInstance(Identity.class) : null;

    if (sourceService != null && identity != null) { // skipped in tests and if source not allowed
        // bibliographic references
        Matcher matcher = bibRefPattern.matcher(text);
        StringBuffer sb = new StringBuffer(text.length());
        while (matcher.find()) {
            String match = matcher.group(1);

            // try to get cached entry
            String replacement = sourceReferenceCache.get(match);
            if (replacement == null) {
                // find corresponding source
                ISource source = sourceService.findByRef(match);
                if (source == null)
                    replacement = "[[" + match + "]]"; // fallback
                else {
                    replacement = "<a href=\"source/show/" + source.getUid() + "\" class=\"sg-data-add\">"
                            + source.getShortTitle() + "</a>";
                }

                // write to cache
                sourceReferenceCache.put(match, replacement);
            }

            matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
        }
        matcher.appendTail(sb);
        text = sb.toString();
    }

    // page reference
    text = text.replaceAll("\\[([0-9f]+:)\\]", "<span class=\"sg-label sg-info\">$1</span>");

    return text;
}

From source file:de.uzk.hki.da.format.CLIConversionStrategy.java

/**
 * Tokenizes commandLine and replaces certain strings.
 * "input" and "output" get replaced by paths of source and destination file.
 * strings beginning with "{" and ending with "}" get replaced by the contents of additionalParams of the ConversionInstruction.
 * Each of the {}-surrounded string gets replaced by exactly one token of additional params.
 *
 * @param ci the ci/*  w  w  w . jav a2 s  . c  om*/
 * @param repName the rep name
 * @return The processed command as list of tokens. The tokenized string has the right format
 * for a call in Runtime.getRuntime().exec(commandToExecute). This holds especially true
 * for filenames (which replace the input/output parameters) that are separated by
 * whitespaces. "file 2.jpg" is represented as one token only.
 */
protected String[] assemble(ConversionInstruction ci, String repName) {

    String commandLine_ = commandLine;

    // replace additional params
    List<String> ap = tokenize(ci.getAdditional_params(), ",");
    for (String s : ap) {

        Pattern pattern = Pattern.compile("\\{.*?\\}");
        Matcher matcher = pattern.matcher(commandLine_);
        commandLine_ = matcher.replaceFirst(s);
    }

    // tokenize before replacement to group original tokens together
    // (to prevent wrong tokenization like two tokens for "file" "2.jpg"
    //  which can result from replacement)
    String[] tokenizedCmd = tokenize(commandLine_);

    String targetSuffix = ci.getConversion_routine().getTarget_suffix();
    if (targetSuffix.equals("*"))
        targetSuffix = FilenameUtils.getExtension(ci.getSource_file().toRegularFile().getAbsolutePath());
    Utilities.replace(tokenizedCmd, "input", ci.getSource_file().toRegularFile().getAbsolutePath());
    Utilities.replace(tokenizedCmd, "output",
            object.getDataPath() + "/" + repName + "/" + Utilities.slashize(ci.getTarget_folder())
                    + FilenameUtils.removeExtension(Matcher.quoteReplacement(
                            FilenameUtils.getName(ci.getSource_file().toRegularFile().getAbsolutePath())))
                    + "." + targetSuffix);

    return tokenizedCmd;
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Generator.java

/**
 * When we sub in literals we have to take in to account the Lang or Datatype of
 * the literal.  N3 needs to have its literals escaped in Python style.  Java regex
 * Matcher is used to do the substitution and it need escaping to avoid group
 * references, Matcher.quoteReplacement() serves the purpose.
 *
 *///from   w  w w.jav  a2 s  .  co  m
public String subInLiterals(String var, Literal literal, String target) {
    String varRegex = "\\?" + var + "(?=\\.\\p{Space}|\\p{Space})";
    if (target == null) {
        log.error("subInLiterals was passed a null target");
        return "blankBecauseTargetOrValueWasNull";
    } else if (var == null) {
        log.warn("subInLiterals was passed a null var name");
        return target;
    } else if (literal == null) {
        log.debug("subInLiterals was passed a null value for var '" + var + "'; returning target: '" + target
                + "'");
        return target;
    }

    try {
        if (literal.getValue() == null)
            log.debug("value of literal for " + var + " was null");
    } catch (com.hp.hpl.jena.datatypes.DatatypeFormatException ex) {
        log.debug("value for " + var + " " + ex.getMessage());
    }

    //if( editConfig != null && editConfig.getFields() != null &&
    //    editConfig.getFields().get(var) != null ){
    //The var might not be in the editConfig.fields if an EditN3Generator
    //is being used to substitute in values that are not on the form, 
    //eg ?fileSize for file uploads

    String replacement = null;
    if (literal.getLexicalForm().length() == 0) {
        log.debug("empty string found on form for " + var + ".");
        replacement = ">::" + var + " was empty::<";
    } else {
        replacement = formatLiteral(literal);
    }

    String out = null;
    if (replacement != null)
        out = target.replaceAll(varRegex, Matcher.quoteReplacement(replacement));
    else
        out = target;

    if (out != null && out.length() > 0)
        return out;
    else {
        log.debug("After attempting to substitue in literals, the target N3 was empty");
        return target;
    }
}

From source file:org.alfresco.dropbox.webscripts.GetNode.java

private void updateChildren(NodeRef nodeRef) {
    Metadata parentMetadata = dropboxService.getMetadata(nodeRef);

    // Get the list of the content returned.
    List<Metadata> list = parentMetadata.getContents();

    for (Metadata child : list) {
        String name = child.getPath().replaceAll(Matcher.quoteReplacement(parentMetadata.getPath() + "/"), "");

        NodeRef childNodeRef = fileFolderService.searchSimple(nodeRef, name);

        if (childNodeRef == null) {
            NodeRef newChildNodeRef = null;

            try {
                if (child.isDir()) {
                    newChildNodeRef = fileFolderService.create(nodeRef, name, ContentModel.TYPE_FOLDER)
                            .getNodeRef();
                    updateChildren(newChildNodeRef);
                    dropboxService.persistMetadata(child, newChildNodeRef);
                } else {
                    newChildNodeRef = fileFolderService.create(nodeRef, name, ContentModel.TYPE_CONTENT)
                            .getNodeRef();
                    Metadata metadata = dropboxService.getFile(newChildNodeRef);
                    dropboxService.persistMetadata(metadata, newChildNodeRef);
                }//from   w w  w  .j a  v a2s  .  c  o  m
                syncUpdate(newChildNodeRef, true);
            } catch (FileExistsException fee) {
                // TODO What to do here?
                fee.printStackTrace();
            }
        } else {
            if (nodeService.getType(childNodeRef).equals(ContentModel.TYPE_CONTENT)) {
                update(childNodeRef);
            } else if (nodeService.getType(childNodeRef).equals(ContentModel.TYPE_FOLDER)) {
                updateChildren(childNodeRef);
            }
        }
    }

    update(nodeRef);
}

From source file:net.ymate.framework.core.taglib.ui.BaseUITag.java

public void writerToMetaPart(String content) {
    __tmplMetaPart.append(Matcher.quoteReplacement(content));
}

From source file:org.sigmah.server.mail.ModelMailService.java

/**
 * Replace a tag with the given replacing value in the source string.
 * // ww w  . j  av a2s.com
 * @param source
 *          The source string.
 * @param tagName
 *          The tag name.
 * @param replacedValue
 *          The replacing value.
 * @return The replaced string.
 */
private static String replaceTag(String source, String tagName, String replacedValue) {
    return source.replaceAll(Pattern.quote(TAG_START + tagName + TAG_END),
            Matcher.quoteReplacement(replacedValue));
}

From source file:dk.dma.msinm.common.settings.Settings.java

/**
 * Returns the value associated with the setting.
 * If it does not exist, it is created/*from www .  j a va  2 s  .c om*/
 *
 * @param setting the source
 * @return the associated value
 */
public String get(Setting setting) {
    Objects.requireNonNull(setting, "Must specify valid setting");

    // If a corresponding system property is set, it takes precedence
    if (System.getProperty(setting.getSettingName()) != null) {
        return System.getProperty(setting.getSettingName());
    }

    // Look for a cached value
    CacheElement<String> value = settingsCache.getCache().get(setting.getSettingName());

    // No cached value
    if (value == null) {
        SettingsEntity result = em.find(SettingsEntity.class, setting.getSettingName());
        if (result == null) {
            result = new SettingsEntity(setting);
            em.persist(result);
        }
        value = new CacheElement<>(result.getValue());

        // Cache it. NB: We cannot cache null, so use a placeholder constant
        if (setting.getCacheTimeout() == null) {
            settingsCache.getCache().put(setting.getSettingName(), value);
        } else {
            settingsCache.getCache().put(setting.getSettingName(), value, setting.getCacheTimeout(),
                    TimeUnit.SECONDS);
        }
    }

    // Check if we need to substitute with system properties
    String result = value.getElement();
    if (result != null && setting.substituteSystemProperties()) {
        for (Object key : System.getProperties().keySet()) {
            result = result.replaceAll("\\$\\{" + key + "\\}",
                    Matcher.quoteReplacement(System.getProperty("" + key)));
        }
    }

    return result;
}

From source file:de.uzk.hki.da.convert.CLIConversionStrategy.java

/**
 * Tokenizes commandLine and replaces certain strings.
 * "input" and "output" get replaced by paths of source and destination file.
 * strings beginning with "{" and ending with "}" get replaced by the contents of additionalParams of the ConversionInstruction.
 * Each of the {}-surrounded string gets replaced by exactly one token of additional params.
 *
 * @param ci the ci/*from  w w  w.ja  v  a2  s. c  om*/
 * @param repName the rep name
 * @return The processed command as list of tokens. The tokenized string has the right format
 * for a call in Runtime.getRuntime().exec(commandToExecute). This holds especially true
 * for filenames (which replace the input/output parameters) that are separated by
 * whitespaces. "file 2.jpg" is represented as one token only.
 */
protected String[] assemble(WorkArea wa, ConversionInstruction ci, String repName) {

    String commandLine_ = commandLine;

    // replace additional params
    List<String> ap = tokenize(ci.getAdditional_params(), ",");
    for (String s : ap) {

        Pattern pattern = Pattern.compile("\\{.*?\\}");
        Matcher matcher = pattern.matcher(commandLine_);
        commandLine_ = matcher.replaceFirst(s);
    }

    // tokenize before replacement to group original tokens together
    // (to prevent wrong tokenization like two tokens for "file" "2.jpg"
    //  which can result from replacement)
    String[] tokenizedCmd = tokenize(commandLine_);

    String targetSuffix = ci.getConversion_routine().getTarget_suffix();
    if (targetSuffix.equals("*"))
        targetSuffix = FilenameUtils.getExtension(wa.toFile(ci.getSource_file()).getAbsolutePath());
    StringUtilities.replace(tokenizedCmd, "input", wa.toFile(ci.getSource_file()).getAbsolutePath());
    StringUtilities.replace(tokenizedCmd, "output",
            wa.dataPath() + "/" + repName + "/" + StringUtilities.slashize(ci.getTarget_folder())
                    + FilenameUtils.removeExtension(Matcher.quoteReplacement(
                            FilenameUtils.getName(wa.toFile(ci.getSource_file()).getAbsolutePath())))
                    + "." + targetSuffix);

    return tokenizedCmd;
}

From source file:no.sesat.search.view.velocity.URLResourceLoader.java

private static String getFallbackURL(final String url, final Site currSite, final Site ancestorSite) {

    final String oldUrl = currSite.getName() + currSite.getConfigContext();
    final String newUrl = ancestorSite.getName() + ancestorSite.getConfigContext();

    return url.replaceFirst(Matcher.quoteReplacement(oldUrl), newUrl);
}