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.clican.pluto.dataprocess.dpl.parser.impl.FunctionParserImpl.java

private String processPriority(String dpl) throws DplParseException {
    dpl = dpl.trim();//ww  w  . j av a  2  s .  c  o  m
    String[] parts = dpl.split("[\\*\\+\\-\\/\\%\\^]");
    if (parts.length == 1) {
        return dpl;
    }
    String dplCopy = dpl;
    for (int i = 0; i < parts.length; i++) {
        int index = dplCopy.indexOf(parts[i]);
        dplCopy = dplCopy.substring(0, index) + " " + dplCopy.substring(index + parts[i].length());
    }
    String[] operations = dplCopy.split(" ");
    List<String> partList = new ArrayList<String>();
    int left = 0;
    int right = 0;
    boolean append = false;
    for (int i = 0; i < parts.length; i++) {
        String part = (operations[i] + parts[i]).trim();

        left += StringUtils.countMatches(parts[i].trim(), "(");

        right += StringUtils.countMatches(parts[i].trim(), ")");

        if (left == right && StringUtils.countMatches(parts[i].trim(), "(") == StringUtils
                .countMatches(parts[i].trim(), ")")) {
            partList.add(part);
            left = 0;
            right = 0;
        } else if (left > right) {
            if (!append) {
                partList.add(part);
                append = true;
            } else {
                String lastOne = partList.remove(partList.size() - 1);
                lastOne += part;
                partList.add(lastOne);
            }
        } else if (left == right) {
            String lastOne = partList.remove(partList.size() - 1);
            lastOne += part;
            partList.add(lastOne);
            left = 0;
            right = 0;
            append = false;
        } else {
            throw new DplParseException("?[" + dpl + "]???");
        }
    }
    if (left != 0 || right != 0) {
        throw new DplParseException("?[" + dpl + "]???");
    }
    String result = "";
    String previousOne = null;
    if (partList.size() == 1) {
        result = partList.get(0);
        if (StringUtils.countMatches(result, "(") > 0 && StringUtils.countMatches(result, "(") > 0) {
            return result;
        } else {
            return "(" + result + ")";
        }
    }
    for (int i = 0; i < partList.size(); i++) {
        String part = partList.get(i);

        if (part.startsWith("*") || part.startsWith("%") || part.startsWith("/") || part.startsWith("^")) {
            if (previousOne == null) {
                throw new DplParseException("?[" + dpl + "]");
            }
            if (FunctionOperation.containOperation(previousOne.substring(0, 1))) {
                previousOne = previousOne.substring(0, 1) + "(" + previousOne.substring(1) + part + ")";
            } else {
                previousOne = "(" + previousOne + part + ")";
            }
            if (i == partList.size() - 1) {
                if (StringUtils.isEmpty(result)) {
                    result = previousOne;
                } else {
                    result = "(" + result + previousOne + ")";
                }
            }
        } else {
            if (part.startsWith("+") || part.startsWith("-")) {
                result += previousOne;
            }
            previousOne = part;
            if (i == partList.size() - 1) {
                result = "(" + result + part + ")";
            }
        }
    }
    return result;
}

From source file:com.predic8.membrane.core.multipart.ReassembleTest.java

private void testXMLContentFilter(String xpath, int expectedNumberOfRemainingElements)
        throws IOException, XPathExpressionException {
    XMLContentFilter cf = new XMLContentFilter(xpath);
    Message m = getResponse();/*from w  w  w.j a v a  2 s  .c  o  m*/
    cf.removeMatchingElements(m);
    Assert.assertEquals("text/xml", m.getHeader().getContentType());
    Assert.assertEquals(expectedNumberOfRemainingElements + 1,
            StringUtils.countMatches(m.getBody().toString(), "<"));
}

From source file:ch.njol.skript.expressions.ExprChatFormat.java

