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:kenh.expl.impl.ExpLParser.java

/**
 * Get the value in brace.//from  ww w  .j  av  a 2  s.co m
 * $      - it will be a variable in environment.
 * #      - will be a function
 * other  - use sub parser
 * 
 * @param variable  the string in brace.
 * @return  Return string or non-string object. Return empty string instead of null.
 * @throws UnsupportedExpressionException
 */
private Object getVariableValue(String variable) throws UnsupportedExpressionException {
    if (variable == null) {
        UnsupportedExpressionException e = new UnsupportedExpressionException("Variable is null.");
        throw e;
    }

    logger.trace("Var: " + variable);

    if (variable.startsWith("$")) {
        // $ - it will be a variable in environment.

        if (variable.indexOf('{') != -1) {
            Object obj = this.parseExpress(variable);
            if (obj instanceof String) {
                variable = (String) obj;
            } else {
                UnsupportedExpressionException ex = new UnsupportedExpressionException(
                        "Unable to get variable");
                ex.push(variable);
                throw ex;
            }
        }

        String name = variable.substring(1);
        int index = name.indexOf('.');
        if (index == -1) {
            return this.getEnvironment().getVariable(name);

        } else {
            // use BeanUtils
            String str = name.substring(index + 1);
            name = name.substring(0, index);
            Object obj = null;
            if ((obj = this.getEnvironment().getVariable(name)) != null) {
                try {
                    return BeanUtils.getProperty(obj, str);
                } catch (Exception e) {
                    return "";
                }
            } else {
                return "";
            }
        }

    } else if (variable.startsWith("#")) {

        // # - will be a function

        int left = StringUtils.countMatches(variable, "(");
        int right = StringUtils.countMatches(variable, ")");

        if (left != right) {
            UnsupportedExpressionException ex = new UnsupportedExpressionException(
                    "'(' and ')' does not match.");
            ex.push(variable);
            throw ex;
        }

        String funcName = StringUtils.substringBefore(variable, "(");
        String funcAfter = StringUtils.substringAfterLast(variable, ")");

        if (StringUtils.isNotBlank(funcAfter)) {
            UnsupportedExpressionException e = new UnsupportedExpressionException("Function parse error.");
            e.push(variable);
            throw e;
        }

        if (funcNamePattern.matcher(funcName).matches()) {
            Object result = executeFunction(variable);
            logger.debug(variable + " -> " + ((result == null) ? "<null>" : result.toString()));
            if (result == null)
                return "";
            return result;
        } else {
            UnsupportedExpressionException e = new UnsupportedExpressionException("Function name parse error.");
            e.push(variable);
            throw e;
        }

    } else {

        if (variable.indexOf('{') != -1) {
            Object obj = this.parseExpress(variable);
            if (obj instanceof String) {
                variable = (String) obj;
            } else {
                UnsupportedExpressionException ex = new UnsupportedExpressionException(
                        "Unable to get variable");
                ex.push(variable);
                throw ex;
            }
        }

        // use sub parser
        try {
            return subParser.parse(variable);
        } catch (UnsupportedExpressionException e) {
            e.push(variable);
            throw e;
        } catch (Exception e) {
            UnsupportedExpressionException ex = new UnsupportedExpressionException(e);
            ex.push(variable);
            throw ex;
        }

    }
}

From source file:eu.europa.fisheries.uvms.rules.service.mapper.fact.xpath.util.XPathRepositoryTest.java

