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:pl.wroc.pwr.jbehaveplugin.configuration.wizard.SelectLocationPage.java

/**
 * Sprawdza czy podany plik jest poprawn nazw dla kodu rdowego Java.
 * // w w  w .ja  va2 s.co m
 * @param fileName nazwa pliku
 * @return true jeeli plik ma poprawn nazw
 */
protected static boolean isValidJavaFileName(String fileName) {
    return StringUtils.countMatches(fileName, ".") == 1 && fileName.endsWith(".java");
}

From source file:plugin.tripleGEOStep.java

/**
 * Perform the equivalent of processing one row. Typically this means reading a row from input 
 * (getRow()) and passing a row to output (putRow)).
 * @param smi - The steps metadata to work with
 * @param sdi - The steps temporary working data to work with (database connections, result sets, 
 *              caches, temporary variables, etc.)
 * @return false if no more rows can be processed or an error occurred.
 * @throws KettleException//w w  w. j a v  a 2s.  com
 */
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    this.meta = ((tripleGEOStepMeta) smi);
    this.data = ((tripleGEOStepData) sdi);

    Object[] row = getRow();

    if (row == null) {

        if (this.shpToRDF != null) {
            RowMetaInterface rm = this.data.outputRowMeta;

            while (rm.getValueMetaList().size() > 1) {
                rm.getValueMetaList().remove(0);
            }

            logBasic("Generating RDF.");

            this.meta = null; // Helps the garbage collector              

            Object[] result = new Object[1];
            result[0] = this.shpToRDF.getModel_rdf();

            putRow(this.data.outputRowMeta, result);

            logBasic("RDF generated.");
        } else {
            logBasic("No rows processed.");
        }

        setOutputDone();
        return false;
    }

    // Load attributes in shpToRDF and init RDF
    if (this.first) {
        this.first = false;

        // Check CSV file 
        Boolean flag_csv = false;
        ClassesCSV[] classes = null;
        CSV csv = null;
        if (!this.meta.getPathCSV().equalsIgnoreCase(Constants.null_)) {
            csv = new CSV(this.meta.getPathCSV());
            if (csv.exist()) {
                classes = csv.read();
                flag_csv = true;
            } else {
                flag_csv = false;
                logBasic("The CSV file doesn't exist.");
            }
        }

        // Verifies if the attribute has a phrase
        String args = this.meta.getAttributeName();

        int count_plus = StringUtils.countMatches(args, Constants.STRING_TO_REPLACE);
        if (count_plus == 0) { // <phrase> or <name_column>
            if (StringUtils.countMatches(args, "\"") > 0) {
                // <phrase>
                logBasic("Attribute Error");
                throw new KettleException(
                        "tripleGEO.Exception.AttributesError: Check your tripleGEO " + "settings.");
            } else {
                // <name_column>
                this.attributeName = args.trim();
                this.phrase = Constants.empty;
            }
        } else if (count_plus == 1) { // <phrase> + <name_column>
            String parts[] = args.split("\\+");
            if (parts.length == 2) {
                if (parts[0] != null && !parts[0].equalsIgnoreCase("") && parts[1] != null
                        && !parts[1].equalsIgnoreCase("")) {
                    this.attributeName = parts[1].trim();
                    this.phrase = parts[0].trim();
                } else {// Error
                    logBasic("Attribute Error");
                    throw new KettleException(
                            "tripleGEO.Exception.AttributesError: Check your tripleGEO " + "settings.");
                }
            } else {// Error
                logBasic("Attribute Error");
                throw new KettleException(
                        "tripleGEO.Exception.AttributesError: Check your tripleGEO " + "settings.");
            }
        } else { // Error
            logBasic("Attribute Error");
            throw new KettleException(
                    "tripleGEO.Exception.AttributesError: Check your tripleGEO " + "settings.");
        }

        if (this.meta.getAttributeName() == null) {
            logBasic("Attribute Not Found");
            throw new KettleException("tripleGEO.Exception.AttributesNotFound: Check your tripleGEO "
                    + "settings and restart columns.");
        }

        this.shpToRDF = new ShpToRDF(this.meta, flag_csv, classes, csv, this.phrase, this.attributeName);

        try {
            this.shpToRDF.getModelFromConfiguration(); // Init RDF             
        } catch (Throwable t) {
            System.out.println(t.toString() + t.getCause().getMessage());
            t.printStackTrace();
        }

        this.data.outputRowMeta = getInputRowMeta().clone();
        this.meta.getFields(this.data.outputRowMeta, getStepname(), null, null, this);

        if ((this.meta.getAttributeName() != null) && (!this.meta.getAttributeName().isEmpty())) {
            RowMetaInterface rm = this.data.outputRowMeta;

            int pos = 0;
            int flag = 0;
            for (ValueMetaInterface vmeta : rm.getValueMetaList()) {

                // Check columns
                if (this.meta.getColumns() != null) {
                    flag = 0;
                    for (ColumnDefinition c : this.meta.getColumns()) {
                        if (c.getColumn_shp() != null) {
                            if (c.getColumn_shp().equalsIgnoreCase(vmeta.getName())
                                    || vmeta.getName().equalsIgnoreCase(Constants.outputField)) {
                                flag++;
                            }
                        } else {
                            if (c.getColumn().equalsIgnoreCase(vmeta.getName())
                                    || vmeta.getName().equalsIgnoreCase(Constants.outputField)) {
                                c.setColumn_shp(vmeta.getName());
                                flag++;
                            }
                        }
                    }
                    if (flag == 0) {
                        logBasic("Attribute Not Found");
                        throw new KettleException(
                                "tripleGEO.Exception.AttributesNotFound: Check your tripleGEO "
                                        + "settings and restart columns.");
                    }
                }

                if ((this.attributeName != null) && (this.attributeName != "")) {
                    if (vmeta.getName().equalsIgnoreCase(this.attributeName)) {
                        this.shpToRDF.setPosAttribute(pos);
                    }
                }

                if (vmeta.getName().equalsIgnoreCase(Constants.the_geom)) {
                    this.shpToRDF.setPosGeometry(pos);
                }

                pos++;
            }
        }

        if ((this.attributeName != null) && (this.attributeName != "")) {
            if (this.shpToRDF.getPosAttribute() < 0) {
                logBasic("Field Not Found (check your tripleGEO settings): " + this.attributeName);
                throw new KettleException("tripleGEO.Exception.FieldForReadNotFound: " + this.attributeName);
            }
        }

        logBasic("tripleGEO step initialized successfully.");
    }

    // Process Row 
    try {
        this.shpToRDF.writeRdfModel(row, this.data.outputRowMeta);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:raptor.swt.chat.ChatUtils.java

License:asdf

public static String stripDoubleUrls(String word) {
    if (StringUtils.countMatches(word, "http://") == 2 || StringUtils.countMatches(word, "https://") == 2) {
        int httpIndex = word.indexOf("http", 1);
        return word.substring(0, httpIndex).trim();
    } else {/*from   ww w . j  a  v  a 2 s  .  co  m*/
        return word;
    }
}

From source file:se.vgregion.domain.infrastructure.webservice.RestCalendarEventsRepository.java

private CalendarEvents extractCalendarEvents(InputStream bis) throws IOException, JAXBException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[4096];
    int n;/*from   www . j a v  a 2 s . co m*/
    while ((n = bis.read(buf)) != -1) {
        baos.write(buf, 0, n);
    }

    String inUtf8 = new String(baos.toByteArray(), "UTF-8");
    String inIso8859 = new String(baos.toByteArray(), "ISO-8859-1");
    int numberSwedishCharactersFromUtf8 = StringUtils.countMatches(inUtf8, "")
            + StringUtils.countMatches(inUtf8, "") + StringUtils.countMatches(inUtf8, "");
    int numberSwedishCharactersFromIso8859 = StringUtils.countMatches(inIso8859, "")
            + StringUtils.countMatches(inIso8859, "") + StringUtils.countMatches(inIso8859, "");

    String toUse;
    if (numberSwedishCharactersFromIso8859 > numberSwedishCharactersFromUtf8) {
        toUse = inIso8859;
    } else {
        toUse = inUtf8;
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(CalendarEvents.class);
    return (CalendarEvents) jaxbContext.createUnmarshaller().unmarshal(new StringReader(toUse));
}

From source file:sernet.verinice.report.service.impl.dynamictable.GraphReportDataModel.java

/**
 * Reads a property of a given element, computes the row identifier, 
 * loads (if existant) row from result hashmap, and adds property to row 
 * (which is instantiated if non-existant)
 * /* w w w. j  a v a2s .c om*/
 * @param rowId
 * @param propertyPosition
 * @return
 */
private CnATreeElement handlePropertyOperand(String rowId, int propertyPosition) {
    String existingPath = rowId;

    if (!resultMap.containsKey(existingPath)) {
        // check recursive upwards if id is already in map
        if (StringUtils.countMatches(rowId, "#") != 1 && rowId.startsWith("#")) {
            existingPath = rowId.substring(0, rowId.lastIndexOf('#'));
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Searching for " + existingPath + " on map");
    }
    if (resultMap.containsKey(existingPath)) {
        createSubRow(rowId, propertyPosition, existingPath);
    } else {
        parentElement = createNewRootRow(rowId, operandStack.peek(), propertyPosition);
    }
    return parentElement;
}

From source file:shelper.ifmock.HttpMock.java

public int findNumberofStringinResponse(String aim) {
    int result = StringUtils.countMatches(requestedbody, aim);
    Reporter.log("httpmock?" + aim + "\n" + result, true);
    return result;
}

From source file:tvbrowser.core.search.booleansearch.BooleanSearcher.java

/**
 * Erzeugt einen neuen Suchbaum. Der Baum wird automatisch optimiert. Es kann
 * immer nur ein Konstruktor gleichzeitig laufen. Fuer Synchronization ist
 * gesorgt./*from   www.j a  v a 2s . com*/
 *
 * @throws ParserException
 */
public BooleanSearcher(String pattern, boolean caseSensitive) throws ParserException {
    Hashtable<String, Object> matcherTab = new Hashtable<String, Object>();
    mCaseSensitive = caseSensitive;
    mReplaceSpCh = true;

    pattern = pattern.trim();
    int braceDifference = StringUtils.countMatches(pattern, "(") - StringUtils.countMatches(pattern, ")");
    if (braceDifference > 0) {
        pattern = pattern + StringUtils.repeat(")", braceDifference);
    }
    pattern = pattern.replaceAll("\\\"", " ");
    pattern = pattern.replaceAll("\\(", " ( ");
    pattern = pattern.replaceAll("\\)", " ) ");

    StringTokenizer tokenizer = new StringTokenizer(pattern);
    Vector<Object> parts = new Vector<Object>();
    while (tokenizer.hasMoreElements()) {

        String s = tokenizer.nextToken();
        if (s.equals("(")) {
            parts.add(subPart(tokenizer));
        } else {
            parts.add(s);
        }
    }
    mRootMatcher = getMatcher(parts, mCaseSensitive, matcherTab);
    mRootMatcher = mRootMatcher.optimize();
}

From source file:uk.ac.ebi.embl.flatfile.reader.FeatureReader.java

private boolean isQuoteBalance(String line) {
    quotecount += StringUtils.countMatches(line, "\"");
    return quotecount % 2 == 0;
}

From source file:uk.ac.ebi.embl.flatfile.reader.QualifierMatcher.java

public Qualifier getQualifier() {
    QualifierFactory qualifierFactory = new QualifierFactory();
    String qualifierName = getString(GROUP_QUALIFIER_NAME);
    String qualifierValue = getString(GROUP_QUALIFIER_VALUE);
    int nofQuotes = StringUtils.countMatches(qualifierValue, "\"");
    Qualifier qualifier = qualifierFactory.createQualifier(qualifierName);
    if (qualifierValue != null) {
        if (!qualifier.isValueQuoted() && nofQuotes != 0) {
            if ((!qualifier.getName().equals(Qualifier.ANTICODON_QUALIFIER_NAME)
                    && !qualifier.getName().equals(Qualifier.COMPARE_QUALIFIER_NAME)))
                error("FT.10", qualifierName, qualifierValue);
        } else if (qualifier.isValueQuoted()) {
            if (nofQuotes == 0) {
                error("FT.10", qualifierName, qualifierValue);
            } else {
                if (qualifierValue.indexOf('"') != 0
                        && qualifierValue.lastIndexOf('"') != qualifierValue.length() - 1)

                {//from   w w  w. j av a2s.  c om
                    error("FT.10", qualifierName, qualifierValue);
                } else if (nofQuotes % 2 != 0) {
                    error("FT.10", qualifierName, qualifierValue);
                }
            }
        }
        qualifierValue = FlatFileUtils.trimLeft(qualifierValue, '"');
        qualifierValue = FlatFileUtils.trimRight(qualifierValue, '"');
        qualifier.setValue(qualifierValue);
        return qualifier;
    } else {
        return qualifier;
    }
}

From source file:uk.ac.ox.it.ords.api.database.queries.FilteredQuery.java

/**
 * Construct a single SQL query from a parameterised request, as supplied
 * from the filter interface via table.jsp
 * //from   w  w w.ja v  a 2  s.co  m
 * @param filter the filter SQL string
 * @param params the array of parameters
 * @return a combined SQL query, or null if either of the components are invalid
 */
protected String createFilterFromParameters(String filter, ParameterList parameters, boolean isCaseSensitive) {
    //
    // We don't want malformed queries...
    //
    if (filter == null || parameters == null)
        return null;
    if (filter.equals("null") || filter.trim().isEmpty())
        return null;

    //
    // Do the number of parameters match the number of placeholders?
    //
    int count = StringUtils.countMatches(filter, "?");
    if (count > 0 && count != parameters.size()) {
        return null;
    }

    //
    // Substitute 'CONTAINS param' with 'LIKE %param%'
    //
    if (filter.contains(" CONTAINS ")) {
        //
        // Identify the parameter that applies
        //
        while (filter.contains(" CONTAINS ")) {
            int index = StringUtils.countMatches(filter.split(" CONTAINS ")[0], "?");
            filter = filter.replaceFirst(" CONTAINS ", " LIKE ");
            String parameter = (String) parameters.getParameter(index).stringValue;
            //
            // Replace surrounding single quotes with '%
            //
            parameters.setParameterValue(index, "%" + parameter + "%");
        }
    }

    //
    // Substitute 'LIKE' with 'ILIKE" or the reverse, as appropriate
    //
    if (isCaseSensitive) {
        filter = filter.replace(" ILIKE ", " LIKE ");
    } else {
        filter = filter.replace(" LIKE ", " ILIKE ");
    }

    //
    // replace HTML quotes in SQL with double quotes
    //
    filter = filter.replaceAll("&quot;", "\"");

    return filter;
}