Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:com.microsoft.tfs.client.eclipse.tpignore.TPIgnoreCache.java

/**
 * Creates a regular expression to match the given resource. If the resource
 * is a project or folder, the pattern matches every path which starts with
 * that folder path. For files, the expression matches that file exactly.
 *
 * @param resource/*  www  .j a va 2s .  com*/
 *        the resource to create a pattern for (must not be
 *        <code>null</code>)
 * @return the pattern string
 */
public static String createIgnorePatternForResource(final IResource resource) {
    Check.notNull(resource, "resource"); //$NON-NLS-1$

    final String path = TPIgnoreCache.createResourceMatchString(resource);

    String patternString = Pattern.quote(path);

    /*
     * Make folders match recursively, other types match only exactly.
     */
    if (resource.getType() == IResource.FOLDER || resource.getType() == IResource.PROJECT) {
        patternString = patternString + ".*"; //$NON-NLS-1$
    }

    return patternString;
}

From source file:com.topekalabs.java.utils.ClassUtils.java

public static Collection<File> getClassFiles(File srcDirectory, String className) {
    notClassNameException(className);/*from  w w w .  j a  v a  2  s.c o  m*/

    return FileUtils.listFiles(srcDirectory,
            new IOFileFilterRegexName(Pattern.quote(className + CLASS_FILE_SUFFIX)), TrueFileFilter.INSTANCE);
}

From source file:net.java.sip.communicator.impl.gui.main.chat.replacers.KeywordReplacer.java

/**
 * Replace operation. Searches for the keyword in the provided piece of
 * content and replaces it with the piece of content surrounded by &lt;b&gt;
 * tags.//from   w  w  w .ja  v  a 2s  . c  o  m
 *
 * @param target the destination to write the result to
 * @param piece the piece of content to process
 */
@Override
public void replace(final StringBuilder target, final String piece) {
    if (this.keyword == null || this.keyword.isEmpty()) {
        target.append(StringEscapeUtils.escapeHtml4(piece));
        return;
    }

    final Matcher m = Pattern
            .compile("(^|\\W)(" + Pattern.quote(keyword) + ")(\\W|$)", Pattern.CASE_INSENSITIVE).matcher(piece);
    int prevEnd = 0;
    while (m.find()) {
        target.append(StringEscapeUtils.escapeHtml4(
                piece.substring(prevEnd, m.start() + m.group(INDEX_OPTIONAL_PREFIX_GROUP).length())));
        prevEnd = m.end() - m.group(INDEX_OPTIONAL_SUFFIX_GROUP).length();
        final String keywordMatch = m.group(INDEX_KEYWORD_MATCH_GROUP).trim();
        target.append("<b>");
        target.append(StringEscapeUtils.escapeHtml4(keywordMatch));
        target.append("</b>");
    }
    target.append(StringEscapeUtils.escapeHtml4(piece.substring(prevEnd)));
}

From source file:com.headstrong.fusion.messaging.service.CBRProcessor.java

/**
 * CBR Expression Samples.//  w  w w  .  j  a va  2s .  c  om
 * <p>
 * HEADER ONLY (#header{type}.equals("type1"))
 * <p>
 * COMPLETE (#header{type}.equals("type1") &&
 * #body{parent.child}.equals("data"))
 * <p>
 * #header refers to the header data and #body refers to the field in the
 * message body. All the field references would be replaced with actual
 * method calls on the header and message bean.
 * 
 * @throws Exception
 */
private void initializeExpressions() throws Exception {
    Map<When, Expression> expressions = new HashMap<When, Expression>();
    for (When when : this.getConfig().getWhen()) {
        String expression = when.getExpression();
        for (Entry<String, String> field : getTokens(expression, "#header").entrySet()) {
            expression = expression.replaceAll(Pattern.quote(field.getKey()),
                    HEADER + ".get(\"" + field.getValue() + "\")");
        }

        for (Entry<String, String> field : getTokens(expression, "#body").entrySet()) {
            expression = expression.replaceAll(Pattern.quote(field.getKey()),
                    BODY + ".getValue(\"" + field.getValue() + "\")");
        }
        // create JEXL- expression
        Expression jexlExpr = ExpressionFactory.createExpression(expression);
        expressions.put(when, jexlExpr);
    }
    this.setExpressions(expressions);
}

