Example usage for org.springframework.util StringUtils countOccurrencesOf

List of usage examples for org.springframework.util StringUtils countOccurrencesOf

Introduction

In this page you can find the example usage for org.springframework.util StringUtils countOccurrencesOf.

Prototype

public static int countOccurrencesOf(String str, String sub) 

Source Link

Document

Count the occurrences of the substring sub in string str .

Usage

From source file:com.consol.citrus.admin.service.TestCaseService.java

/**
 * Get total number of tests in project.
 * @param project//from ww  w.j  a  va  2s.co m
 * @return
 */
public long getTestCount(Project project) {
    long testCount = 0L;
    try {
        List<File> sourceFiles = FileUtils.findFiles(project.getJavaDirectory(),
                StringUtils.commaDelimitedListToSet(project.getSettings().getJavaFilePattern()));
        for (File sourceFile : sourceFiles) {
            String sourceCode = FileUtils.readToString(new FileSystemResource(sourceFile));

            testCount += StringUtils.countOccurrencesOf(sourceCode, "@CitrusTest");
            testCount += StringUtils.countOccurrencesOf(sourceCode, "@CitrusXmlTest");
        }
    } catch (IOException e) {
        log.warn("Failed to read Java source files - list of test cases for this project is incomplete", e);
    }

    return testCount;
}

From source file:org.appverse.web.framework.backend.persistence.services.integration.impl.live.JPAPersistenceService.java

private void checkMaxFilterColumnsToSortDeep(final IntegrationDataFilter filter) {
    // Get maximum deep in "columnsToSort"
    int columnsDeep = 0;
    for (String columnPath : filter.getColumnsToSort()) {
        columnsDeep = Math.max(StringUtils.countOccurrencesOf(columnPath, "."), columnsDeep);
    }/*from   w  w  w  . ja  v a  2s .  c om*/
    if (columnsDeep > 0) {
        StringBuffer e = new StringBuffer();
        e.append(PersistenceMessageBundle.MSG_DAO_INVALID_FILTER_ORDERING_COLUMNS)
                .append(getClassP().getSimpleName()).append(".").append(filter.toString()).append(".")
                .append(PersistenceMessageBundle.MSG_DAO_INVALID_FILTER_ADVIDE);
        logger.error(e.toString());
        throw new PersistenceException(e.toString());
    }
}

From source file:org.appverse.web.framework.backend.persistence.services.integration.impl.live.JPAPersistenceService.java

private void checkMaxFilterConditionsColumnsDeep(final IntegrationDataFilter filter) {
    int columnsDeep = 0;
    // Get maximum deep in "columns"
    if (filter.getColumns() != null) {
        for (String columnPath : filter.getColumns()) {
            columnsDeep = Math.max(StringUtils.countOccurrencesOf(columnPath, "."), columnsDeep);
        }/*  w  ww  .j a  v a  2s . co  m*/
    }
    // Get maximum deep in "columnsIsNull"
    if (filter.getColumnsIsNull() != null) {
        for (String columnPath : filter.getColumnsIsNull()) {
            columnsDeep = Math.max(StringUtils.countOccurrencesOf(columnPath, "."), columnsDeep);
        }
    }
    if (columnsDeep > 1) {
        StringBuffer e = new StringBuffer();
        e.append(PersistenceMessageBundle.MSG_DAO_INVALID_FILTER_CONDITIONS_COLUMNS)
                .append(getClassP().getSimpleName()).append(".").append(filter.toString()).append(".")
                .append(PersistenceMessageBundle.MSG_DAO_INVALID_FILTER_ADVIDE);
        logger.error(e.toString());
        throw new PersistenceException(e.toString());
    }
}

From source file:com.consol.citrus.mvn.plugin.CreateTestMojo.java

/**
 * Returns an array of all namespace declarations, found on wsdl-level.
 *
 * @param wsdl/*from   ww w  .  j  a  v a  2  s . c om*/
 * @return
 */
