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:io.stallion.plugins.flatBlog.comments.tests.TestCommentNotifications.java

@Test
public void testThreadSubscribe() throws Exception {
    CommentsEndpoints resource = new CommentsEndpoints();
    Long now = mils() - 2000;//  w  ww .j  a v  a 2 s  .co m

    // Submit initial comment from Peter, no notifications yet.
    String peterEmail = "test.peter" + DateUtils.mils() + "@stallion.io";
    resource.submitComment(
            newComment(peterEmail, "Peter", "I eagerly await further thoughts!").setThreadSubscribe(true));
    Contact peter = ContactsController.instance().forUniqueKeyOrNotFound("email", peterEmail);
    Assert.assertEquals(0, NotificationController.instance().filter("createdAt", now, ">")
            .filter("contactId", john.getId()).count());
    Assert.assertEquals(0, NotificationController.instance().filter("createdAt", now, ">")
            .filter("contactId", peter.getId()).count());

    // Add two comments
    resource.submitComment(newComment("test.sam@stallion.io", "Sam", "This is an insightful thought."));
    resource.submitComment(newComment("test.shannon@stallion.io", "Shannon", "This is an incredible thing."));

    // Assert tasks and notifications created
    assertTrue(AsyncCoordinator.instance().getPendingTaskCount() > 0);
    List<Notification> notifications = NotificationController.instance().filter("createdAt", now, ">")
            .filter("contactId", peter.getId()).all();
    Assert.assertEquals(2, notifications.size());
    Assert.assertEquals(notifications.get(0).getSendAt(), notifications.get(1).getSendAt());

    Notification notification = notifications.get(0);
    String customKey = "notification---" + notification.getSendAt() + "---" + notification.getContactId();
    Assert.assertTrue(AsyncCoordinator.instance().hasPendingTaskWithCustomKey(customKey));

    // Now try running the task for Peter, 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(peterEmail, mockEmailer.getEmails().get(0).getAddress());
    Log.info("Notify email body: {0}", mockEmailer.getEmails().get(0).getBody());
    String body = mockEmailer.getEmails().get(0).getBody();
    assertTrue(body.contains("/my-subscriptions/"));
    assertTrue("/my-subscriptions/ contact token is empty", !body.contains("/my-subscriptions/\">"));

    assertEquals(2,
            StringUtils.countMatches(mockEmailer.getEmails().get(0).getBody(), "class=\"comment-bodyHtml\""));

}

From source file:com.google.dart.tools.ui.internal.text.dartdoc.DartDocAutoIndentStrategy.java

/**
 * Guesses if the command operates within a newly created DartDoc comment or not. If in doubt, it
 * will assume that the DartDoc is new./*w  ww.  j a v  a2s.c o  m*/
 * 
 * @param document the document
 * @param commandOffset the command offset
 * @return <code>true</code> if the comment should be closed, <code>false</code> if not
 */
private boolean isNewComment(IDocument document, int commandOffset) {

    try {
        int lineIndex = document.getLineOfOffset(commandOffset) + 1;
        if (lineIndex >= document.getNumberOfLines()) {
            return true;
        }

        IRegion line = document.getLineInformation(lineIndex);
        ITypedRegion partition = TextUtilities.getPartition(document, partitioning, commandOffset, false);
        int partitionEnd = partition.getOffset() + partition.getLength();
        if (line.getOffset() >= partitionEnd) {
            return false;
        }

        if (document.getLength() == partitionEnd) {
            return true; // partition goes to end of document - probably a new comment 
        }

        String comment = document.get(partition.getOffset(), partition.getLength());
        int openCount = StringUtils.countMatches(comment, "/*");
        int closeCount = StringUtils.countMatches(comment, "*/");
        return openCount > closeCount;
        //      if (comment.indexOf("/*", 2) != -1) {
        //        return true; // enclosed another comment -> probably a new comment 
        //      }
        //
        //      return false;

    } catch (BadLocationException e) {
        return false;
    }
}

From source file:at.ac.tuwien.inso.subcat.utility.commentparser.Parser.java

License:asdf

