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.seleniumtests.ut.core.TestLogActions.java

/**
 * Same as above but parameter name is 'pwd'
 *//*from  ww  w. j ava 2  s  .c  o m*/
@Test(groups = { "ut" })
public void testPassworkMasking2() {

    testPage._setPassword2("someText");
    TestStep step = TestLogging.getTestsSteps().get(TestLogging.getCurrentTestResult()).get(2);

    // all occurences of the password have been replaced
    Assert.assertFalse(step.toString().contains("someText"));
    Assert.assertEquals(StringUtils.countMatches(step.toString(), "******"), 2);
}

From source file:io.wcm.testing.mock.jcr.AbstractItem.java

@Override
public int getDepth() throws RepositoryException {
    if (StringUtils.equals("/", this.path)) {
        return 0;
    } else {/*from   www .ja v a  2s .  c o m*/
        return StringUtils.countMatches(this.path, "/");
    }
}

From source file:de.dfki.mmf.input.templates.SimpleNLGTemplateParser.java

public Predicate parseTemplate(Predicate predicate) {
    List<String> predicateModifier = predicate.getPredicateModifiers();
    String predicateName = predicate.getPredicateName();
    PredicateElement[] args = predicate.getElements();
    Predicate modifiedPredicate = new Predicate(predicateName);
    //get template resource
    InputStream resource = this.getClass().getClassLoader().getResourceAsStream("PredicateTemplates.template");
    BufferedReader br = new BufferedReader(new InputStreamReader(resource));
    try {/*from  w ww .  j a  v  a2 s . c o  m*/
        //read line by line
        String line = br.readLine();
        while (line != null) {
            //search template for respective predicate
            if (line.startsWith(predicateName)) {
                //count required number of variables for corresponding predicate
                int varCount = StringUtils.countMatches(line, "$");
                if (args != null) {
                    if (args.length != varCount) {
                        throw new IllegalArgumentException(
                                "Incorrect number of arguments used for predicate " + predicateName + ".");
                    }
                }
                //go to line with template output in corresponding languageFormat
                while (!line.startsWith("(" + LanguageFormat.ENG_SIMPLENLG + ")")) {
                    line = br.readLine();
                }
                //plug in the predicate arguments into the template output
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        line = line.replace("$x" + (i + 1), args[i].toString());
                    }
                }
                //retrieve the different parts of the template
                List<String> matchList = new ArrayList<String>();
                //retrieve the arguments stored in "()"
                Pattern regex = Pattern.compile("\\{(.*?)\\}");
                Matcher regexMatcher = regex.matcher(line);
                while (regexMatcher.find()) {
                    // if argument is zoe=null -> this part of template will not be used
                    if (!regexMatcher.group(1).contains("zoe")) {
                        matchList.add(regexMatcher.group(1));
                    }
                }
                ArrayList<PredicateElement> predicateElements = new ArrayList<>();
                ArrayList<PredicateAnnotation> predicateAnnotations = new ArrayList<>();
                for (String str : matchList) {
                    //retrieve annotations for each element
                    String[] splitstring = str.split(":");
                    String grammaticalFunction = "";
                    String questionAnnotation = "";
                    if (splitstring[0].contains("/")) {
                        grammaticalFunction = splitstring[0].split("/")[0];
                        questionAnnotation = splitstring[0].split("/")[1];
                    } else {
                        grammaticalFunction = splitstring[0];
                    }
                    if (grammaticalFunction.trim().equals("NO_NLG")) {
                        predicateAnnotations.add(PredicateAnnotation.valueOf(grammaticalFunction));
                        splitstring[1] = splitstring[1].replaceAll("\\s+", " ");
                        splitstring[1] = splitstring[1].trim();
                        PredicateElement predicateElement = new StringPredicateElement(splitstring[1]);
                        predicateElements.add(predicateElement);
                        continue;
                    }
                    //check if a question for a specific argument is asked
                    if (splitstring[1].contains("[ma]")) {
                        if (!questionAnnotation.equals("")) {
                            predicateAnnotations.add(PredicateAnnotation.valueOf(questionAnnotation));
                        } else {
                            System.out.println(
                                    "Warning: A question about a specific part of the sentence should be asked, but no corresponding question annotation was set.");
                        }
                        continue;
                    } else if (splitstring[1].contains("[xo]")) {
                        if (!questionAnnotation.equals("")) {
                            predicateAnnotations.add(PredicateAnnotation.valueOf(questionAnnotation));
                        }
                        continue;
                    }
                    splitstring[1] = splitstring[1].replaceAll("\\s+", " ");
                    splitstring[1] = splitstring[1].trim();
                    PredicateElement predicateElement = new StringPredicateElement(splitstring[1]);
                    predicateElements.add(predicateElement);
                    predicateElement.setPredicateElementAnnotation(
                            PredicateElementAnnotation.valueOf(grammaticalFunction));
                }
                //create the modified predicate
                modifiedPredicate.setElements(
                        predicateElements.toArray(new StringPredicateElement[predicateElements.size()]));
                //some annotations which affect the entire predicate
                if (predicateModifier != null) {
                    if (predicateModifier.contains("[na]")) {
                        predicateAnnotations.add(PredicateAnnotation.NEGATION);
                    }
                    if (predicateModifier.contains("[xu]")) {
                        predicateAnnotations.add(PredicateAnnotation.YES_NO);
                    }
                    if (predicateModifier.contains("[ko]")) {
                        predicateAnnotations.add(PredicateAnnotation.IMPERATIVE);
                    }
                }
                modifiedPredicate.setPredicateAnnotations(predicateAnnotations);
                break;
            }
            line = br.readLine();
            if (line == null) {
                throw new UnsupportedOperationException("Predicate " + predicateName
                        + " is unknown. You need to specify a template for this predicate first.");
            }
        }

    } catch (IOException e) {
        System.out.println("An IO-Exception occured while reading a line from buffered reader.");
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            System.out.println("An IO-Exception occured while trying to close the buffered reader.");
            e.printStackTrace();
        }
    }
    return modifiedPredicate;
}

