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

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

Introduction

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

Prototype

public static boolean contains(final CharSequence seq, final CharSequence searchSeq) 

Source Link

Document

Checks if CharSequence contains a search CharSequence, handling null .

Usage

From source file:ch.cyberduck.core.ftp.FTPMlsdListResponseReader.java

@Override
public AttributedList<Path> read(final Path directory, final List<String> replies,
        final ListProgressListener listener)
        throws IOException, FTPInvalidListException, ConnectionCanceledException {
    final AttributedList<Path> children = new AttributedList<Path>();
    // At least one entry successfully parsed
    boolean success = false;
    for (String line : replies) {
        final Map<String, Map<String, String>> file = this.parseFacts(line);
        if (null == file) {
            log.error(String.format("Error parsing line %s", line));
            continue;
        }//from  w w  w.j a  v  a 2 s  .c  o  m
        for (Map.Entry<String, Map<String, String>> f : file.entrySet()) {
            final String name = f.getKey();
            // size       -- Size in octets
            // modify     -- Last modification time
            // create     -- Creation time
            // type       -- Entry type
            // unique     -- Unique id of file/directory
            // perm       -- File permissions, whether read, write, execute is allowed for the login id.
            // lang       -- Language of the file name per IANA [11] registry.
            // media-type -- MIME media-type of file contents per IANA registry.
            // charset    -- Character set per IANA registry (if not UTF-8)
            final Map<String, String> facts = f.getValue();
            if (!facts.containsKey("type")) {
                log.error(String.format("No type fact in line %s", line));
                continue;
            }
            final Path parsed;
            if ("dir".equals(facts.get("type").toLowerCase(Locale.ROOT))) {
                parsed = new Path(directory, PathNormalizer.name(f.getKey()), EnumSet.of(Path.Type.directory));
            } else if ("file".equals(facts.get("type").toLowerCase(Locale.ROOT))) {
                parsed = new Path(directory, PathNormalizer.name(f.getKey()), EnumSet.of(Path.Type.file));
            } else if (facts.get("type").toLowerCase(Locale.ROOT).matches("os\\.unix=slink:.*")) {
                parsed = new Path(directory, PathNormalizer.name(f.getKey()),
                        EnumSet.of(Path.Type.file, Path.Type.symboliclink));
                // Parse symbolic link target in Type=OS.unix=slink:/foobar;Perm=;Unique=keVO1+4G4; foobar
                final String[] type = facts.get("type").split(":");
                if (type.length == 2) {
                    final String target = type[1];
                    if (target.startsWith(String.valueOf(Path.DELIMITER))) {
                        parsed.setSymlinkTarget(new Path(target, EnumSet.of(Path.Type.file)));
                    } else {
                        parsed.setSymlinkTarget(
                                new Path(String.format("%s/%s", directory.getAbsolute(), target),
                                        EnumSet.of(Path.Type.file)));
                    }
                } else {
                    log.warn(String.format("Missing symbolic link target for type %s in line %s",
                            facts.get("type"), line));
                    continue;
                }
            } else {
                log.warn(String.format("Ignored type %s in line %s", facts.get("type"), line));
                continue;
            }
            if (!success) {
                if (parsed.isDirectory() && directory.getName().equals(name)) {
                    log.warn(String.format("Possibly bogus response line %s", line));
                } else {
                    success = true;
                }
            }
            if (name.equals(".") || name.equals("..")) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Skip %s", name));
                }
                continue;
            }
            if (facts.containsKey("size")) {
                parsed.attributes().setSize(Long.parseLong(facts.get("size")));
            }
            if (facts.containsKey("unix.uid")) {
                parsed.attributes().setOwner(facts.get("unix.uid"));
            }
            if (facts.containsKey("unix.owner")) {
                parsed.attributes().setOwner(facts.get("unix.owner"));
            }
            if (facts.containsKey("unix.gid")) {
                parsed.attributes().setGroup(facts.get("unix.gid"));
            }
            if (facts.containsKey("unix.group")) {
                parsed.attributes().setGroup(facts.get("unix.group"));
            }
            if (facts.containsKey("unix.mode")) {
                parsed.attributes().setPermission(new Permission(facts.get("unix.mode")));
            } else if (facts.containsKey("perm")) {
                Permission.Action user = Permission.Action.none;
                final String flags = facts.get("perm");
                if (StringUtils.contains(flags, 'r') || StringUtils.contains(flags, 'l')) {
                    // RETR command may be applied to that object
                    // Listing commands, LIST, NLST, and MLSD may be applied
                    user.or(Permission.Action.read);
                }
                if (StringUtils.contains(flags, 'w') || StringUtils.contains(flags, 'm')
                        || StringUtils.contains(flags, 'c')) {
                    user.or(Permission.Action.write);
                }
                if (StringUtils.contains(flags, 'e')) {
                    // CWD command naming the object should succeed
                    user.or(Permission.Action.execute);
                }
                final Permission permission = new Permission(user, Permission.Action.none,
                        Permission.Action.none);
                parsed.attributes().setPermission(permission);
            }
            if (facts.containsKey("modify")) {
                // Time values are always represented in UTC
                parsed.attributes().setModificationDate(this.parseTimestamp(facts.get("modify")));
            }
            if (facts.containsKey("create")) {
                // Time values are always represented in UTC
                parsed.attributes().setCreationDate(this.parseTimestamp(facts.get("create")));
            }
            children.add(parsed);
        }
    }
    if (!success) {
        throw new FTPInvalidListException(children);
    }
    return children;
}

