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:net.bitjump.launchme.utils.FileConfig.java

private String replace(String line, YamlConfiguration newFile, YamlConfiguration oldFile) {
    String resul = line;//from  w  ww  .  jav a2 s  .  c  o m

    for (String value : newFile.getKeys(true)) {
        if (value.equals("version")) // Este parametro no se toca
        {
            continue;
        }

        String cValue = value;
        String spaces = ""; // Estilo

        if (value.contains(".")) {
            String[] vals = value.split("\\.");
            cValue = vals[vals.length - 1];

            int i = 0;
            while (i < StringUtils.countMatches(value, ".")) {
                spaces += "    "; // Style format
                i++;
            }
        }

        if (line.contains(cValue + ":")) {
            Object v = null;
            // Previous structure
            if (oldFile.contains(before + "." + cValue)) {
                v = oldFile.get(before + "." + cValue);
            } else if (newFile.contains(before + "." + cValue)) {
                v = newFile.get(before + "." + cValue);
                // New structure
            } else if (oldFile.contains(value)) {
                v = oldFile.get(value);
            } else {
                v = newFile.get(value);
            }

            resul = spaces + cValue + ":";

            if (v instanceof List) {
                List<Object> vs = (List<Object>) v;
                for (Object v1 : vs) {
                    String val = getFilteredString(v1.toString());
                    resul += System.lineSeparator() + spaces + "- " + val;
                }
            } else if (!(v instanceof MemorySection)) {
                resul += " " + getFilteredString(v.toString());
            } else if (v instanceof MemorySection) {
                before = value;
            }

            resul += System.lineSeparator();
            break;
        }
    }

    return (resul.equals(line) ? resul + System.lineSeparator() : resul);
}

From source file:com.kalessil.phpStorm.phpInspectionsEA.inspectors.apiUsage.PrintfScanfArgumentsInspector.java

@Override
@NotNull//from  w  ww  .ja va2 s.  c o m
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {
        @Override
        public void visitPhpFunctionCall(@NotNull FunctionReference reference) {
            final String functionName = reference.getName();
            if (functionName == null || !functions.containsKey(functionName)) {
                return;
            }

            /* resolve needed parameter */
            final int neededPosition = functions.get(functionName);
            final int minimumArgumentsForAnalysis = neededPosition + 1;
            StringLiteralExpression pattern = null;
            final PsiElement[] params = reference.getParameters();
            if (params.length >= minimumArgumentsForAnalysis) {
                pattern = ExpressionSemanticUtil.resolveAsStringLiteral(params[neededPosition]);
            }
            /* not available */
            if (null == pattern) {
                return;
            }

            final String content = pattern.getContents().trim();
            if (!content.isEmpty()) {
                /* find valid placeholders and extract positions specifiers as well */
                int countWithoutPositionSpecifier = 0;
                int maxPositionSpecifier = 0;
                int countParsedAll = 0;

                /* do normalization: %%, inline variables */
                final String contentAdapted = content.replace("%%", "");
                final String contentNoVars = contentAdapted.replaceAll("\\$\\{?\\$?[a-zA-Z0-9]+\\}?", "");
                if (contentAdapted.length() != contentNoVars.length()) {
                    return;
                }

                final Matcher regexMatcher = regexPlaceHolders.matcher(contentAdapted);
                while (regexMatcher.find()) {
                    ++countParsedAll;

                    if (null != regexMatcher.group(2)) {
                        maxPositionSpecifier = Math.max(maxPositionSpecifier,
                                Integer.parseInt(regexMatcher.group(2)));
                        continue;
                    }

                    ++countWithoutPositionSpecifier;
                }
                final int expectedParametersCount = minimumArgumentsForAnalysis
                        + Math.max(countWithoutPositionSpecifier, maxPositionSpecifier);

                /* check for pattern validity */
                final int parametersInPattern = StringUtils.countMatches(content.replace("%%", ""), "%");
                if (countParsedAll != parametersInPattern) {
                    holder.registerProblem(params[neededPosition], messagePattern,
                            ProblemHighlightType.GENERIC_ERROR);
                    return;
                }

                /* check for arguments matching */
                if (expectedParametersCount != params.length) {
                    /* fscanf/sscanf will also return parsed values as an array if no values containers provided */
                    if (2 == params.length) {
                        final boolean returnsArray = functionName.equals("fscanf")
                                || functionName.equals("sscanf");
                        final PsiElement parent = returnsArray ? reference.getParent() : null;
                        final PsiElement grandParent = parent == null ? null : parent.getParent();
                        if (returnsArray && parent != null) {
                            /* false-positive: dispatching/deconstructing into containers */
                            if (parent instanceof AssignmentExpression
                                    || grandParent instanceof AssignmentExpression) {
                                return;
                            }
                            /* false-positive: dispatching into calls */
                            else if (parent instanceof ParameterList
                                    && grandParent instanceof FunctionReference) {
                                return;
                            }
                        }
                    }

                    /* false-positives: variadic */
                    if (OpenapiTypesUtil.is(params[params.length - 1].getPrevSibling(),
                            PhpTokenTypes.opVARIADIC)) {
                        return;
                    }

                    final String message = messageParameters.replace("%c%",
                            String.valueOf(expectedParametersCount));
                    holder.registerProblem(reference, message, ProblemHighlightType.GENERIC_ERROR);
                }
            }
        }
    };
}