@Test
@SneakyThrows/*from   ww  w  .  j  a  v a  2 s  .c  o m*/
public void testFirstElementIsAlwaysFluxFaMessage() {

    assertNotNull(factList);
    assertTrue(CollectionUtils.isNotEmpty(factList));
    assertTrue(MapUtils.isNotEmpty(repo.getXpathsMap()));

    for (AbstractFact fact : factList) {
        Map<String, String> xpathMap = repo.getMapForSequence(fact.getSequence());
        assertNotNull(xpathMap);
        for (Map.Entry<String, String> entrySet : xpathMap.entrySet()) {
            String value = entrySet.getValue();
            int matches = StringUtils.countMatches(value, "FLUXFAReportMessage");
            if (matches == 2) { // Control for dubble appending!
                System.out.print("\nFact Class : " + fact.getClass().getName());
                System.out.print("\nValue xpath : " + value);
                fail("Found 'FLUXFAReportMessage' twice in the same XPATH!");
            }
            System.out.print("\nTesting value : " + value);
            int valMaxLength = value.length() >= 50 ? 50 : value.length();
            String val = value.substring(0, valMaxLength);
            if (!val.contains("FLUXFAReportMessage")) {
                System.out.print(
                        "Testing value fails : " + value + "\n Fact Class : " + fact.getClass().getName());
            }
            assertTrue(val.contains("FLUXFAReportMessage"));
        }
    }
}

From source file:com.quinsoft.zeidon.utils.PortableFileReader.java

public void readEntities() {
    boolean closeReader = false;
    if (reader == null) {
        reader = new BufferedBinaryStreamReader(inputStream);
        closeReader = true;/* w w w . j a  v  a  2s.c  o  m*/
    }

    lineNumber = 0;
    try {
        ArrayList<PortableFileAttributeHandler> attributeHandlerStack = new ArrayList<PortableFileAttributeHandler>();

        int currentLevel = 0;
        String currentEntityName = null;

        // If we are reading multiple OIs in a single stream we expect to find 'ZEND'
        // to indicate one OI has ended and the next one begins.  Set endOfCurrentOi
        // to true so we can exit activating the current OI.
        boolean endOfCurrentOi = false;

        while (!endOfCurrentOi && (line = reader.readLine()) != null) {
            lineNumber++;

            if (StringUtils.isBlank(line))
                continue;

            String values[] = splitLine(line, ' ');
            attributeName = values[0];
            attributeValue = values[1];

            switch (attributeName.charAt(0)) {
            case 'e':
                attributeName = attributeName.substring(1);
                values = splitLine(attributeValue, ',');
                int level = Integer.parseInt(values[0]);

                if (currentLevel > 0)
                    entityHandler.endEntityAttributes(this, currentEntityName, currentLevel);

                if (values[1] != EMPTY_STRING)
                    entityFlags = Long.parseLong(values[1]);

                currentEntityName = attributeName;

                while (currentLevel >= level) {
                    attributeHandler = attributeHandlerStack.get(currentLevel);
                    entityHandler.endEntity(this, attributeHandler, currentLevel);
                    currentLevel--;
                }

                attributeHandler = entityHandler.createEntity(this, level, entityFlags);

                if (level >= attributeHandlerStack.size())
                    attributeHandlerStack.add(attributeHandler);
                else
                    attributeHandlerStack.set(level, attributeHandler);

                currentLevel = level;
                break;

            case 'a':
                if (incremental || attribFlags) {
                    values = splitLine(attributeName, ',');
                    if (values[1] != EMPTY_STRING) {
                        attributeName = values[0];
                        attributeFlags = Long.parseLong(values[1]);
                    }
                } else
                    attributeFlags = 0;

                attributeName = attributeName.substring(1);
                if (attributeHandler != null) {
                    try {
                        if (attributeValue.length() > 0 && attributeValue.charAt(0) == STRING_STORED_AS_BLOB) {
                            attributeValue = attributeValue.substring(1); // Skip past control char.
                            int length = Integer.parseInt(attributeValue);
                            attributeValueBytes = new byte[length];
                            try {
                                int read = reader.read(attributeValueBytes, length);
                                assert read == length;
                                attributeValue = new String(attributeValueBytes);
                            } catch (IOException e) {
                                throw new ZeidonException("Error reading binary data from portable file");
                            }

                            lineNumber += StringUtils.countMatches(attributeValue, "\n") + 1;
                        }
                        attributeHandler.setAttribute(this);
                    } catch (Throwable e) {
                        throw ZeidonException.prependMessage(e, "Attribute Name '%s'", attributeName);
                    }
                }

                break;

            case 'i':
                int target = Integer.parseInt(attributeName.substring(1));
                int source = Integer.parseInt(attributeValue);

                entityHandler.link(this, target, source);
                break;

            case 'Z':
                if (!"ZEND".equals(line))
                    throw new ZeidonException("Expecting 'ZEND' but got %s instead", line);

                // Set flag to break out of reader loop.
                endOfCurrentOi = true;
                break;

            case 'z':
                boolean erDate;
                attributeHandlerStack.add(null);

                if (lineNumber > 2)
                    throw new ZeidonException("Unexpected beginning of new OI in stream on line %d",
                            lineNumber);

                // Read the flags from the header.  Sample header:
                // z1100-Zeidon    MEMPLOY  mEmploy  07/12/09   20:38:04 1.0a2
                erDate = line.charAt(1) == '1';
                incremental = line.charAt(2) == '1';
                compressed = line.charAt(3) == '1';
                optimisticOIs = line.charAt(4) == '1';
                attribFlags = line.charAt(5) == '1';
                if (compressed)
                    throw new ZeidonException("Reading compressed streams not supported yet.");

                String lodDefName = StringUtils.split(line.substring(24), " ", 3)[0];
                entityHandler.startFile(this, lodDefName);

                if (erDate && isIncremental()) {
                    // File contains the ER date so read it.  We don't support compressed
                    // OIs yet so we don't do anything with it.
                    reader.readLine();
                }

                break;

            case ';':
                // Comment line, so just ignore.
                break;

            case 'm':
                //TODO: Add support for meta flags.
                break;

            default:
                throw new ZeidonException("Line %d doesn't start with e, a, i, or z\n==> %s", lineNumber, line);
            }
        } // while not EOF...

        if (currentLevel > 0)
            entityHandler.endEntityAttributes(this, currentEntityName, currentLevel);

        while (currentLevel > 0) {
            attributeHandler = attributeHandlerStack.get(currentLevel);
            entityHandler.endEntity(this, attributeHandler, currentLevel);
            currentLevel--;
        }

        entityHandler.endFile();
    } catch (Throwable e) {
        // Add line number to the message.
        throw ZeidonException.prependMessage(e, "line:%d", lineNumber);
    } finally {
        if (closeReader) {
            IOUtils.closeQuietly(reader);
            reader = null;
        }
    }
}

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

