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:org.obsidian.test.TestAbstract.java

public <T> String buildConstructionStringFromType(Class<T> type, Constructor[] visitedConstructors) {

    //initialize construction String 
    String constructionString;//from  w  ww  .  j  a v a2 s .com

    //append equality method types
    appendEqualityMethodTypes(type);

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    //if class is abstract, replace with concrete substitution
    if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        type = Helpers.getConcreteSubstitution(type);
    }

    //type's simple name
    String name = type.getSimpleName();

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    if (Helpers.PRIMITIVE_CONSTRUCTIONS.get(name) != null) {
        //get construction from PRIMITIVE_CONSTRUCTIONS
        constructionString = Helpers.PRIMITIVE_CONSTRUCTIONS.get(name);
    } else if (type.isArray()) {
        int numberOfDimensions = StringUtils.countMatches(name, "[]");

        constructionString = name.replace("[]", "");

        for (int i = 0; i < numberOfDimensions; i++) {
            constructionString = constructionString + "[0]";
        }

        constructionString = "new " + constructionString;

    } else if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        constructionString = "null";
    } else if (type.getConstructors().length == 0) {
        constructionString = "null";
    } else {
        //not visited constructors
        ArrayList<Constructor> NVC = Helpers.notVisitedConstructors(type.getConstructors(),
                visitedConstructors);

        Constructor constructor = Helpers.getConstructorWithLeastParametersFromList(NVC);

        if (NVC.isEmpty()) {
            constructionString = "null";
        } else if (constructor.getExceptionTypes().length > 0) {
            constructionString = "null";
        } else {

            visitedConstructors = Helpers.addConstructor(visitedConstructors, constructor);
            constructionString = "new " + name + "(";
            Class[] parameters = constructor.getParameterTypes();
            for (int i = 0; i < parameters.length; i++) {
                constructionString = constructionString
                        + buildConstructionStringFromType(parameters[i], visitedConstructors) + ",";
            }
            if (parameters.length != 0) {
                constructionString = constructionString.substring(0, constructionString.length() - 1);
            }
            constructionString = constructionString + ")";
        }
    }

    //this will prevent ambiguity in constructors with parmeter that 
    //cannot be constructed
    if (constructionString.contains("null")) {
        constructionString = "null";
    }

    return constructionString;
}

From source file:org.opencb.commons.datastore.solr.FacetQueryParser.java

/**
 * Parse a facet and return the map containing the facet fields.
 *
 * @param facet facet string/*  w  w  w . j a v a 2 s .  co  m*/
 * @return the map containing the facet fields.
 */