From source file:com.runstate.util.XmlW.java

static public int getIndexClosingTag(String tag, String text, int start) {
    String open = "<" + tag;
    String close = "</" + tag + ">";
    //        System.err.println("OPEN: "+open);
    //        System.err.println("CLOSE: "+close);
    int closeSz = close.length();
    int nextCloseIdx = text.indexOf(close, start);
    //        System.err.println("first close: "+nextCloseIdx);
    if (nextCloseIdx == -1) {
        return -1;
    }/*from ww w .  j  ava  2  s.  c  om*/
    int count = StringUtils.countMatches(text.substring(start, nextCloseIdx), open);
    //        System.err.println("count: "+count);
    if (count == 0) {
        return -1; // tag is never opened
    }
    int expected = 1;
    while (count != expected) {
        nextCloseIdx = text.indexOf(close, nextCloseIdx + closeSz);
        if (nextCloseIdx == -1) {
            return -1;
        }
        count = StringUtils.countMatches(text.substring(start, nextCloseIdx), open);
        expected++;
    }
    return nextCloseIdx;
}

From source file:net.lldp.checksims.submission.ConcreteSubmission.java

@Override
public int getLinesOfCode() {
    return StringUtils.countMatches(getContentAsString(), "\n") + 1;
}

From source file:com.ing.connector.newbus.WPendingOverridesImpl.java

/**
 * This method will query the database and create an Odd string that
 * represents the collection of agent overrides.
 *//*from  www .  j av  a 2 s  .c om*/