@Test(groups = { "it" })
public void testContextStorageParallelTests(ITestContext testContext) throws Exception {

    executeSubTest2(ParallelMode.TESTS);

    String mainReportContent = FileUtils.readFileToString(new File(
            new File(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory()).getAbsolutePath()
                    + File.separator + "SeleniumTestReport.html"));
    mainReportContent = mainReportContent.replace("\n", "").replace("\r", "");
    Assert.assertEquals(StringUtils.countMatches(mainReportContent, "class=\"fa fa-circle circleSuccess\">"),
            StringUtils.countMatches(mainReportContent, "TestReport.html") - 1);
    Assert.assertEquals(StringUtils.countMatches(mainReportContent, "TestReport.html"), 9);

    // test1Listener4 fails as expected
    Assert.assertTrue(mainReportContent.matches(
            ".*<i class\\=\"fa fa-circle circleSkipped\"></i><a href\\='test1Listener4/TestReport\\.html'.*?>test1Listener4</a>.*"));
}

From source file:net.dv8tion.jda.core.requests.Route.java

private Route(HttpMethod method, String route, String... majorParameters) {
    this.method = method;
    this.route = route;
    this.paramCount = StringUtils.countMatches(route, '{'); //All parameters start with {

    if (paramCount != StringUtils.countMatches(route, '}'))
        throw new IllegalArgumentException(
                "An argument does not have both {}'s for route: " + method + "  " + route);

    //Create a String.format compilable route for parameter compiling.
    compilableRoute = route.replaceAll("\\{.*?\\}", "%s");

    //If this route has major parameters that are unique markers for the ratelimit route, then we need to
    // create a ratelimit compilable route. This goes through and replaces the parameters specified by majorParameters
    // and records the parameter index so that when we compile it later we can select the proper parameters
    // from the ones provided to make sure we inject in the proper indexes.
    if (majorParameters.length != 0) {
        int paramIndex = 0;
        String replaceRoute = route;
        Pattern keyP = Pattern.compile("\\{(.*?)\\}");
        Matcher keyM = keyP.matcher(route);
        //Search the route for all parameters
        while (keyM.find()) {
            String param = keyM.group(1);
            //Attempt to match the found parameter with any of our majorParameters
            for (String majorParam : majorParameters) {
                //If the parameter is a major parameter, replace it with a string token and record its
                // parameter index for later ratelimitRoute compiling.
                if (param.equals(majorParam)) {
                    replaceRoute = replaceRoute.replace(keyM.group(0), "%s");
                    majorParamIndexes.add(paramIndex);
                }//from w w w . ja va2  s . com
            }
            paramIndex++;
        }
        ratelimitRoute = replaceRoute;
    } else
        ratelimitRoute = route;
}

