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:com.hp.autonomy.frontend.find.core.web.ControllerUtilsImpl.java

private String getBaseUrl(final HttpServletRequest request) {
    final String originalUri = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    final String requestUri = originalUri != null ? originalUri : request.getRequestURI();
    final String path = requestUri.replaceFirst(request.getContextPath(), "");
    final int depth = StringUtils.countMatches(path, "/") - 1;

    return depth <= 0 ? "." : StringUtils.repeat("../", depth);
}

From source file:com.samebug.clients.idea.ui.controller.search.ViewController.java

@Override
public void submitTip(final TabController tab, final String tip, final String rawSourceUrl) {
    if (tab == controller) {
        URI tmpSourceUrl = null;/*w w w . j  a v a2 s. co  m*/
        String errorKey = null;
        if (tip.length() < WriteTip.minCharacters) {
            errorKey = "samebug.tip.write.error.tip.short";
        } else if (tip.length() > WriteTip.maxCharacters) {
            errorKey = "samebug.tip.write.error.tip.long";
        } else if (StringUtils.countMatches(tip, TextUtil.lineSeparator) >= WriteTip.maxLines) {
            errorKey = "samebug.tip.write.error.tip.tooManyLines";
        } else {
            if (rawSourceUrl != null && !rawSourceUrl.trim().isEmpty()) {
                try {
                    tmpSourceUrl = new URL(rawSourceUrl).toURI();
                } catch (MalformedURLException e1) {
                    errorKey = "samebug.tip.write.error.source.malformed";
                } catch (URISyntaxException e) {
                    errorKey = "samebug.tip.write.error.source.malformed";
                }
            }
        }
        final String sourceUrl = tmpSourceUrl == null ? null : tmpSourceUrl.toString();
        if (errorKey != null) {
            controller.view.finishPostTipWithError(SamebugBundle.message(errorKey));
        } else {
            ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        IdeaSamebugPlugin.getInstance().getClient().postTip(controller.mySearchId, tip,
                                sourceUrl);
                    } catch (SamebugClientException e) {
                        LOGGER.warn("Failed to send tip", e);
                    }
                }
            });
        }
    }
}

From source file:net.sf.profiler4j.console.util.export.FilenameGenerator.java

/**
 * Checks to see, if the given pattern is correct syntactically, i.e. if the pattern makes sense.
 * <p>/*from   w w w.  j  a  v  a 2 s .c  o  m*/
 * See the class comment for a specification of what constitutes a valid pattern.
 * <p>
 * A pattern for which this method returns {@code true} may still be unusable, e.g. if the target directory
 * is write-protected.
 * 
 * @param pattern The pattern.
 * @return {@code true}, if the pattern is syntactically correct, {@code false} otherwise.
 */
public boolean isValidPattern(String pattern) {
    if (StringUtils.isBlank(pattern))
        return false;

    // It may not contain more than one placeholder for a running-number in the file name.
    String name = extractFileName(pattern);
    if (1 < StringUtils.countMatches(name, PLACEHOLDER__RUNNING_NUMBER))
        return false;

    // With placeholders removed, the pattern must constitute a valid filename in the current system.
    // To check this, we simply try to create the file.
    String pattern_without_placeholders = StringUtils.remove(pattern, "%i");
    if (!isPossibleToCreateFile(pattern_without_placeholders)) {
        return false;
    }
    return true;
}

From source file:io.cloudslang.lang.cli.services.SyncTriggerEventListener.java

