Example usage for java.util.regex Matcher groupCount

List of usage examples for java.util.regex Matcher groupCount

Introduction

In this page you can find the example usage for java.util.regex Matcher groupCount.

Prototype

public int groupCount() 

Source Link

Document

Returns the number of capturing groups in this matcher's pattern.

Usage

From source file:eu.openanalytics.rsb.security.X509AuthenticationFilter.java

@Override
protected Object getPreAuthenticatedPrincipal(final HttpServletRequest request) {
    final String clientDN = (String) getPreAuthenticatedCredentials(request);
    if (clientDN == null) {
        return null;
    }// w w  w  .java 2 s. c o m

    logger.debug("Client DN is '" + clientDN + "'");

    final Matcher matcher = subjectDnPattern.matcher(clientDN);

    if (!matcher.find()) {
        throw new BadCredentialsException("No matching pattern was found in client DN: " + clientDN);
    }

    if (matcher.groupCount() != 1) {
        throw new IllegalArgumentException("Regular expression must contain a single group ");
    }

    final String username = matcher.group(1);

    logger.debug("Extracted Principal name is '" + username + "'");

    return username;
}

From source file:org.codhaus.groovy.grails.validation.routines.RegexValidator.java

/**
 * Validate a value against the set of regular expressions
 * returning a String value of the aggregated groups.
 *
 * @param value The value to validate.//  ww  w. j  a  v a  2  s .c  om
 * @return Aggregated String value comprised of the
 * <i>groups</i> matched if valid or <code>null</code> if invalid
 */
public String validate(String value) {
    if (value == null) {
        return null;
    }

    for (int i = 0; i < patterns.length; i++) {
        Matcher matcher = patterns[i].matcher(value);
        if (matcher.matches()) {
            int count = matcher.groupCount();
            if (count == 1) {
                return matcher.group(1);
            }
            StringBuilder buffer = new StringBuilder();
            for (int j = 0; j < count; j++) {
                String component = matcher.group(j + 1);
                if (component != null) {
                    buffer.append(component);
                }
            }
            return buffer.toString();
        }
    }
    return null;
}

From source file:guru.qas.martini.annotation.StepsAnnotationProcessorTest.java

@Test
public void testPostProcessAfterInitialization() throws IOException, NoSuchMethodException {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    TestSteps steps = context.getBean(TestSteps.class);

    Class<?> wrapped = AopUtils.getTargetClass(steps);
    Method method = wrapped.getMethod("anotherStep", String.class);

    Map<String, StepImplementation> givenBeanIndex = context.getBeansOfType(StepImplementation.class);
    Collection<StepImplementation> givens = givenBeanIndex.values();

    List<StepImplementation> matches = Lists.newArrayList();
    for (StepImplementation given : givens) {
        Method givenMethod = given.getMethod();
        if (givenMethod.equals(method)) {
            matches.add(given);// ww  w  .  j  a  va2 s.  c  o m
        }
    }

    int count = matches.size();
    assertEquals(count, 1, "wrong number of GivenStep objects registered for TestSteps.anotherStep()");

    StepImplementation match = matches.get(0);
    Pattern pattern = match.getPattern();
    Matcher matcher = pattern.matcher("another \"(.+)\" here");
    assertTrue(matcher.find(), "expected Pattern to match Gherkin regular expression");
    assertEquals(matcher.groupCount(), 1, "wrong number of parameters captured for TestSteps.anotherStep()");
}

From source file:com.github.woki.payments.adyen.ClientConfig.java

public HttpHost getProxyHost() {
    if (proxyHost == null && proxyConfig != null) {
        Matcher matcher = PROXY_CONFIG_PATTERN.matcher(proxyConfig);
        if (matcher.matches() && matcher.groupCount() == 6) {
            if (matcher.group(1) == null) {
                proxyHost = HttpHost.create(matcher.group(5) + ":" + matcher.group(6));
            } else {
                proxyUsername = matcher.group(1);
                proxyPassword = matcher.group(2);
                proxyHost = HttpHost.create(matcher.group(3) + ":" + matcher.group(4));
            }// w  w w .  j a  va 2s.c  o m
        }
    }
    return proxyHost;
}

From source file:no.packdrill.android.sparkledroid.lib.parse.csvtsv.TSVParse.java

