Example usage for java.util.regex Pattern pattern

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

Introduction

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

Prototype

pattern

Source Link

Usage

From source file:com.netflix.genie.web.util.BaseRegexAgentMetadataInspector.java

InspectionReport inspectWithPattern(@Nullable final String currentPatternString,
        @Nullable final String metadataAttribute) {
    final Pattern currentPattern = maybeReloadPattern(currentPatternString);

    if (currentPattern == null) {
        return InspectionReport.newAcceptance("Pattern not not set");
    } else if (StringUtils.isBlank(metadataAttribute)) {
        return InspectionReport.newRejection("Metadata attribute not set");
    } else if (currentPattern.matcher(metadataAttribute).matches()) {
        return new InspectionReport(decisionIfMatch,
                "Attribute: " + metadataAttribute + " matches: " + currentPattern.pattern());
    } else {//from   w w  w . j av a 2s .  com
        return new InspectionReport(InspectionReport.Decision.flip(decisionIfMatch),
                "Attribute: " + metadataAttribute + " does not match: " + currentPattern.pattern());
    }
}

From source file:org.paxle.filter.blacklist.impl.Blacklist.java

/**
 * @see org.paxle.filter.blacklist.IBlacklist#isListed(String)
 *///  w  ww  . java 2s.  c o m
public IFilterResult isListed(String url) {
    long time = System.currentTimeMillis();
    Enumeration<Pattern> eter = blacklist.elements();
    while (eter.hasMoreElements()) {
        Pattern temp = eter.nextElement();
        Matcher m = temp.matcher(url);
        if (m.matches()) {
            if (logger.isDebugEnabled()) {
                time = System.currentTimeMillis() - time;
                logger.debug("Duration in 'isListed()' for blacklistcheck: " + time + " ms . URL: " + url);
            }
            return new FilterResult(IFilterResult.LOCATION_REJECTED, temp.pattern());
        }
    }
    if (logger.isDebugEnabled()) {
        time = System.currentTimeMillis() - time;
        logger.debug("Duration in 'isListed()' for blacklistcheck: " + time + " ms . URL: " + url);
    }
    return FilterResult.LOCATION_OKAY_RESULT;
}

From source file:org.parosproxy.paros.core.proxy.ProxyServer.java

public boolean excludeUrl(URI uri) {
    boolean ignore = false;
    if (excludeUrls != null) {
        String uriString = uri.toString();
        for (Pattern p : excludeUrls) {
            if (p.matcher(uriString).matches()) {
                ignore = true;//from w ww. j ava  2s. com
                if (log.isDebugEnabled()) {
                    log.debug("URL excluded: " + uriString + " Regex: " + p.pattern());
                }

                break;
            }
        }
    }

    return ignore;
}

From source file:com.adito.boot.ReplacementEngine.java

