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.opencommercesearch.AbstractSearchServer.java

private List<CategoryGraph> createCategoryGraphAux(Facet facet, String path, String catalogId,
        String categoryId, int depthLimit, String separator) {
    List<CategoryGraph> categoryGraphList = new ArrayList<CategoryGraph>();
    if (facet != null) {

        CategoryGraphBuilder categoryFacetBuilder = new CategoryGraphBuilder();

        boolean filterByDepth = depthLimit > 0 && StringUtils.isNotBlank(separator);

        // iterate through the flat category facet structure and create a
        // graph from it
        for (Filter filter : facet.getFilters()) {
            if (isLoggingDebug()) {
                String filterPath = Utils.findFilterExpressionByName(filter.getFilterQueries(), CATEGORY_PATH);
                logDebug("Generating CategoryGraph for path: " + filterPath);
            }//from w  ww.  j  a va  2 s .  com
            if (filterByDepth && StringUtils.countMatches(filter.getName(), separator) > depthLimit) {
                continue;
            }
            categoryFacetBuilder.addPath(filter);
        }

        if (StringUtils.isBlank(categoryId)) {
            // no category filtering scenario. Return top level list
            categoryGraphList = categoryFacetBuilder.getCategoryGraphList();
        } else {
            // category filtering scenario. Search hierarchy for the actual
            // result node.
            CategoryGraph currentLevelVO = categoryFacetBuilder.search(categoryId,
                    categoryFacetBuilder.getParentNode());
            if (currentLevelVO != null) {
                categoryGraphList = currentLevelVO.getCategoryGraphNodes();
            } else {
                if (isLoggingDebug()) {
                    logDebug("The CategoryGraph is empty for catalog: " + catalogId + " and category: "
                            + categoryId + " path: " + path + " This is expected for leaf categories");
                }
            }
        }
    }

    return categoryGraphList;
}

From source file:org.opencommercesearch.AbstractSearchServerIntegrationTest.java

@SearchTest(newInstance = true, productData = "/product_catalog/sandal.xml")
public void testGetFacetDepthLimit(SearchServer server) throws SearchServerException {
    Facet facet = server.getFacet(site, Locale.US, "categoryPath", 100, 2, ".");
    assertNotNull(facet);/*  w w  w. j a v a  2  s .c o m*/
    for (Facet.Filter filter : facet.getFilters()) {
        assertTrue(StringUtils.countMatches(filter.getName(), ".") <= 2);
    }

    facet = server.getFacet(site, Locale.US, "categoryPath", 100, -1, ".");
    assertNotNull(facet);
    boolean fullFacetDepth = false;
    for (Facet.Filter filter : facet.getFilters()) {
        if (StringUtils.countMatches(filter.getName(), ".") > 2) {
            fullFacetDepth = true;
            break;
        }
    }
    assertEquals(
            "the depth of the generated categoryPath facet should be greater than 2. checkout possible incorrect prune logic",
            true, fullFacetDepth);
}

From source file:org.opencommercesearch.remote.assetmanager.editor.service.RankingRuleAssetValidator.java

private void validate(AssetEditorInfo editorInfo, String attributeValue) {
    if (StringUtils.countMatches(attributeValue, RuleManager.RANKING_SEPARATOR) > 1) {
        editorInfo.getAssetService().addError(RankingRuleProperty.ATTRIBUTE, TOO_MANY_PIPE_OPERATOR_ERROR_MSG);
        if (isLoggingWarning()) {
            logWarning(TOO_MANY_PIPE_OPERATOR_ERROR_MSG);
        }// ww  w.  jav  a2s .c  o m
    } else if (StringUtils.endsWith(attributeValue, RuleManager.RANKING_SEPARATOR)) {
        editorInfo.getAssetService().addError(RankingRuleProperty.ATTRIBUTE,
                MISSING_SECOND_EXPRESSION_ERROR_MSG);
        if (isLoggingWarning()) {
            logWarning(MISSING_SECOND_EXPRESSION_ERROR_MSG);
        }
    }
}

From source file:org.openehr.am.validation.ArchetypeValidator.java

/** Checks one archetype id to be a valid id or not
 * @param slot/*ww w .j a  v  a  2  s.  c om*/
 * @param errors
 * @param oneId
 */
private void checkOneArchetypeId(ArchetypeSlot slot, List<ValidationError> errors, String oneId) {
    // check for the right number of dots in the id
    boolean containsCorrectNumberOfDots = (StringUtils.countMatches(oneId, ".") == 2);

    // check that the id ends with .v[0..9]*
    boolean endsWithDotVNumber = true; // assume it is ok, until proven false
    if (oneId.lastIndexOf(".v") == -1) {
        endsWithDotVNumber = false;
    } else {
        String tail = oneId.substring(oneId.lastIndexOf(".v") + 2);
        log.debug("tail: " + tail);
        if (tail.length() == 0 || !StringUtils.isNumeric(tail)) {
            endsWithDotVNumber = false;
        }
    }

    // check that the first part of the id (the qualified RM Entity) contains the right number of hyphens
    boolean containsCorrectNumberOfHyphensInQualifiedRMEntity = true; // assume it is ok, until proven wrong                        
    String qualifiedRMEntity = oneId.substring(0, oneId.indexOf("."));
    if (StringUtils.countMatches(qualifiedRMEntity, "-") != 2) {
        containsCorrectNumberOfHyphensInQualifiedRMEntity = false;
    }

    // add all the errors
    if (!containsCorrectNumberOfDots) {
        ValidationError error = new ValidationError(ErrorType.VDFAI, "NUMBEROFDOTS", oneId, slot.path());
        errors.add(error);

    }
    if (!endsWithDotVNumber) {
        ValidationError error = new ValidationError(ErrorType.VDFAI, "DOTVNUMBER", oneId, slot.path());
        errors.add(error);

    }
    if (!containsCorrectNumberOfHyphensInQualifiedRMEntity) {
        ValidationError error = new ValidationError(ErrorType.VDFAI, "NUMBEROFHYPHENS", oneId, slot.path());
        errors.add(error);

    }

}

