Example usage for org.apache.commons.lang3 StringUtils countMatches

List of usage examples for org.apache.commons.lang3 StringUtils countMatches

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils countMatches.

Prototype

public static int countMatches(final CharSequence str, final char ch) 

Source Link

Document

Counts how many times the char appears in the given string.

A null or empty ("") String input returns 0 .

 StringUtils.countMatches(null, *)       = 0 StringUtils.countMatches("", *)         = 0 StringUtils.countMatches("abba", 0)  = 0 StringUtils.countMatches("abba", 'a')   = 2 StringUtils.countMatches("abba", 'b')  = 2 StringUtils.countMatches("abba", 'x') = 0 

Usage

From source file:com.work.petclinic.SampleWebUiApplicationTests.java

@Test
public void testVeterinariansPage() throws Exception {
    ResponseEntity<String> page = executeLogin("user", "user");

    page = getPage("http://localhost:" + this.port + "/vets/list.html");

    assertEquals(HttpStatus.OK, page.getStatusCode());

    String body = page.getBody();
    assertNotNull("Page body is null.", body);
    assertTrue("Wrong page", body.contains("<h2>Veterinarians</h2>"));

    String vetList = body.substring(body.indexOf("<tbody>"));
    vetList = vetList.substring(0, vetList.indexOf("</tbody>"));
    assertTrue("Missing expected data.", StringUtils.countMatches(vetList, "<tr>") == 6);
}

From source file:com.entertailion.android.overlaynews.Downloader.java

private synchronized void updateFeeds() {
    Log.d(LOG_TAG, "updateFeeds");
    updateTime = System.currentTimeMillis();
    try {/*ww w .j  ava  2s  .c  o m*/
        // iterate through feeds in database
        ArrayList<RssFeed> feeds = FeedsTable.getFeeds(context);
        Log.d(LOG_TAG, "feeds=" + feeds);
        if (feeds != null) {
            for (RssFeed feed : feeds) {
                // Check if TTL set for feed
                if (feed.getTtl() != -1) {
                    if (System.currentTimeMillis()
                            - (feed.getDate().getTime() + feed.getTtl() * 60 * 1000) < 0) {
                        // too soon
                        Log.d(LOG_TAG, "TTL not reached: " + feed.getTitle());
                        break;
                    }
                }
                String rss = Utils.getRssFeed(feed.getLink(), context, true);
                RssHandler rh = new RssHandler();
                RssFeed rssFeed = rh.getFeed(rss);
                if (rssFeed.getTitle() == null) {
                    try {
                        Uri uri = Uri.parse(feed.getLink());
                        rssFeed.setTitle(uri.getHost());
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "get host", e);
                    }
                }
                Uri uri = Uri.parse(feed.getLink());
                Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost());
                String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost());
                Log.d(LOG_TAG, "icon1=" + icon);
                if (icon == null) {
                    // try base host address
                    int count = StringUtils.countMatches(uri.getHost(), ".");
                    if (count > 1) {
                        int index = uri.getHost().indexOf('.');
                        String baseHost = uri.getHost().substring(index + 1);
                        icon = Utils.getWebSiteIcon(context, "http://" + baseHost);
                        Log.d(LOG_TAG, "icon2=" + icon);
                    }
                }
                if (icon != null) {
                    try {
                        FileInputStream fis = context.openFileInput(icon);
                        Bitmap bitmap = BitmapFactory.decodeStream(fis);
                        fis.close();
                        rssFeed.setImage(icon);
                        rssFeed.setBitmap(bitmap);
                    } catch (Exception e) {
                        Log.d(LOG_TAG, "updateFeeds", e);
                    }
                }
                if (rssFeed.getBitmap() == null && rssFeed.getLogo() != null) {
                    Log.d(LOG_TAG, "logo=" + rssFeed.getLogo());
                    Bitmap bitmap = Utils.getBitmapFromURL(rssFeed.getLogo());
                    if (bitmap != null) {
                        icon = Utils.WEB_SITE_ICON_PREFIX + Utils.clean(rssFeed.getLogo()) + ".png";
                        Utils.saveToFile(context, bitmap, bitmap.getWidth(), bitmap.getHeight(), icon);
                        rssFeed.setImage(icon);
                        rssFeed.setBitmap(bitmap);
                    }
                }
                // update database
                long time = 0;
                if (rssFeed.getDate() != null) {
                    time = rssFeed.getDate().getTime();
                }
                FeedsTable.updateFeed(context, feed.getId(), rssFeed.getTitle(), feed.getLink(),
                        rssFeed.getDescription(), time, rssFeed.getViewDate().getTime(), rssFeed.getLogo(),
                        rssFeed.getImage(), rssFeed.getTtl());
                ItemsTable.deleteItems(context, feed.getId());
                for (RssItem item : rssFeed.getItems()) {
                    if (item.getTitle() != null) {
                        time = 0;
                        if (item.getDate() != null) {
                            time = item.getDate().getTime();
                        }
                        ItemsTable.insertItem(context, feed.getId(), item.getTitle(), item.getLink(),
                                item.getDescription(), item.getContent(), time);
                    }
                }
                // release resources
                Bitmap bitmap = rssFeed.getBitmap();
                if (bitmap != null) {
                    rssFeed.setBitmap(null);
                    bitmap.recycle();
                    bitmap = null;
                }
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "updateFeeds", e);
    }
}

