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:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskLogOutByTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/LOOP-T2-1/result/log/out");
    String responseContent = getContent(response);

    System.out.println(responseContent);

    assertEquals(2, StringUtils.countMatches(responseContent, "Task 1 : Test STDOUT"));
    assertEquals(2, StringUtils.countMatches(responseContent, "Terminate task number 1"));
}

From source file:cc.recommenders.names.CoReNames.java

public static String src2vmType(String type) {
    ensureIsNotNull(type, "type");
    ///*from   www  .  j  a  va  2 s .  c o  m*/
    final PrimitiveType p = PrimitiveType.fromSrc(type);
    if (p != null) {
        return String.valueOf(p.vm());
    }
    int dimensions = 0;
    if (type.endsWith("]")) {
        dimensions = StringUtils.countMatches(type, "[]");
        type = StringUtils.substringBefore(type, "[") + ";";
    }
    return StringUtils.repeat("[", dimensions) + "L" + type.replaceAll("\\.", "/");
}

From source file:com.streamsets.pipeline.stage.processor.fieldfilter.FieldFilterProcessor.java

@Override
protected void process(Record record, SingleLaneBatchMaker batchMaker) throws StageException {
    // use List to preserve the order of list fieldPaths - need to watch out for duplicates though
    List<String> allFieldPaths = record.getEscapedFieldPathsOrdered();
    // use LinkedHashSet to preserve order and dedupe as we go
    LinkedHashSet<String> fieldsToRemove;
    switch (filterOperation) {
    case REMOVE://from w  w w.  ja va  2 s.  c  o m
        fieldsToRemove = new LinkedHashSet<>();
        for (String field : fields) {
            List<String> matchingFieldPaths = FieldPathExpressionUtil.evaluateMatchingFieldPaths(field,
                    fieldPathEval, fieldPathVars, record, allFieldPaths);
            fieldsToRemove.addAll(matchingFieldPaths);
        }
        break;
    case REMOVE_NULL:
        fieldsToRemove = new LinkedHashSet<>();
        for (String field : fields) {
            List<String> matchingFieldPaths = FieldPathExpressionUtil.evaluateMatchingFieldPaths(field,
                    fieldPathEval, fieldPathVars, record, allFieldPaths);
            for (String fieldPath : matchingFieldPaths) {
                if (record.has(fieldPath) && record.get(fieldPath).getValue() == null) {
                    fieldsToRemove.add(fieldPath);
                }
            }
        }
        break;
    case REMOVE_EMPTY:
        fieldsToRemove = new LinkedHashSet<>();
        for (String field : fields) {
            List<String> matchingFieldPaths = FieldPathExpressionUtil.evaluateMatchingFieldPaths(field,
                    fieldPathEval, fieldPathVars, record, allFieldPaths);
            for (String fieldPath : matchingFieldPaths) {
                if (record.has(fieldPath) && record.get(fieldPath).getValue() != null
                        && record.get(fieldPath).getValue().equals("")) {
                    fieldsToRemove.add(fieldPath);
                }
            }
        }
        break;
    case REMOVE_NULL_EMPTY:
        fieldsToRemove = new LinkedHashSet<>();
        for (String field : fields) {
            List<String> matchingFieldPaths = FieldPathExpressionUtil.evaluateMatchingFieldPaths(field,
                    fieldPathEval, fieldPathVars, record, allFieldPaths);
            for (String fieldPath : matchingFieldPaths) {
                if (record.has(fieldPath) && (record.get(fieldPath).getValue() == null
                        || record.get(fieldPath).getValue().equals(""))) {
                    fieldsToRemove.add(fieldPath);
                }
            }
        }
        break;
    case REMOVE_CONSTANT:
        fieldsToRemove = new LinkedHashSet<>();
        for (String field : fields) {
            List<String> matchingFieldPaths = FieldPathExpressionUtil.evaluateMatchingFieldPaths(field,
                    fieldPathEval, fieldPathVars, record, allFieldPaths);
            for (String fieldPath : matchingFieldPaths) {
                if (record.has(fieldPath) && record.get(fieldPath).getValue() != null
                        && record.get(fieldPath).getValue().equals(constant)) {
                    fieldsToRemove.add(fieldPath);
                }
            }
        }
        break;
    case KEEP:
        //Algorithm:
        // - Get all possible field paths in the record
        //
        // - Remove arguments fields which must be retained, its parent fields and the child fields from above set
        //   (Account for presence of wild card characters while doing so) The remaining set of fields is what must be
        //   removed from the record.
        //
        // - Keep fieldsToRemove in order - sorting is too costly
        //List all the possible field paths in this record
        fieldsToRemove = new LinkedHashSet<>(allFieldPaths);
        for (String field : fields) {
            //Keep parent fields
            //get the parent fieldPaths for each of the fields to keep
            List<String> parentFieldPaths = getParentFields(field);
            //remove parent paths from the fieldsToRemove set
            //Note that parent names could contain wild card characters
            for (String parentField : parentFieldPaths) {
                List<String> matchingFieldPaths = FieldRegexUtil.getMatchingFieldPaths(parentField,
                        allFieldPaths);
                fieldsToRemove.removeAll(matchingFieldPaths);
            }

            //Keep the field itself
            //remove the field path itself from the fieldsToRemove set
            //Consider wild card characters
            List<String> matchingFieldPaths = FieldPathExpressionUtil.evaluateMatchingFieldPaths(field,
                    fieldPathEval, fieldPathVars, record, allFieldPaths);
            fieldsToRemove.removeAll(matchingFieldPaths);

            //Keep the children of the field
            //For each of the fieldPaths that match the argument field path, remove all the child paths
            // Remove children at the end to avoid ConcurrentModificationException
            Set<String> childrenToKeep = new HashSet<>();
            for (String matchingFieldPath : matchingFieldPaths) {
                for (String fieldToRemove : fieldsToRemove) {
                    // for the old way, startsWith is appropriate when we have
                    // different path structures, or "nested" (multiple dimensioned) index structures.
                    //  eg: /USA[0]/SanFrancisco/folsom/streets[0] must still match:
                    //      /USA[0]/SanFrancisco/folsom/streets[0][0]   hence: startsWith.
                    if (StringUtils.countMatches(fieldToRemove, "/") == StringUtils
                            .countMatches(matchingFieldPath, "/")
                            && StringUtils.countMatches(fieldToRemove, "[") == StringUtils
                                    .countMatches(matchingFieldPath, "[")) {
                        if (fieldToRemove.equals(matchingFieldPath)) {
                            childrenToKeep.add(fieldToRemove);
                        }
                    } else {
                        if (fieldToRemove.startsWith(matchingFieldPath)) {
                            childrenToKeep.add(fieldToRemove);
                        }
                    }
                }
            }
            fieldsToRemove.removeAll(childrenToKeep);
        }
        break;
    default:
        throw new IllegalStateException(
                Utils.format("Unexpected Filter Operation '{}'", filterOperation.name()));
    }
    // We don't sort because we maintained list fields in ascending order (but not a full ordering)
    // Instead we just iterate in reverse to delete
    Iterator<String> itr = (new LinkedList<>(fieldsToRemove)).descendingIterator();
    while (itr.hasNext()) {
        record.delete(itr.next());
    }
    batchMaker.addRecord(record);
}

