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:org.apache.streams.plugins.cassandra.test.StreamsCassandraResourceGeneratorCLITest.java

@Test
public void testStreamsCassandraResourceGeneratorCLI() throws Exception {

    String sourceDirectory = "target/test-classes/activitystreams-schemas";
    String targetDirectory = "target/generated-resources/test-cli";

    StreamsCassandraResourceGenerator.main(new String[] { sourceDirectory, targetDirectory });

    File testOutput = new File(targetDirectory);

    Assert.assertNotNull(testOutput);/*from   w w w .  ja v a  2 s.com*/
    Assert.assertTrue(testOutput.exists());
    Assert.assertTrue(testOutput.isDirectory());

    Collection<File> outputCollection = FileUtils.listFiles(testOutput,
            StreamsCassandraResourceGeneratorTest.cqlFilter, true);
    Assert.assertEquals(outputCollection.size(), 1);

    Path path = Paths.get(testOutput.getAbsolutePath()).resolve("types.cql");

    Assert.assertTrue(path.toFile().exists());

    String typesCqlBytes = new String(java.nio.file.Files.readAllBytes(path));

    Assert.assertEquals(StringUtils.countMatches(typesCqlBytes, "CREATE TYPE"), 133);
}

From source file:org.apache.streams.plugins.cassandra.test.StreamsCassandraResourceGeneratorMojoIT.java

@Test
public void testStreamsCassandraResourceGeneratorMojo() throws Exception {

    File testDir = ResourceExtractor.simpleExtractResources(getClass(), "/streams-plugin-cassandra");

    Verifier verifier;/*from w  w w.j  a  va 2  s. c o  m*/

    verifier = new Verifier(testDir.getAbsolutePath());

    List<String> cliOptions = new ArrayList<>();
    cliOptions.add("-N");
    verifier.executeGoals(Stream.of("clean", "dependency:unpack-dependencies", "generate-resources")
            .collect(Collectors.toList()));

    verifier.verifyErrorFreeLog();

    verifier.resetStreams();

    Path testOutputPath = Paths.get(testDir.getAbsolutePath()).resolve("target/generated-resources/test-mojo");

    File testOutput = testOutputPath.toFile();

    Assert.assertNotNull(testOutput);
    Assert.assertTrue(testOutput.exists());
    Assert.assertTrue(testOutput.isDirectory());

    Collection<File> outputCollection = FileUtils.listFiles(testOutput,
            StreamsCassandraResourceGeneratorTest.cqlFilter, true);
    Assert.assertEquals(outputCollection.size(), 1);

    Path path = testOutputPath.resolve("types.cql");

    Assert.assertTrue(path.toFile().exists());

    String typesCqlBytes = new String(java.nio.file.Files.readAllBytes(path));

    Assert.assertEquals(StringUtils.countMatches(typesCqlBytes, "CREATE TYPE"), 133);

}

From source file:org.apache.streams.plugins.cassandra.test.StreamsCassandraResourceGeneratorTest.java

/**
 * Test that cassandra resources are generated.
 *
 * @throws Exception Exception//from  www. j  a  v  a  2  s  . c  o  m
 */
@Test
public void testStreamsCassandraResourceGenerator() throws Exception {

    StreamsCassandraGenerationConfig config = new StreamsCassandraGenerationConfig();

    String sourceDirectory = "target/test-classes/activitystreams-schemas";

    config.setSourceDirectory(sourceDirectory);

    config.setTargetDirectory("target/generated-resources/cassandra");

    config.setExclusions(Stream.of("attachments").collect(Collectors.toSet()));

    config.setMaxDepth(2);

    StreamsCassandraResourceGenerator streamsCassandraResourceGenerator = new StreamsCassandraResourceGenerator(
            config);
    streamsCassandraResourceGenerator.run();

    File testOutput = config.getTargetDirectory();

    Assert.assertNotNull(testOutput);
    Assert.assertTrue(testOutput.exists());
    Assert.assertTrue(testOutput.isDirectory());

    Collection<File> outputCollection = FileUtils.listFiles(testOutput, cqlFilter, true);
    Assert.assertEquals(outputCollection.size(), 1);

    Path path = Paths.get(testOutput.getAbsolutePath()).resolve("types.cql");

    Assert.assertTrue(path.toFile().exists());

    String typesCqlBytes = new String(java.nio.file.Files.readAllBytes(path));

    Assert.assertEquals(StringUtils.countMatches(typesCqlBytes, "CREATE TYPE"), 133);

}

From source file:org.asqatasun.processing.ProcessRemarkServiceImpl.java