private void replaceInto(Pattern pattern, String replacementPattern, Replacer replacer, StringBuffer input,
        StringBuffer work) {/* www  .  java 2 s . c o  m*/
    work.ensureCapacity(input.length());
    work.setLength(0);
    if (log.isDebugEnabled())
        log.debug("Getting matcher for " + pattern.pattern());
    Matcher m = pattern.matcher(input);
    log.debug("Got matcher, finding first occurence.");
    while (m.find()) {
        if (log.isDebugEnabled())
            log.debug("Found occurence '" + m.group() + "'");
        String repl = replacer.getReplacement(pattern, m, replacementPattern);
        if (repl != null) {
            if (log.isDebugEnabled())
                log.debug("Found replacement, appending '" + repl + "'");
            if (encoder == null) {
                m.appendReplacement(work, Util.escapeForRegexpReplacement(repl));
            } else {
                m.appendReplacement(work, encoder.encode(Util.escapeForRegexpReplacement(repl)));
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug("Processed matches, appending replacement.");
    m.appendTail(work);
}

From source file:edu.vt.middleware.servlet.filter.SessionAttributeFilter.java

/**
 * Handle all requests sent to this filter.
 *
 * @param  request  <code>ServletRequest</code>
 * @param  response  <code>ServletResponse</code>
 * @param  chain  <code>FilterChain</code>
 *
 * @throws  ServletException  if an error occurs
 * @throws  IOException  if an error occurs
 */// w w w.j a va  2  s.  c o  m
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    boolean success = false;
    String redirect = null;
    if (request instanceof HttpServletRequest) {
        final HttpSession session = ((HttpServletRequest) request).getSession(true);
        final Iterator<String> i = this.attributes.keySet().iterator();
        boolean loop = true;
        while (i.hasNext() && loop) {
            final String name = i.next();
            final Pattern pattern = this.attributes.get(name);
            final Object sessionAttr = session.getAttribute(name);
            if (sessionAttr != null) {
                final String value = String.valueOf(sessionAttr);
                if (pattern.matcher(value).matches()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(value + " matches " + pattern.pattern());
                    }
                    success = true;
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(value + " does not match " + pattern.pattern());
                    }
                    redirect = this.redirects.get(name);
                    success = false;
                    loop = false;
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No session attribute found for " + name);
                }
                if (this.requireAttribute) {
                    redirect = this.redirects.get(name);
                    success = false;
                    loop = false;
                } else {
                    success = true;
                }
            }
        }
    }

    if (!success) {
        if (redirect != null && !"".equals(redirect)) {
            final StringBuffer url = new StringBuffer(redirect);
            if (((HttpServletRequest) request).getRequestURI() != null) {
                url.append("?url=")
                        .append(URLEncoder.encode(((HttpServletRequest) request).getRequestURI(), "UTF-8"));
                if (((HttpServletRequest) request).getQueryString() != null) {
                    url.append(URLEncoder.encode("?", "UTF-8")).append(
                            URLEncoder.encode(((HttpServletRequest) request).getQueryString(), "UTF-8"));
                }
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Forwarding request to " + url.toString());
            }
            this.context.getRequestDispatcher(url.toString()).forward(request, response);
            return;
        } else {
            if (response instanceof HttpServletResponse) {
                ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                        "Request blocked by filter, unable to perform redirect");
                return;
            } else {
                throw new ServletException("Request blocked by filter, unable to perform redirect");
            }
        }
    }
    chain.doFilter(request, response);
}

From source file:com.joliciel.talismane.tokeniser.patterns.TokenPatternImplTest.java

@Test
public void testParsePattern() {
    String regexp = "(?![cdCD]\\z|qu\\z|jusqu\\z).+'.+";
    TokenPatternImpl tokenPattern = new TokenPatternImpl(regexp, Tokeniser.SEPARATORS);
    List<Pattern> patterns = tokenPattern.getParsedPattern();
    Assert.assertEquals(3, patterns.size());
    int i = 0;/* w w w  .  j a  va  2  s . co m*/
    for (Pattern pattern : patterns) {
        if (i == 0) {
            Assert.assertEquals("(?![cdCD]\\z|[qQ]u\\z|[jJ]usqu\\z).+", pattern.pattern());
        } else if (i == 1) {
            Assert.assertEquals("'", pattern.pattern());
        } else if (i == 2) {
            Assert.assertEquals(".+", pattern.pattern());
        }
        i++;
    }

    regexp = "tre (de|d)";
    tokenPattern = new TokenPatternImpl(regexp, Tokeniser.SEPARATORS);
    patterns = tokenPattern.getParsedPattern();
    Assert.assertEquals(3, patterns.size());
    i = 0;
    for (Pattern pattern : patterns) {
        if (i == 0) {
            Assert.assertEquals("[E]tre", pattern.pattern());
        } else if (i == 1) {
            Assert.assertEquals(" ", pattern.pattern());
        } else if (i == 2) {
            Assert.assertEquals("(de|d)", pattern.pattern());
        }
        i++;
    }

    regexp = ".+\\.\\p";
    tokenPattern = new TokenPatternImpl(regexp, Tokeniser.SEPARATORS);
    patterns = tokenPattern.getParsedPattern();
    Assert.assertEquals(3, patterns.size());
    i = 0;
    for (Pattern pattern : patterns) {
        if (i == 0) {
            Assert.assertEquals(".+", pattern.pattern());
        } else if (i == 1) {
            Assert.assertEquals("\\.", pattern.pattern());
        } else if (i == 2) {
            Assert.assertEquals(Tokeniser.SEPARATORS.pattern(), pattern.pattern());
        }
        i++;
    }

    regexp = ".+qu'";
    tokenPattern = new TokenPatternImpl(regexp, Tokeniser.SEPARATORS);
    patterns = tokenPattern.getParsedPattern();
    Assert.assertEquals(2, patterns.size());
    i = 0;
    for (Pattern pattern : patterns) {
        if (i == 0) {
            Assert.assertEquals(".+qu", pattern.pattern());
        } else if (i == 1) {
            Assert.assertEquals("'", pattern.pattern());
        }
        i++;
    }

    regexp = "\\D+\\.a[ \\)]c[abc]";
    tokenPattern = new TokenPatternImpl(regexp, Tokeniser.SEPARATORS);
    patterns = tokenPattern.getParsedPattern();
    LOG.debug(patterns);
    Assert.assertEquals(5, patterns.size());
    i = 0;
    for (Pattern pattern : patterns) {
        if (i == 0) {
            Assert.assertEquals("\\D+", pattern.pattern());
        } else if (i == 1) {
            Assert.assertEquals("\\.", pattern.pattern());
        } else if (i == 2) {
            Assert.assertEquals("a", pattern.pattern());
        } else if (i == 3) {
            Assert.assertEquals("[ \\)]", pattern.pattern());
        } else if (i == 4) {
            Assert.assertEquals("c[abc]", pattern.pattern());
        }
        i++;
    }
}