From source file:com.sonicle.webtop.core.app.sdk.BaseJOOQVisitor.java

protected boolean valueContainsWildcard(String value) {
    int escapedAsterisks = StringUtils.countMatches(value, "\\*");
    int asterisks = StringUtils.countMatches(value, "*");
    return asterisks > escapedAsterisks;
}

From source file:com.joyent.manta.client.MantaClientFindIT.java

/**
 * This test determines that the find() method can recurse to a reasonable
 * number of subdirectories without throwing a {@link StackOverflowError}.
 *
 * As you go over 70 subdirectories, Manta will throw a 500 error. We should
 * be able to recurse to a stack depth far deeper than Manta can support
 * for subdirectories.//from  w w  w .j  ava  2 s  .  c o m
 */
public void findCanDeeplyRecurse() throws IOException {
    final int depth = 70;
    final StringBuilder path = new StringBuilder(testPathPrefix);
    mantaClient.putDirectory(path.toString());

    final int currentDepth = StringUtils.countMatches(testPathPrefix, SEPARATOR);

    // We start with i=currentDepth because we are already currentDepth levels deep
    for (int i = currentDepth; i < depth; i++) {
        path.append(UUID.randomUUID()).append(SEPARATOR);
        mantaClient.putDirectory(path.toString());
        String file = path + String.format("subdirectory-file-%d.txt", i);
        mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8);
    }

    Stream<MantaObject> objects = mantaClient.find(path.toString());
    objects.forEach(object -> {
    });

    /* This test just makes sure that we can run to a deep directory depth
     * without throwing an exception. */
}

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