@Override
public Iterator<Map<String, Cell>> iterator()
//--------------------------------
{
    return new Iterator<Map<String, Cell>>()
    //========================================
    {/*from www  .j  a  v  a 2  s. co m*/
        Map<String, Cell> m = new HashMap<String, Cell>();

        final Pattern languagePattern = Pattern.compile("\"(.+)\"@(\\w\\w)$");

        @Override
        public boolean hasNext() {
            return it.hasNext();
        }

        @Override
        public Map<String, Cell> next()
        //--------------------------------
        {
            CSVRecord record = null;
            int p;
            try {
                record = it.next();
                m.clear();
                for (int i = 0; i < record.size(); i++) {
                    String k = columns[i];
                    String v = record.get(i);
                    if (v == null)
                        continue;
                    if (v.trim().startsWith("_:")) {
                        p = v.indexOf("_:");
                        String name;
                        try {
                            name = v.substring(p + 2);
                        } catch (Exception _e) {
                            name = "";
                        }
                        Cell ri = new Cell(true, name);
                        ri.setUnparsedValue(v);
                        m.put(k, ri);
                        continue;
                    }
                    if ((v.trim().startsWith("<")) && (v.trim().endsWith(">"))) {
                        p = v.indexOf('<');
                        int p1 = v.indexOf('>');
                        if ((p >= 0) && (p1 > 0))
                            v = v.substring(p + 1, p1);
                        URI uri = null;
                        try {
                            uri = new URI(v);
                        } catch (Exception _e) {
                            uri = null;
                        }
                        if (uri != null) {
                            Cell ri = processURI(v);
                            if (ri != null) {
                                m.put(k, ri);
                                continue;
                            }
                        }

                        Matcher patmatch = languagePattern.matcher(v);
                        if ((patmatch.matches()) && (patmatch.groupCount() > 0)) {
                            String s = patmatch.group(1);
                            String lang = null;
                            if (patmatch.groupCount() > 1)
                                lang = patmatch.group(2);
                            if ((s != null) && (lang != null)) {
                                Cell ri = new Cell(s, lang);
                                ri.setUnparsedValue(v);
                                m.put(k, ri);
                                continue;
                            }
                        }

                    }
                    Cell ri = new Cell(v);
                    ri.setUnparsedValue(v);
                    m.put(k, ri);
                }
            } catch (Exception e) {
                lastError = (record == null) ? "" : record.toString();
                lastException = e;
                Log.e(LOGTAG, lastError, e);
                return null;
            }
            return m;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException(
                    "no.packdrill.android.SPARQLClient.parse.csvtsv.iterator.remove");
        }
    };
}

From source file:io.narayana.nta.logparsing.common.LogParser.java

private String logFormat(Handler handler, Matcher matcher) {

    final StringBuilder sb = new StringBuilder(this + " Parser match: handler=`")
            .append(handler.getClass().getSimpleName());

    for (int i = 1; i <= matcher.groupCount(); i++)
        sb.append("`, matcher.group(").append(i).append(")=`").append(matcher.group(i));

    return sb.append("`").toString();
}

From source file:org.datavec.api.records.reader.impl.regex.RegexSequenceRecordReader.java

private List<List<Writable>> loadSequence(String fileContents, URI uri) {
    String[] lines = fileContents.split("(\r\n)|\n"); //TODO this won't work if regex allows for a newline

    int numLinesSkipped = 0;
    List<List<Writable>> out = new ArrayList<>();
    int lineCount = 0;
    for (String line : lines) {
        lineCount++;/*ww  w. j ava 2s . c  o m*/
        if (numLinesSkipped < skipNumLines) {
            numLinesSkipped++;
            continue;
        }
        //Split line using regex matcher
        Matcher m = pattern.matcher(line);
        List<Writable> timeStep;
        if (m.matches()) {
            int count = m.groupCount();
            timeStep = new ArrayList<>(count);
            for (int i = 1; i <= count; i++) { //Note: Matcher.group(0) is the entire sequence; we only care about groups 1 onward
                timeStep.add(new Text(m.group(i)));
            }
        } else {
            switch (errorHandling) {
            case FailOnInvalid:
                throw new IllegalStateException("Invalid line: line does not match regex (line #" + lineCount
                        + ", uri=\"" + uri + "\"), " + "\", regex=" + regex + "\"; line=\"" + line + "\"");
            case SkipInvalid:
                continue;
            case SkipInvalidWithWarning:
                String warnMsg = "Skipping invalid line: line does not match regex (line #" + lineCount
                        + ", uri=\"" + uri + "\"), " + "\"; line=\"" + line + "\"";
                LOG.warn(warnMsg);
                continue;
            default:
                throw new RuntimeException("Unknown error handling mode: " + errorHandling);
            }
        }
        out.add(timeStep);
    }

    return out;
}