public WResult getObject(WObjectKeys keys) {
    String policyId = keys.getStringKey(1);
    String agentSystemSource = keys.getStringKey(2); //JFG2.0
    String companyId = keys.getStringKey(3); //JFG4.0
    String agentParm = keys.getStringKey(4); //CSST400
    String driverSystemSource = getDriver().getSystemSource(); //JFG2.0
    String driverTableType = getDriver().getTableType(); //DIL3.0
    String databaseName = "scldbali"; //DIL3.0
    String procedureName = null; //DIL3.0
    String userType = keys.getStringKey(5);
    String agentName;

    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - userType" + userType);

    WResult result = new WResult();

    WCollection collection = new WCollection("com.ing.connector.model.WAgentOverrideExt");

    result.setModelObject(collection);

    if (!agentSystemSource.equals(driverSystemSource)) //JFG2.0
    {
        result.setStatus(WResult.OBJECT_NOT_FOUND);
        return result;
    }

    if (userType != null && userType.equalsIgnoreCase("internalUser"))
        databaseName = LookUp.getInstance().getStringProperty("Connector.History.Database");
    ;

    // March 2004 deleted int connNo = line

    Connection con = getConnection();
    // March 2004 removed param

    if (driverTableType.equals(TABLETYPECOPY)) //DIL3.0
    { //DIL3.0

        procedureName = "bali_WAgentOverrides_get_p"; //DIL3.0
    } //DIL3.0
    else //DIL3.0
    { //DIL3.0
        //databaseName = "scldpt";                        //RL-004454 RSD 

        procedureName = "bali_WAgentOverridesImpl"; //DIL3.0
    } //DIL3.0
    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - databaseName" + databaseName);
    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - procedureName" + procedureName);
    try {
        Statement stmt = con.createStatement();
        //DIL3.0            stmt.execute("use " + "scldpt");
        stmt.execute("use " + databaseName);
        Registrar.logInfoMessage("exec " + procedureName + " " + policyId + "," + agentParm);
        //DIL3.0            CallableStatement cstmt = con.prepareCall("{call bali_WAgentOverridesImpl(?)}");
        CallableStatement cstmt = con.prepareCall("{call " + procedureName + "(?,?)}"); //CSST400
        cstmt.setString(1, policyId);
        cstmt.setString(2, agentParm); //CSST400

        ResultSet rs = cstmt.executeQuery();

        WDateIsoFormat isoFormat = new WDateIsoFormat();

        while (rs.next()) {

            WAgentOverrideExt single = new WAgentOverrideExt(getDriverName(), getImplTypeName());

            single.setAgentId(rs.getString("agent_number"));
            agentName = new String(rs.getString("agent_name"));
            //RL-009402 - SXL - START
            String formattedAgentName = WStringUtil.formatAgentName(agentName);

            single.setFormattedAgentName(formattedAgentName);

            if (StringUtils.countMatches(agentName, ",") == 2) {
                String lastName = agentName.substring(0, agentName.indexOf(",")).trim();
                String firstName = (agentName.substring(agentName.indexOf(",") + 1, agentName.lastIndexOf(",")))
                        .trim();
                String middleName = (agentName.substring(agentName.lastIndexOf(",") + 1)).trim();
                single.setLastName(lastName);
                single.setFirstName(firstName);
                single.setMiddleName(middleName);
            } else {
                //RL-009402 - SXL - END  
                int i = agentName.indexOf(',');
                if (i != -1) {
                    single.setLastName(agentName.substring(0, i).trim());
                    single.setFirstName(agentName.substring(i + 1).trim());
                } else {
                    single.setLastName(agentName);
                }
            }

            single.setOverridePercent(rs.getDouble("commission_split"));
            single.setContractType(rs.getString("agent_contract_typ"));
            single.setOverrideId(rs.getString("ovr_agent_number")); //CSST400
            single.setOverrideAgentName(rs.getString("ovr_agent_name")); //   KLN/02/13/07//RL-001655    
            single.setLevel(rs.getString("Hierarchy_Type")); //RL-005642 LXJ added
            collection.addElement(single);
        }

        rs.close();
        cstmt.close();
        stmt.close();

        result.setModelObject(collection);

        if (collection.size() == 0) {
            result.setStatus(WResult.OBJECT_NOT_FOUND);
        }

    } catch (SQLException sqle) {
        result.setException(sqle);
        com.ing.connector.Registrar.logError(getClass().getName() + ": " + sqle.getMessage());
    } catch (Exception exc) {
        result.setException(exc);
        com.ing.connector.Registrar.logError(getClass().getName() + ": " + exc.getMessage());
    }

    releaseConnection(con);
    //March 2004 changed param from connNo to con

    return result;

}

From source file:net.bhl.cdt.paxelerate.model.util.CabinGenerator.java

/**
 * This method splits the String into parts and reads out the information in
 * it. This string has the form X-X and it is separated by the "-" operator.
 * //from w  w w.jav a 2s  . com
 * @param seatString
 *            is the string
 */
public void splitSeatString(String seatString) {

    /*
     * This method checks the user input for errors and automatically
     * corrects it!
     */
    seatString = InputChecker.checkStructureString(seatString);

    rowPartsInt = new ArrayList<Integer>();
    numberOfAisles = StringUtils.countMatches(seatString, "-");
    abreast = 0;
    String[] rowParts = seatString.split("-");
    for (String str : rowParts) {
        abreast += Integer.parseInt(str);
        rowPartsInt.add(Integer.parseInt(str));
    }
}

From source file:edu.monash.merc.system.version.TLVersionTrack.java

public boolean isSingleDbs() {
    if (this.trackToken == 0) {
        return false;
    }//  www .  ja  va 2s .  c o m
    String tokenStr = String.valueOf(this.trackToken);
    int matches = StringUtils.countMatches(tokenStr, "1");
    if (matches == 1) {
        return true;
    } else {
        return false;
    }
}

From source file:com.amalto.core.query.analysis.ConditionChecks.java

@Override
public Result visit(Field field) {
    Result result = new Result();
    FieldMetadata fieldMetadata = field.getFieldMetadata();
    // Limit join for contained fields
    if (!result.limitJoins) {
        int level = StringUtils.countMatches(fieldMetadata.getPath(), "/"); //$NON-NLS-1$
        if (level > 2 || !select.getTypes().contains(fieldMetadata.getContainingType())) {
            result.limitJoins = true;// ww  w .ja  v a2s .c  o  m
        }
    }
    if (fieldMetadata.getContainingType().getKeyFields().size() == 1) {
        if (fieldMetadata.isKey() && !(fieldMetadata instanceof CompoundFieldMetadata)) {
            if (keyField != null) {
                // At least twice an Id field means different Id values
                // TODO Support for "entity/id = n AND entity/id = n" (could simplified to "entity/id = n").
                result.id = false;
            } else {
                keyField = fieldMetadata;
                result.id = true;
            }
        }
    } // TODO Support compound key field.
    return result;
}

