Example usage for org.apache.commons.lang3 StringUtils countMatches

List of usage examples for org.apache.commons.lang3 StringUtils countMatches

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils countMatches.

Prototype

public static int countMatches(final CharSequence str, final char ch) 

Source Link

Document

Counts how many times the char appears in the given string.

A null or empty ("") String input returns 0 .

 StringUtils.countMatches(null, *)       = 0 StringUtils.countMatches("", *)         = 0 StringUtils.countMatches("abba", 0)  = 0 StringUtils.countMatches("abba", 'a')   = 2 StringUtils.countMatches("abba", 'b')  = 2 StringUtils.countMatches("abba", 'x') = 0 

Usage

From source file:rapture.kernel.DocApiImpl.java

@Override
public Map<String, RaptureFolderInfo> listDocsByUriPrefix(CallingContext context, String uriPrefix, int depth) {
    RaptureURI internalUri = new RaptureURI(uriPrefix, Scheme.DOCUMENT);
    String authority = internalUri.getAuthority();
    Map<String, RaptureFolderInfo> ret = new HashMap<String, RaptureFolderInfo>();

    // Schema level is special case.
    if (authority.isEmpty()) {
        --depth;//  w  w w.j a  v  a 2s .co  m
        try {
            List<DocumentRepoConfig> configs = this.getDocRepoConfigs(context);
            for (DocumentRepoConfig config : configs) {
                authority = config.getAuthority();
                // NULL or empty string should not exist.
                if ((authority == null) || authority.isEmpty()) {
                    log.warn("Invalid authority (null or empty string) found for "
                            + JacksonUtil.jsonFromObject(config));
                    continue;
                }
                String uri = Scheme.DOCUMENT + "://" + authority;
                ret.put(uri, new RaptureFolderInfo(authority, true));
                if (depth != 0) {
                    ret.putAll(listDocsByUriPrefix(context, uri, depth));
                }
            }

        } catch (RaptureException e) {
            // permission denied
            log.debug("No read permission for " + uriPrefix);
        }
        return ret;
    }

    Repository repository = getRepoFromCache(authority);
    if (repository == null) {
        return ret;
    }

    String parentDocPath = internalUri.getDocPath() == null ? "" : internalUri.getDocPath();
    int startDepth = StringUtils.countMatches(parentDocPath, "/");

    if (log.isDebugEnabled()) {
        log.debug("Loading all children from repo " + internalUri.getAuthority() + " with "
                + internalUri.getDocPath());
    }

    Boolean getAll = (depth <= 0);

    Stack<String> parentsStack = new Stack<String>();
    parentsStack.push(parentDocPath);

    while (!parentsStack.isEmpty()) {
        String currParentDocPath = parentsStack.pop();
        int currDepth = StringUtils.countMatches(currParentDocPath, "/") - startDepth;
        if (!getAll && currDepth >= depth)
            continue;
        boolean top = currParentDocPath.isEmpty();

        // Make sure that you have permission to read the folder.
        try {
            GetDocPayload requestObj = new GetDocPayload();
            requestObj.setContext(context);
            requestObj.setDocUri(currParentDocPath);
            ContextValidator.validateContext(context, EntitlementSet.Doc_listDocsByUriPrefix, requestObj);
        } catch (RaptureException e) {
            // permission denied
            log.debug("No read permission on folder " + currParentDocPath);
            continue;
        }

        List<RaptureFolderInfo> children = repository.getChildren(currParentDocPath);
        if (((children == null) || children.isEmpty()) && (currDepth == 0) && internalUri.hasDocPath()) {
            // return empty result
            return ret;
        } else if (children != null) {
            for (RaptureFolderInfo child : children) {
                String name = child.getName();
                String childDocPath = currParentDocPath + (top ? "" : "/") + name;
                if (name.isEmpty())
                    continue;
                String uri = RaptureURI.builder(Scheme.DOCUMENT, authority).docPath(childDocPath).asString()
                        + (child.isFolder() ? "/" : "");
                ret.put(uri, child);
                if (child.isFolder()) {
                    parentsStack.push(childDocPath);
                }
            }
        }
        if (top)
            startDepth--; // special case
    }
    return ret;
}

From source file:rapture.kernel.ScriptApiImpl.java