private void parseParagraphs(List<ContentNode<T>> ast, String commentFragment) {
    Matcher pm = pPara.matcher(commentFragment);

    int lastEnd = 0;
    while (pm.find()) {
        if (lastEnd != pm.start()) {
            int count = StringUtils.countMatches(pm.group(0), "\n") - 1;
            parseParagraph(ast, commentFragment.substring(lastEnd, pm.start()), count);
        }//from   w  ww.  j  av  a2 s. c  o m

        lastEnd = pm.end();
    }

    if (lastEnd != commentFragment.length()) {
        String frag = commentFragment.substring(lastEnd, commentFragment.length());
        if (frag.trim().length() > 0) {
            parseParagraph(ast, frag, 0);
        }
    }
}

From source file:com.idiro.utils.db.mysql.MySqlUtils.java

public static boolean importTable(JdbcConnection conn, String tableName, Map<String, String> features,
        File fileIn, File tablePath, char delimiter, boolean header) {
    boolean ok = true;
    try {//from w w w  . j  a  v a  2s .  c o  m
        DbChecker dbCh = new DbChecker(conn);
        if (!dbCh.isTableExist(tableName)) {
            logger.debug("The table which has to be imported has not been created");
            logger.debug("Creation of the table");
            Integer ASCIIVal = (int) delimiter;
            String[] options = { ASCIIVal.toString(), tablePath.getCanonicalPath() };
            conn.executeQuery(new MySqlBasicStatement().createExternalTable(tableName, features, options));
        } else {
            //Check if it is the same table 
            if (!dbCh.areFeaturesTheSame(tableName, features.keySet())) {
                logger.warn("Mismatch between the table to import and the table in the database");
                return false;
            }

            logger.warn("Have to check if the table is external or not, I do not know how to do that");

        }
    } catch (SQLException e) {
        logger.debug("Fail to watch the datastore");
        logger.debug(e.getMessage());
        return false;
    } catch (IOException e) {
        logger.warn("Fail to get the output path from a File object");
        logger.warn(e.getMessage());
        return false;
    }

    //Check if the input file has the right number of field
    FileChecker fChIn = new FileChecker(fileIn);
    FileChecker fChOut = new FileChecker(tablePath);
    String strLine = "";
    try {

        if (fChIn.isDirectory() || !fChIn.canRead()) {
            logger.warn("The file " + fChIn.getFilename() + "is a directory or can not be read");
            return false;
        }
        BufferedReader br = new BufferedReader(new FileReader(fileIn));
        //Read first line
        strLine = br.readLine();
        br.close();
    } catch (IOException e1) {
        logger.debug("Fail to open the file" + fChIn.getFilename());
        return false;
    }

    if (StringUtils.countMatches(strLine, String.valueOf(delimiter)) != features.size() - 1) {
        logger.warn("File given does not match with the delimiter '" + delimiter
                + "' given and the number of fields '" + features.size() + "'");
        return false;
    }

    BufferedWriter bw = null;
    BufferedReader br = null;

    try {
        bw = new BufferedWriter(new FileWriter(tablePath));
        logger.debug("read the file" + fileIn.getAbsolutePath());
        br = new BufferedReader(new FileReader(fileIn));
        String delimiterStr = "" + delimiter;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            bw.write("\"" + strLine.replace(delimiterStr, "\",\"") + "\"\n");
        }
        br.close();

        bw.close();
    } catch (FileNotFoundException e1) {
        logger.error(e1.getCause() + " " + e1.getMessage());
        logger.error("Fail to read " + fileIn.getAbsolutePath());
        ok = false;
    } catch (IOException e1) {
        logger.error("Error writting, reading on the filesystem from the directory" + fChIn.getFilename()
                + " to the file " + fChOut.getFilename());
        ok = false;
    }

    return ok;
}

From source file:akka.systemActors.ActorSupervisor.java

public void initialiseGrid() {
    /**//from   w ww .j  a v a 2 s.c  om
     * In der Topologie sind alle Kinder gespeichert, hier wird nur das erste Layer initialisiert
     */
    for (String actorPath : actorTopology.getActorTopology().keySet()) {
        // Children of the first layer
        if (3 == StringUtils.countMatches(actorPath, "/")) {
            // If the actor has not spawned
            if (!actorTopology.getActorTopology().get(actorPath).hasAlreadyBeenSpawned) {
                spawnGridActor(actorPath.replace("/user/ActorSupervisor/", ""), this.actorTopology);
                actorTopology.getActorTopology().get(actorPath).hasAlreadyBeenSpawned = true;
            }
        }
    }
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskLogAllByTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/LOOP-T2-1/result/log/all");
    String responseContent = getContent(response);

    System.out.println(responseContent);

    assertEquals(2, StringUtils.countMatches(responseContent, "Task 1 : Test STDERR"));
    assertEquals(2, StringUtils.countMatches(responseContent, "Task 1 : Test STDOUT"));
    assertEquals(2, StringUtils.countMatches(responseContent, "Terminate task number 1"));
}

