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:com.braffdev.server.core.module.mapping.MappingModule.java

/**
 * @param pattern//from   w  ww .j a  va  2  s .  co m
 * @param method
 * @param handler
 */
private void createMapping(PatternInfo patternInfo, HttpMethod method, RequestHandler handler) {
    String pattern = patternInfo.getPattern().pattern();

    Mapping mapping = new Mapping();
    mapping.setPatternInfo(patternInfo);
    mapping.setLevels(StringUtils.countMatches(pattern, "/"));
    mapping.getHandlerMapping().put(method, handler);
    mapping.setType(MappingType.get(pattern));

    this.mappings.add(mapping);

}

From source file:com.websystique.springmvc.youtube_api.Function.java

public int demsotu(String cau)

{
    String str = cau.replace(".", "").replace(";", "").replace("?", "");
    int sotu = StringUtils.countMatches(str.replaceAll("\\s+", " ").trim(), " ") + 1;
    return sotu;//from  w  ww. j a  va2  s . c o m
}

From source file:io.github.seiferma.jameica.hibiscus.dkb.creditcard.synchronize.csvparser.DKBCsvParser.java

private static int getMetaDataHeaderLength(String csvContent, String lineSeparator) throws IOException {
    int length = 0;
    BufferedReader br = new BufferedReader(new StringReader(csvContent));
    try {//  www .  j  a v  a2s.  co  m
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            int numberOfDelimiters = StringUtils.countMatches(line, ';');
            if (numberOfDelimiters != 0 && numberOfDelimiters != 2) {
                return length;
            }
            length += line.length() + lineSeparator.length();
        }
    } finally {
        IOUtils.closeQuietly(br);
    }
    return length;
}

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

/**
 * Checks that with a data provider, test context does not overlap between test methods and that displayed logs correspond to the method execution and not all method executions
 * @param testContext/*from  w w w .j a v a 2s. c o  m*/
 * @throws Exception
 */
@Test(groups = { "it" })
public void testContextWithDataProvider(ITestContext testContext) throws Exception {

    executeSubTest(5,
            new String[] { "com.seleniumtests.it.stubclasses.StubTestClassForDataProvider.testMethod" }, "",
            "");

    String mainReportContent = FileUtils.readFileToString(new File(
            new File(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory()).getAbsolutePath()
                    + File.separator + "SeleniumTestReport.html"));
    mainReportContent = mainReportContent.replace("\n", "").replace("\r", "");

    // check that all tests are OK and present into summary file. If test is KO (issue #115), the same context is taken for subsequent test method calls
    Assert.assertTrue(mainReportContent.matches(
            ".*<i class=\"fa fa-circle circleSuccess\"></i><a href='testMethod/TestReport.html' .*?>testMethod</a>.*"));
    Assert.assertTrue(mainReportContent.matches(
            ".*<i class=\"fa fa-circle circleSuccess\"></i><a href='testMethod-1/TestReport.html' .*?>testMethod-1</a>.*"));
    Assert.assertTrue(mainReportContent.matches(
            ".*<i class=\"fa fa-circle circleSuccess\"></i><a href='testMethod-2/TestReport.html' .*?>testMethod-2</a>.*"));

    // check each result file to see if it exists and if it only contains information about this method context (log of this method only)
    String detailedReportContent1 = FileUtils
            .readFileToString(Paths.get(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(),
                    "testMethod", "TestReport.html").toFile());
    detailedReportContent1 = detailedReportContent1.replace("\n", "").replace("\r", "").replaceAll(">\\s+<",
            "><");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "data written"), 1);
    Assert.assertTrue(detailedReportContent1.contains("data written: data1"));
    Assert.assertTrue(detailedReportContent1.contains("Test Details - testMethod with params: (data1)"));

    String detailedReportContent2 = FileUtils
            .readFileToString(Paths.get(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(),
                    "testMethod-1", "TestReport.html").toFile());
    detailedReportContent2 = detailedReportContent2.replace("\n", "").replace("\r", "").replaceAll(">\\s+<",
            "><");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "data written"), 1);
    Assert.assertTrue(detailedReportContent2.contains("data written: data2"));
    Assert.assertTrue(detailedReportContent2.contains("Test Details - testMethod-1 with params: (data2)"));

    String detailedReportContent3 = FileUtils
            .readFileToString(Paths.get(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(),
                    "testMethod-2", "TestReport.html").toFile());
    detailedReportContent3 = detailedReportContent3.replace("\n", "").replace("\r", "").replaceAll(">\\s+<",
            "><");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent3, "data written"), 1);
    Assert.assertTrue(detailedReportContent3.contains("data written: data3"));
    Assert.assertTrue(detailedReportContent3.contains("Test Details - testMethod-2 with params: (data3)"));
}

