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.commonjava.maven.ext.manip.util.PropertiesUtils.java

/**
 * This will check if the old version (e.g. in a plugin or dependency) is a property and if so
 * store the mapping in a map.// w w  w  .ja  v a  2  s .  com
 *
 * @param versionPropertyUpdateMap the map to store any updates in
 * @param oldVersion original property value
 * @param newVersion new property value
 * @param originalType that this property is used in (i.e. a plugin or a dependency)
 * @param force Whether to check for an existing property or force the insertion
 * @return true if a property was found and cached.
 * @throws ManipulationException if an error occurs.
 */
public static boolean cacheProperty(Map<String, String> versionPropertyUpdateMap, String oldVersion,
        String newVersion, Object originalType, boolean force) throws ManipulationException {
    boolean result = false;
    if (oldVersion != null && oldVersion.contains("${")) {
        final int endIndex = oldVersion.indexOf('}');
        final String oldProperty = oldVersion.substring(2, endIndex);

        // We don't attempt to cache any value that contains more than one property or contains a property
        // combined with a hardcoded value.
        if (oldVersion.contains("${") && !(oldVersion.startsWith("${") && oldVersion.endsWith("}"))
                || (StringUtils.countMatches(oldVersion, "${") > 1)) {
            logger.debug(
                    "For {} ; original version contains hardcoded value or multiple embedded properties. Not caching value ( {} -> {} )",
                    originalType, oldVersion, newVersion);
        } else if ("project.version".equals(oldProperty)) {
            logger.debug(
                    "For {} ; original version was a property mapping. Not caching value as property is built-in ( {} -> {} )",
                    originalType, oldProperty, newVersion);
        } else {
            logger.debug(
                    "For {} ; original version was a property mapping; caching new value for update {} -> {}",
                    originalType, oldProperty, newVersion);

            final String oldVersionProp = oldVersion.substring(2, oldVersion.length() - 1);

            // We check if we are replacing a property and there is already a mapping. While we don't allow
            // a property to be updated to two different versions, if a dependencyExclusion (i.e. a force override)
            // has been specified this will bypass the check.
            String existingPropertyMapping = versionPropertyUpdateMap.get(oldVersionProp);

            if (existingPropertyMapping != null && !existingPropertyMapping.equals(newVersion)) {
                if (force) {
                    logger.debug("Override property replacement of {} with force version override {}",
                            existingPropertyMapping, newVersion);
                } else {
                    logger.error(
                            "Replacing property '{}' with a new version but the existing version does not match. Old value is {} and new is {}",
                            oldVersionProp, existingPropertyMapping, newVersion);
                    throw new ManipulationException(
                            "Property replacement clash - updating property '{}' to both {} and {} ",
                            oldVersionProp, existingPropertyMapping, newVersion);
                }
            }

            versionPropertyUpdateMap.put(oldVersionProp, newVersion);

            result = true;
        }
    }
    return result;
}

From source file:org.devproof.portal.core.module.common.repository.DataProviderRepositoryImpl.java

private StringBuilder createWhereConditions(Serializable beanQuery, List<Object> queryParameter) {
    StringBuilder hqlQuery = new StringBuilder();
    if (beanQuery != null) {
        appendTableJoin(beanQuery, hqlQuery);
        Method methods[] = beanQuery.getClass().getMethods();
        if (methods.length > 0) {
            boolean firstClause = true;
            for (Method method : methods) {
                if (isGetterWithBeanQuery(method)) {
                    Object value = invokeGetter(beanQuery, method);
                    if (value != null) {
                        if (firstClause) {
                            firstClause = false;
                            hqlQuery.append(" where ");
                        } else {
                            hqlQuery.append(" and ");
                        }/*  w  w w .j a  va 2 s  .  c o m*/
                        BeanQuery bean = method.getAnnotation(BeanQuery.class);
                        hqlQuery.append(bean.value());
                        int countMatches = StringUtils.countMatches(bean.value(), "?");
                        for (int j = 0; j < countMatches; j++) {
                            queryParameter.add(value);
                        }
                    }
                }
            }
        }
    }
    return hqlQuery;
}

From source file:org.dkpro.tc.features.pair.core.ngram.meta.ComboUtils.java

/**
 * Get combinations of ngrams from a pair of documents.
 * // ww w  .j  av a 2s . c o m
 * @param document1NGrams ngrams from document 1
 * @param document2NGrams ngrams from document 2
 * @param minN minimum size for a new combined ngram
 * @param maxN max size for a new combined ngram
 * @param ngramUseSymmetricalCombos whether or not to return view-neutral ngrams
 * @return combinations of ngrams
 */