From source file:com.glaf.activiti.container.ProcessContainer.java

/**
 * //w  ww. ja v  a 2 s.  c  o  m
 * 
 * @param actorId
 * @param rows
 * @return
 */
public List<TaskItem> filter(String actorId, List<TaskItem> rows) {
    List<Agent> agents = this.getAgents(actorId);
    logger.debug(agents);
    List<TaskItem> taskItems = new java.util.concurrent.CopyOnWriteArrayList<TaskItem>();
    if (rows != null && rows.size() > 0) {
        Iterator<TaskItem> iter = rows.iterator();
        while (iter.hasNext()) {
            TaskItem item = iter.next();
            // logger.debug(item.getProcessDescription() + "\t"
            // + item.getTaskDescription() + "\t" + item.getActorId());
            /**
             * ?
             */
            if (StringUtils.equals(actorId, item.getActorId())) {
                taskItems.add(item);
            } else if (StringUtils.contains(item.getActorId(), actorId)) {
                List<String> actorIds = StringTools.split(item.getActorId());
                if (actorIds != null && actorIds.contains(actorId)) {
                    taskItems.add(item);
                }
            } else {
                if (agents != null && agents.size() > 0) {
                    Iterator<Agent> it = agents.iterator();
                    while (it.hasNext()) {
                        Agent agent = it.next();
                        if (!agent.isValid()) {
                            continue;
                        }
                        /**
                         * ???
                         */
                        if (!StringUtils.equals(item.getActorId(), agent.getAssignFrom())) {
                            continue;
                        }
                        switch (agent.getAgentType()) {
                        case 0:// ?
                            taskItems.add(item);
                            break;
                        case 1:// ??
                            if (StringUtils.equalsIgnoreCase(agent.getProcessName(), item.getProcessName())) {
                                taskItems.add(item);
                            }
                            break;
                        case 2:// ??
                            if (StringUtils.equalsIgnoreCase(agent.getProcessName(), item.getProcessName())
                                    && StringUtils.equalsIgnoreCase(agent.getTaskName(), item.getTaskName())) {
                                taskItems.add(item);
                            }
                            break;
                        default:
                            break;
                        }
                    }
                }
            }
        }
    }
    return taskItems;
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyFormAuthenticator.java

/**
 * Process any login information that was included in the request, if any. Returns true if SecurityFilter should
 * abort further processing after the method completes (for example, if a redirect was sent as part of the login
 * processing).// ww  w . j ava 2 s  . co m
 * 
 * @param request
 * @param response
 * @return true if the filter should return after this method ends, false otherwise
 */
public boolean processLogin(SecurityRequestWrapper request, HttpServletResponse response, XWikiContext context)
        throws Exception {
    try {
        Principal principal = MyBasicAuthenticator.checkLogin(request, response, context);
        if (principal != null) {
            return false;
        }
        if ("1".equals(request.getParameter("basicauth"))) {
            return true;
        }
    } catch (Exception e) {
        // in case of exception we continue on Form Auth.
        // we don't want this to interfere with the most common behavior
    }

    // process any persistent login information, if user is not already logged in,
    // persistent logins are enabled, and the persistent login info is present in this request
    if (this.persistentLoginManager != null) {
        String username = convertUsername(this.persistentLoginManager.getRememberedUsername(request, response),
                context);
        String password = this.persistentLoginManager.getRememberedPassword(request, response);

        Principal principal = request.getUserPrincipal();

        // 1) if user is not already authenticated, authenticate
        // 2) if authenticated user for this session does not have the same name, authenticate
        // 3) if xwiki.authentication.always is set to 1 in xwiki.cfg file, authenticate
        if (principal == null || !StringUtils.endsWith(principal.getName(), "XWiki." + username)
                || context.getWiki().ParamAsLong("xwiki.authentication.always", 0) == 1) {
            principal = authenticate(username, password, context);

            if (principal != null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("User " + principal.getName() + " has been authentified from cookie");
                }

                // make sure the Principal contains wiki name information
                if (!StringUtils.contains(principal.getName(), ':')) {
                    principal = new SimplePrincipal(context.getDatabase() + ":" + principal.getName());
                }

                request.setUserPrincipal(principal);
            } else {
                // Failed to authenticate, better cleanup the user stored in the session
                request.setUserPrincipal(null);
                if (username != null || password != null) {
                    // Failed authentication with remembered login, better forget login now
                    this.persistentLoginManager.forgetLogin(request, response);
                }
            }
        }
    }

    // process login form submittal
    if ((this.loginSubmitPattern != null) && request.getMatchableURL().endsWith(this.loginSubmitPattern)) {
        String username = convertUsername(request.getParameter(FORM_USERNAME), context);
        String password = request.getParameter(FORM_PASSWORD);
        String rememberme = request.getParameter(FORM_REMEMBERME);
        rememberme = (rememberme == null) ? "false" : rememberme;
        return processLogin(username, password, rememberme, request, response, context);
    }
    return false;
}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * Create a new <code>URLNormalizer</code> instance.
 * @param url the url to normalize/*from  w w w .  java 2s  .  c om*/
 */