From source file:org.openehr.am.validation.ArchetypeValidator.java

/** Checks for unused codes in the ontology
 * /*from  w  w  w  . jav a  2s . c o m*/
 * @param defList
 * @param errors
 * @param archetype
 */
private void checkForUnusedCodes(List<OntologyDefinitions> defList, List<ValidationError> errors,
        Archetype archetype, Set<String> actuallyUsedCodes) {

    int specialisationDepth = StringUtils.countMatches(archetype.getArchetypeId().domainConcept(), "-");

    // now check for each code if it exists in the definition
    ValidationError error = null;
    for (OntologyDefinitions defs : defList) {
        for (ArchetypeTerm term : defs.getDefinitions()) {
            if (!actuallyUsedCodes.contains(term.getCode())) {
                // at the moment, we only want to report on unused codes 
                // that are on the same specialisation depth as this archetype. 
                if (specialisationDepth == StringUtils.countMatches(term.getCode(), ".")) {
                    error = new ValidationError(ErrorType.WOUC, null, term.getCode(), defs.getLanguage());
                    errors.add(error);
                }
            }
        }
    }
}

From source file:org.openhab.core.init.internal.InitActivator.java

/**
 * Creates a file with given <code>version</code>. The file will be
 * overwritten each time openHAB has been started.
 * //w ww .  j  a  va 2 s .  co  m
 * @param context the bundle context
 */
private void createVersionFile(BundleContext context) {
    String versionString = context.getBundle().getVersion().toString();
    String buildString = "";
    // if the version string contains a qualifier, remove it!
    if (StringUtils.countMatches(versionString, ".") == 3) {
        buildString = StringUtils.substringAfterLast(versionString, ".");
        if (buildString.equals("qualifier")) {
            buildString = "";
        }
        versionString = StringUtils.substringBeforeLast(versionString, ".");
    }

    File file = new File(
            getUserDataDir() + File.separator + STATIC_CONTENT_DIR + File.separator + VERSION_FILE_NAME);
    writeFile(file, versionString);
}

From source file:org.openhab.core.internal.CoreActivator.java

public void start(BundleContext context) throws Exception {
    createUUIDFile();//from   w w  w  .  j  a  v a  2  s . c om

    String versionString = context.getBundle().getVersion().toString();
    // if the version string contains a qualifier, remove it!
    if (StringUtils.countMatches(versionString, ".") == 3) {
        versionString = StringUtils.substringBeforeLast(versionString, ".");
    }
    createVersionFile(versionString);

    logger.info("openHAB runtime has been started (v{}).", versionString);

    java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        rootLogger.removeHandler(handler);
    }

    SLF4JBridgeHandler.install();
}

From source file:org.openhab.core.OpenHAB.java

/**
 * Returns the current openHAB version, retrieving the information from the core bundle version.
 *
 * @return the openHAB runtime version//from  w w w . ja  va2  s  .  c  o m
 */
static public String getVersion() {
    String versionString = FrameworkUtil.getBundle(OpenHAB.class).getVersion().toString();
    // if the version string contains a qualifier, remove it!
    if (StringUtils.countMatches(versionString, ".") == 3) {
        versionString = StringUtils.substringBeforeLast(versionString, ".");
    }
    return versionString;
}

From source file:org.openhab.core.OpenHAB.java

/**
 * Returns the current openHAB build id, retrieving the information from the core bundle version.
 * If the id is "qualifier", i.e. openHAB is run from within the IDE, it returns an empty string.
 *
 * @return the openHAB build id or an empty string, if none is avaiable
 *///from  w ww  .  java  2 s . c  o  m
static public String getBuildId() {
    String versionString = FrameworkUtil.getBundle(OpenHAB.class).getVersion().toString();
    String buildString = "";
    if (StringUtils.countMatches(versionString, ".") == 3) {
        buildString = StringUtils.substringAfterLast(versionString, ".");
        if (buildString.equals("qualifier")) {
            buildString = "";
        }
    }
    return buildString;
}

From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServletTest.java

/**
 * @see {@link AtomFeedDownloadServlet#doGet(HttpServletRequest,HttpServletResponse)}
 *///from w w  w.j a v a2 s  . c  o m
@Test
@Verifies(value = "should exclude entries before the asOfDate value", method = "doGet(HttpServletRequest,HttpServletResponse)")
public void doGet_shouldExcludeEntriesBeforeTheAsOfDateValue() throws Exception {
    //ensures that at least we have an entry to exclude for testing purposes
    AtomFeedUtil.objectCreated(new Encounter());

    AtomFeedDownloadServlet atomFeedDownloadServlet = new AtomFeedDownloadServlet();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/atomfeed");

    Thread.sleep(1000);//wait for at least a second since the dateFormat precision is to seconds

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date asOfDate = new Date();
    request.setParameter("asOfDate", dateFormat.format(asOfDate));
    MockHttpServletResponse response = new MockHttpServletResponse();

    AtomFeedUtil.objectCreated(new Encounter());
    AtomFeedUtil.objectCreated(new Concept());

    Thread.sleep(2000);//wait for 2 seconds for the feed to get updated      
    atomFeedDownloadServlet.service(request, response);

    //only 2 entries added after the asOfDate should have been returned
    Assert.assertEquals(2, StringUtils.countMatches(response.getContentAsString(), "<entry>"));
}