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:io.wcm.handler.url.impl.modes.DefaultUrlMode.java

/**
 * Gets site root level path of a site.//from   www . j  a v a 2 s . c  o  m
 * @param path Path of page within the site
 * @param rootLevel Level of root page
 * @return Site root path for the site. The path is not checked for validness.
 */
private String getRootPath(String path, int rootLevel) {
    String rootPath = Text.getAbsoluteParent(path, rootLevel);

    // strip off everything after first "." - root path may be passed with selectors/extension which is not relevant
    if (StringUtils.contains(rootPath, ".")) {
        rootPath = StringUtils.substringBefore(rootPath, ".");
    }

    return rootPath;
}

From source file:com.glaf.shiro.SystemRealm.java

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    logger.debug("----------------doGetAuthorizationInfo-----------------");
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }/*from   w w w.  j a v a2 s .co m*/
    String actorId = (String) getAvailablePrincipal(principals);
    Set<String> roles = new HashSet<String>();
    Set<String> perms = new HashSet<String>();
    if (actorId != null) {

        LoginContext loginContext = IdentityFactory.getLoginContext(actorId);

        if (loginContext.isSystemAdministrator()) {
            perms.add("SystemAdministrator");
            roles.add("SystemAdministrator");
        }
        Collection<String> roleIds = loginContext.getRoles();
        if (roleIds != null && !roleIds.isEmpty()) {
            for (String roleId : roleIds) {
                if (StringUtils.isNotEmpty(roleId)) {
                    if (!StringUtils.contains(roleId, ":")) {
                        roles.add(roleId);
                    }
                    perms.add(roleId);
                }
            }
        }
        Collection<String> permissions = loginContext.getPermissions();
        if (permissions != null && !permissions.isEmpty()) {
            for (String p : permissions) {
                if (StringUtils.isNotEmpty(p)) {
                    if (!StringUtils.contains(p, ":")) {
                        roles.add(p);
                    }
                    perms.add(p);
                }
            }
        }
        permissions = loginContext.getFunctions();
        if (permissions != null && !permissions.isEmpty()) {
            for (String p : permissions) {
                if (StringUtils.isNotEmpty(p)) {
                    perms.add(p);
                }
            }
        }
    }
    logger.info("-----------------------@shiro@--------------------");
    logger.info("shiro roles:{" + roles + "}");
    logger.info("shiro perms:{" + perms + "}");
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
    info.setStringPermissions(perms);
    return info;
}

From source file:com.zhumeng.dream.orm.PropertyFilter.java

/**
 * @param filterName ,???. eg.//from  w w w .j a  v a  2s . c o  m
 *            LIKES_NAME_OR_LOGIN_NAME
 * @param value .
 */
public PropertyFilter(final String filterName, final String value) {
    String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    init(filterName, value, propertyNameStr);
    if (propertyClass == Enum.class) {
        for (Class<?> clazz : enumObjects) {
            if (propertyNameStr.equalsIgnoreCase(clazz.getSimpleName())) {
                Class<Enum> enumObjet = (Class<Enum>) clazz;

                // add by wucong
                String[] values = StringUtils.split(value, "_");
                if (!StringUtils.contains(value, "_"))
                    this.matchValue = Enum.valueOf(enumObjet, value);
                else
                    this.matchValue = Enum.valueOf(enumObjet, values[0]);// ?
                if (values != null) {
                    matchValues = new Object[values.length];
                    for (int i = 0; i < values.length; i++) {
                        matchValues[i] = Enum.valueOf(enumObjet, values[i]);
                    }
                    if (values.length == 0) {
                        matchValues = new Object[1];
                        matchValues[0] = this.matchValue;
                    }
                }
                break;
            }
        }
    } else {
        /*
         * if(!StringUtils.contains(value, "_")) this.matchValue =
         * ConvertUtils.convertStringToObject(value, propertyClass);
         */

        // add by wucong
        String[] values = null;
        //???"_"
        if (filterName.lastIndexOf("unionId") > 0 || filterName.lastIndexOf("openId") > 0
                || (!StringUtils.contains(value, "_")))//???"_"
            values = new String[] { value };

        else
            values = StringUtils.split(value, "_");
        if ((!StringUtils.contains(value, "_") || filterName.lastIndexOf("unionId") > 0)
                || (!StringUtils.contains(value, "_") && filterName.lastIndexOf("openId") > 0))//???"_"
            this.matchValue = ConvertUtils.convertStringToObject(value, propertyClass);
        else
            this.matchValue = ConvertUtils.convertStringToObject(values[0], propertyClass);// ?
        if (values != null) {
            matchValues = new Object[values.length];
            for (int i = 0; i < values.length; i++) {
                matchValues[i] = ConvertUtils.convertStringToObject(values[i], propertyClass);
            }
            if (values.length == 0) {
                matchValues = new Object[1];
                matchValues[0] = this.matchValue;
            }
        }
    }

}

