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:eu.europa.fisheries.uvms.rules.service.mapper.fact.xpath.util.XPathRepositoryTest.java

private String testValueForDoubles(String value) {
    String test = StringUtils.countMatches(value, "FLUXFAReportMessage") > 1 ? "NO" : "OK";
    if ("NO".equals(test)) {
        failedMap.put(test, value);/*  w  w  w  .  j  a  v  a 2  s  .  c o m*/
    }
    return test;
}

From source file:asmlib.Type.java

public static UtilList<Type> getArgumentTypes(String methodDescriptor) {
    String input = methodDescriptor;
    UtilList<Type> outList = new UtilArrayList<Type>();
    char c;/* w  ww  .ja v  a2s. c  om*/
    int array = 0;
    Type t;

    // Exemplo descrio com "constraints" de generics
    // <T:Ljava/lang/Object;>([TT;)[TT;
    if ((input.charAt(0) != '(') && (input.charAt(0) == '<')) {
        input = input.substring(input.indexOf('('));
    }

    while (input.length() > 0) {
        c = input.charAt(0);
        input = input.substring(1);
        if (c == '[') {
            array++;
        } else if ((c == 'L') || (c == 'T')) {
            int pos = input.indexOf(';') + 1;
            String s = input.substring(0, pos);
            // Handling generics
            int genCount = StringUtils.countMatches(s, "<");
            if (genCount > 0) {
                while (genCount > 0) {
                    pos = input.indexOf('>', pos);
                    genCount--;
                }
                pos = input.indexOf(';', pos) + 1;
                s = input.substring(0, pos);
            }
            input = input.substring(pos);

            t = Type.fromBytecode(c + s);
            if (array > 0) {
                t = t.toArray(array);
                array = 0;
            }

            outList.add(t);
        } else if (c == '(') {
            // do nothing
        } else if (c == 'V') {
            throw new AssertionError("Invalid type in methodDescriptor");
        } else if (c == ')') {
            return outList;
        } else {
            t = Type.fromBytecode(Character.valueOf(c).toString());
            if (!t.isPrimitive())
                throw new AssertionError("Invalid type in methodDescriptor");

            if (array > 0) {
                t = t.toArray(array);
                array = 0;
            }

            outList.add(t);
        }
    }

    throw new Error("Malformed methodDescriptor");
}

From source file:gov.nih.nci.firebird.nes.NesId.java

private boolean isValidNesId(String nesId) {
    return StringUtils.countMatches(nesId, ":") == 1;
}

From source file:MiGA.motifStats.java

public void merge(motifStats m) {

    count += m.getCount();/*from  ww w  .  j a v a  2  s . co m*/
    repeats += m.getNumOfRepeats();
    mbp_len += m.getMbp_len();
    if (max_len < m.getMax_len()) {
        max_len = m.getMax_len();
    }

    avg_len = (double) mbp_len / count;
    avg_repeats = (double) repeats / count;

    lens.addAll(m.getLenList());

    Globals.C -= StringUtils.countMatches(m.motif, "C") * m.getNumOfRepeats();
    Globals.T -= StringUtils.countMatches(m.motif, "T") * m.getNumOfRepeats();
    Globals.G -= StringUtils.countMatches(m.motif, "G") * m.getNumOfRepeats();
    Globals.A -= StringUtils.countMatches(m.motif, "A") * m.getNumOfRepeats();

    Globals.C += StringUtils.countMatches(motif, "C") * m.getNumOfRepeats();
    Globals.T += StringUtils.countMatches(motif, "T") * m.getNumOfRepeats();
    Globals.G += StringUtils.countMatches(motif, "G") * m.getNumOfRepeats();
    Globals.A += StringUtils.countMatches(motif, "A") * m.getNumOfRepeats();

    refresh();
    //mergeNrefresh(m);

    /*String str =  cell(motif,6)+"  "+cell(count,6)+"  "+cell(repeats,7)+"  "+cell(mbp_len,10)
    +"  "+cell(avg_len,10)+"  "+cell(max_len,10)+"  "+cell(avg_repeats,11)
    +"  "+cell(perA,6)+"  "+cell(perT,6)+"  "+cell(perC,6)+"  "+cell(perG,6)+"  ";
    System.out.println(str);*/
}

From source file:com.rockhoppertech.music.DurationParser.java

private static double getDottedValue(String token) {
    String s = token.substring(0, token.indexOf('.'));
    double val = durKeyMap.get(s);
    int dots = StringUtils.countMatches(token, ".");
    val = Duration.getDotted(val, dots);
    return val;
}

