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:testing.test.java

private static String resolveExistUri(String basePath, String filePath) {
    int countSteps = StringUtils.countMatches(filePath, "../");
    String basePathParts[] = basePath.split("/");
    List<String> basePathPartsList = new ArrayList<String>(Arrays.asList(basePathParts));
    basePathPartsList.removeAll(Arrays.asList("", null));
    String newBasePath = "";
    int remainingParts = basePathPartsList.size() - 1 - countSteps;
    for (int i = 0; i <= remainingParts; i++) {
        newBasePath = newBasePath.concat("/").concat(basePathPartsList.get(i));
    }//from  w w  w  .  j a  va 2  s.  c om
    return newBasePath.concat(filePath.substring(filePath.lastIndexOf("../") + 2));
}

From source file:tk.vigaro.helix.listener.ListenerCommandHangman.java

@Override
public void onMessage(MessageEvent event) {
    if (event.getMessage().replace(" ", "").equals(Helix.botPrefix + Commands.letter)
            && Helix.hangman.containsKey(event.getChannel().getChannelId())) {
        event.getChannel().send().message("Letras utilizadas: " + Util.join("-", getHangman(event)[2]));
    } else if (event.getMessage().startsWith(Helix.botPrefix + Commands.letter)
            && event.getMessage().length() > Commands.letter.length() + 2) {
        if (Helix.hangman.containsKey(event.getChannel().getChannelId())) {
            String letter = event.getMessage().split(" ", 2)[1].substring(0, 1);
            String[] status = getHangman(event);
            if (!status[2].contains(letter)) {
                status[2] += letter;/*  w ww. ja v a2s  . c o  m*/
                if (status[0].contains(letter)) {
                    char[] chars = status[0].toCharArray();
                    char letterc = letter.charAt(0);
                    for (int i = 0; i < chars.length; i++) {
                        if (letterc == chars[i]) {
                            char[] s = status[1].toCharArray();
                            s[i] = letterc;
                            status[1] = new String(s);
                        }
                    }
                    if (!status[1].contains("_")) {
                        event.getChannel().send().message("Palavra completa! [" + status[1] + "]");
                        endGame(event);
                    } else {
                        event.getChannel().send().message("Letra encontrada! ["
                                + status[1].replaceAll(letter, Colors.BOLD + letter + Colors.BOLD) + "] "
                                + StringUtils.countMatches(status[1], "_") + " letras restantes");
                    }

                } else {
                    event.getChannel().send().message("Letra nao encontrada! " + Colors.BOLD + letter);
                }
            } else {
                event.getChannel().send().message("Letra ja foi utilizada! " + Colors.BOLD + letter);
            }
        }

    } else if (event.getMessage().startsWith(Helix.botPrefix + Commands.word)
            && event.getMessage().length() > Commands.word.length() + 2) {
        if (getHangman(event)[0].equals(event.getMessage().split(" ", 2)[1].replace(" ", ""))) {
            event.getChannel().send().message("Palavra correta! [" + getHangman(event)[0] + "]");
            endGame(event);
        } else {
            event.getChannel().send().message("Palavra incorreta! [" + getHangman(event)[1] + "]");
        }
    } else if (event.getMessage().startsWith(Helix.botPrefix + Commands.hangman)) {
        if (!Helix.hangman.containsKey(event.getChannel().getChannelId())) {
            String word = Helix.wordList.get(Helix.random.nextInt(Helix.wordList.size() - 1));
            String blank = "";
            for (int i = 0; i < word.length(); i++) {
                blank += word.charAt(i) == '-' ? "-" : "_";
            }
            Helix.hangman.put(event.getChannel().getChannelId(), new String[] { word, blank, "" });
            event.getChannel().send().message("O jogo da forca comecou! [" + getHangman(event)[1] + "] "
                    + StringUtils.countMatches(getHangman(event)[1], "_") + " letras");
        } else {
            event.getChannel().send().message("Um jogo ja esta em progresso! [" + getHangman(event)[1] + "] "
                    + StringUtils.countMatches(getHangman(event)[1], "_") + " letras restantes");
        }
    }

}

From source file:tk.wurst_client.gui.multiplayer.GuiServerFinder.java

/**
 * Called from the main game loop to update the screen.
 *///  www.ja v  a  2  s.co m
@Override
public void updateScreen() {
    ipBox.updateCursorCounter();
    ((GuiButton) buttonList.get(0)).enabled =
            // 1.1.1.1 has a length of 7
            ipBox.getText().trim().length() >= 7
                    // Must have dots
                    && ipBox.getText().contains(".")
                    // Must not have a port
                    && !ipBox.getText().contains(":")
                    // Must have three dots
                    && StringUtils.countMatches(ipBox.getText(), ".") == 3
                    // The first part must be an integer
                    && MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[0])
                    // And the second
                    && MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[1])
                    // And the third
                    && MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[2])
                    // And so on
                    && MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[3]) && !running
                    && MiscUtils.isInteger(maxThreadsBox.getText());
}