public static FrequencyDistribution<String> getCombinedNgrams(FrequencyDistribution<String> document1NGrams,
        FrequencyDistribution<String> document2NGrams, int minN, int maxN, boolean ngramUseSymmetricalCombos) {
    FrequencyDistribution<String> documentComboNGrams = new FrequencyDistribution<String>();
    for (String ngram1 : document1NGrams.getKeys()) {
        int ngram1size = StringUtils.countMatches(ngram1, NGRAM_GLUE) + 1;
        for (String ngram2 : document2NGrams.getKeys()) {
            int ngram2size = StringUtils.countMatches(ngram2, NGRAM_GLUE) + 1;
            if (ngram1size + ngram2size >= minN && ngram1size + ngram2size <= maxN) {
                //final feature value, binary or count, is controlled in the FE
                long value = document1NGrams.getCount(ngram1) * document2NGrams.getCount(ngram2);
                String comboNgram = ngram1 + JOINT + ngram2;
                documentComboNGrams.addSample(comboNgram, value);
                if (ngramUseSymmetricalCombos) {
                    comboNgram = ngram2 + JOINT + ngram1;
                    documentComboNGrams.addSample(comboNgram, value);
                }
            }
        }
    }
    return documentComboNGrams;
}

From source file:org.dkpro.tc.ml.svmhmm.util.CommentsIterator.java

private String extractComment(String rawLine) throws Exception {
    // Ideally there is only one # unless the gold label is #
    // then we have something like [# qid:317 3:1 # # 317 %23]

    // Normal case
    int firstCandidate = rawLine.lastIndexOf("#");
    int countMatches = StringUtils.countMatches(rawLine, "#");
    if (countMatches == 1) {
        return rawLine.substring(firstCandidate + 1);
    }/*from  w  w w  . j a  v  a  2 s  .  c o m*/

    // Occurrence of two # as in [O qid:5 2:7 # #IFTHEN O 5]
    int secondCandidate = rawLine.lastIndexOf("#", firstCandidate);
    if (countMatches == 2) {
        return rawLine.substring(secondCandidate);
    }

    // Is there an # before the one we just found and the first
    // character in the line is #, too 
    if (countMatches == 3 && rawLine.charAt(0) == '#') {
        return rawLine.substring(secondCandidate);
    }

    throw new Exception("Encountered an unexpected case when extracting the comments");

}

From source file:org.dspace.rdf.providing.DataProviderServlet.java

/**
 * Processes requests for both HTTP//from w ww  .  j a  v  a2s.  co m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // set all incoming encoding to UTF-8
    request.setCharacterEncoding("UTF-8");

    // we expect either a path containing only the language information
    // or a path in the form /handle/<prefix>/<suffix>[/language].
    String lang = this.detectLanguage(request);
    String cType = this.detectContentType(request, lang);
    String pathInfo = request.getPathInfo();

    log.debug("lang = " + lang + ", cType = " + cType + " and pathInfo: " + pathInfo);
    if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) {
        String dspaceURI = DSpaceServicesFactory.getInstance().getConfigurationService()
                .getProperty("dspace.url");
        this.serveNamedGraph(dspaceURI, lang, cType, response);
        return;
    }

    // remove trailing slash of the path info and split it.
    String[] path = request.getPathInfo().substring(1).split("/");
    // if we have 2 slashes or less, we sent repository information (see above)
    assert path.length >= 2;

    String handle = path[0] + "/" + path[1];

    log.debug("Handle: " + handle + ".");

    // As we offer a public sparql endpoint, all information that we stored
    // in the triplestore is public. It is important to check whether a
    // DSpaceObject is readable for a anonym user before storing it in the
    // triplestore. It is important to remove DSpaceObjects from the
    // triplestore, that gets revoked or become restricted. As this is done
    // by RDFizer and RDFUtil we do not have to take care for permissions here!
    Context context = null;
    DSpaceObject dso = null;
    try {
        context = new Context(Context.Mode.READ_ONLY);
        dso = handleService.resolveToObject(context, handle);
    } catch (SQLException ex) {
        log.error("SQLException: " + ex.getMessage(), ex);
        context.abort();
        // probably a problem with the db connection => send Service Unavailable
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    } catch (IllegalStateException ex) {
        log.error("Cannot resolve handle " + handle + ". IllegalStateException:" + ex.getMessage(), ex);
        context.abort();
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    if (dso == null) {
        log.info("Cannot resolve handle '" + handle + "' to dso. => 404");
        context.abort();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    String identifier = null;
    try {
        identifier = RDFUtil.generateIdentifier(context, dso);
    } catch (SQLException ex) {
        log.error("SQLException: " + ex.getMessage(), ex);
        context.abort();
        // probably a problem with the db connection => send Service Unavailable
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }
    if (identifier == null) {
        // cannot generate identifier for dso?!
        log.error("Cannot generate identifier for UUID " + dso.getID().toString() + "!");
        context.abort();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    log.debug("Loading and sending named graph " + identifier + ".");
    context.abort();
    this.serveNamedGraph(identifier, lang, cType, response);

}

From source file:org.dspace.rdf.providing.LocalURIRedirectionServlet.java

/**
 * Processes requests for both HTTP/*from   w  w w .  j  ava2 s .  c o  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // we expect a path in the form /resource/<prefix>/<suffix>.
    String pathInfo = request.getPathInfo();

    log.debug("Pathinfo: " + pathInfo);
    if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) {
        log.debug("Path does not contain the expected number of slashes.");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // remove trailing slash of the path info and split it.
    String[] path = request.getPathInfo().substring(1).split("/");

    String handle = path[0] + "/" + path[1];

    // Prepare content negotiation
    int requestedMimeType = Negotiator.negotiate(request.getHeader(ACCEPT_HEADER_NAME));

    Context context = null;
    DSpaceObject dso = null;
    try {
        context = new Context(Context.Mode.READ_ONLY);
        dso = handleService.resolveToObject(context, handle);
    } catch (SQLException ex) {
        log.error("SQLException: " + ex.getMessage(), ex);
        context.abort();
        // probably a problem with the db connection => send Service Unavailable
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    } catch (IllegalStateException ex) {
        log.error("Cannot resolve handle " + handle + ". IllegalStateException:" + ex.getMessage(), ex);
        context.abort();
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    if (dso == null) {
        log.info("Cannot resolve handle '" + handle + "' to dso. => 404");
        context.abort();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // close the context and send forward.
    context.abort();
    Negotiator.sendRedirect(response, handle, "", requestedMimeType, true);
}

From source file:org.ebayopensource.turmeric.eclipse.services.ui.wizards.pages.ConsumerFromExistingWSDLWizardPage.java

/**
 * {@inheritDoc}// ww w .j  a  v a 2 s. com
 */