private Map<String, Object> parseFacet(String facet) throws Exception {
    Map<String, Object> outputMap = new HashMap<>();
    if (facet.contains(AGGREGATION_IDENTIFIER)) {
        // Validate function
        for (String function : AGGREGATION_FUNCTIONS) {
            if (facet.startsWith(function)) {
                return null;
            }
        }
        throw new Exception("Invalid aggregation function: " + facet);
    } else if (facet.contains(RANGE_IDENTIFIER)) {
        // Deal with ranges...
        int numMatches = StringUtils.countMatches(facet, ':');
        if (numMatches > 1) {
            // Special case: facet with type "query" and with a nested "range"
            String[] split = facet.split(":");
            Map<String, Object> rangeMap = new HashMap<>();
            StringBuilder filter = new StringBuilder(split[3]);
            for (int i = 4; i < split.length; i++) {
                filter.append(":").append(split[i]);
            }

            String[] range = split[0].replace("[", ":").replace("..", ":").replace("]", "").split(":");
            rangeMap.put("field", range[0]);
            rangeMap.put("type", "range");
            rangeMap.put("start", parseNumber(range[1]));
            rangeMap.put("end", parseNumber(range[2]));
            rangeMap.put("step", parseNumber(split[1]));

            String[] nested = split[2].split(LABEL_SEPARATOR);
            outputMap.put("field", nested[0]);
            outputMap.put("type", "query");
            outputMap.put("q", filter.toString());
            if (nested.length > 1) {
                Map<String, Object> nestedMap = new HashMap<>();
                nestedMap.put("field", nested[1]);
                nestedMap.put("type", "terms");
                Map<String, Object> auxMap1 = new HashMap<>();
                auxMap1.put(range[0], rangeMap);
                nestedMap.put("facet", auxMap1);

                Map<String, Object> auxMap2 = new HashMap<>();
                auxMap2.put(nested[1], nestedMap);
                outputMap.put("facet", auxMap2);
            } else {
                Map<String, Object> auxMap1 = new HashMap<>();
                auxMap1.put(range[0], rangeMap);
                outputMap.put("facet", auxMap1);
            }
        } else {
            String[] split = facet.replace("[", ":").replace("..", ":").replace("]", "").split(":");
            outputMap.put("field", split[0]);
            outputMap.put("start", parseNumber(split[1]));
            outputMap.put("end", parseNumber(split[2]));
            outputMap.put("step", parseNumber(split[3]));
        }
    } else {
        // Categorical...
        Matcher matcher = CATEGORICAL_PATTERN.matcher(facet);
        if (matcher.find()) {
            boolean isQuery = false;
            outputMap.put("field", matcher.group(1));
            String include = matcher.group(2);
            if (StringUtils.isNotEmpty(include)) {
                include = include.replace("]", "").replace("[", "");
                if (include.endsWith("*")) {
                    outputMap.put("prefix", include.substring(0, include.indexOf("*")));
                } else {
                    isQuery = true;
                    List<String> filters = new ArrayList<>();
                    for (String value : include.split(INCLUDE_SEPARATOR)) {
                        filters.add(matcher.group(1) + ":" + value);
                    }
                    outputMap.put("q", StringUtils.join(filters, " OR "));
                }
            }

            if (isQuery) {
                outputMap.put("type", "query");

                Map<String, Object> auxMap = new HashMap<>();
                auxMap.put("field", matcher.group(1));
                auxMap.put("type", "terms");
                setTermLimit(matcher.group(3), auxMap);

                Map<String, Object> tmpMap = new HashMap<>();
                tmpMap.put(matcher.group(1), auxMap);

                outputMap.put("facet", tmpMap);
            } else {
                outputMap.put("type", "terms");
                setTermLimit(matcher.group(3), outputMap);
            }
        } else {
            throw new Exception("Invalid categorical facet: " + facet);
        }
    }

    return outputMap;
}

From source file:org.opendaylight.controller.config.persist.storage.file.FileStorageAdapter.java

@Override
public void persistConfig(ConfigSnapshotHolder holder) throws IOException {
    Preconditions.checkNotNull(storage, "Storage file is null");

    String content = Files.toString(storage, ENCODING);
    if (numberOfStoredBackups == Integer.MAX_VALUE) {
        resetLastConfig(content);//from  w w w . j  a v  a 2 s.c  o m
        persistLastConfig(holder);
    } else {
        if (numberOfStoredBackups == 1) {
            Files.write("", storage, ENCODING);
            persistLastConfig(holder);
        } else {
            int count = StringUtils.countMatches(content, SEPARATOR_S);
            if ((count + 1) < numberOfStoredBackups) {
                resetLastConfig(content);
                persistLastConfig(holder);
            } else {
                String contentSubString = StringUtils.substringBefore(content, SEPARATOR_E);
                contentSubString = contentSubString.concat(SEPARATOR_E_PURE);
                content = StringUtils.substringAfter(content, contentSubString);
                resetLastConfig(content);
                persistLastConfig(holder);
            }
        }
    }
}

From source file:org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil.java

public static String formatJavaSource(final String input) {
    Iterable<String> split = Splitter.on("\n").trimResults().split(input);

    int basicIndent = 4;
    StringBuilder sb = new StringBuilder();
    int indents = 0, empty = 0;
    for (String line : split) {
        indents -= StringUtils.countMatches(line, "}");
        if (indents < 0) {
            indents = 0;//from  ww w. j  av a 2 s. c  o  m
        }
        if (!line.isEmpty()) {
            sb.append(Strings.repeat(" ", basicIndent * indents));
            sb.append(line);
            sb.append("\n");
            empty = 0;
        } else {
            empty++; // one empty line is allowed
            if (empty < 2) {
                sb.append("\n");
            }
        }
        indents += StringUtils.countMatches(line, "{");
    }
    return ensureEndsWithSingleNewLine(sb.toString());
}

From source file:org.opendaylight.controller.netconf.confignetconfconnector.NetconfMappingTest.java

License:asdf