From source file:com.jaspersoft.jasperserver.remote.connection.TxtFileConnectionStrategy.java

@Override
protected Object internalBuildMetadata(TxtFileConnection connection, InputStream stream) throws IOException {
    InputStreamReader isReader = new InputStreamReader(stream);
    BufferedReader reader = new BufferedReader(isReader);
    String line = reader.readLine();
    final TxtFileParser parser = connection.getParser();
    String delimiter;//from w w w. ja v  a2s  . co m
    if (parser instanceof TxtFileDelimiterParser) {
        delimiter = Pattern.quote(((TxtFileDelimiterParser) parser).getDelimiter());
    } else if (parser instanceof TxtFileRegularExpressionParser) {
        delimiter = ((TxtFileRegularExpressionParser) parser).getRegularExpression();
    } else {
        // shouldn't happen
        throw new IllegalStateException("Unsupported parser type: " + parser.getClass().getName());
    }
    String[] tokens = line.split(delimiter);
    List<String> columns = new ArrayList<String>(tokens.length);
    for (int i = 0; i < tokens.length; i++) {
        final String currentColumnName = connection.hasHeaderLine() ? tokens[i].trim() : buildColumnName(i);
        columns.add(currentColumnName);
    }
    return new TxtFileMetadata().setColumns(columns);
}

From source file:com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsOutputStream.java

/**
 * @param logger The output stream to which this {@link MaskPasswordsOutputStream}
 *               will write to/* w w  w. j a v a2  s .com*/
 * @param passwords A collection of {@link String}s to be masked
 */
public MaskPasswordsOutputStream(OutputStream logger, Collection<String> passwords) {
    this.logger = logger;

    if (passwords != null && passwords.size() > 0) {
        // passwords are aggregated into a regex which is compiled as a pattern
        // for efficiency
        StringBuilder regex = new StringBuilder().append('(');

        int nbMaskedPasswords = 0;
        for (String password : passwords) {
            if (StringUtils.isNotEmpty(password)) { // we must not handle empty passwords
                regex.append(Pattern.quote(password));
                regex.append('|');
                nbMaskedPasswords++;
            }
        }
        if (nbMaskedPasswords++ >= 1) { // is there at least one password to mask?
            regex.deleteCharAt(regex.length() - 1); // removes the last unuseful pipe
            regex.append(')');
            passwordsAsPattern = Pattern.compile(regex.toString());
        } else { // no passwords to hide
            passwordsAsPattern = null;
        }
    } else { // no passwords to hide
        passwordsAsPattern = null;
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFConformerSampler.java

private void run(String inFile) {
    oemolithread ifs = new oemolithread(inFile);
    long start = System.currentTimeMillis();
    int iCounter = 0; //Structures in the SD file.
    int oCounter = 0;

    OEMolBase mol = new OEGraphMol();
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;//  w  w  w. j  a va2  s .  c  o  m

        OEMCMolBase confs = scanner.createConformations(mol, maxConfs);
        oechem.OEWriteMolecule(outputOEThread, confs);
        oCounter += confs.NumConfs();
        confs.delete();

        //Output "." to show that the program is running.
        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 4000 == 0) {
            System.err.printf(" %d %dsec\n", iCounter, (System.currentTimeMillis() - start) / 1000);
        }
    }

    mol.delete();
    ifs.close();
    inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), "");
    System.err.printf("%s: Read %d structures from %s. Written %d confs in %d sec\n", MY_NAME, iCounter, inFile,
            oCounter, (System.currentTimeMillis() - start) / 1000);
}

From source file:org.jboss.forge.website.service.Downloader.java

public void invalidateCachesByAddress(String pattern) {
    pattern = ".*" + Pattern.quote(pattern) + ".*";
    log.info("Invalidating caches for pattern [" + pattern + "]");
    for (CacheEntry entry : cache.values()) {
        if (entry.getAddress().matches(pattern) || Decoder.query(entry.getAddress()).matches(pattern)
                || Decoder.path(entry.getAddress()).matches(pattern)) {
            log.info("Invalidating cache entry [" + entry.getAddress() + "] for pattern [" + pattern + "]");
            entry.invalidate();/*from   ww  w  .jav  a2 s  .  c  o m*/
        }
    }
}