@SuppressWarnings({ "null" }) //First parameter is marked as @NonNull and String#replaceAll won't return null
private static String convertToFriendly(String format) {
    format = format.replaceAll("%%", "%").replaceAll("%1\\$s", "[player]").replaceAll("%2\\$s", "[message]");
    //Format uses %s instead of %1$s and %2$s
    if (format.contains("%s")) {
        if (StringUtils.countMatches(format, "%s") >= 2) {
            // Format uses two %s, the order is player, message
            format = format.replaceFirst("%s", "[player]");
            format = format.replaceFirst("%s", "[message]");
        } else {/*from   w  ww.  j ava  2  s .com*/
            // Format mixes %<number>$s and %s
            format = format.replaceFirst("%s",
                    (format.contains("[player]") || format.contains("%1$s") ? "[message]" : "[player]"));
        }
    }
    return format;
}

From source file:ar.com.zauber.commons.web.uri.factory.RelativePathUriFactory.java

/**
 * Genera el path hasta la ruta de la aplicacin.
 * @param request/* w  w  w  .j a  v a  2s.  c  o m*/
 * @return path
 */
private String generarPath(final HttpServletRequest request, final String destination) {
    try {
        String encoding = request.getCharacterEncoding();
        if (StringUtils.isBlank(encoding)) {
            encoding = defaultEncoding;
        }
        // si estamos en un jsp...
        String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

        if (uri == null) {
            uri = request.getRequestURI();
        }
        uri = URLDecoder.decode(uri, encoding);

        // Saco el contexto
        uri = uri.substring(URLDecoder.decode(request.getContextPath(), encoding).length());

        final String[] ret = comunDenominador(uri, destination);
        uri = ret[0];
        // cuento los subs
        int slashes = StringUtils.countMatches(uri, "/");

        // si empezaba en barra resto 1
        if (uri.startsWith("/")) {
            slashes--;
        }

        final StringBuilder sb = new StringBuilder();
        boolean empty = true;
        for (int i = 0; i < slashes; i++) {
            empty = false;
            sb.append("..");
            if (i + 1 < slashes) {
                sb.append('/');
            }
        }
        if (empty) {
            sb.append('.');
        }

        sb.append(ret[1]);
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        throw new UnhandledException(e);
    }
}

From source file:com.pcms.core.util.UrlUtil.java