From source file:com.palantir.atlasdb.keyvalue.api.TableReference.java

public static TableReference fromString(String s) {
    int dotCount = StringUtils.countMatches(s, ".");
    if (dotCount == 0) {
        return TableReference.createWithEmptyNamespace(s);
    } else if (dotCount == 1) {
        return TableReference.createFromFullyQualifiedName(s);
    } else {//  w ww . j  ava 2 s.  c o  m
        throw new IllegalArgumentException(s + " is not a valid table reference.");
    }
}

From source file:com.knewton.mapreduce.io.sstable.BackwardsCompatibleDescriptor.java

/**
 * Implementation of {@link Descriptor#fromFilename(File, String)} that is backwards compatible
 * with older sstables// ww  w  .ja va  2  s.  c  om
 *
 * @param directory
 * @param name
 * @return A descriptor for the sstable
 */
public static Pair<Descriptor, String> fromFilename(File directory, String name) {
    Iterator<String> iterator = Splitter.on(separator).split(name).iterator();
    iterator.next();
    String tempFlagMaybe = iterator.next();
    String versionMaybe = iterator.next();
    String generationMaybe = iterator.next();
    Pair<Descriptor, String> dsPair;
    if (tempFlagMaybe.equals(SSTable.TEMPFILE_MARKER) && generationMaybe.matches("\\d+")
            && !new Version(versionMaybe).hasAncestors) {
        // old sstable file with temp flag.
        dsPair = Descriptor.fromFilename(directory, directory.getName() + separator + name);
    } else if (versionMaybe.equals(SSTable.TEMPFILE_MARKER)) {
        // new sstable file with temp flag.
        dsPair = Descriptor.fromFilename(directory, name);
    } else if (StringUtils.countMatches(name, String.valueOf(separator)) < NUM_SEPARATORS) {
        // old sstable file with no temp flag.
        dsPair = Descriptor.fromFilename(directory, directory.getName() + separator + name);
    } else {
        // new sstable file with no temp flag.
        dsPair = Descriptor.fromFilename(directory, name);
    }
    // cast so that Pair doens't complain.
    return Pair.create((Descriptor) new BackwardsCompatibleDescriptor(dsPair.left), dsPair.right);
}