From source file:com.videaps.cube.solving.scanning.ScanCubeDelegate.java

public int countUndetected(String cubeColorsStr) {
    // The prefix of the faceColors need to be ignored. For example, R: and B: (Right and Back)
    // are also used as colors Red and Blue.
    cubeColorsStr = cubeColorsStr.replaceAll("[WYOGRB]:", "");
    int xCount = StringUtils.countMatches(cubeColorsStr, "X");
    return xCount;
}

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

/**
 * Check summary format when tests have steps
 * @throws Exception//from   ww w.ja va 2 s.co  m
 */
@Test(groups = { "it" })
public void testMultithreadTestReport() throws Exception {

    SeleniumTestsContextManager.removeThreadContext();
    executeSubTest(5, new String[] { "com.seleniumtests.it.stubclasses.StubTestClass" }, ParallelMode.TESTS,
            new String[] { "testAndSubActions", "testInError", "testWithException" });

    // check content of summary report file
    String mainReportContent = readSummaryFile();

    Assert.assertTrue(mainReportContent
            .matches(".*<a href\\='testAndSubActions/TestReport\\.html'.*?>testAndSubActions</a>.*"));
    Assert.assertTrue(
            mainReportContent.matches(".*<a href\\='testInError/TestReport\\.html'.*?>testInError</a>.*"));

    // check content for details results
    String detailedReportContent1 = readTestMethodResultFile("testAndSubActions");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "Pre test step: setCount"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "Pre test step: set "), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "step 1 -"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "step 2 -"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "Test end"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "Post test step: reset"), 1);

    // check content for details results
    String detailedReportContent2 = readTestMethodResultFile("testInError");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "Pre test step: setCount"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "Pre test step: set "), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "step 1 -"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "Test end"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent2, "Post test step: reset"), 1);

    // check content for details results
    String detailedReportContent3 = readTestMethodResultFile("testWithException");
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent3, "Pre test step: setCount"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent3, "Pre test step: set "), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent3, "step 1 -"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent3, "Test end"), 1);
    Assert.assertEquals(StringUtils.countMatches(detailedReportContent3, "Post test step: reset"), 1);
}

From source file:dhbw.clippinggorilla.external.solr.SOLR.java

/**
 * Creates search string for solr//from   w  w  w.j a  v a2s . com
 *
 * @param string
 * @param and
 * @return
 */
public static String replaceWhitespaces(String string, boolean and) {
    String word;
    String result = "";
    List<String> allMatches = new ArrayList<>();
    if (and) {
        word = " AND ";
    } else {
        word = " OR ";
    }

    if (StringUtils.countMatches(string, '"') > 0 && ((StringUtils.countMatches(string, '"') & 1) == 1)) {
        string = string.concat("\"");
    }

    Matcher m = Pattern.compile("[^,]+").matcher(string);
    while (m.find()) {
        allMatches.add(m.group());
    }

    for (String sub : allMatches) {
        sub = sub.trim();
        result = result.concat("\"" + sub + "\"" + word);
    }

    if (and) {
        result = result.substring(0, result.length() - 5);
    } else {
        result = result.substring(0, result.length() - 4);
    }

    return result;
}