@Override
public synchronized void onEvent(ScoreEvent scoreEvent) throws InterruptedException {
    @SuppressWarnings("unchecked")
    Map<String, Serializable> data = (Map<String, Serializable>) scoreEvent.getData();
    switch (scoreEvent.getEventType()) {
    case EventConstants.SCORE_FINISHED_EVENT:
        flowFinished.set(true);/*  ww  w  . ja va2 s. co  m*/
        break;
    case EventConstants.SCORE_ERROR_EVENT:
        errorMessage.set(SCORE_ERROR_EVENT_MSG + data.get(EventConstants.SCORE_ERROR_LOG_MSG) + " , "
                + data.get(EventConstants.SCORE_ERROR_MSG));
        break;
    case EventConstants.SCORE_FAILURE_EVENT:
        consolePrinter.printWithColor(RED, FLOW_FINISHED_WITH_FAILURE_MSG);
        flowFinished.set(true);
        break;
    case EventConstants.MAVEN_DEPENDENCY_BUILD:
        printDownloadArtifactMessage((String) data.get(EventConstants.MAVEN_DEPENDENCY_BUILD));
        break;
    case EventConstants.MAVEN_DEPENDENCY_BUILD_FINISHED:
        printDownloadArtifactMessage((String) data.get(EventConstants.MAVEN_DEPENDENCY_BUILD_FINISHED));
        break;
    case ScoreLangConstants.SLANG_EXECUTION_EXCEPTION:
        errorMessage.set(SLANG_STEP_ERROR_MSG + data.get(LanguageEventData.EXCEPTION));
        break;
    case ScoreLangConstants.EVENT_STEP_START:
        LanguageEventData eventData = (LanguageEventData) data;
        if (eventData.getStepType() == LanguageEventData.StepType.STEP) {
            String stepName = eventData.getStepName();
            String path = eventData.getPath();
            int matches = StringUtils.countMatches(path, ExecutionPath.PATH_SEPARATOR);
            String prefix = StringUtils.repeat(STEP_PATH_PREFIX, matches);
            consolePrinter.printWithColor(YELLOW, prefix + stepName);
        }
        break;
    case ScoreLangConstants.EVENT_OUTPUT_END:
        // Step end case
        if ((data.get(LanguageEventData.STEP_TYPE)).equals((LanguageEventData.StepType.STEP))) {
            if (this.isDebugMode) {
                Map<String, Serializable> stepOutputs = extractNotEmptyOutputs(data);
                String path = ((LanguageEventData) data).getPath();
                int matches = StringUtils.countMatches(path, ExecutionPath.PATH_SEPARATOR);
                String prefix = StringUtils.repeat(STEP_PATH_PREFIX, matches);

                for (Map.Entry<String, Serializable> entry : stepOutputs.entrySet()) {
                    consolePrinter.printWithColor(WHITE, prefix + entry.getKey() + " = " + entry.getValue());
                }
            }
        }

        // Flow end case
        else if (data.containsKey(LanguageEventData.OUTPUTS) && data.containsKey(LanguageEventData.PATH)
                && data.get(LanguageEventData.PATH).equals(EXEC_START_PATH)) {
            Map<String, Serializable> outputs = extractNotEmptyOutputs(data);
            if (outputs.size() > 0) {
                printForOperationOrFlow(data, WHITE, "\n" + OPERATION_OUTPUTS, "\n" + FLOW_OUTPUTS);
                for (Map.Entry<String, Serializable> entry : outputs.entrySet()) {
                    consolePrinter.printWithColor(WHITE, "- " + entry.getKey() + " = " + entry.getValue());
                }
            }
        }
        break;
    case ScoreLangConstants.EVENT_EXECUTION_FINISHED:
        flowFinished.set(true);
        printFinishEvent(data);
        break;
    default:
        break;
    }
}

From source file:edu.harvard.iq.dataverse.mydata.SolrQueryFormatterTest.java

private void makeQueryTest2(SolrQueryFormatter sqf, int numIds, String paramName, int numParamOccurrences) {

    Long[] idList = this.getListOfLongs(numIds);
    Set<Long> idListSet = new HashSet<>(Arrays.asList(idList));

    String queryClause = sqf.buildIdQuery(idListSet, paramName, null);
    msgt("query clause: " + queryClause);
    assertEquals(StringUtils.countMatches(queryClause, paramName), numParamOccurrences);
}

From source file:com.steeleforge.aem.ironsites.wcm.page.IronSitemap.java

/**
 * Determine inclusion path level and ammend it to paths map
 * //from   ww  w.j ava2 s . co m
 * @param page root page
 */
private void populateInclusions(Page root) {
    int base = root.getDepth();
    int level = -1;
    for (String path : getInclusions()) {
        // handle external links gracefully, assume level 0
        if (StringUtils.startsWith(path, "/")) {
            level = base - StringUtils.countMatches(path, "/") - 1;
        } else {
            level = -1;
        }
        if (level < 0) {
            level = ROOT_LEVEL;
        }
        getPaths(level).add(path);
    }
}

From source file:com.silverpeas.projectManager.model.TaskDetail.java