@SuppressWarnings({ "static-access", "unchecked" })

private String printNote(NodeList nodeList) {
    List<VideoSub> listsub = new ArrayList<VideoSub>();
    List<VideoSub> savelistsub = new ArrayList<VideoSub>();
    for (int count = 0; count < nodeList.getLength(); count++) {
        VideoSub v = new VideoSub();
        Node tempNode = nodeList.item(count);
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
            v.setTextsb(replace_all(replacetext(tempNode.getTextContent().replace("...", "."))));
            if (tempNode.hasAttributes()) {
                NamedNodeMap nodeMap = tempNode.getAttributes();
                for (int i = 0; i < nodeMap.getLength(); i++) {
                    Node node = nodeMap.item(i);
                    if (i == 0) {
                        v.setEnd(node.getNodeValue());
                    } else {
                        v.setStart(node.getNodeValue());
                    }//w  ww  . j av  a  2  s. c  om
                }
            }
        }
        listsub.add(v);
    }
    String savetext = "";
    double sodu = 0;
    double savedur = 0;
    String dutext = "";
    double start = 0;
    String kq = "";
    boolean flag = true;// vo lan dau
    boolean flagchamcuoi = false;// vo lan dau
    for (int i = 0; i < listsub.size(); i++) {
        String cau = listsub.get(i).getTextsb();
        if (flag || flagchamcuoi == true) {
            start = Double.parseDouble(listsub.get(i).getStart());
            savedur = Double.parseDouble(listsub.get(i).getEnd());
            flag = false;
            flagchamcuoi = false;
        }

        double dur = Double.parseDouble(listsub.get(i).getEnd());
        if (sodu != 0) {
            savetext += dutext;
            start = Double.parseDouble(listsub.get(i).getStart());
            start -= sodu;
            System.out.println(sodu + "So du" + start);
            dutext = "";
            sodu = 0;
        }
        if (cau.contains("####") == true) {
            float sogiay = (float) dur;
            float phantram = 0;
            int socau = 0;
            int sotu = demsotu(cau);
            String[] savecau = new String[100];
            int[] savesotu = new int[1000];
            double[] phantramsotu = new double[1000];
            for (String retval : cau.split("####")) { // split("\\|;\\s*|\\.\\s*|\\?\\s*")
                if (retval != "" && retval.length() > 0) {
                    savecau[socau] = retval;
                    savesotu[socau] = (1 + StringUtils.countMatches(retval.trim(), " "));
                    double pt = 0.0;
                    double so1 = (double) savesotu[socau];
                    double so2 = (double) sotu;
                    pt = so1 / so2;
                    phantramsotu[socau] = pt * sogiay;
                    socau++;
                }
            }

            // *******************************
            char[] array = cau.toCharArray();
            // save cau 1
            VideoSub cau1 = new VideoSub();
            cau1.setTextsb((savetext + " " + savecau[0]).replace("\n", " ").replace("'", " ").trim());
            cau1.setStart(start + "");
            String end = (savedur + phantramsotu[0]) + "";
            cau1.setEnd(end + "");
            if (savecau[0] != ".")
                savelistsub.add(cau1);
            // add vao
            savetext = "";
            // cap nhat start
            start += Double.parseDouble(cau1.getEnd());

            savedur = 0;
            // save cau giua
            for (int i1 = 1; i1 < socau - 1; i1++) {
                // add vao
                VideoSub Cau2 = new VideoSub();
                Cau2.setTextsb(savecau[i1].replace("\n", " ").replace("'", " ").trim());
                Cau2.setStart(start + "");
                Cau2.setEnd(phantramsotu[i1] + "");
                if (savecau[i1] != ".")
                    savelistsub.add(Cau2);

                start += phantramsotu[i1];
            }

            // save cau cuoi
            if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == '?'
                    || array[cau.length() - 5] == ';') {
                flagchamcuoi = true;

            }

            System.out.println(cau);
            if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == ';'
                    || array[cau.length() - 5] == '?') {
                if (socau - 1 != 0) {
                    VideoSub Cau3 = new VideoSub();
                    Cau3.setTextsb(savecau[socau - 1].replace("\n", " ").replace("'", "-").trim());
                    Cau3.setStart(start + "");
                    Cau3.setEnd(phantramsotu[socau - 1] + "");
                    if (savecau[socau - 1] != ".")
                        savelistsub.add(Cau3);

                    start += phantramsotu[socau - 1];
                }
            } else {
                dutext = savecau[socau - 1];
                sodu = phantramsotu[socau - 1];
            }
        } else {
            savetext += " " + cau;
            savedur += dur;
        }
    }
    // ================Xuat File Json===============
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < savelistsub.size(); i++) {
        JSONObject obj = new JSONObject();
        if (savelistsub.get(i).getTextsb() != ".") {
            String startadd = savelistsub.get(i).getStart();
            String duradd = savelistsub.get(i).getEnd();
            String textadd = savelistsub.get(i).getTextsb();
            obj.put("start", startadd);
            obj.put("dur", duradd);
            obj.put("text", textadd);
            jsonArray.add(obj);
        }

    }
    String out_String = jsonArray.toJSONString();
    out_String = out_String.toString();

    // ================Xuat File Json===============

    return out_String;
}

