Example usage for org.apache.commons.lang StringUtils countMatches

List of usage examples for org.apache.commons.lang StringUtils countMatches

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils countMatches.

Prototype

public static int countMatches(String str, String sub) 

Source Link

Document

Counts how many times the substring appears in the larger String.

Usage

From source file:org.opennms.netmgt.provision.service.dns.DnsRequisitionUrlConnection.java

/**
 * Foreign Source should be the second path entity, if it exists, otherwise it is
 * set to the value of the zone.//from w ww .  j  a  va  2s . c om
 *
 *   dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>>
 *
 * @param url a {@link java.net.URL} object.
 * @return a {@link java.lang.String} object.
 */
protected static String parseForeignSource(URL url) {

    String path = url.getPath();

    path = StringUtils.removeStart(path, "/");
    path = StringUtils.removeEnd(path, "/");

    String foreignSource = path;

    if (path != null && StringUtils.countMatches(path, "/") == 1) {
        String[] paths = path.split("/");
        foreignSource = paths[1];
    }

    return foreignSource;
}

From source file:org.opennms.test.system.api.NewTestEnvironment.java

public boolean canMinionConnectToOpenNMS(InetSocketAddress sshAddr) {
    try (final SshClient sshClient = new SshClient(sshAddr, "admin", "admin")) {
        // Issue the 'minion:ping' command
        PrintStream pipe = sshClient.openShell();
        pipe.println("minion:ping");
        pipe.println("logout");

        await().atMost(2, MINUTES).until(sshClient.isShellClosedCallable());

        // Grab the output
        String shellOutput = sshClient.getStdout();
        LOG.info("minion:ping output: {}", shellOutput);

        // We're expecting output of the form
        // admin@minion> minion:ping
        // Connecting to ReST...
        // OK/*from  w w w.  j  a v  a2 s .c  om*/
        // Connecting to Broker...
        // OK
        //
        // So it is sufficient to check for 2 'OK's
        return StringUtils.countMatches(shellOutput, "OK") >= 2;
    } catch (Exception e) {
        LOG.error("Failed to reach the Minion from OpenNMS.", e);
    }
    return false;
}

From source file:org.opennms.web.rest.GroupRestServiceTest.java

@Test
public void testUsers() throws Exception {
    createGroup("deleteMe");

    // test add user which does not exist to group
    sendRequest(PUT, "/groups/deleteMe/users/totallyUniqueUser", 400);

    // create user first
    createUser("totallyUniqueUser");

    LOG.debug("add totallyUniqueUser to deleteMe");
    // add user to group
    sendRequest(PUT, "/groups/deleteMe/users/totallyUniqueUser", 303);
    String xml = sendRequest(GET, "/groups/deleteMe", 200);
    assertTrue(xml.contains("totallyUniqueUser"));

    LOG.debug("add totallyUniqueUser to deleteMe a second time");
    // add user to group twice
    sendRequest(PUT, "/groups/deleteMe/users/totallyUniqueUser", 400); // already added

    LOG.debug("get the list of users");
    xml = sendRequest(GET, "/groups/deleteMe/users", 200);
    assertEquals(1, StringUtils.countMatches(xml, "totallyUniqueUser"));
    assertEquals(1, JaxbUtils.unmarshal(OnmsUserList.class, xml).size());

    LOG.debug("get the totallyUniqueUser");
    //get specific user
    xml = sendRequest(GET, "/groups/deleteMe/users/totallyUniqueUser", 200);
    assertNotNull(xml);/*w ww  .jav a  2  s. c  o m*/
    OnmsUser user = JaxbUtils.unmarshal(OnmsUser.class, xml);
    assertNotNull(user);
    assertEquals("totallyUniqueUser", user.getUsername());

    LOG.debug("delete temporary users");
    // clean up
    sendRequest(DELETE, "/groups/deleteMe/users/totallyBogusUser", 400);
    sendRequest(DELETE, "/groups/deleteMe/users/totallyUniqueUser", 200);
    xml = sendRequest(GET, "/groups/deleteMe", 200);
    assertFalse(xml.contains("totallyUniqueUser"));

    LOG.debug("check that users were deleted");
    // list all users of group
    xml = sendRequest(GET, "/groups/deleteMe/users", 200);
    assertNotNull(xml);
    assertEquals(0, JaxbUtils.unmarshal(OnmsUserList.class, xml).size());

    LOG.debug("check specific get when no users");
    // get specific user
    sendRequest(GET, "/groups/deleteMe/users/totallyUniqueUser", 404);
}

From source file:org.opennms.web.rest.v1.GroupRestServiceIT.java