@Override
public void wsdlChanged(final Definition wsdl) {
    final Collection<?> services = wsdl.getServices().values();
    if (services.size() > 0) {
        // only process the first service
        final Service service = (Service) services.toArray()[0];
        if (services.size() > 1) {
            logger.warning("Found multiple service, but only the first service will be processed->"
                    + service.getQName());
        }
        final String targetNs = wsdl.getTargetNamespace();
        targetNamespaceModified(targetNs);
        setTargetNamespace(targetNs);
        if (domainClassifierList == null) {
            // Non-MP
            String nsPart = StringUtils
                    .capitalize(getOrganizationProvider().getNamespacePartFromTargetNamespace(targetNs));
            this.domainName = nsPart;
            if (StringUtils.isNotBlank(nsPart)) {
                this.adminText.setText(nsPart + getAdminName());
            } else {
                this.adminText.setText(getPublicServiceName() + SOAProjectConstants.MAJOR_VERSION_PREFIX
                        + SOAServiceUtil.getServiceMajorVersion(getServiceVersion()));
            }
        }
        String version = SOAIntfUtil.getServiceVersionFromWsdl(wsdl, getPublicServiceName()).trim();
        if (resourceVersionText != null) {
            resourceVersionText.setEditable(true);
            if (StringUtils.isNotBlank(version)) {
                versionFromWSDL = version;
                // has version
                int versionPart = StringUtils.countMatches(version, SOAProjectConstants.DELIMITER_DOT);
                // add "dot number" to version. It will be changed to X.Y.Z
                if (versionPart == 2) {
                    // is new version format, set version text read-only.
                    resourceVersionText.setEditable(false);
                } else {
                    // is v2format
                    while (versionPart < 2) {
                        version += SOAProjectConstants.DELIMITER_DOT + "0";
                        versionPart++;
                    }
                }
                resourceVersionText.setText(version);
            } else {
                // don't have version, use default version.
                resourceVersionText.setText(SOAProjectConstants.DEFAULT_SERVICE_VERSION);
            }
        } else {
            versionFromWSDL = version;
            serviceVersionChanged(version);
        }
        serviceClientText.setText(getAdminName() + SOAProjectConstants.CLIENT_PROJECT_SUFFIX);
    } else {
        serviceClientText.setText(DEFAULT_TEXT_VALUE);
    }
}

From source file:org.ebayopensource.turmeric.eclipse.services.ui.wizards.pages.ConsumeServiceFromExistingWSDLWizardPage.java

