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:net.sourceforge.seqware.pipeline.plugins.CLI_ET.java

@Test
public void runSeqwareCheck() throws IOException {
    String listCommand = " check";
    String listOutput = ITUtility.runSeqwareCLI(listCommand, ReturnValue.SUCCESS, null);
    int countOccurrencesOf = StringUtils.countMatches(listOutput, "Crashed and failed check");
    Assert.assertTrue("Crashed and failed checks", countOccurrencesOf == 0);
}

From source file:net.tenorite.badges.validators.SpecialWords.java

private void validateBadge(Game game, PlayingStats playingStats, BadgeRepository.BadgeOps badgeOps,
        Consumer<BadgeEarned> onBadgeEarned) {
    String name = playingStats.getPlayer().getName();
    int count = StringUtils.countMatches(playingStats.getSpecialsSequence(), word);
    if (count != 0) {
        long nextLevel = badgeOps.getProgress(badge, name) + count;
        updateBadgeLevel(game, name, badge, nextLevel, badgeOps, onBadgeEarned);
    }//from www.j  ava  2  s  .c  o m
}

From source file:nl.mawoo.wcmscript.cli.Application.java

public static void main(String[] args) throws IOException, ScriptException {
    UUID instanceId = UUID.randomUUID();
    WCMScript wcmScript = new WCMScript(instanceId);

    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

    int indentation = 0;
    StringBuilder code = new StringBuilder();
    while (true) {
        try {//ww  w  .  ja  v a 2s.  c o m
            System.out.print("> " + StringUtils.repeat("  ", indentation));
            String line = bf.readLine();
            indentation += StringUtils.countMatches(line, '{');
            indentation -= StringUtils.countMatches(line, '}');
            code.append(line).append('\n');

            if (indentation == 0) {
                eval(wcmScript, code);
            }
        } catch (IOException e) {
            LOGGER.error("IO exception: " + e.getMessage(), e);
        }
    }
}

From source file:nl.sidn.dnslib.util.IPUtil.java

public static byte[] ipv6tobytes(String ip) {
    int parts = StringUtils.countMatches(ip, ":");
    int missing = 7 - parts;

    for (int i = 0; i < missing; i++) {
        ip = ip + ":0000";
    }//from   w  ww. j ava 2 s  . c om

    return InetAddresses.forString(ip).getAddress();
}

From source file:objenome.util.ClassUtils.java

/**
 * <p>Gets the abbreviated class name from a {@code String}.</p>
 *
 * <p>The string passed in is assumed to be a class name - it is not checked.</p>
 *
 * <p>The abbreviation algorithm will shorten the class name, usually without
 * significant loss of meaning.</p>
 * <p>The abbreviated class name will always include the complete package hierarchy.
 * If enough space is available, rightmost sub-packages will be displayed in full
 * length.</p>//from www.ja v  a  2  s  .com
 *
 * <p>The following table illustrates the algorithm:</p>
 * <table summary="abbreviation examples">
 * <tr><td>className</td><td>len</td><td>return</td></tr>
 * <tr><td>              null</td><td> 1</td><td>""</td></tr>
 * <tr><td>"java.lang.String"</td><td> 5</td><td>"j.l.String"</td></tr>
 * <tr><td>"java.lang.String"</td><td>15</td><td>"j.lang.String"</td></tr>
 * <tr><td>"java.lang.String"</td><td>30</td><td>"java.lang.String"</td></tr>
 * </table>
 * @param className  the className to get the abbreviated name for, may be {@code null}
 * @param len  the desired length of the abbreviated name
 * @return the abbreviated name or an empty string
 * @throws IllegalArgumentException if len &lt;= 0
 * @since 3.4
 */
public static String getAbbreviatedName(String className, int len) {
    if (len <= 0) {
        throw new IllegalArgumentException("len must be > 0");
    }
    if (className == null) {
        return StringUtils.EMPTY;
    }

    int availableSpace = len;
    int packageLevels = StringUtils.countMatches(className, '.');
    String[] output = new String[packageLevels + 1];
    int endIndex = className.length() - 1;
    for (int level = packageLevels; level >= 0; level--) {
        int startIndex = className.lastIndexOf('.', endIndex);
        String part = className.substring(startIndex + 1, endIndex + 1);
        availableSpace -= part.length();
        if (level > 0) {
            // all elements except top level require an additional char space
            availableSpace--;
        }
        if (level == packageLevels) {
            // ClassName is always complete
            output[level] = part;
        } else {
            output[level] = availableSpace > 0 ? part : part.substring(0, 1);
        }
        endIndex = startIndex - 1;
    }

    return StringUtils.join(output, '.');
}