From source file:com.adobe.cq.wcm.core.components.internal.models.v1.NavigationImpl.java

private int getLevel(Page page) {
    return StringUtils.countMatches(page.getPath(), "/") - 1;
}

From source file:com.petersoft.advancedswing.enhancedtextarea.EnhancedTextArea.java

private void initGUI() {
    try {//from  w w w  .j a  v a2s . c o  m
        BorderLayout thisLayout = new BorderLayout();
        this.setLayout(thisLayout);
        this.setPreferredSize(new java.awt.Dimension(725, 290));
        {
            jToolBar = new JToolBar();
            this.add(jToolBar, BorderLayout.NORTH);
            {
                jSaveButton = new JButton();
                jToolBar.add(jSaveButton);
                jSaveButton.setText("Save");
                jSaveButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/disk.png")));
                jSaveButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jSaveButtonActionPerformed(evt);
                    }
                });
            }
            {
                jLineWrapButton = new JToggleButton();
                jToolBar.add(jLineWrapButton);
                jLineWrapButton.setText("Wrap");
                jLineWrapButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/linewrap.png")));
                jLineWrapButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jLineWrapButtonActionPerformed(evt);
                    }
                });
            }
            {
                jFontBiggerButton = new JButton();
                jToolBar.add(jFontBiggerButton);
                jFontBiggerButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/font_add.png")));
                jFontBiggerButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jFontBiggerButtonActionPerformed(evt);
                    }
                });
            }
            {
                jFontSmallerButton = new JButton();
                jToolBar.add(jFontSmallerButton);
                jFontSmallerButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/font_delete.png")));
                jFontSmallerButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jFontSmallerButtonActionPerformed(evt);
                    }
                });
            }
            {
                jLabel1 = new JLabel();
                jToolBar.add(jLabel1);
                jLabel1.setText(" ");
            }
            {
                jSearchTextField = new JSearchTextField();
                jToolBar.add(jSearchTextField);
                jSearchTextField.setMaximumSize(new java.awt.Dimension(100, 22));
                jSearchTextField.setPreferredSize(new java.awt.Dimension(100, 22));
                jSearchTextField.setSize(new java.awt.Dimension(100, 22));
                jSearchTextField.addKeyListener(new KeyAdapter() {
                    public void keyReleased(KeyEvent evt) {
                        jSearchTextFieldKeyReleased(evt);
                    }
                });

            }
            {
                jSeparatorLabel = new JLabel();
                jToolBar.add(jSeparatorLabel);
                jSeparatorLabel.setText(" ");
            }
            {
                GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
                Font[] fonts = e.getAllFonts();
                String fontNames[] = new String[fonts.length];
                int x = 0;
                for (Font f : fonts) {
                    fontNames[x++] = f.getFontName();
                }
                ComboBoxModel jFontComboBoxModel = new DefaultComboBoxModel(fontNames);
                jFontComboBox = new JComboBox();
                jToolBar.add(jFontComboBox);
                jFontComboBox.setModel(jFontComboBoxModel);
                jFontComboBox.setMaximumSize(new java.awt.Dimension(180, 22));
                jFontComboBox.setPreferredSize(new java.awt.Dimension(180, 22));
                jFontComboBox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jFontComboBoxActionPerformed(evt);
                    }
                });
            }
            {
                pager = new Pager();
                jToolBar.add(pager);
                pager.setVisible(false);
            }
        }
        {
            jScrollPane1 = new JScrollPane();
            this.add(jScrollPane1, BorderLayout.CENTER);
            {
                jTextArea = new JTextArea();
                jTextArea.getDocument().addDocumentListener(this);
                lines = new JTextArea(" 1 ");
                lines.setBackground(new Color(200, 230, 245));
                lines.setEditable(false);
                jScrollPane1.setRowHeaderView(lines);

                jTextArea.getDocument().addDocumentListener(new DocumentListener() {
                    public String getText() {
                        int caretPosition = jTextArea.getDocument().getLength();
                        Element root = jTextArea.getDocument().getDefaultRootElement();

                        int base = 0;
                        if (separateByLine == false) {
                            if (str != null) {
                                base = StringUtils.countMatches(
                                        str.substring(0, (pager.getPage() - 1) * pageSize),
                                        System.getProperty("line.separator"));
                                if (base == 1) {
                                    base = 0;
                                }
                            }
                        } else {
                            base = (pager.getPage() - 1) * pageSize;
                        }
                        base += lineNoBase;
                        String text = " " + (base + 1) + " " + System.getProperty("line.separator");
                        for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
                            text += " " + (base + i) + " " + System.getProperty("line.separator");
                        }
                        return text;
                    }

                    @Override
                    public void changedUpdate(DocumentEvent de) {
                        lines.setText(getText());
                    }

                    @Override
                    public void insertUpdate(DocumentEvent de) {
                        lines.setText(getText());
                    }

                    @Override
                    public void removeUpdate(DocumentEvent de) {
                        lines.setText(getText());
                    }

                });
                jScrollPane1.setViewportView(jTextArea);
            }
        }
        {
            jStatusPanel = new JPanel();
            FlowLayout jStatusPanelLayout = new FlowLayout();
            jStatusPanelLayout.setAlignment(FlowLayout.LEFT);
            jStatusPanel.setLayout(jStatusPanelLayout);
            this.add(jStatusPanel, BorderLayout.SOUTH);
            {
                jStatusLabel = new JLabel();
                jStatusPanel.add(jStatusLabel);
            }
            {
                jSearchLabel = new JLabel();
                jStatusPanel.add(jSearchLabel);
            }
        }
        this.jFontComboBox.setSelectedItem(jTextArea.getFont().getFamily() + ".plain");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.galenframework.tests.runner.GalenMainTest.java