private String[] extractNamespacesOnWsdlLevel(XmlObject wsdl) {
    int cursor = wsdl.xmlText().indexOf(":") + ":definitions ".length();
    String nsWsdlOrig = wsdl.xmlText().substring(cursor, wsdl.xmlText().indexOf(">", cursor));
    int noNs = StringUtils.countOccurrencesOf(nsWsdlOrig, "xmlns:");
    String[] namespacesWsdl = new String[noNs];
    cursor = 0;
    for (int i = 0; i < noNs; i++) {
        int begin = nsWsdlOrig.indexOf("xmlns:", cursor);
        int end = nsWsdlOrig.indexOf("\"", begin + 20);
        namespacesWsdl[i] = nsWsdlOrig.substring(begin, end) + "\"";
        cursor = end;
    }
    return namespacesWsdl;
}

From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java

/**
 * Searches each level inside the bundle for entries based on the search
 * strategy chosen./*from w  w  w  .  j a v a 2s  .c  o m*/
 *
 * @param bundle      the bundle to do the lookup
 * @param fullPattern matching pattern
 * @param dir         directory inside the bundle
 * @param result      set of results (used to concatenate matching sub dirs)
 * @param searchType  the search strategy to use
 */
@SuppressWarnings("unchecked")
private void doRetrieveMatchingBundleEntries(Bundle bundle, String fullPattern, String dir,
        Set<Resource> result, int searchType) {

    Enumeration<?> candidates;

    switch (searchType) {
    case OsgiResourceUtils.PREFIX_TYPE_NOT_SPECIFIED:
    case OsgiResourceUtils.PREFIX_TYPE_BUNDLE_SPACE:
        // returns an enumeration of URLs
        candidates = bundle.findEntries(dir, null, false);
        break;
    case OsgiResourceUtils.PREFIX_TYPE_BUNDLE_JAR:
        // returns an enumeration of Strings
        candidates = bundle.getEntryPaths(dir);
        break;
    case OsgiResourceUtils.PREFIX_TYPE_CLASS_SPACE:
        // returns an enumeration of URLs
        throw new IllegalArgumentException("class space does not support pattern matching");
    default:
        throw new IllegalArgumentException("unknown searchType " + searchType);
    }

    // entries are relative to the root path - miss the leading /
    if (candidates != null) {
        boolean dirDepthNotFixed = (fullPattern.contains(FOLDER_WILDCARD));
        while (candidates.hasMoreElements()) {
            Object path = candidates.nextElement();
            String currPath;

            if (path instanceof String)
                currPath = handleString((String) path);
            else
                currPath = handleURL((URL) path);

            if (!currPath.startsWith(dir)) {
                // Returned resource path does not start with relative
                // directory:
                // assuming absolute path returned -> strip absolute path.
                int dirIndex = currPath.indexOf(dir);
                if (dirIndex != -1) {
                    currPath = currPath.substring(dirIndex);
                }
            }

            if (currPath.endsWith(FOLDER_SEPARATOR) && (dirDepthNotFixed
                    || StringUtils.countOccurrencesOf(currPath, FOLDER_SEPARATOR) < StringUtils
                            .countOccurrencesOf(fullPattern, FOLDER_SEPARATOR))) {
                // Search subdirectories recursively: we manually get the
                // folders on only one level

                doRetrieveMatchingBundleEntries(bundle, fullPattern, currPath, result, searchType);
            }
            if (getPathMatcher().match(fullPattern, currPath)) {
                if (path instanceof URL)
                    result.add(new UrlContextResource((URL) path, currPath));
                else
                    result.add(new OsgiBundleResource(bundle, currPath));

            }
        }
    }
}

From source file:org.apache.ignite.yardstick.cache.load.IgniteCacheRandomOperationBenchmark.java

/**
 * @return SQL string.// w w  w.  j a v a  2 s  . c o m
 */
private String randomizeSql(String sql) {
    int cnt = StringUtils.countOccurrencesOf(sql, "%s");

    Integer[] sub = new Integer[cnt];

    for (int i = 0; i < cnt; i++)
        sub[i] = nextRandom(args.range());

    sql = String.format(sql, sub);

    return sql;
}