From source file:de.quadrillenschule.azocamsyncd.gui.ExploreWifiSDPanel.java

private void createSubNodes(DefaultMutableTreeNode parent, LinkedList<AZoFTPFile> afs) {
    String parentNodeName = parent.toString();
    for (AZoFTPFile af : afs) {
        String nodeName = af.dir + af.ftpFile.getName();
        if (af.ftpFile.isDirectory()) {
            if (!parentNodeName.equals(nodeName)) {

                if (nodeName.contains(parentNodeName)) {
                    if (StringUtils.countMatches(nodeName, "/") - 1 == StringUtils.countMatches(parentNodeName,
                            "/")) {
                        DefaultMutableTreeNode tn = new DefaultMutableTreeNode(nodeName);
                        parent.add(tn);//w w  w  .j  a v a  2 s .  c  o m
                        createSubNodes(tn, afs);
                    }
                }
                ;
            }
        }
        //isFile
        if (af.ftpFile.isFile()) {
            if (nodeName.contains(parentNodeName)) {
                if (StringUtils.countMatches(nodeName, "/") == 1
                        + StringUtils.countMatches(parentNodeName, "/")) {
                    DefaultMutableTreeNode tn = new DefaultMutableTreeNode(nodeName);

                    parent.add(tn);

                }
            }
            ;
        }

    }
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskLogErrByTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/LOOP-T2-1/result/log/err");
    String responseContent = getContent(response);

    System.out.println(responseContent);

    assertEquals(2, StringUtils.countMatches(responseContent, "Task 1 : Test STDERR"));
}

From source file:ext.usercenter.UserAuthService.java

/**
 * ?<br>/*from ww w.  j  a va 2  s  . co  m*/
 * ?????<br>
 * ??sessiontoken??
 * 
 * @param response
 * @param request
 * 
 * @param session
 * @return validateTokenResult
 */
public static void refreshLoginInfo(Request request, Response response, Session session) {
    if (null == session) {
        throw new IllegalArgumentException("illegal method input param. params: session=" + session);
    }

    // ?session??
    if (null != sessionDomain && !sessionDomain.equals("www.helome.com")
            && StringUtils.countMatches(request.getHeader("Cookie"), "PLAY_SESSION") > 1) {
        response.setCookie("PLAY_SESSION", "", -86400, "/", null, false, true);
    }

    String token = session.get(LOGIN_TOKEN_SESSION_KEY);

    if (StringUtils.isNotBlank(token)) {
        ValidateTokenResult validateTokenResult = validateToken(token);
        if (validateTokenResult != ValidateTokenResult.VALID) {
            removeTokenInSession(session);
            UserInfoCookieService.discardCookie();
        }
        // session
        if (ValidateTokenResult.KICKED == validateTokenResult) {
            session.put(KICKED_FLAG_KEY, "1");
        }

        if (ValidateTokenResult.VALID == validateTokenResult) {
            UserInfoCookieService.createOrUpdateCookie(false);
        }
    }

}

From source file:com.nridge.connector.common.con_com.transform.TParentChild.java

private boolean isMatch(String[] aRelPCArray, String aType, int aLevel) {
    int levelCount;
    String[] pcLevelArray;/*from  w  w w.j  ava2s .c  om*/

    for (String pcString : aRelPCArray) {
        levelCount = StringUtils.countMatches(pcString, "/");
        if ((aLevel == 0) && (levelCount == 0)) {
            if (StringUtils.equals(aType, pcString))
                return true;
        } else {
            pcLevelArray = pcString.split("/");
            if (pcLevelArray.length > aLevel) {
                if (StringUtils.equals(aType, pcLevelArray[aLevel]))
                    return true;
            }
        }
    }

    return false;
}