/**
* 
* @param elementHtml//from   ww w . j  av  a2s . c  o  m
* @return 
*/
private int getElementCurrentlyOpenCount(String elementHtml) {
    int openTagCounter = StringUtils.countMatches(elementHtml, ESCAPED_OPEN_TAG)
            - StringUtils.countMatches(elementHtml, CLOSE_TAG_OCCUR);
    int closureTagCounter = StringUtils.countMatches(elementHtml, AUTO_CLOSE_TAG_OCCUR)
            + StringUtils.countMatches(elementHtml, CLOSE_TAG_OCCUR);
    return (openTagCounter - closureTagCounter);
}

From source file:org.astrojournal.logging.JTextPaneAppender.java

@Override
public void append(final LogEvent event) {
    final String message = new String(this.getLayout().toByteArray(event));
    try {//from   w  w  w. ja v a2s .c  o  m
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    if (jTextPane != null) {
                        try {
                            Document doc = jTextPane.getDocument();
                            if (event.getLevel().equals(Level.DEBUG)) {
                                doc.insertString(doc.getLength(), message, styleSmall);
                            } else if (event.getLevel().equals(Level.INFO)) {
                                if (message.startsWith(
                                        AJMetaInfo.NAME.getInfo() + " " + AJMetaInfo.VERSION.getInfo())) {
                                    doc.insertString(doc.getLength(), message, styleSmallItalic);
                                } else if (message.indexOf("Testing pdflatex") != -1) {
                                    String[] lines = message.split("\n");
                                    doc.insertString(doc.getLength(), lines[0], styleBold);
                                    for (int i = 1; i < lines.length; i++) {
                                        doc.insertString(doc.getLength(), lines[i] + "\n", styleSmallItalic);
                                    }
                                    doc.insertString(doc.getLength(), "\n\n", styleRegular);
                                } else if (StringUtils.countMatches(message, "\n") > 1) {
                                    doc.insertString(doc.getLength(), message, styleSmallItalic);
                                } else if (!message.startsWith("\t")) {
                                    doc.insertString(doc.getLength(), message, styleBold);
                                } else {
                                    doc.insertString(doc.getLength(), message, styleRegular);
                                }
                            } else if (event.getLevel().equals(Level.WARN)) {
                                doc.insertString(doc.getLength(), message, styleBlue);
                            } else {
                                doc.insertString(doc.getLength(), message, styleRed);
                            }
                        } catch (BadLocationException e) {
                            LOGGER.error(e, e);
                        }
                    }
                } catch (final Throwable t) {
                    LOGGER.error("Unable to append log to text pane: " + t.getMessage()
                            + ". Please see help menu for reporting this issue.", t);
                }
            }
        });
    } catch (final IllegalStateException e) {
        LOGGER.error("Unable to append log to text pane: " + e.getMessage()
                + ". Please see help menu for reporting this issue.", e);
    }
}

From source file:org.auraframework.util.javascript.directive.impl.IncludeDirectiveTest.java

/**
 * Test duplicate include directives// www . ja  v  a2s .c o  m
 * TODO: W-2537655
 * Disable the test, since we don't handle the cyclic includes now. The test can be used when fixing the bug.
 */
public void _testCommonInclude() throws Exception {
    getResourceFile("/testdata/javascript/includeDirective/testCommonInclude.js");
    getResourceFile("/testdata/javascript/includeDirective/testCommonInclude_inner1.js");
    getResourceFile("/testdata/javascript/includeDirective/testCommonInclude_inner2.js");
    getResourceFile("/testdata/javascript/includeDirective/testCommonInclude_commonstuff.js");
    DirectiveBasedJavascriptGroup jg = new DirectiveBasedJavascriptGroup("testDummy",
            getResourceFile("/testdata/"), "javascript/includeDirective/testCommonInclude.js",
            ImmutableList.<DirectiveType<?>>of(DirectiveTypes.includeType),
            EnumSet.of(JavascriptGeneratorMode.TESTING));
    DirectiveParser dp = new DirectiveParser(jg, jg.getStartFile());

    dp.parseFile();
    String generateContent = dp.generate(JavascriptGeneratorMode.TESTING);

    // FIXME: if we want to error out when duplicate includes, change the assertion.
    // System.out.println(generateContent);
    int count = StringUtils.countMatches(generateContent, "file testCommonInclude_commonstuff.js");
    assertEquals(1, count);
}

From source file:org.blockartistry.mod.Restructured.util.ItemStackHelper.java

