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:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

public boolean isFindBugsWarningAtLine(String requestedSourceFileName, int requestedLineNumber) {
    if (!testType.equals(FINDBUGS))
        return false;

    // TODO handle multi-line FB warnings
    Pattern pattern = Pattern.compile("At (\\w+\\.java):\\[line (\\d+)\\]");
    Matcher matcher = pattern.matcher(shortTestResult);
    if (matcher.matches() && matcher.groupCount() > 1) {
        String sourceFileName = matcher.group(1);
        String lineNumber = matcher.group(2);
        if (requestedSourceFileName.equals(sourceFileName)
                && requestedLineNumber == Integer.parseInt(lineNumber)) {
            return true;
        }/*from   w ww. j  a  v a 2s. com*/
    }
    return false;
}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

/**
* @param viewSourceLink TODO//from   w  ww .j  av  a  2s. c  om
 * @return Returns the location in the file where the PMD warning occurs.
*/
private @HTML String getPmdLocation(String viewSourceLink) {
    String pmdLocation = shortTestResult;
    int i = pmdLocation.indexOf(':');
    if (i > 0)
        pmdLocation = pmdLocation.substring(i + 1);

    if (pmdLocation == null || pmdLocation.equals(""))
        return "";
    //  src/oop2/searchTree/EmptyTree.java:19
    Pattern pattern = Pattern.compile("([\\w/]+\\.java):(\\d+)");
    Matcher matcher = pattern.matcher(pmdLocation);
    if (matcher.matches() && matcher.groupCount() > 1) {
        String sourceFileName = matcher.group(1);
        String startHighlight = matcher.group(2);
        int numToHighlight = 1;
        int numContext = 0;
        return createSourceCodeLink(viewSourceLink, pmdLocation, sourceFileName, startHighlight, numToHighlight,
                numContext);
    }
    return XSSScrubber.scrubbedStr(pmdLocation);
}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

private @HTML String getFindbugsHotlink(String viewSourceLink) {
    if (!testType.equals(FINDBUGS))
        throw new IllegalArgumentException("is type " + testType + ", not findbugs");
    if (shortTestResult == null || shortTestResult.equals(""))
        return "";
    // At ExtractHRefs.java:[line 64]
    // TODO handle multi-line FB warnings
    String p = "At (\\w+\\.java):\\[line (\\d+)\\]";
    Pattern pattern = Pattern.compile(p);
    Matcher matcher = pattern.matcher(shortTestResult);
    if (matcher.matches() && matcher.groupCount() > 1) {
        String sourceFileName = matcher.group(1);
        String startHighlight = matcher.group(2);
        int numToHighlight = 1;
        int numContext = 0;
        return createSourceCodeLink(viewSourceLink, shortTestResult, sourceFileName, startHighlight,
                numToHighlight, numContext);
    }//from  ww  w.j  a  va  2  s . co m
    return XSSScrubber.scrubbedStr(shortTestResult);
}

From source file:com.adrup.saldo.bank.ica.IcaManager.java