private void assertCorrectRefNamesForDependencies(Element config) {
    NodeList modulesList = config.getElementsByTagName("modules");
    assertEquals(1, modulesList.getLength());

    Element modules = (Element) modulesList.item(0);

    String trimmedModules = XmlUtil.toString(modules).replaceAll("\\s", "");
    int defaultRefNameCount = StringUtils.countMatches(trimmedModules, "ref_dep2");
    int userRefNameCount = StringUtils.countMatches(trimmedModules, "ref_dep_user_two");

    assertEquals(0, defaultRefNameCount);
    assertEquals(2, userRefNameCount);/* w w w . j a  v a 2s  .  c  o m*/
}

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
    final List<IpAddress> lstIpAddress = new ArrayList<>();
    if (StringUtils.isBlank(excludeIpFilter)) {
        return lstIpAddress;
    }/*from   w ww.  j a v a 2  s .co  m*/
    final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
    for (String ip : arrIps) {
        if (StringUtils.countMatches(ip, "-") == 1) {
            final String[] arrIpRange = StringUtils.split(ip, '-');
            String strStartIp = StringUtils.trim(arrIpRange[0]);
            String strEndIp = StringUtils.trim(arrIpRange[1]);
            Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
                    "Invalid exclude IP filter: invalid IP address value " + strStartIp);
            Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
                    "Invalid exclude IP filter: invalid IP address value " + strEndIp);
            Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
                    "Invalid exclude IP filter: IP address [" + strStartIp + "] not in subnet range "
                            + subnetInfo.getCidrSignature());
            Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
                    "Invalid exclude IP filter: IP address [" + strEndIp + "] not in subnet range "
                            + subnetInfo.getCidrSignature());
            int startIp = subnetInfo.asInteger(strStartIp);
            int endIp = subnetInfo.asInteger(strEndIp);

            Preconditions.checkArgument(startIp < endIp,
                    "Invalid exclude IP filter: Invalid range [" + ip + "] ");
            for (int iter = startIp; iter <= endIp; iter++) {
                String ipAddress = ipFormat(toIpArray(iter));
                validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
            }
        } else {
            validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
        }
    }
    return lstIpAddress;
}

From source file:org.opendaylight.groupbasedpolicy.neutron.ovsdb.util.InventoryHelper.java

/**
 * Construct a String that can be used to create a {@link NodeId}.
 * The String is constructed by getting the Datapath ID from the OVSDB bridge
 * augmentation, converting that to a Long, and prepending it with the
 * "openflow:" prefix./*from   w  w  w  . j a va 2  s .co m*/
 *
 * @param ovsdbBridge The {@link OvsdbBridgeAugmentation}
 * @param ovsdbTpIid the {@link OvsdbTerminationPointAugmentation}
 * @param dataBroker the {@link DataBroker}
 * @return String representation of the Inventory NodeId, null if it fails
 */
public static String getInventoryNodeIdString(OvsdbBridgeAugmentation ovsdbBridge,
        InstanceIdentifier<OvsdbTerminationPointAugmentation> ovsdbTpIid, DataBroker dataBroker) {
    DatapathId dpid = ovsdbBridge.getDatapathId();
    if (dpid == null) {
        OvsdbBridgeAugmentation bridgeData = getOvsdbBridgeFromTerminationPoint(ovsdbTpIid, dataBroker);
        dpid = bridgeData.getDatapathId();
        if (dpid == null) {
            LOG.error("No Data Path ID for OVSDB Bridge {}", ovsdbBridge);
            return null;
        }
    }
    Long macLong = getLongFromDpid(ovsdbBridge.getDatapathId().getValue());
    String nodeIdString = "openflow:" + String.valueOf(macLong);
    if (StringUtils.countMatches(nodeIdString, ":") != 1) {
        LOG.error("{} is not correct format for NodeId.", nodeIdString);
        return null;
    }
    return nodeIdString;
}

From source file:org.opendaylight.groupbasedpolicy.neutron.ovsdb.util.InventoryHelper.java

/**
 * Construct a string that can be used to create a
 * {@link org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId}.
 * The String is constructed by first getting the inventory Node ID string, and then
 * adding the port number obtained by the OVSDB augmentation.
 *
 * @param inventoryNodeId The string representation of the Inventory NodeId
 * @param ovsdbTp The {@link OvsdbTerminationPointAugmentation}
 * @param tpIid the InstanceIdentifier for OvsdbTerminationPointAugmentation
 * @param dataBroker the {@link DataBroker}
 * @return String representation of the Inventory NodeConnectorId, null if it fails
 *///from ww w  .j  a  v a  2  s .c  o m
