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.qcadoo.mes.basic.tree.ProductNumberingServiceImpl.java

private List<String> findRootsForNodeNumber(final String nodeNumber) {
    List<String> roots = Lists.newArrayList();

    String number = nodeNumber;/*  w  w w.  ja va  2s.co  m*/

    for (int i = 0; i < StringUtils.countMatches(nodeNumber, "."); i++) {
        number = number.substring(0, number.lastIndexOf('.'));

        roots.add(number);
    }

    return roots;
}

From source file:com.seleniumtests.it.core.TestSeleniumRobotTestListener.java

@Test(groups = { "it" })
public void testContextStorageParallelClasses(ITestContext testContext) throws Exception {

    executeSubTest2(ParallelMode.CLASSES);

    String mainReportContent = FileUtils.readFileToString(new File(
            new File(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory()).getAbsolutePath()
                    + File.separator + "SeleniumTestReport.html"));
    mainReportContent = mainReportContent.replace("\n", "").replace("\r", "");
    Assert.assertEquals(StringUtils.countMatches(mainReportContent, "class=\"fa fa-circle circleSuccess\">"),
            StringUtils.countMatches(mainReportContent, "TestReport.html") - 1);
    Assert.assertEquals(StringUtils.countMatches(mainReportContent, "TestReport.html"), 9);

    // test1Listener4 fails as expected
    Assert.assertTrue(mainReportContent.matches(
            ".*<i class\\=\"fa fa-circle circleSkipped\"></i><a href\\='test1Listener4/TestReport\\.html'.*?>test1Listener4</a>.*"));
}

From source file:io.stallion.plugins.flatBlog.comments.tests.TestCommentNotifications.java

@Test
public void testMentionEmails() throws Exception {
    CommentsEndpoints resource = new CommentsEndpoints();
    Long now = mils() - 2000;//from   w w w  . j a v a2 s. c  o  m

    // Initial comment
    String timEmail = "test.tim." + now + "@stallion.io";
    resource.submitComment(newComment(timEmail, "Timothy", "I hope someone replies to me and mentions me!")
            .setMentionSubscribe(true));
    Contact tim = ContactsController.instance().forUniqueKeyOrNotFound("email", timEmail);
    // No notifications yet
    Assert.assertEquals(0, NotificationController.instance().filter("createdAt", now, ">")
            .filter("contactId", john.getId()).count());
    Assert.assertEquals(0, NotificationController.instance().filter("createdAt", now, ">")
            .filter("contactId", tim.getId()).count());

    // Two people reply to Timothy, one additional comment
    resource.submitComment(
            newComment("test.sherry@stallion.io", "Sherry", "Hey @Timothy, I will reply to you."));
    resource.submitComment(
            newComment("test.travis@stallion.io", "Travis", "Hey @Timothy, have a second reply."));
    resource.submitComment(newComment("test.mike@stallion.io", "Mike", "This is an unrelated comment."));

    // Two notifications, with the same send time
    List<Notification> notifications = NotificationController.instance().filter("createdAt", now, ">")
            .filter("contactId", tim.getId()).all();
    Assert.assertEquals(2, notifications.size());
    Assert.assertEquals(notifications.get(0).getSendAt(), notifications.get(1).getSendAt());

    // Verify pending task
    Notification notification = notifications.get(0);
    String customKey = "notification---" + notification.getSendAt() + "---" + notification.getContactId();
    assertTrue(AsyncCoordinator.instance().getPendingTaskCount() > 0);
    Assert.assertTrue(AsyncCoordinator.instance().hasPendingTaskWithCustomKey(customKey));

    // Now try running the task for 'three', the user with a daily email
    // Should get 1 email with 2 comments in it

    MockEmailer mockEmailer = new MockEmailer();
    Stubbing.stub(EmailSender.class, "executeSend", mockEmailer);

    AsyncTask task = AsyncTaskController.instance().forUniqueKey("customKey", customKey);
    AsyncTaskExecuteRunnable runnable = new AsyncTaskExecuteRunnable(task);
    runnable.run(true);

    // Should be an email sent with two comments in it
    assertEquals(1, mockEmailer.getEmails().size());
    assertEquals(timEmail, mockEmailer.getEmails().get(0).getAddress());
    Log.info("Notify email body: {0}", mockEmailer.getEmails().get(0).getBody());
    assertEquals(2,
            StringUtils.countMatches(mockEmailer.getEmails().get(0).getBody(), "class=\"comment-bodyHtml\""));

}