From source file:com.flexive.shared.FxFormatUtils.java

/**
 * Checks the email. Also allows local email addresses without a domain (e.g. 'root@localhost').
 *
 * @param email the email to check/*from w w w. j  a  va  2  s.c  o  m*/
 * @return the email without whitespaces
 * @throws com.flexive.shared.exceptions.FxInvalidParameterException
 *          if the email is invalid
 */
public static String checkEmail(String email) throws FxInvalidParameterException {
    final boolean valid = !StringUtils.isEmpty(email) && email.indexOf('@') > 0
            && (StringUtils.countMatches(email, "@") == 1) && (email.indexOf('@') < email.length() - 1);
    if (!valid) {
        if (StringUtils.isEmpty(email))
            throw new FxInvalidParameterException("EMAIL", "ex.account.email.empty");
        throw new FxInvalidParameterException("EMAIL", "ex.account.email.invalid", email);
    }
    return email.trim();
}

From source file:net.sf.yal10n.svn.SVNUtilTest.java

/**
 * Test various diffs with and without property changes.
 * @throws Exception any error//from  w  w w .j  a  v  a 2  s  .  co m
 */
@Test
public void testChangedPropertiesOnly() throws Exception {
    SVNUtil svnUtil = new SVNUtil();
    Log log = new NullLog();

    String svnUrl = "file://"
            + new File("./src/test/resources/svnrepos/detectchanges-props-only").getCanonicalPath() + "/trunk";
    String destination = new File("./target/svnrepos/detectchanges-props-only").getCanonicalPath();
    if (new File(destination).exists()) {
        FileUtils.deleteDirectory(destination);
    }

    String revision = svnUtil.checkout(log, ScmType.SVN, svnUrl, destination);
    Assert.assertEquals("6", revision);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
    Date expectedDate = simpleDateFormat.parse("2013-11-19 18:10:46 +0100");
    SVNInfo info = svnUtil.checkFile(log, ScmType.SVN, svnUrl, destination, "testfile.txt");
    Assert.assertEquals(revision, info.getRevision());
    Date actualDate = simpleDateFormat.parse(info.getCommittedDate());
    Assert.assertEquals("Expected: " + expectedDate + " - but got: " + actualDate, expectedDate.getTime(),
            actualDate.getTime());

    // revision 2: only prop change
    SVNLogChange result = svnUtil.log(log, ScmType.SVN, svnUrl, destination, "testfile.txt", "1", "2");
    Assert.assertEquals(SVNLogChange.MODIFICATION, result);
    String diff = svnUtil.diff(log, ScmType.SVN, svnUrl, destination, "testfile.txt", "1", "2");
    UnifiedDiff unifiedDiff = null;
    if (!diff.isEmpty()) {
        unifiedDiff = new UnifiedDiff(diff);
        Assert.assertTrue(unifiedDiff.getHunks().isEmpty());
    }

    // revision 3: only file change (real diff)
    result = svnUtil.log(log, ScmType.SVN, svnUrl, destination, "testfile.txt", "2", "3");
    Assert.assertEquals(SVNLogChange.MODIFICATION, result);
    diff = svnUtil.diff(log, ScmType.SVN, svnUrl, destination, "testfile.txt", "2", "3");
    unifiedDiff = new UnifiedDiff(diff);
    Assert.assertFalse(unifiedDiff.getHunks().isEmpty());

    // revision 4: combined change of file and property
    result = svnUtil.log(log, ScmType.SVN, svnUrl, destination, "testfile.txt", "3", "4");
    Assert.assertEquals(SVNLogChange.MODIFICATION, result);
    diff = svnUtil.diff(log, ScmType.SVN, svnUrl, destination, "testfile.txt", "3", "4");
    unifiedDiff = new UnifiedDiff(diff);
    Assert.assertFalse(unifiedDiff.getHunks().isEmpty());

    // revision 6: a changeset with two file changed, but only one is important
    diff = svnUtil.diff(log, ScmType.SVN, svnUrl, destination, "testfile.txt", "5", "6");
    Assert.assertEquals(1, StringUtils.countMatches(diff, "Index: "));
    unifiedDiff = new UnifiedDiff(diff);
    Assert.assertFalse(unifiedDiff.getHunks().isEmpty());
    Assert.assertEquals("testfile.txt\t(revision 5)", unifiedDiff.getOriginalName());
}