From source file:org.apache.jmeter.protocol.http.parser.HTMLParser.java

/**
 * // ww  w  . j  a v  a 2 s  .  c o m
 * @param userAgent User Agent
 * @return version null if not IE or the version after MSIE
 */
protected Float extractIEVersion(String userAgent) {
    if (StringUtils.isEmpty(userAgent)) {
        log.info("userAgent is null");
        return null;
    }
    Matcher matcher = IE_UA_PATTERN.matcher(userAgent);
    String ieVersion = null;
    if (matcher.find()) {
        if (matcher.groupCount() > 0) {
            ieVersion = matcher.group(1);
        } else {
            ieVersion = matcher.group();
        }
    }
    if (ieVersion != null) {
        return Float.valueOf(ieVersion);
    } else {
        return null;
    }
}

From source file:be.hikage.maven.plugin.xmlmerge.MergeXmlMojo.java

public void execute() throws MojoExecutionException {
    getLog().info("EXECUTE on " + outputDirectory.getAbsolutePath());
    getLog().info("Process prolog : " + processProlog);

    List<File> xmlFiles = new ArrayList<File>();

    Pattern regex = Pattern.compile(mergeFilenamePattern);

    getLog().info("Search file that match " + mergeFilenamePattern);
    findXmlToMerge(inputDirectory, xmlFiles);

    getLog().info("Number of file found to merge :" + xmlFiles.size());

    try {// w  w w. ja  v  a  2s .co  m
        for (File fileToMerge : xmlFiles) {
            Matcher matcher = regex.matcher(fileToMerge.getName());
            if (matcher.matches() && matcher.groupCount() == 2) {

                String baseFileName = matcher.group(2);

                File basefile = getBaseFile(fileToMerge, baseFileName);
                File outputFile = getOutputFile(fileToMerge, baseFileName);

                getLog().debug("Merge Base :" + basefile.getAbsolutePath());
                getLog().debug("Merge Transform :" + fileToMerge.getAbsolutePath());
                getLog().debug("Merge Output :" + outputFile.getAbsolutePath());

                if (basefile.exists()) {

                    StringBuilder prologHeader = processProlog ? new StringBuilder() : null;
                    Document documentBase = Dom4JUtils.readDocument(basefile.toURI().toURL(), prologHeader);
                    Document result = xmlMerger.mergeXml(documentBase, loadXml(fileToMerge));

                    writeMergedXml(outputFile, result, prologHeader);

                    if (removeMergeDocumentAfterProcessing) {
                        boolean fileDeleted = fileToMerge.delete();
                        if (!fileDeleted)
                            getLog().warn("Unable to delete file :" + fileToMerge.getAbsolutePath());
                    }

                } else {
                    getLog().warn("No filebase found for " + fileToMerge.getAbsolutePath());
                }

            } else {
                throw new MojoExecutionException("The file do not matches regex");

            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to merge xml", e);
    }

}

From source file:org.candlepin.common.util.JaxRsExceptionResponseBuilder.java

/**
 * This method inspects exception and decides whether it relates to wrong
 * parameters passed to a JAX-RS resource method.
 * @param exception/*from  w w w .j a  v  a  2s .c o m*/
 *        JAX-RS implementation generated exception.
 * @return True if and only if the exception contains error regarding JAX-RS
 *         parameters
 */
public final boolean canHandle(final Exception exception) {
    Throwable cause = exception.getCause();

    if (cause instanceof CandlepinParameterParseException) {
        return true;
    }
    String msg = exception.getMessage();

    if (StringUtils.isNotEmpty(msg)) {
        Matcher paramMatcher = PARAM_REGEX.matcher(msg);
        Matcher illegalValMatcher = ILLEGAL_VAL_REGEX.matcher(msg);
        if (paramMatcher.find() && illegalValMatcher.find()) {
            if ((paramMatcher.groupCount() == 2) && (illegalValMatcher.groupCount() == 2)) {
                return true;
            }
        }
    }

    return false;
}