From source file:io.stallion.plugins.flatBlog.comments.CommentsEndpoints.java

@GET
@Path("/comments/assets/:path")
public String dashboardJsx(@PathParam("path") String path) throws IOException {
    if (StringUtils.countMatches(path, ".") > 1) {
        throw new UsageException("Invalid asset file path: " + path);
    }//from w  ww  .  j a va 2s .  c om
    URL url = getClass().getResource("/assets/" + path);
    if (url == null) {
        throw new io.stallion.exceptions.NotFoundException("Missing file path: " + path);
    }
    if (Settings.instance().getDevMode() && url.toString().contains("/target/classes/")) {
        String newPath = url.toString().replace("/target/classes/", "/src/main/resources/");
        url = new URL(newPath);

    }
    if (path.endsWith(".css")) {
        Context.getResponse().setContentType("text/css");
    } else {
        Context.getResponse().setContentType("text/javascript");
    }
    return org.apache.commons.io.IOUtils.toString(url);
}

From source file:cepdest.pattern.holder.EnhancedPatternsHolder.java

private String toPlainText(String prefix, EnhancedPatternNode node, String patternId) {

    StringBuilder sb = new StringBuilder();
    String newPrefix = prefix + node.toString(patternId);

    List<String> sons = node.getSonsForPatternId(patternId);
    if (sons == null || sons.isEmpty()) {
        sb.append(newPrefix);/*from  w  ww. j a v a2s  .  co  m*/
        sb.append("\n");
    } else {
        int index = StringUtils.countMatches(newPrefix, node.toString(patternId));
        if (index <= sons.size()) {
            sb.append(toPlainText(newPrefix, getNodeFromId(sons.get(index - 1)), patternId));
        } else {
            sb.append(newPrefix);
            sb.append("\n");
        }
    }
    return sb.toString();
}

From source file:functionaltests.NodeSourceCommandsFunctTest.java

private int listNodes(String nodeSourceName, int expectedNumberOfNodes) {

    System.out.println(LOG_HEADER + " List nodes");

    String output;//w  w w  .j  a  v  a2  s.c o m

    do {

        output = waitForFreeNodesAndList(nodeSourceName);

    } while (StringUtils.countMatches(output, "FREE") != expectedNumberOfNodes);

    return StringUtils.countMatches(output, nodeSourceName);
}

From source file:info.rmapproject.api.responsemgr.ResourceResponseManagerTestIT.java

/**
 * Test the RMap Resource RDF stmts.//from www .  ja v  a 2 s.c  o m
 */
@Test
public void getRMapResourceRdfStmtsWithLimit() {
    Response response = null;
    try {
        //create 1 disco
        RMapDiSCO rmapDisco = TestUtils.getRMapDiSCO(TestFile.DISCOA_XML);
        String discoURI = rmapDisco.getId().toString();
        assertNotNull(discoURI);
        rmapService.createDiSCO(rmapDisco, requestEventDetails);

        MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>();
        params.add(Constants.LIMIT_PARAM, "2");

        response = resourceResponseManager.getRMapResourceTriples(discoURI, RdfMediaType.APPLICATION_RDFXML,
                params);

        assertNotNull(response);
        String body = response.getEntity().toString();

        assertEquals(303, response.getStatus());
        assertTrue(body.contains("page number"));

        URI location = response.getLocation();
        MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUri(location).build()
                .getQueryParams();
        String untildate = parameters.getFirst(Constants.UNTIL_PARAM);

        //check page 1 just has 2 statements
        params.add(Constants.PAGE_PARAM, "1");
        params.add(Constants.UNTIL_PARAM, untildate);

        response = resourceResponseManager.getRMapResourceTriples(discoURI, RdfMediaType.APPLICATION_RDFXML,
                params);
        assertEquals(200, response.getStatus());
        body = response.getEntity().toString();
        int numMatches = StringUtils.countMatches(body, "xmlns=");
        assertEquals(2, numMatches);

    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception thrown " + e.getMessage());
    }

}

From source file:com.seleniumtests.it.core.TestSeleniumRobotTestListener.java