From source file:main.java.miro.browser.browser.widgets.browser.display.HeightModifier.java

@Override
public void handleEvent(Event event) {

    GC gc;/*from  ww  w. j  ava  2  s  .  com*/
    String textString = null;
    Text s = (Text) event.widget;
    int lineHeight = s.getLineHeight();

    Rectangle cd = s.getClientArea();
    int lineWidth = s.getClientArea().width;
    if (event.widget instanceof Text) {
        textString = s.getText();
        gc = new GC(s);
    } else if (event.widget instanceof Link) {
        Link l = (Link) event.widget;
        textString = l.getText();
        gc = new GC(l);
    } else {
        return;
    }

    int newLineCount = StringUtils.countMatches(textString, "\n");
    if (newLineCount > 0) {
        //         textString = textString.replace("\n", " ");
        //         s.setText(textString);
    }

    newLineCount = StringUtils.countMatches(textString, "\n");
    if (textString == null | textString.length() == 0) {
        textString = "None";

        if (event.widget instanceof Text) {
            ((Text) event.widget).setText(textString);
        } else {
            ((Link) event.widget).setText(textString);
        }
    }

    RowData rowData = (RowData) field.getLayoutData();

    // Calculate new height, based on strinWidth
    int stringWidth = gc.stringExtent(textString).x;

    // Divide by our width, factor is how many lines we expect from this
    // input
    double factor = stringWidth / (double) (lineWidth);

    int minLines = field.getMinLines();
    int lines = Math.max((int) factor, minLines);

    // Calculate our new preferred height
    int height = (int) (Math.ceil(lines) * lineHeight);
    for (int i = 0; i < newLineCount; i++) {
        height += lineHeight;
    }
    //      rowData.height = height;

    //      if (height == 0 | height >= minLines) {
    //         rowData.height = height;
    //      } else if (height < minLines) {
    //         rowData.height = minLines;
    //      }
    //      field.setLayoutData(rowData);

    Composite c = field.getParent();
    while (!(c instanceof DisplayWidget)) {
        c = c.getParent();
    }

    DisplayWidget dw = (DisplayWidget) c;
    dw.getParent().layout();
    dw.getParent().getParent().layout();
    Point size = dw.computeSize(dw.getSize().x, SWT.DEFAULT);
    //      Point size = dw.computeSize(SWT.DEFAULT, SWT.DEFAULT);
    Point wat = dw.getParent().computeSize(SWT.DEFAULT, SWT.DEFAULT);

    ScrolledComposite scroller = (ScrolledComposite) dw.getParent();
    scroller.setMinHeight(size.y);
    dw.layout(true);
    dw.pack();
}

From source file:com.videaps.cube.solving.access.ColorPicker.java

public String mostFrequentColor(String colorStr) {
    String mostFrequentColor = null;
    int maxColorCount = 0;
    for (String color : colorMap.values()) {
        int count = StringUtils.countMatches(colorStr, color);
        if (count > maxColorCount) {
            mostFrequentColor = color;/*from  w  w  w.j  a  v a  2s. c  o  m*/
            maxColorCount = count;
        }
    }
    if (mostFrequentColor == null) {
        mostFrequentColor = "X";
    }
    return mostFrequentColor;
}

From source file:com.linagora.obm.ui.page.ContactPage.java

public int countNameInList(String name) {
    return StringUtils.countMatches(dataContainer.getText(), name);
}

From source file:com.chiorichan.factory.groovy.EmbeddedGroovyEngine.java