@Override
public void wsdlChanged(final Definition wsdl) {
    final Collection<?> services = wsdl.getServices().values();
    if (services.size() > 0) {
        // only process the first service
        final Service service = (Service) services.toArray()[0];
        if (services.size() > 1) {
            logger.warning("Found multiple service, but only the first service will be processed->"
                    + service.getQName());
        }//w ww.j a v  a2s. com
        final String targetNs = wsdl.getTargetNamespace();
        targetNamespaceModified(targetNs);
        setTargetNamespace(targetNs);
        if (domainClassifierList == null) {
            // Non-MP
            String nsPart = StringUtils
                    .capitalize(getOrganizationProvider().getNamespacePartFromTargetNamespace(targetNs));
            this.domainName = nsPart;
            if (StringUtils.isNotBlank(nsPart)) {
                this.adminText.setText(nsPart + getAdminName());
            } else {
                this.adminText.setText(getPublicServiceName() + SOAProjectConstants.MAJOR_VERSION_PREFIX
                        + SOAServiceUtil.getServiceMajorVersion(getServiceVersion()));
            }
        }
        String version = SOAIntfUtil.getServiceVersionFromWsdl(wsdl, getPublicServiceName()).trim();
        if (resourceVersionText != null) {
            resourceVersionText.setEditable(true);
            if (StringUtils.isNotBlank(version)) {
                versionFromWSDL = version;
                // has version
                int versionPart = StringUtils.countMatches(version, SOAProjectConstants.DELIMITER_DOT);
                // add "dot number" to version. It will be changed to X.Y.Z
                if (versionPart == 2) {
                    // is new version format, set version text read-only.
                    resourceVersionText.setEditable(false);
                } else {
                    // is v2format
                    while (versionPart < 2) {
                        version += SOAProjectConstants.DELIMITER_DOT + "0";
                        versionPart++;
                    }
                }
                resourceVersionText.setText(version);
            } else {
                // don't have version, use default version.
                resourceVersionText.setText(SOAProjectConstants.DEFAULT_SERVICE_VERSION);
            }
        } else {
            versionFromWSDL = version;
            serviceVersionChanged(version);
        }
    }
}

From source file:org.ebayopensource.turmeric.eclipse.services.ui.wizards.pages.ServiceFromExistingWSDLWizardPage.java

@Override
public void wsdlChanged(Definition wsdl) {
    boolean nsChanged = false;
    if (wsdl != null) {
        try {/*from w  w  w.  j  a  va2s . c  o  m*/
            final String targetNamespace = WSDLUtil.getTargetNamespace(wsdl);
            if (StringUtils.isNotBlank(targetNamespace)) {
                setTypeNamespace(targetNamespace);
                setTargetNamespace(targetNamespace);
                nsChanged = true;
            }

        } catch (WSDLException e) {
            SOALogger.getLogger().warning(e);
            updateStatus(e.getLocalizedMessage());
        }
        if (domainClassifierList == null) {
            // Non-MP
            String nsPart = StringUtils.capitalize(
                    getOrganizationProvider().getNamespacePartFromTargetNamespace(getTargetNamespace()));
            if (StringUtils.isNotBlank(nsPart)) {
                getResourceNameText().setText(nsPart + getResourceName());
            } else {
                getResourceNameText().setText(getPublicServiceName() + SOAProjectConstants.MAJOR_VERSION_PREFIX
                        + SOAServiceUtil.getServiceMajorVersion(getServiceVersion()));
            }
        }
        String version = SOAIntfUtil.getServiceVersionFromWsdl(wsdl, getPublicServiceName()).trim();
        resourceVersionText.setEditable(true);
        versionFromWSDL = null;
        if (StringUtils.isNotBlank(version)) {
            versionFromWSDL = version;
            // has version
            int versionPart = StringUtils.countMatches(version, SOAProjectConstants.DELIMITER_DOT);
            // add "dot number" to version. It will be changed to X.Y.Z
            if (versionPart == 2) {
                // is new version format, set version text read-only.
                resourceVersionText.setEditable(false);
            } else {
                // is v2format
                while (versionPart < 2) {
                    version += SOAProjectConstants.DELIMITER_DOT + "0";
                    versionPart++;
                }
            }
            resourceVersionText.setText(version);
        } else {
            // don't have version, use default version.
            resourceVersionText.setText(SOAProjectConstants.DEFAULT_SERVICE_VERSION);
        }
    }

    if (nsChanged == false) {
        setTargetNamespace("");
        setTypeNamespace("");
    }
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java

private static boolean isNewStylePrototocol(String typeLibString) {
    return StringUtils.countMatches(typeLibString, SOATypeLibraryConstants.PROTOCOL_DELIMITER) == 2;
}