From source file:io.wcm.handler.url.impl.Externalizer.java

/**
 * Checks if the given URL is already externalized.
 * For this check some heuristics are applied.
 * @param url URL/*from   w  w  w.  j  av a2 s  . co  m*/
 * @return true if path is already externalized.
 */
public static boolean isExternalized(String url) {
    return StringUtils.contains(url, "://") // protocol detected
            || StringUtils.startsWith(url, "//") // protocol-relative mode detected
            || StringUtils.startsWith(url, "mailto:") // mailto link detected
            || StringUtils.startsWith(url, "#"); // anchor or integrator placeholder detected
}

From source file:com.mirth.connect.util.MessageImporter.java

private void importVfsFile(FileObject file, MessageWriter messageWriter, int[] result)
        throws InterruptedException, MessageImportException {
    InputStream inputStream = null;

    try {//  w  ww  .j a  va 2  s .c  om
        inputStream = file.getContent().getInputStream();

        // scan the first XML_SCAN_BUFFER_SIZE bytes in the file to see if it contains message xml
        char[] cbuf = new char[XML_SCAN_BUFFER_SIZE];
        new InputStreamReader(inputStream, CHARSET).read(cbuf);

        if (StringUtils.contains(new String(cbuf), OPEN_ELEMENT)) {
            logger.debug("Importing file: " + file.getName().getURI());

            // re-open the input stream to reposition it at the beginning of the stream
            inputStream.close();
            inputStream = file.getContent().getInputStream();
            importMessagesFromInputStream(inputStream, messageWriter, result);
        }
    } catch (IOException e) {
        throw new MessageImportException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:de.filiberry.bathcontrol.Activator.java

/**
 * /*from   ww  w  .j  a  v a 2s. com*/
 */
public void messageArrived(String topic, MqttMessage message) throws Exception {
    LOGGER.debug("MQTT Message arrived...");
    String messageData = new String(message.getPayload());
    boolean messageOK = false;
    try {
        // --
        if (StringUtils.contains(topic, mqttTopicTempWintergarten)) {
            bathControlContext.setTempWintergarten(new Double(messageData));
            messageOK = true;
        }
        // --
        if (StringUtils.contains(topic, mqttTopicTempBadezimmer)) {
            bathControlContext.setTempBadezimmer(new Double(messageData));
            messageOK = true;
        }
        // --
        if (StringUtils.contains(topic, mqttTopicMoistureBadezimmer)) {
            bathControlContext.setMoistureBadezimmer(new Double(messageData));
            messageOK = true;
        }
        if (StringUtils.contains(topic, mqttTopicTempAussen)) {
            bathControlContext.setTempAussen(new Double(messageData));
            messageOK = true;
        }

        // --
        if (messageOK) {
            LOGGER.info("Message on Topic " + topic + " Value=" + messageData + " Arrived and set to Context");
        } else {
            LOGGER.info("Unknown Message on Topic=" + topic);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

}

From source file:ch.cyberduck.core.sftp.SFTPChallengeResponseAuthentication.java

public boolean authenticate(final Host host, final Credentials credentials, final LoginCallback controller)
        throws BackgroundException {
    if (StringUtils.isBlank(host.getCredentials().getPassword())) {
        return false;
    }/*from   w  w  w.  j  a v a  2  s.  com*/
    if (log.isDebugEnabled()) {
        log.debug(String.format("Login using challenge response authentication with credentials %s",
                credentials));
    }
    try {
        session.getClient().auth(credentials.getUsername(),
                new AuthKeyboardInteractive(new ChallengeResponseProvider() {
                    /**
                     * Password sent flag
                     */
                    private final AtomicBoolean password = new AtomicBoolean();

                    private String name = StringUtils.EMPTY;

                    private String instruction = StringUtils.EMPTY;

                    @Override
                    public List<String> getSubmethods() {
                        return Collections.emptyList();
                    }

                    @Override
                    public void init(final Resource resource, final String name, final String instruction) {
                        if (StringUtils.isNoneBlank(instruction)) {
                            this.instruction = instruction;
                        }
                        if (StringUtils.isNoneBlank(name)) {
                            this.name = name;
                        }
                    }

                    @Override
                    public char[] getResponse(final String prompt, final boolean echo) {
                        if (log.isDebugEnabled()) {
                            log.debug(String.format("Reply to challenge name %s with instruction %s", name,
                                    instruction));
                        }
                        final String response;
                        // For each prompt, the corresponding echo field indicates whether the user input should
                        // be echoed as characters are typed
                        if (!password.get()
                                // Some servers ask for one-time passcode first
                                && !StringUtils.contains(prompt, "Verification code")) {
                            // In its first callback the server prompts for the password
                            if (log.isDebugEnabled()) {
                                log.debug("First callback returning provided credentials");
                            }
                            response = credentials.getPassword();
                            password.set(true);
                        } else {
                            final StringAppender message = new StringAppender().append(instruction)
                                    .append(prompt);
                            // Properly handle an instruction field with embedded newlines.  They should also
                            // be able to display at least 30 characters for the name and prompts.
                            final Credentials additional = new Credentials(credentials.getUsername()) {
                                @Override
                                public String getPasswordPlaceholder() {
                                    return StringUtils.removeEnd(StringUtils.strip(prompt), ":");
                                }
                            };
                            try {
                                final StringAppender title = new StringAppender().append(name).append(
                                        LocaleFactory.localizedString("Provide additional login credentials",
                                                "Credentials"));
                                controller.prompt(host, additional, title.toString(), message.toString(),
                                        new LoginOptions().user(false).keychain(false));
                            } catch (LoginCanceledException e) {
                                return EMPTY_RESPONSE;
                            }
                            response = additional.getPassword();
                        }
                        // Responses are encoded in ISO-10646 UTF-8.
                        return response.toCharArray();
                    }

                    @Override
                    public boolean shouldRetry() {
                        return false;
                    }
                }));
    } catch (IOException e) {
        throw new SFTPExceptionMappingService().map(e);
    }
    return session.getClient().isAuthenticated();
}

From source file:com.glaf.core.web.rest.MxFileSystemResource.java

@GET
@POST//from  ww  w.j  av a  2  s.c om
@Path("/dir")
@ResponseBody
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public byte[] dir(@Context HttpServletRequest request) throws IOException {
    Map<String, Object> params = RequestUtils.getParameterMap(request);
    LogUtils.debug(params);
    JSONArray array = new JSONArray();
    String path = request.getParameter("path");
    if (StringUtils.isEmpty(path)) {
        path = "/WEB-INF";
    }
    String root = SystemProperties.getAppPath() + "/" + path;
    LogUtils.debug("root:" + root);
    File dir = new File(root);
    if (dir.exists() && dir.isDirectory()) {
        File[] contents = dir.listFiles();
        if (contents != null) {
            for (int i = 0; i < contents.length; i++) {
                File file = contents[i];
                if (file.exists() && file.isDirectory()) {
                    if (StringUtils.contains(file.getName(), "jdbc.properties")) {
                        continue;
                    }
                    if (StringUtils.contains(file.getName(), "hibernate.cfg.xml")) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", DigestUtils.md5Hex(path + "/" + file.getName()));
                    json.put("parentId", DigestUtils.md5Hex(path + "/"));
                    json.put("startIndex", i + 1);
                    json.put("date", DateUtils.getDateTime(new Date(file.lastModified())));
                    json.put("name", file.getName());
                    json.put("path", path + "/" + file.getName());
                    json.put("class", "folder");
                    json.put("leaf", false);
                    json.put("isParent", true);
                    array.add(json);
                }
            }
        }
    }
    LogUtils.debug(array.toJSONString());
    return array.toJSONString().getBytes("UTF-8");
}

From source file:fi.foyt.fni.test.ui.base.gamelibrary.GameLibraryProposeGameTestsBase.java

@Test
@SqlSets("basic-users")
public void testPropose() throws Exception {
    if ("chrome".equals(getBrowser())) {
        // FIXME: File uploading fails with bad gateway on Sauce Labs when using Chrome.
        return;/*from  w w w  .j  a v a 2 s.co m*/
    }

    loginInternal("user@foyt.fi", "pass");
    navigate("/gamelibrary/proposegame/");

    File testPng = getTestPng();
    File testPdf = getTestPdf();

    waitAndSendKeys(".gamelibrary-propose-game-form-name", "My awesome game");
    waitAndSendKeys(".gamelibrary-propose-game-form-description", "This game is just pretty awesome");
    waitAndSendKeys(".gamelibrary-propose-game-form-authors-share", "5");

    waitAndSendKeys(".gamelibrary-propose-game-form-section-image input[name='file']",
            testPng.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-image .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-image .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-image .upload-field-file-name",
            testPng.getName(), true, true);

    waitAndSendKeys(".gamelibrary-propose-game-form-section-downloadable input[name='file']",
            testPdf.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-downloadable .upload-field-file-name",
            testPdf.getName(), true, true);

    waitAndSendKeys(".gamelibrary-propose-game-form-section-printable input[name='file']",
            testPdf.getAbsolutePath());
    waitForSelectorPresent(".gamelibrary-propose-game-form-section-printable .upload-field-file-name");
    assertSelectorCount(".gamelibrary-propose-game-form-section-printable .upload-field-file-name", 1);
    assertSelectorText(".gamelibrary-propose-game-form-section-printable .upload-field-file-name",
            testPdf.getName(), true, true);

    waitAndClick(".gamelibrary-propose-game-send");

    MimeMessage[] messages = getGreenMail().getReceivedMessages();
    assertEquals(2, messages.length);

    List<String> recipientAddressses = new ArrayList<>();

    for (MimeMessage message : messages) {
        assertEquals("New Publication into the Game Library", message.getSubject());
        assertTrue(StringUtils.contains((String) message.getContent(),
                "Test User (user@foyt.fi) has proposed that My awesome game"));
        Address[] recipients = message.getRecipients(RecipientType.TO);

        for (Address recipient : recipients) {
            String address = ((InternetAddress) recipient).getAddress();
            if (!recipientAddressses.contains(address)) {
                recipientAddressses.add(address);
            }
        }

    }

    assertEquals(Arrays.asList("librarian@foyt.fi", "admin@foyt.fi"), recipientAddressses);

    waitForSelectorVisible(".gamelibrary-publication h3 a");

    assertSelectorText(".gamelibrary-publication h3 a", "My awesome game", true, true);
    assertSelectorText(".gamelibrary-publication .gamelibrary-publication-description",
            "This game is just pretty awesome", true, true);

    executeSql(
            "update PublicationFile set contentType = 'DELETE' where id in (select printableFile_id from BookPublication where id in (select id from Publication where creator_id = ?) union select downloadableFile_id from BookPublication where id in (select id from Publication where creator_id = ?))",
            2, 2);
    executeSql("update Publication set defaultImage_id = null where creator_id = ?", 2);
    executeSql(
            "Update BookPublication set printableFile_id = null, downloadableFile_id = null where id in (select id from Publication where creator_id = ?)",
            2);
    executeSql(
            "delete from PublicationImage where publication_id in (select id from Publication where creator_id = ?)",
            2);
    executeSql("delete from PublicationFile where contentType = 'DELETE'");
    executeSql("delete from BookPublication where id in (select id from Publication where creator_id = ?)", 2);
    executeSql("delete from Publication where creator_id = ?", 2);
}

From source file:de.bmarwell.j9kwsolver.util.ResponseUtils.java

/**
 * Parses the content from the response, if any.
 * @param response the response sent by the server.
 * @return a CaptchaReturn object if captcha was offered, otherwise null.
 */// ww w . j a va  2s . co m
public static CaptchaReturn captchaGetResponseToCaptchaReturn(final String response) {
    CaptchaReturn cr = null;

    if (StringUtils.isEmpty(response)) {
        RequestToURI.LOG.debug("Content ist leer!");

        return cr;
    }

    /* converting answer to object */
    if (StringUtils.containsIgnoreCase(response, "NO CAPTCHA")) {
        /* No captcha available */
        cr = null;
        RequestToURI.LOG.debug("No captcha available atm: {}.", response);
    } else if (StringUtils.contains(response, "phrase")) {
        /* Extended Answer */
        CaptchaReturnExtended cre = ResponseUtils.getExtendedFromResponse(response);
        RequestToURI.LOG.debug("CRE: {}.", cre);
        cr = cre;
    } else {
        /* 
         * simple response contains only digits or few extra information
         * INT or INT|mouse or INT|confirm
         */
        RequestToURI.LOG.debug("Simple response: {}.", response);
        String[] splitresponse = StringUtils.split(response, '|');

        if (splitresponse.length < 1) {
            RequestToURI.LOG.warn("Simple response doesn't contain enough items");
            return cr;
        }

        if (!NumberUtils.isDigits(splitresponse[0])) {
            RequestToURI.LOG.error("Response's first item isn't a captcha id." + " Found {} instead.",
                    splitresponse[0]);
            return cr;
        }

        cr = new CaptchaReturn();
        cr.setCaptchaID(splitresponse[0]);
        // TODO: add items
    }

    return cr;
}