@Override
public Map<String, RaptureFolderInfo> listScriptsByUriPrefix(CallingContext context, String uriPrefix,
        int depth) {
    RaptureURI internalUri = new RaptureURI(uriPrefix, Scheme.SCRIPT);
    Boolean getAll = false;/*  w ww  .  j av a  2s . com*/
    String authority = internalUri.getAuthority();
    Map<String, RaptureFolderInfo> ret = new HashMap<String, RaptureFolderInfo>();

    // Schema level is special case.
    if (authority.isEmpty()) {
        --depth;
        try {
            List<RaptureFolderInfo> children = RaptureScriptStorage.getChildren("");
            for (RaptureFolderInfo child : children) {
                if (child.getName().isEmpty())
                    continue;
                String uri = "script://" + child.getName();
                ret.put(uri, child);
                if (depth != 0) {
                    ret.putAll(listScriptsByUriPrefix(context, uri, depth));
                }
            }

        } catch (RaptureException e) {
            // permission denied
            log.debug("No read permission for " + uriPrefix);
        }
        return ret;
    }

    String parentDocPath = internalUri.getShortPath();
    if (parentDocPath.endsWith("/"))
        parentDocPath = parentDocPath.substring(0, parentDocPath.length() - 1);

    if (log.isDebugEnabled()) {
        log.debug("Loading all children from repo " + internalUri.getAuthority() + " with " + parentDocPath);
    }
    if (depth <= 0)
        getAll = true;

    Stack<String> parentsStack = new Stack<String>();
    parentsStack.push(parentDocPath);

    int startDepth = StringUtils.countMatches(parentDocPath, "/");

    while (!parentsStack.isEmpty()) {
        String currParentDocPath = parentsStack.pop();
        int currDepth = StringUtils.countMatches(currParentDocPath, "/") - startDepth;
        if (!getAll && currDepth >= depth)
            continue;

        // Make sure that you have permission to read the folder.
        try {
            GetScriptPayload requestObj = new GetScriptPayload();
            requestObj.setContext(context);
            // Note: Inconsistent
            requestObj.setScriptURI(currParentDocPath);
            ContextValidator.validateContext(context, EntitlementSet.Script_listScriptsByUriPrefix, requestObj);
        } catch (RaptureException e) {
            // permission denied
            log.debug("No read permission on folder " + currParentDocPath);
            continue;
        }

        boolean top = currParentDocPath.isEmpty();
        List<RaptureFolderInfo> children = RaptureScriptStorage.getChildren(currParentDocPath);

        if (((children == null) || children.isEmpty()) && (currDepth == 0) && internalUri.hasDocPath()) {
            return ret;
        } else if (children != null) {
            for (RaptureFolderInfo child : children) {
                String childDocPath = currParentDocPath + (top ? "" : "/") + child.getName();
                if (child.getName().isEmpty())
                    continue;
                // Special case: for Scripts childDocPath includes the authority

                String childUri = Scheme.SCRIPT + "://" + childDocPath + (child.isFolder() ? "/" : "");
                ret.put(childUri, child);
                if (child.isFolder()) {
                    parentsStack.push(childDocPath);
                }
            }
        }

    }
    return ret;
}

From source file:rapture.kernel.SeriesApiImpl.java