From source file:com.bluexml.side.Framework.alfresco.propertiesUpdater.PatternPropertiesUpdater.java

public String getNewValue(String currentKey, String template) {
    if (logger.isDebugEnabled()) {
        logger.debug("[getNewValue] currentProperty :" + currentKey);
        logger.debug("[getNewValue] template :" + template);
        logger.debug("[getNewValue] oldValues:" + oldValues);
        logger.debug("[getNewValue] newValues:" + newValues);
    }/*from  w  w  w  .jav a2 s.c o  m*/
    Pattern p = Pattern.compile(EXPRESSION_PATTERN);

    String expressionProperty = getExpressionProperty(currentKey);

    if (template.contains(expressionProperty)) {
        // need special treatment since the property to update is used in template
        extractCurrentPropertyValue(currentKey, template, p, expressionProperty);
    }

    Matcher matcher = p.matcher(template);
    // simply apply the template
    String newValue = template;
    while (matcher.find()) {
        String key = matcher.group(1);

        String newPropertyValue = getNewValue(key);
        if (logger.isDebugEnabled()) {
            logger.debug("** replace " + key + " by :" + newPropertyValue);
        }
        newValue = newValue.replaceAll(Pattern.quote(matcher.group()), newPropertyValue);

    }
    if (logger.isDebugEnabled()) {
        logger.debug("* Computed new value :" + newValue);
    }
    return newValue;
}

From source file:gov.nih.nci.cbiit.cmts.util.ResourceUtils.java

/**
 * Get the relative path from one file to another, specifying the directory separator.
* If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
* '\'.//from  w w  w .  j a v a  2s  .com
*
 * @param targetPath is calculated to this file
* @param basePath is calculated from this file
* @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)
* @return target relative path from the base
*/

public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {
    if (targetPath.toLowerCase().startsWith("file:/")) {
        targetPath = targetPath.substring(6);
        while (targetPath.startsWith("/"))
            targetPath = targetPath.substring(1);
    }
    if (basePath.toLowerCase().startsWith("file:/")) {
        basePath = basePath.substring(6);
        while (basePath.startsWith("/"))
            basePath = basePath.substring(1);
    }

    String tempS = basePath;
    while (true) {
        File baseF = new File(tempS);
        if ((baseF.exists()) && (baseF.isFile())) {
            basePath = baseF.getAbsolutePath();
            break;
        }
        if (!pathSeparator.equals("/"))
            break;
        if (tempS.startsWith("/"))
            break;
        tempS = "/" + tempS;
    }
    tempS = targetPath;
    while (true) {
        File targetF = new File(tempS);
        if ((targetF.exists()) && (targetF.isFile())) {
            targetPath = targetF.getAbsolutePath();
            break;
        }
        if (!pathSeparator.equals("/"))
            break;
        if (tempS.startsWith("/"))
            break;
        tempS = "/" + tempS;
    }

    // Normalize the paths
    //System.out.println("ResourceUtils.getRelativePath()..target("+pathSeparator+"):"+targetPath);
    //System.out.println("ResourceUtils.getRelativePath()..base("+pathSeparator+"):"+basePath);
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);
    // Undo the changes to the separators made by normalization

    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    //System.out.println("ResourceUtils.getRelativePath()..normalizedTarget("+pathSeparator+"):"+normalizedTargetPath);
    //System.out.println("ResourceUtils.getRelativePath()..normalizedBase("+pathSeparator+"):"+normalizedBasePath);

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));
    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuffer common = new StringBuffer();
    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].trim().equals(base[commonIndex].trim())) {
        common.append(target[commonIndex].trim() + pathSeparator);
        commonIndex++;
    }
    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        File ff = new File(targetPath);
        if ((ff.exists()) && (ff.isFile()))
            return ff.getAbsolutePath();
        else
            throw new IllegalArgumentException("No common path element found for '" + normalizedTargetPath
                    + "' and '" + normalizedBasePath + "'");
    }
    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;
    File baseResource = new File(normalizedBasePath);
    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();
    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }
    StringBuffer relative = new StringBuffer();
    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;
        for (int i = 0; i < numDirsUp; i++) {
            relative.append(".." + pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    //System.out.println("ResourceUtils.getRelativePath()..relativeTarget:"+relative.toString());
    return relative.toString();
}