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

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

Introduction

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

Prototype

public static int countMatches(String str, String sub) 

Source Link

Document

Counts how many times the substring appears in the larger String.

Usage

From source file:org.jasig.ssp.dao.EarlyAlertDao.java

/**
 * Returns string where clause of the HQL query based on parameters inputted
 *  NOTE: Includes the word where, so if already specified, replace with and!
 *    REQUIRES EarlyAlert with alias of ea and Campus with alias c elsewhere in HQL Query!
 * @param termCode//from  w w w  .  j a v a  2s . com
 * @param createdDateFrom
 * @param createdDateTo
 * @param campus
 * @param status
 * @return
 */
private String createEarlyAlertReportHQLWhereClause(String termCode, Date createdDateFrom, Date createdDateTo,
        Campus campus, ObjectStatus status) {
    final StringBuilder whereClause = new StringBuilder("where ");
    String whereClauseToReturn = "";

    if (termCode != null) {
        whereClause.append("ea.courseTermCode = :courseTermCode and ");
    }

    if (createdDateFrom != null) {
        whereClause.append("ea.createdDate >= :createdDateFrom and ");
    }

    if (createdDateTo != null) {
        whereClause.append("ea.createdDate <= :createdDateTo and ");
    }

    if (campus != null) {
        whereClause.append("c.id = :campusId and ");
    }

    if (status != null) {
        whereClause.append("objectStatus = :objectStatus ");
    }

    if (StringUtils.countMatches(whereClause.toString(), "and") > 0) {
        final int endingAnd = whereClause.indexOf("and", whereClause.length() - 5);

        if (endingAnd < 0) {
            whereClauseToReturn = whereClause.toString();
        } else {
            whereClauseToReturn = whereClause.toString().substring(0, endingAnd - 1);
        }
    }
    return whereClauseToReturn;
}

From source file:org.jboss.as.test.integration.management.cli.ForLoopTestCase.java

@Test
public void testTryFor() throws Exception {
    try {//from w  w w.  ja  va 2  s. co  m
        addProperty("prop1", "prop1_a");
        addProperty("prop2", "prop1_a");
        addProperty("prop3", "prop1_a");
        addProperty("prop4", "prop1_a");
        addProperty("prop5", "prop1_a");

        cli.sendLine("try");
        cli.sendLine("for propName in :read-children-names(child-type=system-property");
        cli.sendLine("/system-property=$propName:remove");
        cli.sendLine("/system-property=$propName:remove");
        cli.sendLine("done");
        cli.sendLine("catch");
        cli.sendLine("echo FAILURE");
        cli.sendLine("end-try");

        String line = cli.readOutput();
        assertTrue(line, line.contains("success") && line.contains("FAILURE"));

        cli.sendLine("try");
        cli.sendLine("for propName in :read-children-names(child-type=system-property");
        cli.sendLine("/system-property=$propName:remove");
        cli.sendLine("done");
        cli.sendLine("catch");
        cli.sendLine("echo FAILURE");
        cli.sendLine("end-try");

        line = cli.readOutput();
        assertEquals(line, 4, StringUtils.countMatches(line, "success"));

    } finally {
        removeProperties();
    }
}

From source file:org.jboss.pressgang.ccms.contentspec.utils.CSTransformer.java