From source file:org.zaproxy.zap.extension.plugnhack.MonitoredPagesManager.java

protected List<String> getIncludeRegexes() {
    List<String> list = new ArrayList<String>(this.includeRegexes.size());
    for (Pattern pattern : this.includeRegexes) {
        list.add(pattern.pattern());
    }//from  ww w  . ja  va2  s .  c  om
    return list;
}

From source file:org.zaproxy.zap.extension.plugnhack.MonitoredPagesManager.java

protected List<String> getExcludeRegexes() {
    List<String> list = new ArrayList<String>(this.excludeRegexes.size());
    for (Pattern pattern : this.excludeRegexes) {
        list.add(pattern.pattern());
    }/* w  w  w. java  2s  . c om*/
    return list;
}

From source file:org.apache.nifi.processor.util.StandardValidators.java

public static Validator createRegexMatchingValidator(final Pattern pattern) {
    return new Validator() {
        @Override/*from ww w. j a v  a2 s  . c  o m*/
        public ValidationResult validate(final String subject, final String input,
                final ValidationContext context) {
            if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
                return new ValidationResult.Builder().subject(subject).input(input)
                        .explanation("Expression Language Present").valid(true).build();
            }

            final boolean matches = pattern.matcher(input).matches();
            return new ValidationResult.Builder().input(input).subject(subject).valid(matches)
                    .explanation(
                            matches ? null : "Value does not match regular expression: " + pattern.pattern())
                    .build();
        }
    };
}

From source file:org.jaffa.qm.util.PropertyFilter.java

/** Returns true if the field matches any rule and is not marked for exclusion.
 * A false is returned if the field matches any rule and is marked for exclusion.
 * A null is returned if the field does not match any rule.
 * <p>//from www .  ja  v a2  s. c o  m
 * This method is expensive and should be used sparingly.
 * It is provided primarily to support custom fields that are
 * not part of the mapping file, and which hence cannot be supported by the
 * more efficient 'isFieldIncluded()' method.
 */
public Boolean includeField(String field) {
    for (int i = 0; i < m_rules.length; i++) {
        Pattern p = m_filterPatterns[i];
        boolean exclude = m_filterTypes[i];
        if (p != null && p.matcher(field).matches()) {
            if (log.isDebugEnabled())
                log.debug("field '" + field + "' has been " + (exclude ? "excluded" : "included")
                        + " by pattern '" + p.pattern() + "'");
            return !exclude;
        }
    }
    return null;
}