From source file:functionaltests.job.log.TestPreciousLogs.java

private void testPreciousLogs(boolean createJavaTask, boolean forkEnv, boolean generateError) throws Exception {
    TaskFlowJob job = new TaskFlowJob();
    job.setName(this.getClass().getSimpleName());

    Map<String, List<String>> expectedOutput = new LinkedHashMap<>();

    for (int i = 0; i < 3; i++) {
        String forkOutput = "forkOutput-" + i;
        String preOutput = "preOutput-" + i;
        String postOutput = "postOutput-" + i;

        List<String> expectedTaskOutput = new ArrayList<>();
        expectedTaskOutput.add(TASK_OUTPUT);
        expectedTaskOutput.add(preOutput);
        if (!generateError) {
            expectedTaskOutput.add(postOutput);
        }//  w  ww .  j a  v  a 2s  .  c  o m

        Task task;
        if (createJavaTask) {
            JavaTask javaTask = new JavaTask();
            if (generateError) {
                javaTask.setExecutableClassName(TestJavaTaskWithError.class.getName());
            } else {
                javaTask.setExecutableClassName(TestJavaTask.class.getName());
            }

            if (forkEnv) {
                ForkEnvironment env = new ForkEnvironment();
                env.setEnvScript(createScript(forkOutput));
                javaTask.setForkEnvironment(env);
                expectedTaskOutput.add(forkOutput);
            }

            task = javaTask;
        } else {
            NativeTask nativeTask = new NativeTask();

            File script = new File(
                    getClass().getResource("/functionaltests/executables/test_echo_task.sh").getFile());
            if (!script.exists()) {
                Assert.fail("Can't find script " + script.getAbsolutePath());
            }
            nativeTask.setCommandLine(script.getAbsolutePath());
            task = nativeTask;
        }

        if (generateError) {
            task.setMaxNumberOfExecution(NB_EXECUTIONS);
        } else {
            task.setMaxNumberOfExecution(1);
            task.setOnTaskError(OnTaskError.CANCEL_JOB);
        }
        task.setPreciousLogs(true);
        task.setName("Task-" + i);
        task.setPreScript(createScript(preOutput));
        task.setPostScript(createScript(postOutput));

        expectedOutput.put(task.getName(), expectedTaskOutput);

        job.addTask(task);
    }

    Scheduler scheduler = schedulerHelper.getSchedulerInterface();

    String userURI = scheduler.getUserSpaceURIs().get(0);
    File userFile = new File(new URI(userURI));

    // Clean all log files in user space
    for (File logFile : FileUtils.listFiles(userFile, new String[] { "log" }, true)) {
        FileUtils.deleteQuietly(logFile);
    }

    JobId jobId = schedulerHelper.testJobSubmission(job, true, false);

    JobResult jobResult = scheduler.getJobResult(jobId);
    Map<String, TaskResult> results = jobResult.getAllResults();
    List<File> logFiles = new ArrayList<>();
    for (String taskName : expectedOutput.keySet()) {

        File taskLog = new File(userFile.toString() + "/" + jobId.value(),
                String.format("TaskLogs-%s-%s.log", jobId.value(), results.get(taskName).getTaskId().value()));
        logFiles.add(taskLog);
        if (!taskLog.exists()) {
            Assert.fail("Task log file " + taskLog.getAbsolutePath() + " doesn't exist");
        }
        String output = new String(FileToBytesConverter.convertFileToByteArray(taskLog));
        System.out.println("Log file for " + taskName + ":");
        System.out.println(output);

        for (String expectedLine : expectedOutput.get(taskName)) {
            Assert.assertTrue("Output doesn't contain line " + expectedLine, output.contains(expectedLine));
            int expectedOccurrences = (generateError ? NB_EXECUTIONS : 1);
            Assert.assertEquals(
                    "Output doesn't contain " + expectedOccurrences + " occurrences of line " + expectedLine,
                    expectedOccurrences, StringUtils.countMatches(output, expectedLine));
        }
    }

    // Test log removal
    schedulerHelper.removeJob(jobId);

    waitUntilAllLogsWereRemoved(jobId, logFiles);
}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * Updates the directory path for remote svn repos.
 *
 * @param location//ww w .  j  av a2s. co  m
 *            the adress of the repo
 * @param oldPath
 *            the current path
 * @return an updated path
 */