From source file:com.linuxbox.enkive.imap.message.EnkiveImapMessage.java

@Override
public Long getTextualLineCount() {
    loadMessage();//w  ww .j a va2s .c  o  m
    long lineCount = 0;
    try {
        lineCount = StringUtils.countOccurrencesOf(message.getReconstitutedEmail(), "\n");
    } catch (IOException e) {
        LOGGER.error("Error retrieving message with UUID " + messageId, e);
    }
    return lineCount;
}

From source file:com.phoenixnap.oss.ramlapisync.naming.NamingHelper.java

/**
 * Attempts to infer the name of an action (intent) from a resource's relative URL and action details
 * /* w  ww .ja va2 s.c om*/
 * @param controllerizedResource The resource that is mapped to the root controller
 * @param resource The child resource that will be mapped as a method of the root controller
 * @param action The RAML action object
 * @param actionType The ActionType/HTTP Verb for this Action
 * @return The java name of the method that will represent this Action
 */
public static String getActionName(RamlResource controllerizedResource, RamlResource resource,
        RamlAction action, RamlActionType actionType) {

    String url = resource.getUri();
    //Since this will be part of a resource/controller, remove the parent portion of the URL if enough details remain
    //to infer a meaningful method name
    if (controllerizedResource != resource
            && StringUtils.countOccurrencesOf(url, "{") < StringUtils.countOccurrencesOf(url, "/") - 1) {
        url = url.replace(controllerizedResource.getUri(), "");
    }

    //sanity check
    if (StringUtils.hasText(url)) {

        //Split the url into segments by seperator
        String[] splitUrl = url.split("/");
        String name = "";
        int nonIdsParsed = 0;
        int index = splitUrl.length - 1;
        boolean singularizeNext = false;

        //Parse segments until end is reached or we travers a maximum of 2 non Path Variable segments, these 2 should both have at least 1
        //id path variable each otherwise they would have been typically part of the parent controller
        //or we have REALLY long URL nesting which isnt really a happy place.
        while (nonIdsParsed < 2 && index >= 0) {

            String segment = splitUrl[index];
            //Lets check for ID path variables
            if (segment.contains("{") && segment.contains("}")) {
                //should we add this to Method name
                //peek
                if (index > 0 && index == splitUrl.length - 1) {
                    String peek = splitUrl[index - 1].toLowerCase();
                    if (segment.toLowerCase().contains(Inflector.singularize(peek))) {
                        //this is probably the Id
                        name = name + "ById";
                    } else {
                        name = name + "By" + StringUtils.capitalize(segment.substring(1, segment.length() - 1));
                    }
                }
                //Since we probably found an ID, it means that method acts on a single resource in the collection. probably :)
                singularizeNext = true;
            } else {
                segment = cleanNameForJava(segment);
                if (singularizeNext) { //consume singularisation
                    if (!segment.endsWith("details")) {
                        name = Inflector.singularize(StringUtils.capitalize(segment)) + name;
                    } else {
                        name = StringUtils.capitalize(segment) + name;
                    }
                    singularizeNext = false;
                } else {
                    name = StringUtils.capitalize(segment) + name;
                }

                nonIdsParsed++;
                if (singularizeNext) { //consume singularisation
                    singularizeNext = false;
                }
            }
            index--;
        }

        //Add the http verb into the mix
        boolean collection = false;
        String tail = splitUrl[splitUrl.length - 1];
        if (!Inflector.singularize(tail).equals(tail) && !tail.endsWith("details")) {
            collection = true;
        }
        String prefix = convertActionTypeToIntent(actionType, collection);
        if (collection && RamlActionType.POST.equals(actionType)) {
            name = Inflector.singularize(name);
        }

        return prefix + name;
    }
    //Poop happened. return nothing
    return null;
}

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