/**
 * Comes from https://github.com/galenframework/galen/issues/184
 * Test Retry Handler/*from  w w  w .j a v  a 2 s .c om*/
 * @throws Exception
 */
@Test
public void shouldRunJavascriptTests_andRetryThem() throws Exception {
    File htmlReportDir = Files.createTempDir();
    JsTestRegistry.get().clear();

    new GalenMain()
            .execute(new String[] { "test", getClass().getResource("/js-tests/testretry.test.js").getFile(),
                    "--htmlreport", htmlReportDir.getAbsolutePath() });

    List<String> events = JsTestRegistry.get().getEvents();

    assertThat(events,
            contains("Before test suite event", "Before test event for: Test A", "Test A invoked",
                    "After test event for: Test A", "Retry handler invoked for test: Test A",
                    "Before test event for: Test A", "Test A invoked", "After test event for: Test A",
                    "Retry handler invoked for test: Test A", "Before test event for: Test A", "Test A invoked",
                    "After test event for: Test A", "Retry handler invoked for test: Test A",
                    "Before test event for: Test B", "Test B invoked", "After test event for: Test B",
                    "Retry handler invoked for test: Test B", "Before test event for: Test B", "Test B invoked",
                    "After test event for: Test B", "Retry handler invoked for test: Test B",
                    "Before test event for: Test B", "Test B invoked", "After test event for: Test B",
                    "Retry handler invoked for test: Test B", "Before test event for: Test C", "Test C invoked",
                    "After test event for: Test C", "After test suite event"));

    String htmlReportContent = FileUtils
            .readFileToString(new File(htmlReportDir.getAbsolutePath() + File.separator + "report.html"));

    int amountOfReportedTests = StringUtils.countMatches(htmlReportContent, "\"testId\"");
    assertThat("Amount of reported tests should be", amountOfReportedTests, is(3));
}