From source file:de.citec.sc.matoll.utils.visualizeSPARQL.java

public static String doVisual(String query, String name) {

    String prefix = "\\begin{figure}\n" + "\\centering\n" + "\\begin{tikzpicture}[\n"
            + "    scale = 0.7, transform shape, thick,\n"
            + "    every node/.style = {draw, circle, minimum size = 10mm},\n"
            + "    grow = down,  % alignment of characters\n" + "    level 1/.style = {sibling distance=3cm},\n"
            + "    level 2/.style = {sibling distance=4cm}, \n"
            + "    level 3/.style = {sibling distance=2cm}, \n" + "    level distance = 2.3cm\n" + "  ]\n";

    String suffix = "\\end{tikzpicture}\n" + "\\caption{Visualisation for " + name + "}\n" + "\\label{fig:"
            + name.replace("\\_", "") + "}\n" + "\\end{figure}";

    /*/*from  w  w w. j  a  va  2 s.com*/
    Split into parts; each triple is seperated with a .
    */
    String[] parts = query.split("\\.");

    List<List<String>> relations = new ArrayList<>();
    Map<String, Integer> variables = new HashMap<>();
    Map<String, String> deprel = new HashMap<>();
    Map<String, String> node_name = new HashMap<>();

    for (String s : parts) {
        /*
        ignore everything which starts with optional or union (TODO: fix this)
        */
        if (s.contains("<conll:head>") && !s.contains("OPTIONAL") && !s.contains("UNION")
                && !s.contains("SELECT")) {
            String value = (s.replace("}", "")).trim();
            String[] tmp = value.split("<conll:head>");
            String subj = tmp[0].trim();
            String obj = tmp[1].trim();
            variables.put(subj, 0);
            variables.put(obj, 0);
            List<String> relation = new ArrayList<>();
            relation.add(subj);
            relation.add(obj);
            relations.add(relation);
        }

        if (s.contains("<conll:deprel>") && !s.contains("OPTIONAL") && !s.contains("UNION")
                && !s.contains("SELECT")) {
            String value = (s.replace("}", "")).trim();
            String[] tmp = value.split("<conll:deprel>");
            String subj = tmp[0].trim();
            String obj = tmp[1].trim();
            /*
            TODO: Be aware that sometimes the deprel is hiden in an additional variable.
            In the moment ignore it, but make sure it is taken correctly
            */
            if (!obj.contains("?"))
                deprel.put(subj, obj.replace("\"", ""));
        }
    }

    //
    String head_variable = findRoot(relations);
    if (head_variable != null) {
        variables.put(head_variable, 1);
        String latex_output = "\\node[fill = gray!40, " + "shape = rectangle, rounded corners, "
                + "minimum width = 2cm, font = \\sffamily] " + "(" + Integer.toString(variable_counter) + ") {"
                + head_variable + "}\n";
        node_name.put(head_variable, Integer.toString(variable_counter));
        int counter = 0;
        for (List<String> relation : relations) {
            String subj = relation.get(0);
            if (!node_name.containsKey(subj)) {
                counter += 1;
                latex_output += "child {node[fill = blue!40, shape = rectangle, rounded corners, "
                        + "minimum width = 1cm, font = \\sffamily]  " + "("
                        + Integer.toString(variable_counter + 1) + ") {" + subj + "}\n";
                latex_output += recursiveLoop(subj, relations, node_name);
            }
        }
        //            //Set final number of}
        int oc_1 = StringUtils.countMatches(latex_output + "};\n", "}");
        int oc_2 = StringUtils.countMatches(latex_output, "{");
        if (oc_2 > oc_1) {
            for (int i = 0; i < oc_2 - oc_1; i++)
                latex_output += "}";
        }
        String output = "";
        if (oc_1 > oc_2) {
            output = prefix + latex_output + ";\n";
        } else {
            output = prefix + latex_output + "};\n";
        }

        output += "\\begin{scope}[nodes = {draw = none}]\n";
        for (List<String> relation : relations) {
            String subj = node_name.get(relation.get(0));
            String obj = node_name.get(relation.get(1));
            String dep = deprel.get(relation.get(0));
            output += "\\path (" + subj + ")     -- (" + obj + ") node [near start, left]  {\\text{" + dep
                    + "}};\n";
        }
        output += "\\draw[densely dashed, rounded corners, thin];\n";
        output += "\\end{scope} \n";

        // \begin{scope}[nodes = {draw = none}]
        //    \path (3)     -- (0) node [near start, left]  {\text{prep}};
        //    \path (4)     -- (3) node [near start, right] {\text{nsubj}};
        //    \path (1)     -- (0) node [near start, right] {\text{cop}};
        //    \draw[densely dashed, rounded corners, thin];
        //  \end{scope}     

        return output + suffix;
    } else {
        return null;
    }
}