@Test
public void testUsers() throws Exception {
    createGroup("deleteMe");

    // test add user which does not exist to group
    sendRequest(PUT, "/groups/deleteMe/users/totallyUniqueUser", 400);

    // create user first
    createUser("totallyUniqueUser");

    LOG.debug("add totallyUniqueUser to deleteMe");
    // add user to group
    sendRequest(PUT, "/groups/deleteMe/users/totallyUniqueUser", 204);
    String xml = sendRequest(GET, "/groups/deleteMe", 200);
    assertTrue(xml.contains("totallyUniqueUser"));

    LOG.debug("add totallyUniqueUser to deleteMe a second time");
    // add user to group twice
    sendRequest(PUT, "/groups/deleteMe/users/totallyUniqueUser", 400); // already added

    LOG.debug("get the list of users");
    xml = sendRequest(GET, "/groups/deleteMe/users", 200);
    assertEquals(1, StringUtils.countMatches(xml, "totallyUniqueUser"));
    assertEquals(1, JaxbUtils.unmarshal(OnmsUserList.class, xml).size());

    LOG.debug("get the totallyUniqueUser");
    //get specific user
    xml = sendRequest(GET, "/groups/deleteMe/users/totallyUniqueUser", 200);
    assertNotNull(xml);//  ww w. ja  va2s.  co  m
    OnmsUser user = JaxbUtils.unmarshal(OnmsUser.class, xml);
    assertNotNull(user);
    assertEquals("totallyUniqueUser", user.getUsername());

    LOG.debug("delete temporary users");
    // clean up
    sendRequest(DELETE, "/groups/deleteMe/users/totallyBogusUser", 400);
    sendRequest(DELETE, "/groups/deleteMe/users/totallyUniqueUser", 204);
    xml = sendRequest(GET, "/groups/deleteMe", 200);
    assertFalse(xml.contains("totallyUniqueUser"));

    LOG.debug("check that users were deleted");
    // list all users of group
    xml = sendRequest(GET, "/groups/deleteMe/users", 200);
    assertNotNull(xml);
    assertEquals(0, JaxbUtils.unmarshal(OnmsUserList.class, xml).size());

    LOG.debug("check specific get when no users");
    // get specific user
    sendRequest(GET, "/groups/deleteMe/users/totallyUniqueUser", 404);
}

From source file:org.openo.sdnhub.overlayvpndriver.common.util.CheckIpV6Util.java

private static boolean checkIpIllegalChar(String ip) {
    HashSet<String> validChar = new HashSet<>(Arrays.asList("//", "..", ":::"));

    if (checkStringContainItemFromSet(ip, validChar) || StringUtils.countMatches(ip, "::") > 1
            || (StringUtils.countMatches(ip, "/") > 1 && ip.endsWith("::"))) {
        LOGGER.error("checkIpIllegalChar ip is invalid.");
        return false;
    } else {//from   w  ww  . j a  v  a  2 s. c o  m
        String regex = "[0-9a-f: ]*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(ip.toLowerCase(Locale.getDefault()));
        return matcher.matches();
    }
}

From source file:org.openscore.lang.cli.services.SyncTriggerEventListener.java

@Override
public synchronized void onEvent(ScoreEvent scoreEvent) throws InterruptedException {
    @SuppressWarnings("unchecked")
    Map<String, Serializable> data = (Map<String, Serializable>) scoreEvent.getData();
    switch (scoreEvent.getEventType()) {
    case EventConstants.SCORE_FINISHED_EVENT:
        flowFinished.set(true);/*from w  ww.ja va  2s.c  o m*/
        break;
    case EventConstants.SCORE_ERROR_EVENT:
        errorMessage.set(SCORE_ERROR_EVENT_MSG + data.get(EventConstants.SCORE_ERROR_LOG_MSG) + " , "
                + data.get(EventConstants.SCORE_ERROR_MSG));
        break;
    case EventConstants.SCORE_FAILURE_EVENT:
        printWithColor(Ansi.Color.RED, FLOW_FINISHED_WITH_FAILURE_MSG);
        flowFinished.set(true);
        break;
    case ScoreLangConstants.SLANG_EXECUTION_EXCEPTION:
        errorMessage.set(SLANG_STEP_ERROR_MSG + data.get(EXCEPTION));
        break;
    case ScoreLangConstants.EVENT_INPUT_END:
        String taskName = (String) data.get(LanguageEventData.levelName.TASK_NAME.name());
        if (StringUtils.isNotEmpty(taskName)) {
            String path = (String) data.get(LanguageEventData.PATH);
            int matches = StringUtils.countMatches(path, ExecutionPath.PATH_SEPARATOR);
            String prefix = StringUtils.repeat(TASK_PATH_PREFIX, matches);
            printWithColor(Ansi.Color.YELLOW, prefix + taskName);
        }
        break;
    case ScoreLangConstants.EVENT_OUTPUT_END:
        Map<String, Serializable> outputs = extractOutputs(data);

        for (String key : outputs.keySet()) {
            printWithColor(Ansi.Color.WHITE, "- " + key + " = " + outputs.get(key));
        }
        break;

    case EVENT_EXECUTION_FINISHED:
        flowFinished.set(true);
        printFinishEvent(data);
        break;
    }
}