From source file:tk.wurst_client.gui.multiplayer.GuiServerFinder.java

/**
 * Draws the screen and all the components in it.
 *//*  w  w  w.j  ava  2 s  .  c  om*/
@Override
public void drawScreen(int par1, int par2, float par3) {
    drawDefaultBackground();
    drawCenteredString(fontRendererObj, "Server Finder", width / 2, 20, 16777215);
    drawCenteredString(fontRendererObj, "This will search for servers with similar IPs", width / 2, 40,
            10526880);
    drawCenteredString(fontRendererObj, "to the IP you type into the field below.", width / 2, 50, 10526880);
    drawCenteredString(fontRendererObj, "The servers it finds will be added to your server list.", width / 2,
            60, 10526880);
    drawString(fontRendererObj, "Numeric IP without port", width / 2 - 100, height / 4 + 24, 10526880);
    ipBox.drawTextBox();
    drawString(fontRendererObj, "Max. threads:", width / 2 - 100, height / 4 + 60, 10526880);
    maxThreadsBox.drawTextBox();
    if (!((GuiButton) buttonList.get(0)).enabled)
        if (ipBox.getText().length() == 0)
            drawCenteredString(fontRendererObj, "4IP field is empty!", width / 2, height / 4 + 73, 10526880);
        else if (ipBox.getText().contains(":"))
            drawCenteredString(fontRendererObj, "4Ports are not supported!", width / 2, height / 4 + 73,
                    10526880);
        else if (!MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[0]))
            drawCenteredString(fontRendererObj, "4Hostnames are not supported!", width / 2, height / 4 + 73,
                    10526880);
        else if (StringUtils.countMatches(ipBox.getText(), ".") >= 1
                && !MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[1]))
            drawCenteredString(fontRendererObj, "4Hostnames are not supported!", width / 2, height / 4 + 73,
                    10526880);
        else if (StringUtils.countMatches(ipBox.getText(), ".") >= 2
                && !MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[2]))
            drawCenteredString(fontRendererObj, "4Hostnames are not supported!", width / 2, height / 4 + 73,
                    10526880);
        else if (StringUtils.countMatches(ipBox.getText(), ".") >= 3
                && !MiscUtils.isInteger(ipBox.getText().split("\\.", -1)[3]))
            drawCenteredString(fontRendererObj, "4Hostnames are not supported!", width / 2, height / 4 + 73,
                    10526880);
        else if (StringUtils.countMatches(ipBox.getText(), ".") < 3)
            drawCenteredString(fontRendererObj, "4IP is too short!", width / 2, height / 4 + 73, 10526880);
        else if (StringUtils.countMatches(ipBox.getText(), ".") > 3)
            drawCenteredString(fontRendererObj, "4IP is too long!", width / 2, height / 4 + 73, 10526880);
        else if (!MiscUtils.isInteger(maxThreadsBox.getText()))
            drawCenteredString(fontRendererObj, "4Max. threads must be a number!", width / 2, height / 4 + 73,
                    10526880);
        else if (running)
            if (checked == 1024)
                drawCenteredString(fontRendererObj, "2Done!", width / 2, height / 4 + 73, 10526880);
            else
                drawCenteredString(fontRendererObj, "2Searching...", width / 2, height / 4 + 73, 10526880);
        else
            drawCenteredString(fontRendererObj, "4Unknown error! Bug?", width / 2, height / 4 + 73, 10526880);
    drawString(fontRendererObj, "Checked: " + checked + " / 1024", width / 2 - 100, height / 4 + 84, 10526880);
    drawString(fontRendererObj, "Working: " + working, width / 2 - 100, height / 4 + 94, 10526880);
    super.drawScreen(par1, par2, par3);
}

From source file:topology.ActorTopology.java

/**
 * Checks if an Actor is located on Level 1 on the Grid hierarchy. (/user/ActorSupervisor/Level_1/Level_2)
 *
 * @param actorPath/*from  www  .  j a va  2  s.c o m*/
 * @return True if Actor is located on Level 1.
 */
protected boolean isRootActor(String actorPath) {
    return StringUtils.countMatches(actorPath, "/") == 3;
}

From source file:ui.server.GetTables.java

/**
 * The GC Content for the nucleotide sequence
 * /* w  w  w.java  2  s. co m*/
 * @return the gc constant value
 */
public double getGCContent(String aSequence) {
    double g = StringUtils.countMatches(aSequence, "G") * 1.0;
    double c = StringUtils.countMatches(aSequence, "C") * 1.0;
    double t = StringUtils.countMatches(aSequence, "T") * 1.0;
    double u = StringUtils.countMatches(aSequence, "U") * 1.0;
    double a = StringUtils.countMatches(aSequence, "A") * 1.0;

    if (u == 0) {// if dna
        double q = a + t + g + c;
        double s = t / q;
        return s * 100;
    } else if (t == 0) {// if rna
        return ((g + c) / (a + g + u + c)) * 100;
    } else {
        return ((g + c) / (a + g + u + t + c)) * 100;
    }
}