From source file:functionaltests.TagCommandsFunctTest.java

@Test
public void testJobOutputWithTag() throws Exception {
    typeLine("joboutput(" + jobId.longValue() + ", 'LOOP-T2-1')");

    runCli();/*from   w  ww  .j  a  v a 2  s.  com*/

    String out = this.capturedOutput.toString();
    System.setOut(stdOut);
    System.out.println("------------- testJobOutputWithTag:");
    System.out.println(out);
    assertEquals(2, StringUtils.countMatches(out, "Task 1 : Test STDERR"));
    assertEquals(2, StringUtils.countMatches(out, "Task 1 : Test STDOUT"));
    assertEquals(2, StringUtils.countMatches(out, "Terminate task number 1"));
    assertTrue(!out.contains("Task 2 : Test STDERR"));
    assertTrue(!out.contains("Task 2 : Test STDOUT"));
    assertTrue(!out.contains("Terminate task number 2"));
}

From source file:fr.fastconnect.factory.tibco.bw.maven.source.MassMavenizerMojo.java

private Properties initProperties(AbstractProject p) {
    if (archetypeProperties == null) {
        archetypeProperties = new Properties();
    }//from www .  j ava  2  s .  c om

    archetypeProperties.put("rootProjectGroupId", rootProjectGroupId);
    archetypeProperties.put("rootProjectArtifactId", rootProjectArtifactId);
    archetypeProperties.put("rootProjectVersion", rootProjectVersion);

    String s = AbstractProjectsListMojo.getRelativePath(p.getAbsolutePath(), getRootProjectPath(p),
            File.separator);
    String rootRelativePath = "../..";
    for (int i = StringUtils.countMatches(s, File.separator); i > 0; i--) {
        rootRelativePath += "/..";
    }
    archetypeProperties.put("rootRelativePath", rootRelativePath);

    if (isProjlib) {
        archetypeProperties.put("projectPackaging", AbstractBWMojo.PROJLIB_TYPE);
    } else {
        archetypeProperties.put("projectPackaging", AbstractBWMojo.BWEAR_TYPE);
    }

    archetypeProperties.put("bwProjectName", p.getProjectName());
    archetypeProperties.put("groupId", projectGroupId);
    archetypeProperties.put("artifactId", p.getArtifactId());
    if (projectVersion == null || projectVersion.isEmpty()) {
        projectVersion = "[inherited]";
        archetypeProperties.put("versionIsInherited", "true");
    }
    archetypeProperties.put("version", projectVersion);
    if (bwProjectLocation == null) {
        bwProjectLocation = "";
        archetypeProperties.put("bwProjectLocationIsInherited", "true");
    }
    archetypeProperties.put("bwProjectLocation", bwProjectLocation);

    archetypeProperties.put("putPOMInParentDirectory", p.getPutPOMInParentDirectory().toString());

    return archetypeProperties;
}