@Override
public boolean eval(ScriptingContext context) throws Exception {
    String source = context.readString();

    int fullFileIndex = 0;
    String[] dontStartWith = new String[] { "println", "print", "echo", "def", "import", "if", "for", "do", "}",
            "else", "//", "/*", "\n", "\r" };

    StringBuilder output = new StringBuilder();

    while (fullFileIndex < source.length()) {
        int startIndex = source.indexOf(MARKER_START, fullFileIndex);
        if (-1 != startIndex) {
            // Append all the simple text until the marker

            String fragment = escapeFragment(source.substring(fullFileIndex, startIndex));
            if (!fragment.isEmpty())
                output.append(fragment);

            int endIndex = source.indexOf(MARKER_END, Math.max(startIndex, fullFileIndex));

            if (endIndex == -1)
                throw new ScriptingException(ReportingLevel.E_PARSE,
                        "Marker `<%` was not closed after line "
                                + (StringUtils.countMatches(output.toString(), "\n") + 1)
                                + ", please check your source file and try again.");

            // Re gets the fragment?
            fragment = source.substring(startIndex + MARKER_START.length(), endIndex);

            boolean appendPrint = true;

            for (String s : dontStartWith)
                if (fragment.trim().startsWith(s) || fragment.startsWith(s) || fragment.trim().isEmpty())
                    appendPrint = false;

            // void will disable the print depend
            if (fragment.trim().startsWith("void")) {
                appendPrint = false;/*  w w  w .  j av a2 s  .co m*/
                fragment = fragment.replace(" *void ?", "");
            }

            if (appendPrint)
                fragment = "print " + fragment;

            if (!fragment.isEmpty())
                output.append(fragment + "; ");

            // Position index after end marker
            fullFileIndex = endIndex + MARKER_END.length();
        } else {
            String fragment = escapeFragment(source.substring(fullFileIndex));

            if (!fragment.isEmpty())
                output.append(fragment);

            // Position index after the end of the file
            fullFileIndex = source.length() + 1;
        }
    }

    context.baseSource(output.toString());
    try {
        Script script = GroovyRegistry.getCachedScript(context, binding);
        if (script == null) {
            GroovyShell shell = registry.getNewShell(context, binding);
            script = registry.makeScript(shell, output.toString(), context);
        }
        context.result().object(script.run());
    } catch (Throwable t) {
        // Clear the input source code and replace it with the exception stack trace
        // context.resetAndWrite( ExceptionUtils.getStackTrace( t ) );
        context.reset();
        throw t;
    }
    return true;
}

From source file:it.vige.greenarea.sgaplconsole.controllers.utils.RelativeViewHandler.java

/**
 * Transform the given URL to a relative URL <b>in the context of the
 * current faces request</b>. If the given URL is not absolute do nothing
 * and return the given url. The returned relative URL is "equal" to the
 * original url but will not start with a '/'. So the browser can request
 * the "same" resource but in a relative way and this is important behind
 * reverse proxies!/*from  w w  w . ja  v  a 2 s. c  om*/
 * 
 * @param context
 * @param theURL
 * @return
 */
private String getRelativeURL(final FacesContext context, final String theURL) {
    final HttpServletRequest request = ((HttpServletRequest) context.getExternalContext().getRequest());
    logger.debug("Context Path <" + getPath(request) + "> e url originale <" + theURL + ">");
    String result = theURL;
    if (theURL.startsWith("/")) {
        int subpath = StringUtils.countMatches(getPath(request), "/") - 1;
        String pathPrefix = "";
        if (subpath > 0) {
            while (subpath > 0) {
                pathPrefix += "/..";
                subpath--;
            }
            pathPrefix = StringUtils.removeStart(pathPrefix, "/");
        }
        result = pathPrefix + result;
    }
    logger.debug("Result <<<" + result + ">>>>  ");
    logger.debug("--------------------------------------------------------------------");
    return result;
}