@Override
public Map<String, RaptureFolderInfo> listSeriesByUriPrefix(CallingContext context, String uriPrefix,
        int depth) {
    RaptureURI internalUri = new RaptureURI(uriPrefix, SERIES);
    String authority = internalUri.getAuthority();
    Map<String, RaptureFolderInfo> ret = new HashMap<String, RaptureFolderInfo>();

    // Schema level is special case.
    if (authority.isEmpty()) {
        --depth;//from   w  w w.java 2 s . c  o m
        try {
            List<SeriesRepoConfig> configs = getSeriesRepoConfigs(context);
            for (SeriesRepoConfig config : configs) {
                authority = config.getAuthority();
                // NULL or empty string should not exist.
                if ((authority == null) || authority.isEmpty()) {
                    log.warn("Invalid authority (null or empty string) found for "
                            + JacksonUtil.jsonFromObject(config));
                    continue;
                }
                String uri = new RaptureURI(authority, SERIES).toString();
                ret.put(uri, new RaptureFolderInfo(authority, true));
                if (depth != 0) {
                    ret.putAll(listSeriesByUriPrefix(context, uri, depth));
                }
            }

        } catch (RaptureException e) {
            // permission denied
            log.debug("No read permission for " + uriPrefix);
        }
        return ret;
    }

    SeriesRepo repo = getRepoFromCache(internalUri.getAuthority());
    Boolean getAll = false;
    if (repo == null) {
        return ret;
    }
    String parentDocPath = internalUri.getDocPath() == null ? "" : internalUri.getDocPath();
    int startDepth = StringUtils.countMatches(parentDocPath, "/");

    if (log.isDebugEnabled()) {
        log.debug("Loading all children from repo " + internalUri.getAuthority() + " with "
                + internalUri.getDocPath());
    }
    if (depth <= 0)
        getAll = true;

    Stack<String> parentsStack = new Stack<String>();
    parentsStack.push(parentDocPath);

    while (!parentsStack.isEmpty()) {
        String currParentDocPath = parentsStack.pop();
        int currDepth = StringUtils.countMatches(currParentDocPath, "/") - startDepth;
        if (!getAll && currDepth >= depth)
            continue;
        boolean top = currParentDocPath.isEmpty();
        // Make sure that you have permission to read the folder.
        try {
            ListSeriesByUriPrefixPayload requestObj = new ListSeriesByUriPrefixPayload();
            requestObj.setContext(context);
            requestObj.setSeriesUri(currParentDocPath);
            ContextValidator.validateContext(context, EntitlementSet.Series_listSeriesByUriPrefix, requestObj);
        } catch (RaptureException e) {
            // permission denied
            log.debug("No read permission on folder " + currParentDocPath);
            continue;
        }

        List<RaptureFolderInfo> children = repo.listSeriesByUriPrefix(currParentDocPath);
        if ((children == null) || (children.isEmpty()) && (currDepth == 0) && (internalUri.hasDocPath())) {
            return ret;
        } else {
            for (RaptureFolderInfo child : children) {
                String childDocPath = currParentDocPath + (top ? "" : "/") + child.getName();
                if (child.getName().isEmpty())
                    continue;
                String childUri = RaptureURI.builder(Scheme.SERIES, authority).docPath(childDocPath).asString()
                        + (child.isFolder() ? "/" : "");
                ret.put(childUri, child);
                if (child.isFolder()) {
                    parentsStack.push(childDocPath);
                }
            }
        }
        if (top)
            startDepth--; // special case
    }
    return ret;
}

From source file:rs.metropolitan.data_changer.base.ToDouble.java

@Override
public Double changeString(String data) {
    try {/*ww  w .j av a  2s  .c  o  m*/
        String dot = ".";
        String beforeDot = StringUtils.substringBefore(data, dot);
        String afterDot = StringUtils.substringBefore(data, dot);
        if (StringUtils.isNumeric(beforeDot) && StringUtils.isNumeric(afterDot)
                && StringUtils.countMatches(data, dot) == 1) {
            return new Double(data);
        }
        return null;
    } catch (NumberFormatException ex) {
        System.err.print(ex.getLocalizedMessage());
        return null;
    } catch (Exception ex) {
        System.err.print(ex.getLocalizedMessage());
        return null;
    }
}

From source file:rs.metropolitan.data_changer.base.ToInteger.java

@Override
public Integer changeString(String data) {
    try {//from w w w.  j  ava2  s  .c o  m
        String dot = ".";
        if (StringUtils.isNumeric(data) && StringUtils.countMatches(data, dot) == 0) {
            return new Integer(data);
        }
        return null;
    } catch (NumberFormatException ex) {
        System.err.print(ex.getLocalizedMessage());
        return null;
    } catch (Exception ex) {
        System.err.print(ex.getLocalizedMessage());
        return null;
    }
}

From source file:schemareader.Element.java

/**
 * Gets depth//  ww w  . j a va2  s. c  om
 *
 * @return Depth as a <code>int</code>
 */
public int getDepth() {
    return StringUtils.countMatches(this.fullPath, "/") + 1;
}

From source file:se.trixon.jota.client.ui.editor.module.DualListPanel.java