private static int setLineNumbers(final Node node, int current) {
    if (node instanceof ContentSpec) {
        for (final Node childNode : ((ContentSpec) node).getNodes()) {
            current = setLineNumbers(childNode, current);
        }//w ww.  j  a v  a 2 s . c  o m

        final Level baseLevel = ((ContentSpec) node).getBaseLevel();
        if (!baseLevel.getTags(false).isEmpty() || baseLevel.getConditionStatement() != null) {
            current++;
        }

        for (final Node childNode : ((ContentSpec) node).getChildNodes()) {
            current = setLineNumbers(childNode, current);
        }

        return current;
    } else {
        node.setLineNumber(current);
        current++;

        if (node instanceof Level) {
            for (final Node childNode : ((Level) node).getChildNodes()) {
                current = setLineNumbers(childNode, current);
            }
        } else if (node instanceof FileList) {
            final List<File> files = ((FileList) node).getValue();
            current += files == null || files.isEmpty() ? 0 : (files.size() - 1);
        } else if (node instanceof KeyValueNode) {
            if (((KeyValueNode) node).getKey().equals(CommonConstants.CS_PUBLICAN_CFG_TITLE)
                    || ((KeyValueNode) node).getKey().endsWith("-" + CommonConstants.CS_PUBLICAN_CFG_TITLE)) {
                final String publicanCfg = (String) ((KeyValueNode) node).getValue();
                current += StringUtils.countMatches(publicanCfg, "\n");
            } else if (((KeyValueNode) node).getKey().equals(CommonConstants.CS_ENTITIES_TITLE)) {
                final String entities = (String) ((KeyValueNode) node).getValue();
                current += StringUtils.countMatches(entities, "\n");
            }
        } else if (node instanceof SpecTopic && !((SpecTopic) node).getRelationships().isEmpty()) {
            int numPrereqs = ((SpecTopic) node).getPrerequisiteRelationships().size();
            int numReferTo = ((SpecTopic) node).getRelatedRelationships().size();
            int numLinkList = ((SpecTopic) node).getLinkListRelationships().size();

            if (numPrereqs > 0) {
                current += numPrereqs + 1;
            }
            if (numReferTo > 0) {
                current += numReferTo + 1;
            }
            if (numLinkList > 0) {
                current += numLinkList + 1;
            }
        }

        return current;
    }
}

From source file:org.jboss.tools.ws.ui.bot.test.websocket.StubMethodsHelper.java

static int countImports(TextEditor editor) {
    return StringUtils.countMatches(editor.getText(), "import ");
}

From source file:org.jboss.windup.reporting.ReportUtil.java

public static String calculateRelativePathToRoot(File reportDirectory, File htmlOutputPath) {
    Validate.notNull(reportDirectory, "Report directory is null, but a required field.");
    Validate.notNull(htmlOutputPath, "HTML output directory is null, but a required field.");

    String archiveOutput = FilenameUtils.normalize(reportDirectory.getAbsolutePath());
    String htmlOutput = FilenameUtils.normalize(htmlOutputPath.getAbsolutePath());

    if (LOG.isDebugEnabled()) {
        LOG.debug("archiveOutput: " + archiveOutput);
        LOG.debug("htmlOutput: " + htmlOutput);
    }/* w w  w  .ja  va2s  .  c  om*/

    String relative = StringUtils.removeStart(htmlOutput, archiveOutput);
    relative = StringUtils.replace(relative, "\\", "/");

    int dirCount = (StringUtils.countMatches(relative, "/") - 1);
    String relPath = "";
    for (int i = 0; i < dirCount; i++) {
        relPath += "../";
    }
    return relPath;
}

From source file:org.jetbrains.jet.codegen.SuperGenTest.java

public void testKt2887() {
    loadFile("super/kt2887.kt");
    String text = generateToText();
    // There should be exactly one bridge in this example
    assertEquals(1, StringUtils.countMatches(text, "bridge"));
}

From source file:org.jfrog.build.extractor.clientConfiguration.util.PublishedItemsHelper.java

/**
 * Checks whether to continue searching recursively for files.
 *
 * @param absoluteRoot//from  w  w w  . j  a  v a 2  s  . c  om
 * @param dir
 * @param pattern
 * @param recursive
 * @return boolean
 */
private static boolean continueDepthSearch(File absoluteRoot, File dir, Pattern pattern, boolean recursive) {
    if (recursive) {
        return true;
    }

    int relativePathDepth = StringUtils.countMatches(getRelativePath(absoluteRoot, dir).replace("\\", "/"),
            "/");
    int patternPathDepth = StringUtils.countMatches(pattern.toString(), "/");
    return relativePathDepth < patternPathDepth;
}

From source file:org.jumpmind.db.sql.SqlScriptReader.java

protected boolean inQuotedArea(String s) {
    return StringUtils.countMatches(s, "'") % 2 != 0 || StringUtils.countMatches(s, "\"") % 2 != 0
            || StringUtils.countMatches(s, "`") % 2 != 0;
}

From source file:org.jumpmind.symmetric.DbExportImportTest.java