From source file:org.alfresco.bm.cm.FolderData.java

/**
 * @param id                the unique ID of the folder.  The value must be unique but is dependent on the format used by the system in test
 * @param context           an arbitrary context in which the folder path is valid.  The format is determined by the target test system.
 * @param path              the folder path with the given context.  The <tt>context</tt> and <tt>path</tt> combination must be unique
 * @param folderCount       the number of subfolders in the folder
 * @param fileCount         the number of files in the folder
 * // w ww . jav a  2s .c om
 * @throws IllegalArgumentException if the values are <tt>null</tt>
 */
public FolderData(String id, String context, String path, long folderCount, long fileCount) {
    if (id == null || context == null || path == null) {
        throw new IllegalArgumentException();
    }
    if (!path.isEmpty() && (!path.startsWith("/") || path.endsWith("/"))) {
        throw new IllegalArgumentException("Path must start with '/' and not end with '/'.");
    }

    this.id = id;
    this.context = context;
    this.path = path;
    this.fileCount = fileCount;
    this.folderCount = folderCount;

    // Derived data
    this.level = StringUtils.countMatches(path, "/");
    this.name = FilenameUtils.getName(path);
    this.parentPath = FilenameUtils.getFullPathNoEndSeparator(path);
}

From source file:org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelperIntegrationTest.java

@Test(groups = { "Integration", "Broken" })
public void testStopCommandWaitsToStopWithSigTerm() {
    StopCommandSoftwareProcess entity = app.createAndManageChild(
            EntitySpec.create(StopCommandSoftwareProcess.class, StopCommandSoftwareProcessImpl.class));
    entity.start(ImmutableList.of(loc));
    VanillaSoftwareProcessSshDriver driver = (VanillaSoftwareProcessSshDriver) entity.getDriver();
    String launchContents = Joiner.on('\n').join("#!/usr/bin/env bash", "function trap_handler_command {",
            "  echo stopping...", "  exit 13", "}", "trap \"trap_handler_command\" SIGTERM", "while true; do",
            "  sleep 1", "done");
    driver.copyResource(ImmutableMap.of(), new ReaderInputStream(new StringReader(launchContents), "UTF-8"),
            "launch.sh", true);
    driver.executeLaunchCommand("nohup bash launch.sh > /dev/null &");
    ScriptHelper stopCommandScriptHelper = driver.stopCommandScriptHelper();
    stopCommandScriptHelper.execute();//from  w  w w . j a v  a2s . co  m
    assertEquals(StringUtils.countMatches(stopCommandScriptHelper.getResultStdout(), "Attempted to stop PID"),
            1, "SIGTERM should be tried one time");
    assertFalse(stopCommandScriptHelper.getResultStdout().contains("stopped with SIGKILL"),
            "SIGKILL should not be sent after SIGTERM fails.");

    SshMachineLocation machineLocation = (SshMachineLocation) Iterables.getFirst(entity.getLocations(), null);
    int checkPidFileExitCode = machineLocation.execCommands("Check for pid file",
            ImmutableList.of("ls " + driver.getRunDir() + '/' + VanillaSoftwareProcessSshDriver.PID_FILENAME));
    assertEquals(checkPidFileExitCode, 2, "pid file should be deleted.");
}

From source file:org.apache.brooklyn.entity.software.base.lifecycle.ScriptHelperIntegrationTest.java