public TaskDetail(int id, int mereId, int chrono, String nom, String description, int organisateurId,
        int responsableId, float charge, float consomme, float raf, int statut, Date dateDebut, Date dateFin,
        String codeProjet, String descriptionProjet, int estDecomposee, String instanceId, String path) {
    this.id = id;
    this.mereId = mereId;
    this.chrono = chrono;
    this.nom = nom;
    this.description = description;
    this.organisateurId = organisateurId;
    this.responsableId = responsableId;
    this.charge = charge;
    this.consomme = consomme;
    this.raf = raf;
    this.statut = statut;
    this.dateDebut = dateDebut;
    this.dateFin = dateFin;
    this.codeProjet = codeProjet;
    this.descriptionProjet = descriptionProjet;
    this.estDecomposee = estDecomposee;
    this.instanceId = instanceId;
    this.path = path;
    // Initialize level because level has never been set before.
    this.level = StringUtils.countMatches(this.path, "/") - 2;
}

From source file:info.magnolia.jcr.util.PropertiesImportExport.java

/**
 * Transforms the keys to the following inner notation: <code>/some/path/node.prop</code> or
 * <code>/some/path/node.@type</code>.
 *//*from   w  w w . jav a  2s .c  o  m*/
private Properties keysToInnerFormat(Properties properties) {
    Properties cleaned = new OrderedProperties();

    for (Object o : properties.keySet()) {
        String orgKey = (String) o;
        // explicitly enforce certain syntax
        if (!orgKey.startsWith("/")) {
            throw new IllegalArgumentException("Missing trailing '/' for key: " + orgKey);
        }
        if (StringUtils.countMatches(orgKey, ".") > 1) {
            throw new IllegalArgumentException("Key must not contain more than one '.': " + orgKey);
        }
        if (orgKey.contains("@") && !orgKey.contains(".@")) {
            throw new IllegalArgumentException("Key containing '@' must be preceded by a '.': " + orgKey);
        }
        // if this is a node definition (no property)
        String newKey = orgKey;

        String propertyName = StringUtils.substringAfterLast(newKey, ".");
        String keySuffix = StringUtils.substringBeforeLast(newKey, ".");
        String path = StringUtils.removeStart(keySuffix, "/");

        // if this is a path (no property)
        if (StringUtils.isEmpty(propertyName)) {
            // no value --> is a node
            if (StringUtils.isEmpty(properties.getProperty(orgKey))) {
                // make this the type property if not defined otherwise
                if (!properties.containsKey(orgKey + ".@type")) {
                    cleaned.put(path + ".@type", NodeTypes.ContentNode.NAME);
                }
                continue;
            }
            throw new IllegalArgumentException(
                    "Key for a path (everything without a '.' is considered to be a path) must not contain a value ('='): "
                            + orgKey);
        }
        cleaned.put(path + "." + propertyName, properties.get(orgKey));
    }
    return cleaned;
}

From source file:aliview.primer.OligoCalc.java

public static double getEurofinsTM(String sequence) {

    sequence = sequence.toUpperCase();/*from w w  w .  ja va2  s  .c o m*/
    double L = sequence.length();
    double ng = StringUtils.countMatches(sequence, "G");
    double nc = StringUtils.countMatches(sequence, "C");
    double na = StringUtils.countMatches(sequence, "A");
    double nt = StringUtils.countMatches(sequence, "T");

    double tm;
    if (sequence.length() > 15) {
        tm = 69.3 + 41 * (ng + nc) / L - 650 / L;
    } else {
        tm = 2 * (na + nt) + 4 * (ng + nc);
    }

    return tm;
}

From source file:alluxio.cli.ConfigurationDocGeneratorTest.java

private void checkFileContents(String source, List<String> target, TYPE fType) throws Exception {
    assertTrue(fType.equals(TYPE.CSV) || fType.equals(TYPE.YML));
    //assert file contents
    if (fType == TYPE.CSV) {
        assertEquals(2, target.size());//  www .  jav a 2 s .  c  o  m
        assertEquals(ConfigurationDocGenerator.CSV_FILE_HEADER, target.get(0));
        assertEquals(source, target.get(1));
    } else if (fType == TYPE.YML) {
        assertEquals(StringUtils.countMatches(source, "\n") + 1, target.size());
        assertEquals(source, Joiner.on("\n").join(target));
    }
}