private static Path updateDirectoryPath(String location, Path oldPath) {
    Path targetDirectory = Paths.get(oldPath.toAbsolutePath().toString());
    // check whether the svn repo is given via a url or is given via a path
    if (!location.startsWith("file://")) {

        // We need to get the name of the checked out folder / repo.
        int occurences = StringUtils.countMatches(location, "/");
        int index = StringUtils.ordinalIndexOf(location, "/", occurences);
        String temp = location.substring(index + 1);

        // stitch the last part of the hyperlink to the targetDirectory to
        // receive the structure
        targetDirectory = Paths.get(targetDirectory.toString(), temp);
    } else {
        targetDirectory = targetDirectory.resolve(Paths.get(location).getFileName());
    }
    return targetDirectory;
}

From source file:com.github.heartsemma.enderauth.Database.java

/**
 * @param sql (SQL Statement to be executed)
 * @param variables (Variables within the SQL statement that will be securely injected into the sql statement. May be empty.)
 * @return A ResultSet containing the result of the MySQL query entered. Returns null if the MySQL is not a select query.
 * /*from ww  w  .  ja  v a 2  s.  c  o m*/
 * <br><br> This command runs the entered MySQL query 'sql', and substitutes the question marks with the variables in the array.
 * It then returns an arraylist that represents the results of that MySQL query.
 */
private ResultSet transact(String sql, ArrayList<Object> variables) throws SQLException {

    if (!databaseInitialized) {
        validate();
    }

    logger.debug("transact() sql statement execution method called.");
    logger.debug("Checking for null parameters...");
    Preconditions.checkNotNull(sql);

    ResultSet returnedResultSet = null;

    if (variables == null || variables.size() == 0) {
        logger.debug("Executing command " + sql + ".");

        try (Statement statement = connection.createStatement()) {
            statement.execute(sql);
            returnedResultSet = statement.getResultSet();
            statement.close();
        }

    } else {
        logger.debug("Checking if amount of variables equals");
        Preconditions.checkArgument(variables.size() == StringUtils.countMatches(sql, "?"));

        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            for (int i = 1; i <= variables.size(); i++) {
                preparedStatement.setObject(i, variables.get(i));
            }
            logger.debug("Executing command " + preparedStatement.toString() + ".");
            preparedStatement.execute();
            returnedResultSet = preparedStatement.getResultSet();
            preparedStatement.close();
        }
    }

    connection.commit();

    return returnedResultSet;

}

From source file:graph.module.OntologyEdgeModule.java

/**
 * Gets all edges but the one given by the key.
 * /*from w w  w.  j a va 2  s  .  co  m*/
 * @param node
 *            The edges must include this node.
 * @param butEdgeKey
 *            The key that is NOT added to the results.
 * @return A collection of edges that are indexed by node, but none from the
 *         butEdgeKey (though they may be added if included under other
 *         keys).
 */
public Collection<Edge> getAllButEdges(Node node, Object butEdgeKey) {
    MultiMap<Object, Edge> indexedEdges = relatedEdges_.get(node);
    if (indexedEdges == null) {
        return new ConcurrentLinkedQueue<>();
    }

    Collection<Edge> edges = new HashSet<>();
    for (Object key : indexedEdges.keySet()) {
        if (!key.equals(butEdgeKey)) {
            // Need to check same function level as butEdge
            if (StringUtils.countMatches((String) key, FUNC_SPLIT) == StringUtils
                    .countMatches((String) butEdgeKey, FUNC_SPLIT))
                edges.addAll(indexedEdges.get(key));
        }
    }
    return edges;
}

From source file:com.seleniumtests.it.reporter.TestSeleniumTestsReporter2.java

/**
 * Check issue #143 where all \@AfterMethod calls are displayed in all test if its first parameter is not a method reference 
 * @throws Exception/*from w w  w .  j a v  a2  s.c  o  m*/
 */
@Test(groups = { "it" })
public void testTestReportContainsOnlyItsAfterMethodSteps() throws Exception {
    executeSubTest(new String[] { "com.seleniumtests.it.stubclasses.StubTestClassForIssue143" });

    String detailedReportContent1 = readTestMethodResultFile("testOk1");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "Post test step: reset2"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "Post test step: reset "), 2); // displayed twice because no Method parameter present

    String detailedReportContent2 = readTestMethodResultFile("testOk2");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "Post test step: reset2"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "Post test step: reset "), 2); // displayed twice because no Method parameter present

    String logs = readSeleniumRobotLogFile();
    Assert.assertTrue(logs.contains("When using @AfterMethod in tests")); // check error message is shown
    Assert.assertTrue(
            logs.contains("public void com.seleniumtests.it.stubclasses.StubTestClassForIssue143.reset()")); // check method name is displayed
}