@Test
public void exportTestDatabaseSQL() throws Exception {
    ISymmetricEngine engine = getSymmetricEngine();
    Table[] tables = engine.getSymmetricDialect().readSymmetricSchemaFromXml().getTables();

    DbExport export = new DbExport(engine.getDatabasePlatform());
    export.setFormat(Format.SQL);
    export.setNoCreateInfo(false);/*from   w  ww.j a  v a2  s.c  o  m*/
    export.setNoData(true);
    export.setSchema(getSymmetricEngine().getSymmetricDialect().getPlatform().getDefaultSchema());
    export.setCatalog(getSymmetricEngine().getSymmetricDialect().getPlatform().getDefaultCatalog());
    export.setCompatible(Compatible.H2);
    String output = export.exportTables(tables).toLowerCase();

    Assert.assertEquals(output, 43, StringUtils.countMatches(output, "create table \"sym_"));
    final int EXPECTED_VARCHAR_MAX = engine.getDatabasePlatform().getName()
            .equals(DatabaseNamesConstants.SQLITE) ? 269 : 43;
    final String EXPECTED_STRING = "varchar(" + Integer.MAX_VALUE + ")";
    Assert.assertEquals(
            "Expected " + EXPECTED_VARCHAR_MAX + " " + EXPECTED_STRING + " in the following output: " + output,
            EXPECTED_VARCHAR_MAX, StringUtils.countMatches(output, EXPECTED_STRING));
}

From source file:org.keycloak.testsuite.client.OIDCPairwiseClientRegistrationTest.java

@Test
public void loginUserToPairwiseClient() throws Exception {
    // Create public client
    OIDCClientRepresentation publicClient = create();

    // Login to public client
    oauth.clientId(publicClient.getClientId());
    OAuthClient.AuthorizationEndpointResponse loginResponse = oauth.doLogin("test-user@localhost", "password");
    OAuthClient.AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(loginResponse.getCode(),
            publicClient.getClientSecret());
    AccessToken accessToken = oauth.verifyToken(accessTokenResponse.getAccessToken());
    Assert.assertEquals("test-user", accessToken.getPreferredUsername());
    Assert.assertEquals("test-user@localhost", accessToken.getEmail());
    String tokenUserId = accessToken.getSubject();

    // Assert public client has same subject like userId
    UserRepresentation user = realmsResouce().realm("test").users().search("test-user", 0, 1).get(0);
    Assert.assertEquals(user.getId(), tokenUserId);

    // Create pairwise client
    OIDCClientRepresentation clientRep = createRep();
    clientRep.setSubjectType("pairwise");
    OIDCClientRepresentation pairwiseClient = reg.oidc().create(clientRep);
    Assert.assertEquals("pairwise", pairwiseClient.getSubjectType());

    // Login to pairwise client
    oauth.clientId(pairwiseClient.getClientId());
    oauth.openLoginForm();/* www. j a  v  a  2s  .co  m*/
    loginResponse = new OAuthClient.AuthorizationEndpointResponse(oauth);
    accessTokenResponse = oauth.doAccessTokenRequest(loginResponse.getCode(), pairwiseClient.getClientSecret());

    // Assert token payloads don't contain more than one "sub"
    String accessTokenPayload = getPayload(accessTokenResponse.getAccessToken());
    Assert.assertEquals(1, StringUtils.countMatches(accessTokenPayload, "\"sub\""));
    String idTokenPayload = getPayload(accessTokenResponse.getIdToken());
    Assert.assertEquals(1, StringUtils.countMatches(idTokenPayload, "\"sub\""));
    String refreshTokenPayload = getPayload(accessTokenResponse.getRefreshToken());
    Assert.assertEquals(1, StringUtils.countMatches(refreshTokenPayload, "\"sub\""));

    accessToken = oauth.verifyToken(accessTokenResponse.getAccessToken());
    Assert.assertEquals("test-user", accessToken.getPreferredUsername());
    Assert.assertEquals("test-user@localhost", accessToken.getEmail());

    // Assert pairwise client has different subject than userId
    String pairwiseUserId = accessToken.getSubject();
    Assert.assertNotEquals(pairwiseUserId, user.getId());

    // Send request to userInfo endpoint
    Client jaxrsClient = javax.ws.rs.client.ClientBuilder.newClient();
    try {
        // Check that userInfo contains pairwise subjectId as well
        Response userInfoResponse = UserInfoClientUtil.executeUserInfoRequest_getMethod(jaxrsClient,
                accessTokenResponse.getAccessToken());
        UserInfo userInfo = UserInfoClientUtil.testSuccessfulUserInfoResponse(userInfoResponse, "test-user",
                "test-user@localhost");
        String userInfoSubId = userInfo.getSubject();
        Assert.assertEquals(pairwiseUserId, userInfoSubId);
    } finally {
        jaxrsClient.close();
    }
}