@Test(groups = { "it" })
public void testRetryOnException() throws Exception {

    executeSubTest(1, new String[] { "com.seleniumtests.it.stubclasses.StubTestClass" }, ParallelMode.METHODS,
            new String[] { "testAndSubActions", "testInError", "testWithException" });

    String mainReportContent = FileUtils.readFileToString(new File(
            new File(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory()).getAbsolutePath()
                    + File.separator + "SeleniumTestReport.html"));
    mainReportContent = mainReportContent.replace("\n", "").replace("\r", "");
    Assert.assertTrue(//  w  ww .  j a v  a  2s .  co  m
            mainReportContent.matches(".*<a href\\='testInError/TestReport\\.html'.*?>testInError</a>.*"));
    Assert.assertTrue(mainReportContent
            .matches(".*<a href\\='testWithException/TestReport\\.html'.*?>testWithException</a>.*"));

    // check failed test is not retried (AssertionError) based on log. No more direct way found
    String detailedReportContent2 = FileUtils
            .readFileToString(Paths.get(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(),
                    "testInError", "TestReport.html").toFile());
    detailedReportContent2 = detailedReportContent2.replace("\n", "").replace("\r", "").replaceAll(">\\s+<",
            "><");
    Assert.assertTrue(detailedReportContent2.contains("Failed in 1 times"));
    Assert.assertFalse(detailedReportContent2
            .contains("[RETRYING] class com.seleniumtests.it.stubclasses.StubTestClass.testInError"));

    // check test with exception is retried based on log. No more direct way found
    String detailedReportContent3 = FileUtils
            .readFileToString(Paths.get(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(),
                    "testWithException", "TestReport.html").toFile());
    detailedReportContent3 = detailedReportContent3.replace("\n", "").replace("\r", "").replaceAll(">\\s+<",
            "><");
    Assert.assertTrue(detailedReportContent3.contains("Failed in 3 times"));
    Assert.assertTrue(detailedReportContent3
            .contains("[RETRYING] class com.seleniumtests.it.stubclasses.StubTestClass.testWithException"));

    // check that in case of retry, steps are not logged twice
    Assert.assertTrue(detailedReportContent3.contains("step 1"));
    Assert.assertTrue(detailedReportContent3.contains("<li>played 3 times")); // only the last step is retained
    Assert.assertFalse(detailedReportContent3.contains("<li>played 2 times")); // only the last step is retained
    Assert.assertEquals(StringUtils.countOccurrencesOf(detailedReportContent3, "step 1"), 1);

}

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

@Test(groups = { "it" })
public void testCucumberRetryOnException() throws Exception {

    executeSubCucumberTests("error_scenario", 1);

    String mainReportContent = FileUtils.readFileToString(new File(
            new File(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory()).getAbsolutePath()
                    + File.separator + "SeleniumTestReport.html"));
    mainReportContent = mainReportContent.replace("\n", "").replace("\r", "");
    Assert.assertTrue(mainReportContent/*from www.ja v  a  2  s .  com*/
            .matches(".*<a href\\='error_scenario/TestReport\\.html'.*?>error_scenario</a>.*"));

    // check failed test is not retried (AssertionError) based on log. No more direct way found
    String detailedReportContent = FileUtils
            .readFileToString(Paths.get(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(),
                    "error_scenario", "TestReport.html").toFile());
    detailedReportContent = detailedReportContent.replace("\n", "").replace("\r", "").replaceAll(">\\s+<",
            "><");
    Assert.assertTrue(detailedReportContent.contains("Failed in 3 times"));
    Assert.assertTrue(detailedReportContent
            .contains("[RETRYING] class com.seleniumtests.core.runner.CucumberTestPlan.feature"));

    // check that in case of retry, steps are not logged twice and step name is the cucumber step name (defined by annotation
    Assert.assertTrue(detailedReportContent.contains("write_error"));
    Assert.assertEquals(StringUtils.countOccurrencesOf(detailedReportContent, "Start method error_scenario"),
            3);
    Assert.assertEquals(StringUtils.countOccurrencesOf(detailedReportContent, "Finish method error_scenario"),
            3);

}