/**
 * ?/*from w ww .ja va2  s. c  o m*/
 *
 * @param uri URI {@link HttpServletRequest#getRequestURI()}
 * @return
 */
public static String[] getParams(String uri) {
    if (uri == null) {
        throw new IllegalArgumentException("URI can not be null");
    }
    if (!uri.startsWith("/")) {
        throw new IllegalArgumentException("URI must start width '/'");
    }
    int mi = uri.indexOf("-");
    int pi = uri.indexOf(".");
    String[] params;
    if (mi != -1) {
        String paramStr;
        if (pi != -1) {
            paramStr = uri.substring(mi, pi);
        } else {
            paramStr = uri.substring(mi);
        }
        params = new String[StringUtils.countMatches(paramStr, "-")];
        int fromIndex = 1;
        int nextIndex = 0;
        int i = 0;
        while ((nextIndex = paramStr.indexOf("-", fromIndex)) != -1) {
            params[i++] = paramStr.substring(fromIndex, nextIndex);
            fromIndex = nextIndex + 1;
        }
        params[i++] = paramStr.substring(fromIndex);
    } else {
        params = new String[0];
    }
    return params;
}

From source file:net.polydawn.mdm.Plumbing.java

public static boolean fetch(Repository repo, MdmModuleDependency module) throws ConfigInvalidException,
        MdmRepositoryIOException, MdmRepositoryStateException, MdmException, IOException {
    switch (module.getStatus().getType()) {
    case MISSING:
        throw new MajorBug();
    case UNINITIALIZED:
        if (module.getRepo() == null)
            try {
                RepositoryBuilder builder = new RepositoryBuilder();
                builder.setWorkTree(new File(repo.getWorkTree() + "/" + module.getPath()));
                builder.setGitDir(new File(repo.getDirectory() + "/modules/" + module.getPath()));
                module.repo = builder.build();

                // we actually *might* not have to make the repo from zero.
                // this getRepo gets its effective data from SubmoduleWalk.getSubmoduleRepository...
                // which does its job by looking in the working tree of the parent repo.
                // meaning if it finds nothing, it certainly won't find any gitdir indirections.
                // so, even if this is null, we might well have a gitdir cached that we still have to go find.
                final FileBasedConfig cfg = (FileBasedConfig) module.repo.getConfig();
                if (!cfg.getFile().exists()) { // though seemly messy, this is the same question the jgit create() function asks, and it's not exposed to us, so.
                    module.repo.create(false);
                } else {
                    // do something crazy, because... i think the user's expectation after blowing away their submodule working tree is likely wanting a clean state of index and such here
                    try {
                        new Git(module.getRepo()).reset().setMode(ResetType.HARD).call();
                    } catch (CheckoutConflictException e) {
                        /* Can a hard reset even have a conflict? */
                        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
                    } catch (GitAPIException e) {
                        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
                    }/*from  ww w.  j  a  v  a2 s.co  m*/
                }

                // set up a working tree which points to the gitdir in the parent repo:

                // handling paths in java, god forbid relative paths, is such an unbelievable backwater.  someday please make a whole library that actually disambiguates pathnames from filedescriptors properly
                int ups = StringUtils.countMatches(module.getPath(), "/");
                // look up the path between the `repo` and its possible git dir location.  if the gitdir is relocated, we have adjust our own relocations to compensate.
                String parentGitPointerStr = ".git/";
                String parentWorktreePointerStr = "../";
                // load it ourselves because we explicitly want the unresolved path, not what jgit would give us back from `repo.getDirectory().toString()`.
                File parentGitPointer = new File(repo.getWorkTree(), ".git");
                if (parentGitPointer.isFile()) {
                    // this shouldn't have to be recursive fortunately (that recursion is done implicitly by the chaining of each guy at each stage).
                    // this does however feel fairly fragile.  it's considerable that perhaps we should try to heuristically determine when paths are just to crazy to deal with.  but, on the off chance that check was overzealous, it would be very irritating, so let's not.
                    // frankly, if you're doing deeply nested submodules, or other advanced gitdir relocations, at some point you're taking it upon yourself to deal with the inevitably complex outcomes and edge case limitations.
                    parentGitPointerStr = IOForge.readFileAsString(parentGitPointer);
                    if (!"gitdir:".equals(parentGitPointerStr.substring(0, 7)))
                        throw new ConfigInvalidException(
                                "cannot understand location of parent project git directory");
                    parentGitPointerStr = parentGitPointerStr.substring(7).trim() + "/";
                    parentWorktreePointerStr = repo.getConfig().getString("core", null, "worktree") + "/";
                }
                // jgit does not appear to create the .git file correctly here :/
                // nor even consider it to be jgit's job to create the worktree yet, apparently, so do that
                module.repo.getWorkTree().mkdirs();
                // need modules/[module]/config to contain 'core.worktree' = appropriate
                String submoduleWorkTreeRelativeToGitDir = StringUtils.repeat("../", ups + 2)
                        + parentWorktreePointerStr + module.getPath();
                StoredConfig cnf = module.repo.getConfig();
                cnf.setString("core", null, "worktree", submoduleWorkTreeRelativeToGitDir);
                cnf.save();
                // need [module]/.git to contain 'gitdir: appropriate' (which appears to not be normal gitconfig)
                String submoduleGitDirRelativeToWorkTree = StringUtils.repeat("../", ups + 1)
                        + parentGitPointerStr + "modules/" + module.getPath();
                IOForge.saveFile("gitdir: " + submoduleGitDirRelativeToWorkTree + "\n",
                        new File(module.repo.getWorkTree(), ".git"));
            } catch (IOException e) {
                throw new MdmRepositoryIOException("create a new submodule", true, module.getHandle(), e);
            }

        try {
            if (initLocalConfig(repo, module))
                repo.getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true, "the local git configuration file", e);
        }
        try {
            setMdmRemote(module);
            module.getRepo().getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true,
                    "the git configuration file for submodule " + module.getHandle(), e);
        }
    case INITIALIZED:
        if (module.getVersionName() == null || module.getVersionName().equals(module.getVersionActual()))
            return false;
    case REV_CHECKED_OUT:
        try {
            if (initModuleConfig(repo, module))
                module.getRepo().getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true,
                    "the git configuration file for submodule " + module.getHandle(), e);
        }

        final String versionBranchName = "refs/heads/mdm/release/" + module.getVersionName();
        final String versionTagName = "refs/tags/release/" + module.getVersionName();

        /* Fetch only the branch labelled with the version requested. */
        if (module.getRepo().getRef(versionBranchName) == null)
            try {
                RefSpec releaseBranchRef = new RefSpec().setForceUpdate(true).setSource(versionBranchName)
                        .setDestination(versionBranchName);
                RefSpec releaseTagRef = new RefSpec().setForceUpdate(true).setSource(versionTagName)
                        .setDestination(versionTagName);
                new Git(module.getRepo()).fetch().setRemote("origin")
                        .setRefSpecs(releaseBranchRef, releaseTagRef).setTagOpt(TagOpt.NO_TAGS).call();
            } catch (InvalidRemoteException e) {
                throw new MdmRepositoryStateException(
                        "find a valid remote origin in the config for the submodule", module.getHandle(), e);
            } catch (TransportException e) {
                URIish remote = null;
                try { //XXX: if we went through all the work to resolve the remote like the fetch command does, we could just as well do it and hand the resolved uri to fetch for better consistency.
                    remote = new RemoteConfig(module.getRepo().getConfig(), "origin").getURIs().get(0);
                } catch (URISyntaxException e1) {
                }
                throw new MdmRepositoryIOException("fetch from a remote", false, remote.toASCIIString(), e)
                        .setAdditionalMessage("check your connectivity and try again?");
            } catch (GitAPIException e) {
                throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
            }

        /* Drop the files into the working tree. */
        try {
            new Git(module.getRepo()).checkout().setName(versionBranchName).setForce(true).call();
        } catch (RefAlreadyExistsException e) {
            /* I'm not creating a new branch, so this exception wouldn't even make sense. */
            throw new MajorBug(e);
        } catch (RefNotFoundException e) {
            /* I just got this branch, so we shouldn't have a problem here. */
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (InvalidRefNameException e) {
            /* I just got this branch, so we shouldn't have a problem here. */
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (CheckoutConflictException e) {
            // this one is just a perfectly reasonable message with a list of files in conflict; we'll take it.
            throw new MdmRepositoryStateException(module.getHandle(), e); // this currently gets translated to a :'( exception and it's probably more like a :(
        } catch (GitAPIException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        }
        return true;
    default:
        throw new MajorBug();
    }
}