public URLNormalizer(String url) {
    super();
    // make sure URL is valid
    String fixedURL = url;
    try {
        if (StringUtils.contains(fixedURL, " ")) {
            LOG.warn("URL syntax is invalid as it contains space "
                    + "character(s). Replacing them with %20. URL: " + url);
            fixedURL = StringUtils.replace(fixedURL, " ", "%20");
        }
        new URI(fixedURL);
    } catch (URISyntaxException e) {
        throw new URLException("Invalid URL syntax: " + url, e);
    }
    if (!CharEncoding.isSupported(CharEncoding.UTF_8)) {
        throw new URLException("UTF-8 is not supported by your system.");
    }
    this.url = fixedURL.trim();
}

From source file:com.wso2.code.quality.matrices.ChangesFinder.java

/**
 * saving the  Repo Names in the array and calling to Get files content
 *
 * @param rootJsonObject JSON object containing the repositories which are having the current selected commit from the given patch
 * @param commitHash     the current selected commit hash
 * @param gitHubToken    github token for accessing the github REST API
 *//*from w  w  w .j  av  a  2 s  .co  m*/

public void saveRepoNamesInAnArray(JSONObject rootJsonObject, String commitHash, String gitHubToken) {
    JSONArray jsonArrayOfItems = (JSONArray) rootJsonObject.get(GITHUB_SEARCH_API_ITEMS_KEY_STRING);
    // setting the size of the repoLocationArray
    repoLocation = new String[jsonArrayOfItems.length()];
    //adding the repo name to the array
    IntStream.range(0, jsonArrayOfItems.length()).forEach(i -> {
        JSONObject jsonObject = (JSONObject) jsonArrayOfItems.get(i);
        JSONObject repositoryJsonObject = (JSONObject) jsonObject.get(GITHUB_SEARCH_API_REPOSITORY_KEY_STRING);
        repoLocation[i] = (String) repositoryJsonObject
                .get(GITHUB_SEARCH_API_FULL_NAME_OF_REPOSITORY_KEY_STRING);
    });
    logger.info("Repo names having the given commit are successfully saved in an array");

    SdkGitHubClient sdkGitHubClient = new SdkGitHubClient(gitHubToken);

    //        for running through the repoName Array
    IntStream.range(0, repoLocation.length).filter(i -> StringUtils.contains(repoLocation[i], "wso2/"))
            .forEach(i -> {
                //clearing all the data in the current fileNames and lineRangesChanged arraylists for each repository
                //authorNames.clear();
                fileNames.clear();
                lineRangesChanged.clear();
                patchString.clear();
                Map<String, ArrayList<String>> mapWithFileNamesAndPatch = null;
                try {
                    mapWithFileNamesAndPatch = sdkGitHubClient.getFilesChanged(repoLocation[i], commitHash);
                } catch (CodeQualityMatricesException e) {
                    logger.error(e.getMessage(), e.getCause()); // as exceptions cannot be thrown inside a lambda expression
                    System.exit(2);
                }
                fileNames = mapWithFileNamesAndPatch.get("fileNames");
                patchString = mapWithFileNamesAndPatch.get("patchString");
                saveRelaventEditLineNumbers(fileNames, patchString);
                try {
                    iterateOverFileChanges(repoLocation[i], commitHash, gitHubToken);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e.getCause()); // as exceptions cannot be thrown inside a lambda expression
                    System.exit(3);
                }
            });

    // for printing the author names and commit hashes for a certain commit.
    System.out.println(authorNames);
    System.out.println(commitHashObtainedForPRReview);
}