From source file:varioustests.swingworkertests.SearchForWordWorker.java

@Override
protected Integer doInBackground() throws Exception {
    // The number of instances the word is found
    int matches = 0;

    /*//from  w  ww . j  a  v  a2 s . c o  m
     * List all text files under the given directory using the Apache IO library. This process cannot be
     * interrupted (stopped through cancellation). That is why we are checking right after the process whether
     * it was interrupted or not.
     */
    publish("Listing all text files under the directory: " + directory);
    final List<File> textFiles = new ArrayList<>(
            FileUtils.listFiles(directory, new SuffixFileFilter(".txt"), TrueFileFilter.TRUE));
    SearchForWordWorker.failIfInterrupted();
    publish("Found " + textFiles.size() + " text files under the directory: " + directory);

    for (int i = 0, size = textFiles.size(); i < size; i++) {
        /*
         * In order to respond to the cancellations, we need to check whether this thread (the worker thread)
         * was interrupted or not. If the thread was interrupted, then we simply throw an InterruptedException
         * to indicate that the worker thread was cancelled.
         */
        SearchForWordWorker.failIfInterrupted();

        // Update the status and indicate which file is being searched. 
        final File file = textFiles.get(i);
        publish("Searching file: " + file);

        /*
         * Read the file content into a string, and count the matches using the Apache common IO and Lang
         * libraries respectively.
         */
        final String text = FileUtils.readFileToString(file);
        matches += StringUtils.countMatches(text, word);

        // Update the progress
        setProgress((i + 1) * 100 / size);
    }

    // Return the number of matches found
    return matches;
}

From source file:VCF.Genotype.java

/**
 * Get a specified piece of data for this genotype.  Returns "." if field is
 * not present for this genotype./* ww  w .ja  va2s.  co m*/
 * @param name The format of the data to be retrieved (as a string)
 * @return The data
 * @throws VCF.Exceptions.VCFNoDataException If there is a no data for the
 * requested format
 */
public String getData(String name) throws VCFNoDataException {
    List<String> format = position.getFormat();
    int pos = format.indexOf(name);

    String info = geno.getInfo();
    if (pos == -1) {
        throw new VCFNoDataException("No data field called " + name);
    }

    if (StringUtils.countMatches(info, ':') < pos) {
        return ".";
    } else {
        int start;
        if (pos == 0) {
            start = 0;
        } else {
            start = StringUtils.ordinalIndexOf(info, ":", pos) + 1;
        }
        int end = StringUtils.ordinalIndexOf(info, ":", pos + 1);
        if (end == -1) {
            end = info.length();
        }

        return info.substring(start, end);

        //            Pattern p = Pattern.compile("(?:\\S+?:){" + pos + "}(\\S+?)(?::|$)");
        //            Matcher m = p.matcher(geno.getInfo());
        //            m.find();
        //            return m.group(1);
    }
}

From source file:visualization.GridD3Json.java

public static HashSet<String> getSupervisorChildren(ActorTopology topology) {
    HashSet<String> childrenSet = new HashSet<String>();
    for (String path : topology.getActorTopology().keySet()) {
        if (StringUtils.countMatches(path, "/") == 3)
            childrenSet.add(path.replace("/user/ActorSupervisor/", ""));
    }//from  ww  w.  ja  v a 2 s . co m
    return childrenSet;
}

From source file:wong.spance.html.ArrayTableGroupTest.java

@Test
public void testCss1() throws Exception {
    builder = new ArrayTableGroup(TableMeta.newMeta().addColumn("111").addColumn("222").addColumn("333"));
    Object[][] arr = new Object[][] { { "s0", "b2", "2" }, { "s0", "b2", "3" }, { "s1", "b2", "4" },
            { "s1", "b ", "5" }, { "s1", "bB 22--", "5" } };
    builder.apply(new SimpleDataStore(arr));
    assertEquals(builder.getTable().getBody().length, arr.length);

    builder.group(RowSpan.newRule().on(0), RowSpan.newRule().on(1));
    String html = builder.render(new DefaultModifiers().setAttribute("table", "class", "table-class")
            .setAttribute("table th", "class", "head").setAttribute("tbody tr", "style", "kkkk")
            .replace("tr:last-child td:nth-child(1)", "(\\d+)", "XXX$1ttt"));
    System.out.println(html);/*from  w  w w.j  av  a  2 s  .c  om*/

    assertArrayEquals("2 3 3".split(" "), StringUtils.substringsBetween(html, "rowspan=\"", "\""));

    assertEquals(1, StringUtils.countMatches(html, "class=\"table-class\""));
    assertEquals(3, StringUtils.countMatches(html, "class=\"head\""));
    assertEquals(5, StringUtils.countMatches(html, "style=\"kkk"));
    assertEquals(1, StringUtils.countMatches(html, "XXX22ttt"));
}