From source file:org.opentestsystem.authoring.testauth.publish.PublisherUtil.java

protected static Identifier buildIdentifierPrim(final String name, final String label, final String version) {
    String xmlLabel = StringEscapeUtils.escapeXml(label);
    final List<String> fields = Lists
            .newArrayList(Iterables.filter(Lists.newArrayList(StringUtils.trimToNull(name),
                    StringUtils.trimToNull(xmlLabel), StringUtils.trimToNull(version)), Predicates.notNull()));

    if (StringUtils.countMatches(name, "-") == 2) {
        String id = StringUtils.substringAfter(name, "-");
        return new Identifier(id, name, xmlLabel, version);
    }/* ww  w. j  a  v  a2 s.c om*/
    return new Identifier(StringUtils.join(fields.toArray(), "-"), name, xmlLabel, version);
}

From source file:org.opentestsystem.authoring.testitembank.persistence.ItemRepositoryImpl.java

@Override
public List<Item> findItemsByTenantIdAndItemBankAndIdentifierIn(String tenantId, String itemBank,
        List<String> identifierList) {
    final Query query = new Query();
    query.addCriteria(Criteria.where("tenantId").is(tenantId));
    query.addCriteria(Criteria.where("itemBank").is(itemBank));
    // Note that we expect here identifiers  to be structured as, for example,  item-200-1234 or stim-187-345
    if (identifierList.isEmpty() == false && StringUtils.countMatches(identifierList.get(0), "-") == 2) {
        query.addCriteria(Criteria.where("identifier").in(identifierList));
    } else/*  w w  w.  j ava 2  s  .c  om*/
        query.addCriteria(Criteria.where("allIncludedMetatdata.Identifier").in(identifierList));
    return this.mongoTemplate.find(query, Item.class);
}

From source file:org.opentestsystem.delivery.AccValidator.handlers.ValidationHandler.java

private Boolean validateAccommodationCodes(String code) {
    Boolean isValid = true;/* www. j a  v a2s.  c o m*/
    if (checkWhiteSpaces(code)) {
        isValid = false;
    } else {

        List<String> specialAllowedCharacters = new ArrayList<String>();
        specialAllowedCharacters.add("&amp;");
        specialAllowedCharacters.add("&apos;");
        specialAllowedCharacters.add("&gt;");
        specialAllowedCharacters.add("&lt;");
        specialAllowedCharacters.add("&quot;");
        if (code.contains(",")) {
            isValid = false;
        } else if (code.contains(";")) {
            for (String test : specialAllowedCharacters) {
                if (StringUtils.countMatches(code, ";") > StringUtils.countMatches(code, test)) {
                    isValid = false;
                    break;
                }
            }
        }
    }
    return isValid;
}

From source file:org.openvpms.web.component.im.archetype.AbstractArchetypeHandlers.java

/**
 * Finds the most specific wildcarded short name from a collection of
 * wildcarded short names that matches the supplied short names.
 *
 * @param shortNames the short names//from  w w  w . j a v a2 s.  c om
 * @param wildcards  the wildcarded short names
 * @return the most specific short name, or <code>null</code> if none
 *         can be found
 */
protected String getShortName(String[] shortNames, Collection<String> wildcards) {
    String match = null;
    int bestDotCount = -1; // more dots in a short name, the more specific
    int bestWildCardCount = -1; // less wildcards, the more specific
    int bestMatchCount = -1; // fewer matches, the more specific
    for (String wildcard : wildcards) {
        boolean found = true;
        for (String shortName : shortNames) {
            if (!TypeHelper.matches(shortName, wildcard)) {
                found = false;
                break;
            }
        }
        if (found) {
            if (match == null) {
                match = wildcard;
                bestDotCount = StringUtils.countMatches(wildcard, ".");
                bestWildCardCount = StringUtils.countMatches(wildcard, "*");
                String[] matches = DescriptorHelper.getShortNames(wildcard);
                bestMatchCount = matches.length;
            } else {
                int dotCount = StringUtils.countMatches(wildcard, ".");
                int wildcardCount = StringUtils.countMatches(wildcard, "*");
                if (dotCount > bestDotCount
                        || (dotCount == bestDotCount && wildcardCount < bestWildCardCount)) {
                    bestDotCount = dotCount;
                    bestWildCardCount = wildcardCount;
                    match = wildcard;
                } else {
                    String[] wildcardMatches = DescriptorHelper.getShortNames(wildcard);
                    int matchCount = wildcardMatches.length;
                    if (matchCount < bestMatchCount) {
                        bestMatchCount = matchCount;
                        match = wildcard;
                    }
                }
            }
        }
    }
    return match;
}