@Override
public Map<AccountHashKey, RemoteAccount> getAccounts(Map<AccountHashKey, RemoteAccount> accounts)
        throws BankException {
    Log.d(TAG, "getAccounts()");

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // Android doesn't like ICA's cert, so we need a forgiving TrustManager
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    HttpClient httpClient = new SaldoHttpClient(mContext,
            new ThreadSafeClientConnManager(params, schemeRegistry), null);

    try {//from  w w w  .  j a v a2  s  .c o m
        // get login page

        Log.d(TAG, "getting login page");

        String res = HttpHelper.get(httpClient, LOGIN_URL);

        Matcher matcher = Pattern.compile(VIEWSTATE_REGEX).matcher(res);
        if (!matcher.find()) {
            Log.e(TAG, "No viewstate match.");
            Log.d(TAG, res);
            throw new IcaException("No viewState match.");
        }
        String viewState = matcher.group(1);
        Log.d(TAG, "viewState= " + viewState);

        // do login post, should redirect us to the accounts page
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);

        parameters.add(new BasicNameValuePair(VIEWSTATE_PARAM, viewState));
        parameters.add(new BasicNameValuePair(USER_PARAM, mBankLogin.getUsername()));
        parameters.add(new BasicNameValuePair(PASS_PARAM, mBankLogin.getPassword()));
        parameters.add(new BasicNameValuePair(BUTTON_PARAM, "Logga in"));

        res = HttpHelper.post(httpClient, LOGIN_URL, parameters);

        if (res.contains("login-error")) {
            Log.d(TAG, "auth fail");
            throw new AuthenticationException("auth fail");
        }

        // extract account info
        matcher = Pattern.compile(ACCOUNTS_REGEX).matcher(res);

        int remoteId = 1;
        int count = 0;
        while (matcher.find()) {
            count++;
            int groupCount = matcher.groupCount();
            for (int i = 1; i <= groupCount; i++) {
                Log.d(TAG, i + ":" + matcher.group(i));
            }
            if (groupCount < 2) {
                throw new BankException("Pattern match issue: groupCount < 2");
            }

            int ordinal = remoteId;
            String name = Html.fromHtml(matcher.group(1)).toString();
            long balance = Long.parseLong(matcher.group(2).replaceAll("\\,|\\.| ", "")) / 100;
            accounts.put(new AccountHashKey(String.valueOf(remoteId), mBankLogin.getId()),
                    new Account(String.valueOf(remoteId), mBankLogin.getId(), ordinal, name, balance));
            remoteId++;
        }
        if (count == 0) {
            Log.d(TAG, "no accounts added");
            Log.d(TAG, res);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new IcaException(e.getMessage(), e);
    } catch (HttpException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new IcaException(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return accounts;
}

From source file:org.apache.kylin.monitor.QueryParser.java

public void parseQueryLog(String filePath, String dPath) throws ParseException, IOException {

    logger.info("Start parsing file " + filePath + " !");

    //        writer config init
    FileSystem fs = this.getHdfsFileSystem();
    org.apache.hadoop.fs.Path resultStorePath = new org.apache.hadoop.fs.Path(dPath);
    OutputStreamWriter writer = new OutputStreamWriter(fs.append(resultStorePath));
    CSVWriter cwriter = new CSVWriter(writer, '|', CSVWriter.NO_QUOTE_CHARACTER);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
    Pattern p_query_start = Pattern.compile("^\\[.*\\]:\\[(.*),.*\\]\\[.*\\]\\[.*QueryService.logQuery.*\\].*");
    Pattern p_query_end = Pattern.compile("^Message:(.*)$");
    Pattern p_query_body = Pattern.compile(
            "^\\[.*\\]:\\[((\\d{4}-\\d{2}-\\d{2}).*)\\]\\[.*\\]\\[.*\\].*\n^=+\\[QUERY\\]=+\n^SQL:(.*)\n^User:(.*)\n^Success:(.*)\n^Duration:(.*)\n^Project:(.*)\n^(Realization Names|Cube Names): \\[(.*)\\]\n^Cuboid Ids: \\[(.*)\\]\n^Total scan count:(.*)\n^Result row count:(.*)\n^Accept Partial:(.*)\n(^Is Partial Result:(.*)\n)?^Hit Cache:(.*)\n^Message:(.*)",
            Pattern.MULTILINE);//  w ww  . j  a va  2  s  . co m
    Matcher m_query_start = p_query_start.matcher("");
    Matcher m_query_end = p_query_end.matcher("");
    Matcher m_query_body = p_query_body.matcher("");

    boolean query_start = false;
    StringBuffer query_body = new StringBuffer("");
    Path path = Paths.get(filePath);
    try {
        BufferedReader reader = Files.newBufferedReader(path, ENCODING);
        String line = null;
        while ((line = reader.readLine()) != null) {
            m_query_start.reset(line); //reset the input
            m_query_end.reset(line);

            // set start flag ,clear StringBuffer
            if (m_query_start.find()) {
                query_start = true;
                query_body = new StringBuffer("");
            }
            if (query_start) {
                query_body.append(line + "\n");
            }
            if (m_query_end.find()) {
                query_start = false;
                m_query_body.reset(query_body);
                logger.info("parsing query...");
                logger.info(query_body);
                //                    skip group(8) and group(14)
                if (m_query_body.find()) {
                    ArrayList<String> groups = new ArrayList<String>();
                    int grp_count = m_query_body.groupCount();
                    for (int i = 1; i <= grp_count; i++) {
                        if (i != 8 && i != 14) {
                            String grp_item = m_query_body.group(i);
                            grp_item = grp_item == null ? "" : grp_item.trim();
                            groups.add(grp_item);
                        }
                    }

                    long start_time = format.parse(groups.get(0)).getTime()
                            - (int) (Double.parseDouble(groups.get(5)) * 1000);
                    groups.set(0, format.format(new Date(start_time)));
                    groups.add(DEPLOY_ENV);
                    String[] recordArray = groups.toArray(new String[groups.size()]);
                    //                        write to hdfs
                    cwriter.writeNext(recordArray);

                }

            }

        }
    } catch (IOException ex) {
        logger.info("Failed to write to hdfs:", ex);
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (cwriter != null) {
            cwriter.close();
        }
        if (fs != null) {
            fs.close();
        }
    }

    logger.info("Finish parsing file " + filePath + " !");

}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

public StackTraceElement getExceptionSourceFromLongTestResult() {
    if (!isError())
        throw new IllegalStateException(
                "Can ONLY get exception source from test outcome of type " + TestOutcome.ERROR);
    String testResult = getLongTestResult();
    if (Strings.isNullOrEmpty(testResult))
        throw new IllegalStateException("No stack trace available in this outcome: " + outcome);

    BufferedReader reader = null;
    try {/*  w ww.  ja v a 2  s .c o  m*/
        reader = new BufferedReader(new StringReader(getLongTrimmedTestResult()));
        Pattern pattern = Pattern.compile("\\((\\w+\\.java):(\\d+)\\)");
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;

            Matcher matcher = pattern.matcher(line);
            if (!matchesIgnoreSet(line) && matcher.find() && matcher.groupCount() > 1) {
                return MarmosetUtilities.parseStackTrace(line);
            }
        }
    } catch (IOException ignore) {
        // Cannot really happen with a stringreader
    }
    return null;
}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

public @HTML String getExceptionLocation(String viewSourceLink) {
    StringBuffer buf = new StringBuffer();
    if (isError()) {
        String testResult = getLongTestResult();
        if (Strings.isNullOrEmpty(testResult))
            return "";
        BufferedReader reader = null;
        Pattern pattern = FINDBUGS_LOCATION_REGEX;
        try {/*w w w  .j  a v  a 2 s  .c o  m*/
            reader = new BufferedReader(new StringReader(getLongTrimmedTestResult()));
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                // System.out.println("line: " +line);
                Matcher matcher = pattern.matcher(line);
                if (!matchesIgnoreSet(line) && matcher.find() && matcher.groupCount() > 1) {
                    String sourceFileName = matcher.group(1);
                    String startHighlight = matcher.group(2);
                    int numToHighlight = 1;
                    int numContext = 0;
                    buf.append(createSourceCodeLink(viewSourceLink, line, sourceFileName, startHighlight,
                            numToHighlight, numContext));
                    buf.append("<br>");
                    // Return after we find the first hot-link-able stack frame
                    return XSSScrubber.asHTML(buf.toString());
                } else {
                    buf.append(line + "<br>\n");
                }
            }
        } catch (IOException ignore) {
            throw new RuntimeException("DAMMIT JIM!", ignore);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
    return XSSScrubber.asHTML(buf.toString());
}

From source file:com.thoughtworks.go.config.CachedGoConfigIntegrationTest.java

@Test
public void shouldFailWhenTryingToAddPipelineWithTheSameNameAsAnotherPipelineDefinedRemotely_FullConfigSave()
        throws Exception {
    assertThat(configWatchList.getCurrentConfigRepos().size()).isEqualTo(1);
    repoConfigDataSource.onCheckoutComplete(configRepo.getMaterialConfig(), externalConfigRepo,
            latestModification);//from   www.ja va 2s  .com
    assertThat(cachedGoConfig.currentConfig().hasPipelineNamed(new CaseInsensitiveString("pipe1"))).isTrue();

    final PipelineConfig dupPipelineConfig = PipelineMother
            .twoBuildPlansWithResourcesAndSvnMaterialsAtUrl("pipe1", "ut", "www.spring.com");
    try {
        goConfigDao.updateConfig(new UpdateConfigCommand() {
            @Override
            public CruiseConfig update(CruiseConfig cruiseConfig) throws Exception {
                cruiseConfig.getGroups().first().add(dupPipelineConfig);
                return cruiseConfig;
            }
        });
        fail("Should have thrown");
    } catch (RuntimeException ex) {
        String errorMessage = ex.getMessage();
        assertThat(errorMessage).contains(
                "You have defined multiple pipelines named 'pipe1'. Pipeline names must be unique. Source(s):");
        Matcher matcher = Pattern.compile("^.*\\[(.*),\\s(.*)\\].*$", Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(errorMessage);
        assertThat(matcher.matches()).isTrue();
        assertThat(matcher.groupCount()).isEqualTo(2);
        PipelineConfig pipe1 = goConfigService.pipelineConfigNamed(new CaseInsensitiveString("pipe1"));
        List<String> expectedSources = asList(dupPipelineConfig.getOriginDisplayName(),
                pipe1.getOriginDisplayName());
        List<String> actualSources = new ArrayList<>();
        for (int i = 1; i <= matcher.groupCount(); i++) {
            actualSources.add(matcher.group(i));
        }
        assertThat(actualSources.size()).isEqualTo(expectedSources.size());
        assertThat(actualSources.containsAll(expectedSources)).isTrue();
    }
}

From source file:com.jaeksoft.searchlib.Client.java

public int updateTextDocuments(StreamSource streamSource, String charset, Integer bufferSize,
        String capturePattern, Integer langPosition, List<String> fieldList, InfoCallback infoCallBack)
        throws SearchLibException, IOException, NoSuchAlgorithmException, URISyntaxException,
        InstantiationException, IllegalAccessException, ClassNotFoundException {
    if (capturePattern == null)
        throw new SearchLibException("No capture pattern");
    if (fieldList == null || fieldList.size() == 0)
        throw new SearchLibException("empty field list");
    String[] fields = fieldList.toArray(new String[fieldList.size()]);
    Matcher matcher = Pattern.compile(capturePattern).matcher("");
    BufferedReader br = null;//ww  w  .j  av a2s . com
    Reader reader = null;
    SchemaField uniqueSchemaField = getSchema().getFieldList().getUniqueField();
    String uniqueField = uniqueSchemaField != null ? uniqueSchemaField.getName() : null;
    if (charset == null)
        charset = "UTF-8";
    if (bufferSize == null)
        bufferSize = 50;
    try {
        Collection<IndexDocument> docList = new ArrayList<IndexDocument>(bufferSize);
        reader = streamSource.getReader();
        if (reader == null)
            reader = new InputStreamReader(streamSource.getInputStream(), charset);
        br = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
        String line;
        int docCount = 0;
        IndexDocument lastDocument = null;
        String lastUniqueValue = null;
        while ((line = br.readLine()) != null) {
            matcher.reset(line);
            if (!matcher.matches())
                continue;
            LanguageEnum lang = LanguageEnum.UNDEFINED;
            int matcherGroupCount = matcher.groupCount();
            if (langPosition != null && matcherGroupCount >= langPosition)
                lang = LanguageEnum.findByNameOrCode(matcher.group(langPosition));
            IndexDocument document = new IndexDocument(lang);
            int i = matcherGroupCount < fields.length ? matcherGroupCount : fields.length;
            String uniqueValue = null;
            while (i > 0) {
                String value = matcher.group(i--);
                String f = fields[i];
                document.add(f, value, 1.0F);
                if (f.equals(uniqueField))
                    uniqueValue = value;
            }
            // Consecutive documents with same uniqueKey value are merged
            // (multivalued)
            if (uniqueField != null && lastDocument != null && uniqueValue != null
                    && uniqueValue.equals(lastUniqueValue)) {
                lastDocument.addIfNotAlreadyHere(document);
                continue;
            }
            docList.add(document);
            if (docList.size() == bufferSize)
                docCount = updateDocList(0, docCount, docList, infoCallBack);
            lastUniqueValue = uniqueValue;
            lastDocument = document;
        }
        if (docList.size() > 0)
            docCount = updateDocList(0, docCount, docList, infoCallBack);
        return docCount;
    } finally {
        if (br != null)
            if (br != reader)
                IOUtils.close(br);
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.regexp.HtmlUnitRegExpProxy.java

String computeReplacementValue(final String replacement, final String originalString, final Matcher matcher) {

    int lastIndex = 0;
    final StringBuilder result = new StringBuilder();
    int i;//  www  .  j av  a  2 s. c  om
    while ((i = replacement.indexOf('$', lastIndex)) > -1) {
        if (i > 0) {
            result.append(replacement, lastIndex, i);
        }
        String ss = null;
        if (i < replacement.length() - 1 && (i == lastIndex || replacement.charAt(i - 1) != '$')) {
            final char next = replacement.charAt(i + 1);
            // only valid back reference are "evaluated"
            if (next >= '1' && next <= '9') {
                final int num1digit = next - '0';
                final char next2 = (i + 2 < replacement.length()) ? replacement.charAt(i + 2) : 'x';
                final int num2digits;
                // if there are 2 digits, the second one is considered as part of the group number
                // only if there is such a group
                if (next2 >= '1' && next2 <= '9') {
                    num2digits = num1digit * 10 + (next2 - '0');
                } else {
                    num2digits = Integer.MAX_VALUE;
                }
                if (num2digits <= matcher.groupCount()) {
                    ss = matcher.group(num2digits);
                    i++;
                } else if (num1digit <= matcher.groupCount()) {
                    ss = StringUtils.defaultString(matcher.group(num1digit));
                }
            } else {
                switch (next) {
                case '&':
                    ss = matcher.group();
                    break;
                case '0':
                    if (browserVersion_.hasFeature(JS_REGEXP_GROUP0_RETURNS_WHOLE_MATCH)) {
                        ss = matcher.group();
                    }
                    break;
                case '`':
                    ss = originalString.substring(0, matcher.start());
                    break;
                case '\'':
                    ss = originalString.substring(matcher.end());
                    break;
                case '$':
                    ss = "$";
                    break;
                default:
                }
            }
        }
        if (ss == null) {
            result.append('$');
            lastIndex = i + 1;
        } else {
            result.append(ss);
            lastIndex = i + 2;
        }
    }

    result.append(replacement, lastIndex, replacement.length());

    return result.toString();
}