@Test(groups = { "Integration", "Broken" })
public void testStopWithSigtermIsKilledWithSigKill() {
    StopCommandSoftwareProcess entity = app.createAndManageChild(
            EntitySpec.create(StopCommandSoftwareProcess.class, StopCommandSoftwareProcessImpl.class));
    entity.start(ImmutableList.of(loc));
    VanillaSoftwareProcessSshDriver driver = (VanillaSoftwareProcessSshDriver) entity.getDriver();
    String launchContents = Joiner.on('\n').join("#!/usr/bin/env bash", "function trap_handler_command {",
            "  while true; do", "    echo \"Do nothing.\"", "    sleep 1", "  done", "}",
            "trap \"trap_handler_command\" SIGTERM", "while true; do", "  sleep 1", "done");
    driver.copyResource(ImmutableMap.of(), new ReaderInputStream(new StringReader(launchContents), "UTF-8"),
            "launch.sh", true);
    driver.executeLaunchCommand("nohup bash launch.sh > /dev/null &");
    ByteArrayOutputStream stdOut = new ByteArrayOutputStream(15);
    SshMachineLocation machineLocation = (SshMachineLocation) Iterables.getFirst(entity.getLocations(), null);
    machineLocation.execCommands(//from  w w  w  . ja va  2s  . c om
            ImmutableMap.<String, Object>of(ExecWithLoggingHelpers.STDOUT.getName(), stdOut),
            "check process is stopped",
            ImmutableList.of("cat " + driver.getRunDir() + '/' + VanillaSoftwareProcessSshDriver.PID_FILENAME),
            MutableMap.<String, Object>of());
    int launchedProcessPid = Integer.parseInt(Strings.trimEnd(new String(stdOut.toByteArray())));
    log.info(format("Pid of launched long running process %d.", launchedProcessPid));
    ScriptHelper stopCommandScriptHelper = driver.stopCommandScriptHelper();
    stopCommandScriptHelper.execute();
    assertEquals(StringUtils.countMatches(stopCommandScriptHelper.getResultStdout(), "Attempted to stop PID"),
            16, "SIGTERM should be tried one time");
    assertEquals(StringUtils.countMatches(stopCommandScriptHelper.getResultStdout(),
            "Sent SIGKILL to " + launchedProcessPid), 1, "SIGKILL should be sent after SIGTERM fails.");

    int processCheckExitCode = machineLocation.execCommands("check whether process is still running",
            ImmutableList.of("ps -p " + launchedProcessPid + " > /dev/null"));
    assertNotEquals(processCheckExitCode, 0);
    int checkPidFileExitCode = machineLocation.execCommands("Check for pid file",
            ImmutableList.of("ls " + driver.getRunDir() + '/' + VanillaSoftwareProcessSshDriver.PID_FILENAME));
    assertEquals(checkPidFileExitCode, 2, "pid file should be deleted.");
}

From source file:org.apache.calcite.test.CalciteAssert.java

public static Function<ResultSet, Void> checkResultContains(final String expected, final int count) {
    return new Function<ResultSet, Void>() {
        public Void apply(ResultSet s) {
            try {
                final String actual = Util.toLinux(CalciteAssert.toString(s));
                assertTrue(actual + " should have " + count + " occurrence of " + expected,
                        StringUtils.countMatches(actual, expected) == count);
                return null;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }//  w  ww  .j  a  v a  2 s. com
        }
    };
}

From source file:org.apache.calcite.test.MaterializationTest.java

@Test
public void testSingleMaterializationMultiUsage() {
    String q = "select *\n" + "from (select * from \"emps\" where \"empid\" < 300)\n"
            + "join (select * from \"emps\" where \"empid\" < 200) using (\"empid\")";
    try (final TryThreadLocal.Memo ignored = Prepare.THREAD_TRIM.push(true)) {
        MaterializationService.setThreadLocal();
        CalciteAssert.that()//from   w w w .  j ava  2 s .  co m
                .withMaterializations(JdbcTest.HR_MODEL, "m0", "select * from \"emps\" where \"empid\" < 500")
                .query(q).enableMaterializations(true).explainMatches("", new Function<ResultSet, Void>() {
                    public Void apply(ResultSet s) {
                        try {
                            final String actual = Util.toLinux(CalciteAssert.toString(s));
                            final String scan = "EnumerableTableScan(table=[[hr, m0]])";
                            assertTrue(actual + " should have had two occurrences of " + scan,
                                    StringUtils.countMatches(actual, scan) == 2);
                            return null;
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).sameResultWithMaterializationsDisabled();
    }
}