From source file:com.intuit.tank.auth.TankAuthenticator.java

public String login() {
    String login = identity.login();
    if (login == "success") {
        if (uri == null || StringUtils.countMatches(uri, "/") <= 1) {
            return "/projects/index.xhtml";
        }//from   www  .j  av a  2s.  c  o  m
    }
    return uri;
}

From source file:cc.kune.core.server.utils.XmlW.java

/**
 * Gets the index closing tag.//from   www . j  a  v  a  2s.c  om
 * 
 * @param tag
 *          the tag
 * @param text
 *          the text
 * @param start
 *          the start
 * @return the index closing tag
 */
static public int getIndexClosingTag(final String tag, final String text, final int start) {
    final String open = "<" + tag;
    final String close = "</" + tag + ">";
    // System.err.println("OPEN: "+open);
    // System.err.println("CLOSE: "+close);
    final int closeSz = close.length();
    int nextCloseIdx = text.indexOf(close, start);
    // System.err.println("first close: "+nextCloseIdx);
    if (nextCloseIdx == -1) {
        return -1;
    }
    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:com.haulmont.cuba.core.global.EntityLoadInfoBuilder.java

/**
 * Parse an info from the string./*w  ww  . j  av a2  s . c o m*/
 *
 * @param str string representation of the info. See {@link EntityLoadInfo} for formats.
 * @return info instance or null if the string can not be parsed. Any exception is silently swallowed.
 */
@Nullable
public EntityLoadInfo parse(String str) {
    boolean isNew = false;
    if (str.startsWith(EntityLoadInfo.NEW_PREFIX)) {
        str = str.substring("NEW-".length());
        isNew = true;
    }

    int idDashPos = str.indexOf('-');
    if (idDashPos == -1) {
        if (isNew) {
            MetaClass metaClass = metadata.getSession().getClass(str);
            if (metaClass == null) {
                return null;
            }
            Entity entity = metadata.create(metaClass);
            MetaProperty primaryKeyProp = metadata.getTools().getPrimaryKeyProperty(metaClass);
            boolean stringKey = primaryKeyProp != null && primaryKeyProp.getJavaType().equals(String.class);
            return new EntityLoadInfo(entity.getId(), metaClass, null, stringKey, true);
        }
        return null;
    }

    String entityName = str.substring(0, idDashPos);
    MetaClass metaClass = metadata.getSession().getClass(entityName);
    if (metaClass == null) {
        return null;
    }

    Object id;
    String viewName;
    boolean stringKey = false;

    MetaProperty primaryKeyProp = metadata.getTools().getPrimaryKeyProperty(metaClass);
    if (primaryKeyProp == null)
        return null;

    if (primaryKeyProp.getJavaType().equals(UUID.class)) {
        int viewDashPos = -1;
        int dashCount = StringUtils.countMatches(str, "-");
        if (dashCount < 5) {
            return null;
        }
        if (dashCount >= 6) {
            int i = 0;
            while (i < 6) {
                viewDashPos = str.indexOf('-', viewDashPos + 1);
                i++;
            }

            viewName = str.substring(viewDashPos + 1);
        } else {
            viewDashPos = str.length();
            viewName = null;
        }
        String entityIdStr = str.substring(idDashPos + 1, viewDashPos);
        try {
            id = UuidProvider.fromString(entityIdStr);
        } catch (Exception e) {
            return null;
        }
    } else {
        String entityIdStr;
        if (primaryKeyProp.getJavaType().equals(String.class)) {
            stringKey = true;
            int viewDashPos = str.indexOf("}-", idDashPos + 2);
            if (viewDashPos > -1) {
                viewName = str.substring(viewDashPos + 2);
            } else {
                viewDashPos = str.length() - 1;
                viewName = null;
            }
            entityIdStr = str.substring(idDashPos + 2, viewDashPos);
        } else {
            int viewDashPos = str.indexOf('-', idDashPos + 1);
            if (viewDashPos > -1) {
                viewName = str.substring(viewDashPos + 1);
            } else {
                viewDashPos = str.length();
                viewName = null;
            }
            entityIdStr = str.substring(idDashPos + 1, viewDashPos);
        }
        try {
            if (primaryKeyProp.getJavaType().equals(Long.class)) {
                id = Long.valueOf(entityIdStr);
            } else if (primaryKeyProp.getJavaType().equals(Integer.class)) {
                id = Integer.valueOf(entityIdStr);
            } else {
                id = entityIdStr;
            }
        } catch (Exception e) {
            return null;
        }
    }

    return new EntityLoadInfo(id, metaClass, viewName, stringKey, isNew);
}

From source file:com.itbeyond.common.EOTrackMeClient.java

public void OnCompleteLocation() {
    EOTrackMe.removeSentLines(data);//from w  ww. j  a va2 s.co  m
    sentLocationsCount = StringUtils.countMatches(data, "|");
    Utilities.LogDebug("Sent locations count: " + sentLocationsCount);

    updateStatus("Last Send: " + sentLocationsCount);

    OnComplete();
}