From source file:com.github.cherimojava.data.mongo.io._DeEncoding.java

@Test
public void noDuplicateIdWritten() {
    ExplicitIdEntity eid = factory.readEntity(ExplicitIdEntity.class, "{\"_id\":\"explicit\"}");
    assertEquals("explicit", eid.getName());
    EntityCodec<ExplicitIdEntity> codec = new EntityCodec<>(db,
            EntityFactory.getProperties(ExplicitIdEntity.class));

    StringWriter swriter = new StringWriter();
    JsonWriter writer = new JsonWriter(swriter);
    codec.encode(writer, eid, null);/*from w  w w  .j a v  a 2  s  .  c o m*/
    assertEquals(1, StringUtils.countMatches(swriter.toString(), "explicit"));

    ExplicitIdEntity eid2 = factory.create(ExplicitIdEntity.class);
    eid2.setName("once");
    swriter = new StringWriter();
    writer = new JsonWriter(swriter);
    codec.encode(writer, eid2, null);
    assertEquals(1, StringUtils.countMatches(swriter.toString(), "once"));
}

From source file:com.videaps.cube.solving.scanning.ScanCubeDelegate.java

public Collection<String> replaceOneUndetectedBrick(String cubeColorStr, Collection<String> cubeColors) {
    Collection<String> replacedCubeColors = new ArrayList<String>();
    String[] colors = { "W", "Y", "O", "R", "B", "G" };
    String replaceColor = "X";
    for (String color : colors) {
        int colorCount = StringUtils.countMatches(cubeColorStr, color);
        if (colorCount == 8) {
            replaceColor = color;//from   ww w  .  j ava  2  s .  c o  m
        }
    }

    for (String faceColors : cubeColors) {
        String replacedFaceColors = faceColors.replace("X", replaceColor);
        replacedCubeColors.add(replacedFaceColors);
    }
    return replacedCubeColors;
}

From source file:net.gtaun.wl.race.dialog.TrackCheckpointEditDialog.java