From source file:imperial.modaclouds.monitoring.sda.weka.TimeSeriesForecasting.java

/**
 * This method calculates the target metrics using correlation algorithm with the weka library.
 * /*from   w w w  .  ja  v  a2  s. com*/
 * @param arffFile   the arff file for weka
 * @param method   the time series forecasting algorithm for weka
 * @param target   the target metric
 * @param predictionStep_str   the prediction step in future
 * @return   the value of the target metric
 */
public double[][] compute(String arffFile, String method, String target, int predictionStep) {

    double[][] result = null;

    int nbTargets = StringUtils.countMatches(target, ",") + 1;

    try {

        Instances data = new Instances(new BufferedReader(new FileReader(arffFile)));

        WekaForecaster forecaster = new WekaForecaster();

        forecaster.setFieldsToForecast(target);

        switch (method) {
        case "LinearRegression":
            forecaster.setBaseForecaster(new LinearRegression());
            break;
        case "GaussianProcess":
            forecaster.setBaseForecaster(new GaussianProcesses());
            break;
        case "SMOreg":
            forecaster.setBaseForecaster(new SMOreg());
            break;
        }

        forecaster.buildForecaster(data, System.out);

        forecaster.primeForecaster(data);

        List<List<NumericPrediction>> forecast = forecaster.forecast(predictionStep, System.out);

        result = new double[predictionStep][nbTargets];

        for (int i = 0; i < predictionStep; i++) {
            List<NumericPrediction> predsAtStep = forecast.get(i);
            for (int j = 0; j < nbTargets; j++) {
                NumericPrediction predForTarget = predsAtStep.get(j);
                result[i][j] = predForTarget.predicted();
                //System.out.print("" + predForTarget.predicted() + " ");
            }
            //System.out.println();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return result;
}

From source file:com.feilong.core.lang.StringUtilTest.java

/**
 * Search count./*from  w w w  .j  a  v a 2s  .  co  m*/
 */
@Test
public void testSearchCount() {
    String source = "jiiiiiinxin.feilong";
    assertEquals(8, StringUtils.countMatches(source, "i"));
    assertEquals(2, StringUtils.countMatches(source, "in"));
    assertEquals(3, StringUtils.countMatches(source, "ii"));
    assertEquals(1, StringUtils.countMatches(source, "xin"));
    assertEquals(1, StringUtils.countMatches("xin", "xin"));
    assertEquals(1, StringUtils.countMatches("xin", "i"));
    assertEquals(2, StringUtils.countMatches("xiin", "i"));
    assertEquals(2, StringUtils.countMatches("xiiiin", "ii"));
}

From source file:kenh.expl.impl.ExpLParser.java

/**
 * Parse the expression./*www. ja v a2 s  .c o m*/
 * This method will looking for string in brace, and get the value back.
 * @param express  The expression
 * @return    Return string or non-string object. Return empty string instead of null.
 */
private Object parseExpress(String express) throws UnsupportedExpressionException {
    if (express == null) {
        UnsupportedExpressionException e = new UnsupportedExpressionException("Expression is null.");
        throw e;
    }

    logger.trace("Expr: " + express);

    int left = StringUtils.countMatches(express, "{");
    int right = StringUtils.countMatches(express, "}");

    if (left != right) {
        UnsupportedExpressionException ex = new UnsupportedExpressionException("'{' and '}' does not match.");
        ex.push(express);
        throw ex;
    }

    if (left == 0)
        return express;

    String sResult = null; // String type result
    Object oResult = null; // Non-string type result

    StringBuffer resultBuffer = new StringBuffer();

    try {
        String context = express;
        while (!context.equals("")) {
            String[] s = splitExpression(context);
            if (!s[0].equals(""))
                resultBuffer.append(s[0]);
            if (!s[1].equals("")) {
                String variable = StringUtils.substring(s[1], 1, s[1].length() - 1);
                Object obj = getVariableValue(variable);
                logger.debug(variable + " -> " + ((obj == null) ? "<null>" : obj.toString()));
                try {
                    String str = convertToString(obj);
                    resultBuffer.append(str);
                } catch (UnsupportedExpressionException e) {
                    if (oResult == null)
                        oResult = obj;
                    else {
                        UnsupportedExpressionException ex = new UnsupportedExpressionException(
                                "Multi non-string objects returned. [" + oResult.getClass().getCanonicalName()
                                        + ", " + obj.getClass().getCanonicalName() + "]");
                        ex.push(express);
                        throw ex;
                    }
                }
            }
            context = s[2];
        }

    } catch (UnsupportedExpressionException e) {
        e.push(express);
        throw e;
    } catch (Exception e) {
        UnsupportedExpressionException ex = new UnsupportedExpressionException(e);
        ex.push(express);
        throw ex;
    }

    sResult = resultBuffer.toString();
    Object returnObj = null;
    if (StringUtils.isBlank(sResult)) {
        if (oResult != null)
            returnObj = oResult;
        else
            returnObj = sResult;
    } else {
        if (oResult != null) {
            UnsupportedExpressionException e = new UnsupportedExpressionException(
                    "Non-string object exist. [" + oResult.getClass().getCanonicalName() + "]");
            e.push(express);
            throw e;
        } else
            returnObj = sResult;
    }

    logger.debug(express + " -> " + ((returnObj == null) ? "<null>" : returnObj.toString()));
    return returnObj;
}

From source file:com.seleniumtests.ut.core.TestLogActions.java

/**
 * Check that if a step accepts a variable number of arguments, they are replaced
 *//*from   w  w  w . j a  v a 2 s. c  o  m*/
@Test(groups = { "ut" })
public void testMultiplePassworkMaskingWithList() {

    testPage._setPasswords(Arrays.asList("someText", "someOtherText"));
    TestStep step = TestLogging.getTestsSteps().get(TestLogging.getCurrentTestResult()).get(2);

    // all occurences of the password have been replaced
    Assert.assertFalse(step.toString().contains("someText"));
    Assert.assertFalse(step.toString().contains("someOtherText"));
    Assert.assertTrue(step.toString().contains(
            "sendKeys on TextFieldElement Text, by={By.id: text2} with args: (true, true, [******,], )"));
    Assert.assertEquals(StringUtils.countMatches(step.toString(), "******"), 3);
}

From source file:MiGA.motifStats.java

public void mergeNrefresh(motifStats m) {
    //teleutaia allagh gia 200% bug

    if (motif.contains("A")) {
        perA = (double) (mbp_len / motif.length())
                * (StringUtils.countMatches(motif, "A") + StringUtils.countMatches(m.getMotif(), "A"))
                / (Globals.A) * 100;//from   ww w  .  j  ava2  s  .  com
    }
    if (motif.contains("T")) {
        perT = (double) (mbp_len / motif.length())
                * (StringUtils.countMatches(motif, "T") + StringUtils.countMatches(m.getMotif(), "T"))
                / (Globals.T) * 100;

    }
    if (motif.contains("G")) {
        perG = (double) (mbp_len / motif.length())
                * (StringUtils.countMatches(motif, "G") + StringUtils.countMatches(m.getMotif(), "G"))
                / (Globals.G) * 100;
    }
    if (motif.contains("C")) {
        perC = (double) (mbp_len / motif.length())
                * (StringUtils.countMatches(motif, "C") + StringUtils.countMatches(m.getMotif(), "C"))
                / (Globals.C) * 100;
    }
}

From source file:com.frostwire.search.eztv.EztvSearchPerformer.java

protected boolean isValidHtml(String html) {
    if (html == null || html.contains("Cloudflare")) {
        return false;
    }//from  w  ww .j  a  va 2 s  .c o  m
    String[] keywords = getKeywords().split(" ");
    String k = null;
    // select the first keyword with length >= 3
    for (int i = 0; k == null && i < keywords.length; i++) {
        String s = keywords[i];
        if (s.length() >= 3) {
            k = s;
        }
    }
    if (k == null) {
        k = keywords[0];
    }

    int count = StringUtils.countMatches(html.toLowerCase(Locale.US), k.toLowerCase(Locale.US));

    return count > 9;
}

From source file:com.sangupta.fileanalysis.formats.ApacheLogFileHandler.java

private DBColumn detectDBColumn(String token, DBColumn lastDetectedColumn) {
    if (token.equals("-")) {
        return new DBColumn("col", DBColumnType.STRNG);
    }/*from   w  w  w.  j av  a 2s.c om*/

    // for last column
    if (lastDetectedColumn != null) {
        if ("verb".equals(lastDetectedColumn.name)) {
            return new DBColumn("path", DBColumnType.STRNG);
        }
    }

    // check if this is an IP
    int dots = StringUtils.countMatches(token, ".");
    if (dots == 3) {
        return new DBColumn("ip", DBColumnType.STRNG);
    }

    // check for date and time
    if (token.contains("/") && token.contains(":")) {
        return new DBColumn("date", DBColumnType.TIMESTAMP);
    }

    // check for verb
    if (FileAnalysisHelper.isAnyOf(token, HTTP_VERBS)) {
        return new DBColumn("verb", DBColumnType.STRNG);
    }

    // check for os
    if (FileAnalysisHelper.isAnyOf(token, OS_TYPES)) {
        return new DBColumn("os", DBColumnType.STRNG);
    }

    // response type
    if (FileAnalysisHelper.isAnyOf(token, RESPONSE_TYPE)) {
        return new DBColumn("response_type", DBColumnType.STRNG);
    }

    // referrer
    if (FileAnalysisHelper.startsWithAny(token, SCHEMES)) {
        return new DBColumn("referrer", DBColumnType.STRNG);
    }

    // protocol
    if (FileAnalysisHelper.startsWithAny(token, PROTOS)) {
        return new DBColumn("protocol", DBColumnType.STRNG);
    }

    if (FileAnalysisHelper.containsAny(token, OS_DECIPHER_WORDS)
            && FileAnalysisHelper.containsAny(token, BROWSER_DECIPHER_WORDS)) {
        return new DBColumn("user_agent", DBColumnType.STRNG);
    }

    return null;
}

From source file:info.novatec.testit.livingdoc.runner.CommandLineRunnerTest.java

private int countLines(String val) {
    return StringUtils.countMatches(val, "\n");
}