public static ItemStack getItemStack(final String name, final int quantity) {

    ItemStack result = null;//from  ww w .  j av  a 2  s. c  o m

    // Parse out the possible subtype from the end of the string
    String workingName = name;
    int subType = -1;

    if (StringUtils.countMatches(name, ":") == 2) {
        workingName = StringUtils.substringBeforeLast(name, ":");
        final String num = StringUtils.substringAfterLast(name, ":");

        if (num != null && !num.isEmpty()) {

            if ("*".compareTo(num) == 0)
                subType = OreDictionary.WILDCARD_VALUE;
            else {
                try {
                    subType = Integer.parseInt(num);
                } catch (Exception e) {
                    // It appears malformed - assume the incoming name
                    // is
                    // the real name and continue.
                    ;
                }
            }
        }
    }

    // Check the OreDictionary first for any alias matches. Otherwise
    // go to the game registry to find a match.
    final List<ItemStack> ores = OreDictionary.getOres(workingName);
    if (!ores.isEmpty()) {
        result = ores.get(0).copy();
        result.stackSize = quantity;
    } else {
        final Item i = GameData.getItemRegistry().getObject(new ResourceLocation(workingName));
        if (i != null) {
            result = new ItemStack(i, quantity);
        }
    }

    // If we did have a hit on a base item, set the subtype
    // as needed.
    if (result != null && subType != -1) {
        result.setItemDamage(subType);
    }

    return result;
}

From source file:org.blockartistry.mod.ThermalRecycling.util.ItemStackHelper.java

public static ItemStack getItemStack(final String name, final int quantity) {

    if (name == null || name.isEmpty())
        return null;

    // Check our preferred list first. If we have a hit, use it.
    ItemStack result = preferred.get(name);

    if (result != null) {

        result = result.copy();//from  w  w  w .j  a  v  a 2s . co m
        result.stackSize = quantity;

    } else {

        // Parse out the possible subtype from the end of the string
        String workingName = name;
        int subType = -1;

        if (StringUtils.countMatches(name, ":") == 2) {
            workingName = StringUtils.substringBeforeLast(name, ":");
            final String num = StringUtils.substringAfterLast(name, ":");

            if (num != null && !num.isEmpty()) {

                if ("*".compareTo(num) == 0)
                    subType = OreDictionary.WILDCARD_VALUE;
                else {
                    try {
                        subType = Integer.parseInt(num);
                    } catch (Exception e) {
                        // It appears malformed - assume the incoming name
                        // is
                        // the real name and continue.
                        ;
                    }
                }
            }
        }

        // Check the OreDictionary first for any alias matches. Otherwise
        // go to the game registry to find a match.
        final ArrayList<ItemStack> ores = OreDictionary.getOres(workingName);
        if (!ores.isEmpty()) {
            result = ores.get(0).copy();
            result.stackSize = quantity;
        } else {
            final Item i = GameData.getItemRegistry().getObject(workingName);
            if (i != null) {
                result = new ItemStack(i, quantity);
            }
        }

        // If we did have a hit on a base item, set the sub-type
        // as needed.
        if (result != null && subType != -1) {
            if (subType == OreDictionary.WILDCARD_VALUE && !result.getHasSubtypes()) {
                ModLog.warn("[%s] GENERIC requested but Item does not support sub-types", name);
            } else {
                result.setItemDamage(subType);
            }
        }
    }

    return result;
}

From source file:org.carewebframework.fhir.validator.FhirValidate.java

private static boolean isResource(UriDt id) {
    return StringUtils.countMatches(id.getValue(), "/") % 2 == 1;
}

From source file:org.chombo.util.BasicUtils.java

/**
 * @param record//from  w  w w . j a v a2s. c om
 * @param fieldDelim
 * @param numFields
 * @param failOnInvalid
 * @return
 */
public static String[] splitFields(String record, String fieldDelim, int numFields, boolean failOnInvalid) {
    String[] items = record.split(fieldDelim);
    if (items.length != numFields) {
        if (items.length < numFields) {
            //check if trailing blank fields
            int delimCount = StringUtils.countMatches(record, fieldDelim);
            if (delimCount == numFields - 1) {
                //trailing blank fields
                String[] extItems = new String[numFields];
                for (int i = 0; i < numFields; ++i) {
                    if (i < items.length) {
                        extItems[i] = items[i];
                    } else {
                        //fill trailing fields with blanks
                        extItems[i] = "";
                    }
                }
                items = extItems;
            } else {
                //got too few fields
                items = null;
            }
        } else {
            //got too many fields
            items = null;
        }

        if (null == items && failOnInvalid) {
            throw new IllegalArgumentException(
                    "invalid field count expected " + numFields + " found " + items.length);
        }
    }
    return items;
}