From source file:kenh.xscript.elements.Debug.java

private void list(JList c) {
    if (result == null)
        return;//from   w  w  w . j  av a 2 s.c  o m

    if (StringUtils.isBlank(c.getSelectedValue().toString()))
        return;

    if (this.getEnvironment() != null) {

        String context = "";
        try {
            Object obj = this.getEnvironment().getVariable(c.getSelectedValue().toString());
            if (obj != null) {

                context = c.getSelectedValue().toString() + LINE_SEP + LINE_SEP;

                context += "-- Class: " + obj.getClass().getCanonicalName() + LINE_SEP;

                context += LINE_SEP;
                context += "-- Fields: " + LINE_SEP;
                Field[] fields = obj.getClass().getFields();

                for (Field field : fields) {
                    int i = field.getModifiers();
                    String retval = Modifier.toString(i);
                    if (StringUtils.contains(retval, "public")) {
                        context += "\t" + field.getName() + " - " + retval + LINE_SEP;
                    }
                }

                context += LINE_SEP;
                context += "-- Method: " + LINE_SEP;
                java.lang.reflect.Method[] methods = obj.getClass().getMethods();

                for (java.lang.reflect.Method method : methods) {
                    int i = method.getModifiers();
                    String retval = Modifier.toString(i);
                    if (StringUtils.contains(retval, "public")) {
                        Class[] pcs = method.getParameterTypes();
                        StringBuffer sb = new StringBuffer();

                        for (Class c_ : pcs) {
                            String s = c_.getSimpleName();
                            sb.append(s + ", ");
                        }

                        String p = StringUtils.trimToEmpty(StringUtils.substringBeforeLast(sb.toString(), ","));

                        context += "\t" + method.getName() + "(" + p + ") - " + retval + LINE_SEP;
                    }
                }

            } else {
                context = "<null>";
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            context = sw.toString();
        }

        result.setText(context);

    } else {
        result.setText(c.getSelectedValue().toString());
    }

    result.setCaretPosition(0);
    c.requestFocus();
}

From source file:com.thoughtworks.go.matchers.ConsoleOutMatcher.java

public static TypeSafeMatcher<String> printedRuleDoesNotMatchFailure(final String root, final String rule) {
    return new TypeSafeMatcher<String>() {
        public String consoleOut;
        public String message;

        public boolean matchesSafely(String consoleOut) {
            this.consoleOut = consoleOut;
            this.message = "The rule [" + rule + "] cannot match any resource under [" + root + "]";

            return StringUtils.contains(consoleOut, message);
        }/* ww w . j a  va  2 s . com*/

        public void describeTo(Description description) {
            description.appendText("Expected console to contain [" + message + "] but was " + consoleOut);
        }
    };
}

From source file:com.dchq.docker.volume.driver.controller.DockerVolumeDriverControllerIntegrationTests.java

@Test
public void getTest() {

    String name = RandomStringUtils.randomAlphabetic(6);
    CreateRequest request = new CreateRequest();
    request.setName(name);/*from   w ww.j  ava 2 s .c o  m*/

    String response = restTemplate.postForObject(baseUrl + DockerVolumeDriverController.CREATE, request,
            String.class);
    Assert.assertNotNull(response);
    Assert.assertEquals(response, "{\"Err\":\"\"}");

    PathRequest getRequest = new PathRequest();
    getRequest.setName(name);

    String getResponse = restTemplate.postForObject(baseUrl + DockerVolumeDriverController.GET, getRequest,
            String.class);
    Assert.assertNotNull(getResponse);
    Assert.assertTrue(StringUtils.contains(getResponse, "\"Err\":\"\""));
    logger.info("Response [{}]", getResponse);
}

From source file:com.nridge.ds.content.ds_content.ContentType.java

/**
 * Given a URL, return the type name that matches its pattern
 * or <code>Content.CONTENT_TYPE_UNKNOWN</code>.
 *
 * @param aURL URL to examine.//from  w ww .j  av a 2s. c o  m
 *
 * @return Type name.
 */
public String nameByURL(String aURL) {
    if (StringUtils.isNotEmpty(aURL)) {
        DataBag dataBag;
        String urlPattern;

        int rowCount = mTable.rowCount();
        for (int row = 0; row < rowCount; row++) {
            dataBag = mTable.getRowAsBag(row);
            urlPattern = dataBag.getValueAsString("url_pattern");
            if (StringUtils.isNotEmpty(urlPattern)) {
                if (StringUtils.contains(aURL, urlPattern))
                    return dataBag.getValueAsString("type_type");
            }
        }
    }

    return Content.CONTENT_TYPE_UNKNOWN;
}

From source file:com.feilong.servlet.http.ResponseDownloadUtil.java

/**
 * Down load data.//from  w ww .  ja  v a2  s.  com
 *
 * @param saveFileName
 *            the save file name
 * @param inputStream
 *            the input stream
 * @param contentLength
 *            the content length
 * @param request
 *            the request
 * @param response
 *            the response
 */
private static void downLoadData(String saveFileName, InputStream inputStream, Number contentLength,
        HttpServletRequest request, HttpServletResponse response) {
    Date beginDate = new Date();
    String length = FileUtil.formatSize(contentLength.longValue());
    LOGGER.info("begin download~~,saveFileName:[{}],contentLength:[{}]", saveFileName, length);
    try {
        OutputStream outputStream = response.getOutputStream();
        IOWriteUtil.write(inputStream, outputStream);
        if (LOGGER.isInfoEnabled()) {
            String pattern = "end download,saveFileName:[{}],contentLength:[{}],time use:[{}]";
            LOGGER.info(pattern, saveFileName, length, formatDuration(beginDate));
        }
    } catch (IOException e) {
        /*
         * ?,  ClientAbortException , ?,????, ,.
         * ??, ??
         * ?,???...???,
         * ?, KILL?, ,?? ClientAbortException.
         */
        //ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error
        final String exceptionName = e.getClass().getName();

        if (StringUtils.contains(exceptionName, "ClientAbortException")
                || StringUtils.contains(e.getMessage(), "ClientAbortException")) {
            String pattern = "[ClientAbortException],maybe user use Thunder soft or abort client soft download,exceptionName:[{}],exception message:[{}] ,request User-Agent:[{}]";
            LOGGER.warn(pattern, exceptionName, e.getMessage(), RequestUtil.getHeaderUserAgent(request));
        } else {
            LOGGER.error("[download exception],exception name: " + exceptionName, e);
            throw new UncheckedIOException(e);
        }
    }
}