public static WlListDialog create(Player player, EventManager eventManager, AbstractDialog parent,
        RaceServiceImpl service, TrackCheckpoint checkpoint, boolean isCreateNew) {
    PlayerStringSet stringSet = service.getLocalizedStringSet().getStringSet(player);
    Track track = checkpoint.getTrack();

    if (track.getCheckpoints().contains(checkpoint) == false)
        player.setLocation(checkpoint.getLocation());

    return WlListDialog.create(player, eventManager).parentDialog(parent)
            .caption(() -> stringSet.format("Dialog.TrackCheckpointEditDialog.Caption", track.getName(),
                    checkpoint.getNumber()))

            .item(() -> stringSet.get("Common.OK"), () -> isCreateNew,
                    (i) -> i.getCurrentDialog().showParentDialog())

            .item(() -> stringSet.get("Dialog.TrackCheckpointEditDialog.Teleport"), () -> {
                if (player.getLocation().equals(checkpoint.getLocation()))
                    return false;
                return track.getCheckpoints().contains(checkpoint);
            }, (i) -> {//w  w  w.j  a v  a 2  s  . c o m
                player.setLocation(checkpoint.getLocation());
                i.getCurrentDialog().show();
            })

            .item(() -> {
                Radius loc = checkpoint.getLocation();
                String item = stringSet.format("Dialog.TrackCheckpointEditDialog.Position", loc.getX(),
                        loc.getY(), loc.getZ(), loc.getInteriorId());
                return item;
            }, (i) -> {
                Radius oldLoc = checkpoint.getLocation();
                String caption = stringSet.get("Dialog.TrackCheckpointEditPositionDialog.Caption");
                String message = stringSet.format("Dialog.TrackCheckpointEditPositionDialog.Text",
                        oldLoc.getX(), oldLoc.getY(), oldLoc.getZ(), oldLoc.getInteriorId());

                WlInputDialog.create(player, eventManager).parentDialog(i.getCurrentDialog()).caption(caption)
                        .message(message).onClickOk((d, text) -> {
                            player.playSound(1083);

                            try (Scanner scanner = new Scanner(text)) {
                                Radius loc = new Radius(scanner.nextFloat(), scanner.nextFloat(),
                                        scanner.nextFloat(), scanner.nextInt(), oldLoc.getWorldId(),
                                        oldLoc.getRadius());
                                checkpoint.setLocation(loc);
                                d.showParentDialog();
                            } catch (NoSuchElementException e) {
                                ((WlInputDialog) d).setAppendMessage(stringSet.get(
                                        "Dialog.TrackCheckpointEditPositionDialog.IllegalFormatAppendMessage"));
                                i.getCurrentDialog().show();
                            }
                        }).build().show();
            })

            .item(ListDialogItemRadio.create()
                    .selectedIndex(() -> checkpoint.getType() == RaceCheckpointType.NORMAL ? 0 : 1)
                    .itemText(() -> stringSet.get("Dialog.TrackCheckpointEditDialog.Type"))
                    .item(stringSet.get("Track.Checkpoint.Type.Normal"), Color.RED,
                            (i) -> checkpoint.setType(RaceCheckpointType.NORMAL))
                    .item(stringSet.get("Track.Checkpoint.Type.Air"), Color.BLUE,
                            (i) -> checkpoint.setType(RaceCheckpointType.AIR))
                    .onSelect((i) -> i.getCurrentDialog().show()).build())

            .item(() -> stringSet.format("Dialog.TrackCheckpointEditDialog.Size", checkpoint.getSize()),
                    (i) -> {
                        String caption = stringSet.get("Dialog.TrackCheckpointEditSizeDialog.Caption");
                        String message = stringSet.format("Dialog.TrackCheckpointEditSizeDialog.Text",
                                checkpoint.getSize());

                        WlInputDialog.create(player, eventManager).parentDialog(i.getCurrentDialog())
                                .caption(caption).message(message).onClickOk((d, text) -> {
                                    player.playSound(1083);

                                    try (Scanner scanner = new Scanner(text)) {
                                        checkpoint.setSize(scanner.nextFloat());
                                        d.showParentDialog();
                                    } catch (NoSuchElementException e) {
                                        ((WlInputDialog) d).setAppendMessage(stringSet.get(
                                                "Dialog.TrackCheckpointEditSizeDialog.IllegalFormatAppendMessage"));
                                        i.getCurrentDialog().show();
                                    }
                                }).build().show();
                    })

            .item(() -> {
                String code = checkpoint.getScript();
                int lines = StringUtils.countMatches(code, "\n");
                return stringSet.format("Dialog.TrackCheckpointEditDialog.Script", lines, code.length());
            }, (i) -> {
                String title = stringSet.format("Dialog.TrackCheckpointEditDialog.CheckpointFormat",
                        checkpoint.getNumber() + 1);
                String code = checkpoint.getScript();
                new CodeEditorDialog(player, eventManager, i.getCurrentDialog(), service, title, code,
                        (newCode) -> {
                            checkpoint.setScript(newCode);
                            i.getCurrentDialog().showParentDialog();
                        }).show();
            })

            .item(() -> stringSet.get("Dialog.TrackCheckpointEditDialog.UpdatePosition"), () -> {
                if (player.getLocation().equals(checkpoint.getLocation()))
                    return false;
                return track.getCheckpoints().contains(checkpoint);
            }, (i) -> {
                checkpoint.setLocation(player.getLocation());
                player.sendMessage(Color.LIGHTBLUE,
                        stringSet.get("Dialog.TrackCheckpointEditDialog.UpdatePositionMessage"));
                i.getCurrentDialog().show();
            })

            .item(() -> stringSet.get("Dialog.TrackCheckpointEditDialog.Delete"),
                    () -> track.getCheckpoints().contains(checkpoint), (i) -> {
                        track.removeChechpoint(checkpoint);
                    })

            .onClickOk((d, i) -> player.playSound(1083)).build();
}