From source file:com.callidusrobotics.ConsoleColleague.java

public void splash(final String text, final boolean trimmed) {
    MessageBox box;/*from  w w w .  j a v a 2 s .c  o m*/
    if (trimmed) {
        final int newlines = StringUtils.countMatches(text, "\n");
        box = TextBoxBuilder.buildFancyMessageBox(null, newlines + 5, text.length() + 2 - newlines,
                boxForeground, boxBackground, Layout.CENTER);
    } else {
        box = TextBoxBuilder.buildFancyMessageBox(null, getHeight(), getWidth(), boxForeground, boxBackground,
                Layout.CENTER);
    }

    box.addLine(text, fontForeground, fontBackground, true);
    console.clear();
    box.draw(console);
    box.pause(console);
    console.clear();

    if (leftPane != null) {
        leftPane.draw(console);
    }

    drawDisplay();
}

From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java

/**
 * Use the given source pattern (e.g. "/var/lib/tomcat7/war/*") and
 * transform it into a grouping regular expression (e.g.
 * "/var/lib/tomcat7/war/(.*)"). You get exactly one group per '*'.
 * Currently only one '*' is supported. '?' are also not supported.
 *///from  www  .  java2 s.  c om
private static String transformSourcePatternToRegularExpression(String sourcePattern) {
    if (StringUtils.countMatches(sourcePattern, "?") > 0) {
        throw new IllegalArgumentException("No support for '?' yet.");
    }

    switch (StringUtils.countMatches(sourcePattern, "*")) {
    case 0:
        // No match, nothing to do
        return sourcePattern;
    case 1:
        // One match, we're fine
        return sourcePattern.replace(".", "\\.").replace("*", "(.*") + ")";
    default:
        // More than one match, crash and burn
        throw new IllegalArgumentException("No support for multiple '*' yet.");
    }
}

From source file:functionaltests.TagCommandsFunctTest.java

@Test
public void testJobOutput() throws Exception {
    typeLine("joboutput(" + jobId.longValue() + ")");

    runCli();/*from www  .  j a va 2  s.  co m*/

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