public static String getInventoryNodeConnectorIdString(String inventoryNodeId,
        OvsdbTerminationPointAugmentation ovsdbTp, InstanceIdentifier<OvsdbTerminationPointAugmentation> tpIid,
        DataBroker dataBroker) {
    Long ofport = null;
    if (ovsdbTp.getOfport() != null && ovsdbTp.getOfport() > MAX_OF_PORT) {
        LOG.debug("Invalid OpenFlow port {} for {}", ovsdbTp.getOfport(), ovsdbTp);
        return null;
    }
    if (ovsdbTp.getOfport() == null) {
        OvsdbTerminationPointAugmentation readOvsdbTp = getOvsdbTerminationPoint(tpIid, dataBroker);
        if (readOvsdbTp == null || readOvsdbTp.getOfport() == null || readOvsdbTp.getOfport() > MAX_OF_PORT) {
            LOG.debug("Couldn't get OpenFlow port for {}", ovsdbTp);
            return null;
        }
        ofport = readOvsdbTp.getOfport();
    } else {
        ofport = ovsdbTp.getOfport();
    }
    String nodeConnectorIdString = inventoryNodeId + ":" + String.valueOf(ofport);

    if (StringUtils.countMatches(nodeConnectorIdString, ":") != 2) {
        LOG.error("{} is not correct format for NodeConnectorId.", nodeConnectorIdString);
        return null;
    }
    return nodeConnectorIdString;
}

From source file:org.opendaylight.vpnservice.itm.impl.ItmUtils.java

public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
    final List<IpAddress> lstIpAddress = new ArrayList<>();
    if (StringUtils.isBlank(excludeIpFilter)) {
        return lstIpAddress;
    }//w  ww .  jav a  2  s . co  m
    final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
    for (String ip : arrIps) {
        if (StringUtils.countMatches(ip, "-") == 1) {
            final String[] arrIpRange = StringUtils.split(ip, '-');
            String strStartIp = StringUtils.trim(arrIpRange[0]);
            String strEndIp = StringUtils.trim(arrIpRange[1]);
            Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
                    new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strStartIp)
                            .toString());
            Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
                    new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strEndIp)
                            .toString());
            Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
                    new StringBuilder("Invalid exclude IP filter: IP address [").append(strStartIp)
                            .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
            Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
                    new StringBuilder("Invalid exclude IP filter: IP address [").append(strEndIp)
                            .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
            int startIp = subnetInfo.asInteger(strStartIp);
            int endIp = subnetInfo.asInteger(strEndIp);

            Preconditions.checkArgument(startIp < endIp,
                    new StringBuilder("Invalid exclude IP filter: Invalid range [").append(ip).append("] ")
                            .toString());
            for (int i = startIp; i <= endIp; i++) {
                String ipAddress = ipFormat(toIpArray(i));
                validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
            }
        } else {
            validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
        }
    }
    return lstIpAddress;
}

From source file:org.openecomp.sdc.common.config.AbsEcompErrorManager.java

private EcompErrorInfo setDescriptionParams(EcompErrorInfo ecompErrorInfo, String ecompErrorName,
        String... descriptionParams) {
    String description = ecompErrorInfo.getDescription();
    // Counting number of params in description
    int countMatches = StringUtils.countMatches(description, PARAM_STR);
    // Catching cases when there are more params passed than there are in
    // the description (formatter will ignore extra params and won't throw
    // exception)
    if (countMatches != descriptionParams.length) {
        return getErrorInfoForDescriptionParamsMismatch(ecompErrorName);
    }/*from www .j a va  2  s.c o m*/
    // Setting params of the description if any
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb, Locale.US);
    try {
        formatter.format(description, (Object[]) descriptionParams).toString();
        ecompErrorInfo.setDescription(formatter.toString());
    } catch (IllegalFormatException e) {
        // Number of passed params doesn't match number of params in config
        // file
        return getErrorInfoForDescriptionParamsMismatch(ecompErrorName);
    } finally {
        formatter.close();
    }
    return ecompErrorInfo;
}