@Test(groups = { "it" })
public void testContextStorageParallelMethods(ITestContext testContext) throws Exception {

    executeSubTest2(ParallelMode.METHODS);

    String mainReportContent = FileUtils.readFileToString(new File(
            new File(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory()).getAbsolutePath()
                    + File.separator + "SeleniumTestReport.html"));
    mainReportContent = mainReportContent.replace("\n", "").replace("\r", "");
    Assert.assertEquals(StringUtils.countMatches(mainReportContent, "class=\"fa fa-circle circleSuccess\">"),
            StringUtils.countMatches(mainReportContent, "TestReport.html") - 1);
    Assert.assertEquals(StringUtils.countMatches(mainReportContent, "TestReport.html"), 9);

    // test1Listener4 fails as expected
    Assert.assertTrue(mainReportContent.matches(
            ".*<i class\\=\"fa fa-circle circleSkipped\"></i><a href\\='test1Listener4/TestReport\\.html'.*?>test1Listener4</a>.*"));
}

From source file:fr.noop.subtitle.vtt.VttParser.java

protected SubtitleTimeCode parseTimeCode(String timeCodeString, int subtitleOffset)
        throws SubtitleParsingException {
    try {/*from w  w w.  j a  v  a 2s.  c o m*/
        int separatorCount = StringUtils.countMatches(timeCodeString, ":");
        if (separatorCount > 1) {
            // hh:mm:ss.ms
            int offset = timeCodeString.indexOf(":");
            int hour = Integer.parseInt(timeCodeString.substring(0, offset));
            String buffer = timeCodeString.substring(offset + 1);
            offset = buffer.indexOf(":");
            int minute = Integer.parseInt(buffer.substring(0, offset));
            buffer = buffer.substring(offset + 1);
            offset = buffer.indexOf(".");
            int second = Integer.parseInt(buffer.substring(0, offset));
            buffer = buffer.substring(offset + 1);
            int millisecond = Integer.parseInt(buffer);
            return new SubtitleTimeCode(hour, minute, second, millisecond, subtitleOffset);
        } else {
            // mm:ss.ms
            int offset = timeCodeString.indexOf(":");
            int minute = Integer.parseInt(timeCodeString.substring(0, offset));
            String buffer = timeCodeString.substring(offset + 1);
            offset = buffer.indexOf(".");
            int second = Integer.parseInt(buffer.substring(0, offset));
            buffer = buffer.substring(offset + 1);
            int millisecond = Integer.parseInt(buffer);
            return new SubtitleTimeCode(0, minute, second, millisecond, subtitleOffset);
        }
    } catch (NumberFormatException e) {
        throw new SubtitleParsingException(String.format("Unable to parse time code: %s", timeCodeString));
    }
}

From source file:edu.isi.karma.view.VWorksheet.java

public void updateHeaderViewNodes(ArrayList<VHNode> oldOrderedNodes) {

    ArrayList<String> oldPaths = new ArrayList<>();
    for (VHNode node : oldOrderedNodes)
        oldPaths.addAll(node.getAllPaths());

    ArrayList<String> newPaths = new ArrayList<>();
    for (VHNode node : this.headerViewNodes)
        newPaths.addAll(node.getAllPaths());

    //1/. Get all paths in old that are not in new
    ArrayList<String> pathsToDel = new ArrayList<>();
    for (String oldPath : oldPaths) {
        if (!newPaths.contains(oldPath)) {
            pathsToDel.add(oldPath);/*  ww  w . j ava 2s  .  c o  m*/
        }
    }

    //2. Get all paths in new that are not in old
    ArrayList<String> pathsToAdd = new ArrayList<>();
    for (int i = 0; i < newPaths.size(); i++) {
        String newPath = newPaths.get(i);
        if (!oldPaths.contains(newPath)) {
            if (i != 0) {
                String after = newPaths.get(i - 1);
                int difference = StringUtils.countMatches(after, "/") - StringUtils.countMatches(newPath, "/");
                for (int k = 0; k < difference; k++) {
                    after = after.substring(0, after.lastIndexOf("/"));
                }
                pathsToAdd.add(newPath + "$$" + after);
            } else {
                pathsToAdd.add(newPath + "$$" + "null");
            }
        }
    }

    ArrayList<VHNode> allNodes = new ArrayList<>();
    allNodes.addAll(oldOrderedNodes);
    this.headerViewNodes = allNodes;

    for (String path : pathsToDel) {
        deleteHeaderViewPath(this.headerViewNodes, path);
    }

    for (String path : pathsToAdd) {
        addHeaderViewPath(path);
    }
}