private String requestArg(OptionHandler optionHandler) {
    String input = JOptionPane.showInputDialog(this, optionHandler.getLongArg(), optionHandler.getTitle(),
            JOptionPane.PLAIN_MESSAGE);

    if (input != null) {
        input = input.trim();//from ww w.  j a v a  2 s  . c o  m
        boolean invalidInput = StringUtils.isBlank(input);

        String[] intKeys = { "num", "port", "rate", "seconds", "size" };
        String argType = StringUtils.split(optionHandler.getLongArg(), "=", 2)[1].toLowerCase();

        boolean shouldBeInt = ArrayUtils.contains(intKeys, argType);

        if (shouldBeInt) {
            try {
                Integer.parseInt(input);
            } catch (NullPointerException | NumberFormatException e) {
                invalidInput = true;
            }
        } else if (optionHandler instanceof RsyncOption && optionHandler == RsyncOption.CHOWN) {
            invalidInput = input.startsWith(":") || input.endsWith(":")
                    || StringUtils.countMatches(input, ":") != 1;
        }

        if (invalidInput) {
            Message.error(this, "Invalid input", "try again");
            input = requestArg(optionHandler);
        } else {
            return input;
        }
    }

    return input;
}

From source file:starnubserver.resources.connections.Players.java

/**
 * Recommended: For Plugin Developers & Anyone else.
 * <p>/*from   ww  w  .  ja v a 2 s  .c o  m*/
 * Uses: This method is used to pull a player record using any type of
 * parameter. (Packet, Uuid, IP, NAME, clientCTX, Starbound ID, StarNub ID)
 * <p>
 * @param playerIdentifier Object that represent a player and it can take many forms
 * @return Player which represents the player that was retrieved by the provided playerIdentifier
 */
public PlayerSession getOnlinePlayerByAnyIdentifier(Object playerIdentifier) {
    if (playerIdentifier instanceof PlayerSession) {
        return (PlayerSession) playerIdentifier;
    } else if (playerIdentifier instanceof Packet) {
        return playerByPacket((Packet) playerIdentifier);
    } else if (playerIdentifier instanceof String) {
        String identifierString = (String) playerIdentifier;
        if (isStarNubId(identifierString)) {
            return playerByStarNubClientID(Integer.parseInt(identifierString.replaceAll("[sS]", "")));
        } else if (StringUtils.countMatches(identifierString, "-") >= 4) {
            return playerByUUID(UUID.fromString(identifierString));
        } else if (StringUtils.countMatches(identifierString, ".") == 3) {
            try {
                return playerByIP(InetAddress.getByName(identifierString));
            } catch (UnknownHostException e) {
                return null;
            }
        } else {
            try {
                return playerByStarboundClientID(Integer.parseInt(identifierString));
            } catch (Exception e) {
                return playerByName(identifierString);
            }
        }
    } else if (playerIdentifier instanceof UUID) {
        return playerByUUID((UUID) playerIdentifier);
    } else if (playerIdentifier instanceof InetAddress) {
        return playerByIP((InetAddress) playerIdentifier);
    } else if (playerIdentifier instanceof ChannelHandlerContext) {
        return playerByCTX((ChannelHandlerContext) playerIdentifier);
    } else if (playerIdentifier instanceof Integer) {
        return playerByStarboundClientID((int) playerIdentifier);
    } else {
        return null;
    }
}

From source file:syncthing.android.service.SyncthingUtils.java

public static boolean isIpAddress(String ipAddress) {
    if (ipv4Pattern.matcher(ipAddress).matches()) {
        return true;
    }//from  ww w . ja  va  2s .c  o  m
    if (ipv6Pattern.matcher(ipAddress).matches()) {
        return true;
    }
    //just assume the user input a valid ipv6 addr
    return StringUtils.countMatches(ipAddress, "::") > 0;
}

From source file:syncthing.android.service.SyncthingUtils.java

public static boolean isIpAddressWithPort(String ipAddress) {
    if (ipv4PatternPort.matcher(ipAddress).matches()) {
        return true;
    }//  ww  w . j  av a 2s  .c  o  m
    if (ipv6PatternPort.matcher(ipAddress).matches()) {
        return true;
    }
    //just assume the user input a valid ipv6 addr
    return StringUtils.countMatches(ipAddress, "::") > 0;
}