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

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

Introduction

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

Prototype

public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) 

Source Link

Document

Checks if CharSequence contains a search CharSequence irrespective of case, handling null .

Usage

From source file:org.apache.nifi.web.controller.ControllerSearchService.java

private ComponentSearchResultDTO search(final String searchStr, final Connection connection) {
    final List<String> matches = new ArrayList<>();

    // search id and name
    addIfAppropriate(searchStr, connection.getIdentifier(), "Id", matches);
    addIfAppropriate(searchStr, connection.getVersionedComponentId().orElse(null), "Version Control ID",
            matches);//from   www.  jav  a  2s .  c  om
    addIfAppropriate(searchStr, connection.getName(), "Name", matches);

    // search relationships
    for (final Relationship relationship : connection.getRelationships()) {
        addIfAppropriate(searchStr, relationship.getName(), "Relationship", matches);
    }

    // search prioritizers
    final FlowFileQueue queue = connection.getFlowFileQueue();
    for (final FlowFilePrioritizer comparator : queue.getPriorities()) {
        addIfAppropriate(searchStr, comparator.getClass().getName(), "Prioritizer", matches);
    }

    // search expiration
    if (StringUtils.containsIgnoreCase("expires", searchStr)
            || StringUtils.containsIgnoreCase("expiration", searchStr)) {
        final int expirationMillis = connection.getFlowFileQueue().getFlowFileExpiration(TimeUnit.MILLISECONDS);
        if (expirationMillis > 0) {
            matches.add("FlowFile expiration: " + connection.getFlowFileQueue().getFlowFileExpiration());
        }
    }

    // search back pressure
    if (StringUtils.containsIgnoreCase("back pressure", searchStr)
            || StringUtils.containsIgnoreCase("pressure", searchStr)) {
        final String backPressureDataSize = connection.getFlowFileQueue().getBackPressureDataSizeThreshold();
        final Double backPressureBytes = DataUnit.parseDataSize(backPressureDataSize, DataUnit.B);
        if (backPressureBytes > 0) {
            matches.add("Back pressure data size: " + backPressureDataSize);
        }

        final long backPressureCount = connection.getFlowFileQueue().getBackPressureObjectThreshold();
        if (backPressureCount > 0) {
            matches.add("Back pressure count: " + backPressureCount);
        }
    }

    // search the source
    final Connectable source = connection.getSource();
    addIfAppropriate(searchStr, source.getIdentifier(), "Source id", matches);
    addIfAppropriate(searchStr, source.getName(), "Source name", matches);
    addIfAppropriate(searchStr, source.getComments(), "Source comments", matches);

    // search the destination
    final Connectable destination = connection.getDestination();
    addIfAppropriate(searchStr, destination.getIdentifier(), "Destination id", matches);
    addIfAppropriate(searchStr, destination.getName(), "Destination name", matches);
    addIfAppropriate(searchStr, destination.getComments(), "Destination comments", matches);

    if (matches.isEmpty()) {
        return null;
    }

    final ComponentSearchResultDTO result = new ComponentSearchResultDTO();
    result.setId(connection.getIdentifier());

    // determine the name of the search match
    if (StringUtils.isNotBlank(connection.getName())) {
        result.setName(connection.getName());
    } else if (!connection.getRelationships().isEmpty()) {
        final List<String> relationships = new ArrayList<>(connection.getRelationships().size());
        for (final Relationship relationship : connection.getRelationships()) {
            if (StringUtils.isNotBlank(relationship.getName())) {
                relationships.add(relationship.getName());
            }
        }
        if (!relationships.isEmpty()) {
            result.setName(StringUtils.join(relationships, ", "));
        }
    }

    // ensure a name is added
    if (result.getName() == null) {
        result.setName("From source " + connection.getSource().getName());
    }

    result.setMatches(matches);
    return result;
}

From source file:org.apache.nifi.web.controller.ControllerSearchService.java

private ComponentSearchResultDTO search(final String searchStr, final RemoteProcessGroup group) {
    final List<String> matches = new ArrayList<>();
    addIfAppropriate(searchStr, group.getIdentifier(), "Id", matches);
    addIfAppropriate(searchStr, group.getVersionedComponentId().orElse(null), "Version Control ID", matches);
    addIfAppropriate(searchStr, group.getName(), "Name", matches);
    addIfAppropriate(searchStr, group.getComments(), "Comments", matches);
    addIfAppropriate(searchStr, group.getTargetUris(), "URLs", matches);

    // consider the transmission status
    if ((StringUtils.containsIgnoreCase("transmitting", searchStr)
            || StringUtils.containsIgnoreCase("transmission enabled", searchStr)) && group.isTransmitting()) {
        matches.add("Transmission: On");
    } else if ((StringUtils.containsIgnoreCase("not transmitting", searchStr)
            || StringUtils.containsIgnoreCase("transmission disabled", searchStr)) && !group.isTransmitting()) {
        matches.add("Transmission: Off");
    }/*  www.j a  v a 2 s  . c o  m*/

    if (matches.isEmpty()) {
        return null;
    }

    final ComponentSearchResultDTO result = new ComponentSearchResultDTO();
    result.setId(group.getIdentifier());
    result.setName(group.getName());
    result.setMatches(matches);
    return result;
}

From source file:org.apache.struts2.views.util.DefaultUrlHelper.java

public String buildUrl(String action, HttpServletRequest request, HttpServletResponse response,
        Map<String, Object> params, String scheme, boolean includeContext, boolean encodeResult,
        boolean forceAddSchemeHostAndPort, boolean escapeAmp) {
    StringBuilder link = new StringBuilder();

    boolean changedScheme = false;

    // FIXME: temporary hack until class is made a properly injected bean
    Container cont = ActionContext.getContext().getContainer();
    int httpPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTP_PORT));
    int httpsPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTPS_PORT));

    // only append scheme if it is different to the current scheme *OR*
    // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true
    if (forceAddSchemeHostAndPort) {
        String reqScheme = request.getScheme();
        changedScheme = true;//from w w  w .  ja  v  a 2  s . com
        link.append(scheme != null ? scheme : reqScheme);
        link.append("://");
        link.append(request.getServerName());

        if (scheme != null) {
            // If switching schemes, use the configured port for the particular scheme.
            if (!scheme.equals(reqScheme)) {
                if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(scheme.equals("http") ? httpPort : httpsPort);
                }
                // Else use the port from the current request.
            } else {
                int reqPort = request.getServerPort();

                if ((scheme.equals("http") && (reqPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && reqPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(reqPort);
                }
            }
        }
    } else if ((scheme != null) && !scheme.equals(request.getScheme())) {
        changedScheme = true;
        link.append(scheme);
        link.append("://");
        link.append(request.getServerName());

        if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(scheme.equals("http") ? httpPort : httpsPort);
        }
    }

    if (action != null) {
        // Check if context path needs to be added
        // Add path to absolute links
        if (action.startsWith("/") && includeContext) {
            String contextPath = request.getContextPath();
            if (!contextPath.equals("/")) {
                link.append(contextPath);
            }
        } else if (changedScheme) {

            // (Applicable to Servlet 2.4 containers)
            // If the request was forwarded, the attribute below will be set with the original URL
            String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

            // If the attribute wasn't found, default to the value in the request object
            if (uri == null) {
                uri = request.getRequestURI();
            }

            link.append(uri.substring(0, uri.lastIndexOf('/') + 1));
        }

        // Add page
        link.append(action);
    } else {
        // Go to "same page"
        String requestURI = (String) request.getAttribute("struts.request_uri");

        // (Applicable to Servlet 2.4 containers)
        // If the request was forwarded, the attribute below will be set with the original URL
        if (requestURI == null) {
            requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
        }

        // If neither request attributes were found, default to the value in the request object
        if (requestURI == null) {
            requestURI = request.getRequestURI();
        }

        link.append(requestURI);
    }

    //if the action was not explicitly set grab the params from the request
    if (escapeAmp) {
        buildParametersString(params, link, AMP);
    } else {
        buildParametersString(params, link, "&");
    }

    String result = link.toString();

    if (StringUtils.containsIgnoreCase(result, "<script")) {
        result = StringEscapeUtils.escapeEcmaScript(result);
    }
    try {
        result = encodeResult ? response.encodeURL(result) : result;
    } catch (Exception ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not encode the URL for some reason, use it unchanged", ex);
        }
        result = link.toString();
    }

    return result;
}

From source file:org.apache.syncope.client.console.panels.ParametersDetailsPanel.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private Panel getFieldPanel(final String id, final AttrTO attrTO) {
    final String valueHeaderName = getString("values");

    final PlainSchemaTO schemaTO = schemaRestClient.read(SchemaType.PLAIN, attrTO.getSchema());

    final FieldPanel panel;
    switch (schemaTO.getType()) {
    case Date:
        final String datePattern = schemaTO.getConversionPattern() == null
                ? SyncopeConstants.DEFAULT_DATE_PATTERN
                : schemaTO.getConversionPattern();

        if (StringUtils.containsIgnoreCase(datePattern, "H")) {
            panel = new AjaxDateTimeFieldPanel("panel", schemaTO.getKey(), new Model<>(), datePattern);
        } else {/*w w  w  .  j a va  2 s.c  o m*/
            panel = new AjaxDateFieldPanel("panel", schemaTO.getKey(), new Model<>(), datePattern);
        }
        break;
    case Boolean:
        panel = new AjaxDropDownChoicePanel<>(id, valueHeaderName, new Model<>(), false);
        ((AjaxDropDownChoicePanel<String>) panel).setChoices(Arrays.asList("true", "false"));

        if (!attrTO.getValues().isEmpty()) {
            ((AjaxDropDownChoicePanel) panel).setChoiceRenderer(new IChoiceRenderer<String>() {

                private static final long serialVersionUID = -3724971416312135885L;

                @Override
                public String getDisplayValue(final String value) {
                    return value;
                }

                @Override
                public String getIdValue(final String value, final int i) {
                    return value;
                }

                @Override
                public String getObject(final String id,
                        final IModel<? extends List<? extends String>> choices) {
                    return id;
                }
            });
        }
        ((AjaxDropDownChoicePanel<String>) panel).setNullValid(false);
        break;
    case Enum:
        panel = new AjaxDropDownChoicePanel<>(id, valueHeaderName, new Model<>(), false);
        ((AjaxDropDownChoicePanel<String>) panel).setChoices(SchemaUtils.getEnumeratedValues(schemaTO));

        if (!attrTO.getValues().isEmpty()) {
            ((AjaxDropDownChoicePanel) panel).setChoiceRenderer(new IChoiceRenderer<String>() {

                private static final long serialVersionUID = -3724971416312135885L;

                @Override
                public String getDisplayValue(final String value) {
                    return value;
                }

                @Override
                public String getIdValue(final String value, final int i) {
                    return value;
                }

                @Override
                public String getObject(final String id,
                        final IModel<? extends List<? extends String>> choices) {
                    return id;
                }
            });
        }
        ((AjaxDropDownChoicePanel<String>) panel)
                .setNullValid("false".equalsIgnoreCase(schemaTO.getMandatoryCondition()));
        break;

    case Long:
        panel = new AjaxSpinnerFieldPanel.Builder<Long>().build(id, valueHeaderName, Long.class,
                new Model<Long>());
        break;

    case Double:
        panel = new AjaxSpinnerFieldPanel.Builder<Double>().build(id, valueHeaderName, Double.class,
                new Model<Double>());
        break;

    case Binary:
        panel = new BinaryFieldPanel(id, valueHeaderName, new Model<>(), schemaTO.getMimeType(),
                schema.getModelObject());
        break;

    case Encrypted:
        panel = new EncryptedFieldPanel(id, valueHeaderName, new Model<>(), true);
        break;

    default:
        panel = new AjaxTextFieldPanel(id, valueHeaderName, new Model<>(), false);
    }
    if (schemaTO.isMultivalue()) {
        return new MultiFieldPanel.Builder<>(new PropertyModel<List<String>>(attrTO, "values")).build(id,
                valueHeaderName, panel);
    } else {
        panel.setNewModel(attrTO.getValues());
    }

    panel.setRequired("true".equalsIgnoreCase(schemaTO.getMandatoryCondition()));
    return panel;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.DefaultAccountRule.java

@Transactional(readOnly = true)
@Override// w w w  .  ja  v  a2s .c o m
public void enforce(final User user) {
    this.conf.getSchemasNotPermitted().stream().map(schema -> user.getPlainAttr(schema))
            .filter(attr -> attr.isPresent()).map(attr -> attr.get().getValuesAsStrings())
            .filter(values -> (values != null && !values.isEmpty()))
            .forEachOrdered(values -> this.conf.getWordsNotPermitted().add(values.get(0)));

    if (user.getUsername() == null) {
        throw new AccountPolicyException("Invalid account");
    }

    // check min length
    if (this.conf.getMinLength() > 0 && this.conf.getMinLength() > user.getUsername().length()) {
        throw new AccountPolicyException("Username too short");
    }

    // check max length
    if (this.conf.getMaxLength() > 0 && this.conf.getMaxLength() < user.getUsername().length()) {
        throw new AccountPolicyException("Username too long");
    }

    // check words not permitted
    this.conf.getWordsNotPermitted().stream()
            .filter(word -> StringUtils.containsIgnoreCase(user.getUsername(), word)).forEachOrdered(item -> {
                throw new AccountPolicyException("Used word(s) not permitted");
            });

    // check case
    if (this.conf.isAllUpperCase() && !user.getUsername().equals(user.getUsername().toUpperCase())) {
        throw new AccountPolicyException("No lowercase characters permitted");
    }
    if (this.conf.isAllLowerCase() && !user.getUsername().equals(user.getUsername().toLowerCase())) {
        throw new AccountPolicyException("No uppercase characters permitted");
    }

    // check pattern
    Pattern pattern = (this.conf.getPattern() == null) ? DEFAULT_PATTERN
            : Pattern.compile(this.conf.getPattern());
    if (!pattern.matcher(user.getUsername()).matches()) {
        throw new AccountPolicyException("Username does not match pattern");
    }

    // check prefix
    this.conf.getPrefixesNotPermitted().stream().filter(prefix -> user.getUsername().startsWith(prefix))
            .forEachOrdered(item -> {
                throw new AccountPolicyException("Prefix not permitted");
            });

    // check suffix
    this.conf.getSuffixesNotPermitted().stream().filter(suffix -> user.getUsername().endsWith(suffix))
            .forEachOrdered(item -> {
                throw new AccountPolicyException("Suffix not permitted");
            });
}

From source file:org.apache.syncope.core.persistence.jpa.dao.DefaultPasswordRule.java

@Transactional(readOnly = true)
@Override// w  w w  .j  a  v a 2s.co  m
public void enforce(final User user) {
    this.conf.getSchemasNotPermitted().stream().map(schema -> user.getPlainAttr(schema))
            .filter(attr -> attr.isPresent()).map(attr -> attr.get().getValuesAsStrings())
            .filter(values -> (values != null && !values.isEmpty()))
            .forEachOrdered(values -> this.conf.getWordsNotPermitted().add(values.get(0)));

    String clearPassword = user.getClearPassword();
    String password = user.getPassword();

    if (password != null && clearPassword != null) {
        // check length
        if (this.conf.getMinLength() > 0 && this.conf.getMinLength() > clearPassword.length()) {
            throw new PasswordPolicyException("Password too short");
        }

        if (this.conf.getMaxLength() > 0 && this.conf.getMaxLength() < clearPassword.length()) {
            throw new PasswordPolicyException("Password too long");
        }

        // check words not permitted
        this.conf.getWordsNotPermitted().stream()
                .filter(word -> StringUtils.containsIgnoreCase(clearPassword, word)).forEachOrdered(item -> {
                    throw new PasswordPolicyException("Used word(s) not permitted");
                });

        // check digits occurrence
        if (this.conf.isDigitRequired() && !checkDigit(clearPassword)) {
            throw new PasswordPolicyException("Password must contain digit(s)");
        }

        // check lowercase alphabetic characters occurrence
        if (this.conf.isLowercaseRequired() && !checkLowercase(clearPassword)) {
            throw new PasswordPolicyException("Password must contain lowercase alphabetic character(s)");
        }

        // check uppercase alphabetic characters occurrence
        if (this.conf.isUppercaseRequired() && !checkUppercase(clearPassword)) {
            throw new PasswordPolicyException("Password must contain uppercase alphabetic character(s)");
        }

        // check prefix
        this.conf.getPrefixesNotPermitted().stream().filter(prefix -> clearPassword.startsWith(prefix))
                .forEachOrdered(item -> {
                    throw new PasswordPolicyException("Prefix not permitted");
                });

        // check suffix
        this.conf.getSuffixesNotPermitted().stream().filter(suffix -> clearPassword.endsWith(suffix))
                .forEachOrdered(item -> {
                    throw new PasswordPolicyException("Suffix not permitted");
                });

        // check digit first occurrence
        if (this.conf.isMustStartWithDigit() && !checkFirstDigit(clearPassword)) {
            throw new PasswordPolicyException("Password must start with a digit");
        }

        if (this.conf.isMustntStartWithDigit() && checkFirstDigit(clearPassword)) {
            throw new PasswordPolicyException("Password mustn't start with a digit");
        }

        // check digit last occurrence
        if (this.conf.isMustEndWithDigit() && !checkLastDigit(clearPassword)) {
            throw new PasswordPolicyException("Password must end with a digit");
        }

        if (this.conf.isMustntEndWithDigit() && checkLastDigit(clearPassword)) {
            throw new PasswordPolicyException("Password mustn't end with a digit");
        }

        // check alphanumeric characters occurence
        if (this.conf.isAlphanumericRequired() && !checkAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password must contain alphanumeric character(s)");
        }

        // check non alphanumeric characters occurence
        if (this.conf.isNonAlphanumericRequired() && !checkNonAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password must contain non-alphanumeric character(s)");
        }

        // check alphanumeric character first occurrence
        if (this.conf.isMustStartWithAlpha() && !checkFirstAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password must start with an alphanumeric character");
        }

        if (this.conf.isMustntStartWithAlpha() && checkFirstAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password mustn't start with an alphanumeric character");
        }

        // check alphanumeric character last occurrence
        if (this.conf.isMustEndWithAlpha() && !checkLastAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password must end with an alphanumeric character");
        }

        if (this.conf.isMustntEndWithAlpha() && checkLastAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password mustn't end with an alphanumeric character");
        }

        // check non alphanumeric character first occurrence
        if (this.conf.isMustStartWithNonAlpha() && !checkFirstNonAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password must start with a non-alphanumeric character");
        }

        if (this.conf.isMustntStartWithNonAlpha() && checkFirstNonAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password mustn't start with a non-alphanumeric character");
        }

        // check non alphanumeric character last occurrence
        if (this.conf.isMustEndWithNonAlpha() && !checkLastNonAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password must end with a non-alphanumeric character");
        }

        if (this.conf.isMustntEndWithNonAlpha() && checkLastNonAlphanumeric(clearPassword)) {
            throw new PasswordPolicyException("Password mustn't end with a non-alphanumeric character");
        }

        if (!this.conf.isUsernameAllowed() && user.getUsername() != null
                && user.getUsername().equals(clearPassword)) {

            throw new PasswordPolicyException("Password mustn't be equal to username");
        }
    }
}

From source file:org.apache.zeppelin.rest.SecurityRestApi.java

/**
 * Get userlist//from   ww w .ja  v  a  2 s .  c  o  m
 * Returns list of all user from available realms
 *
 * @return 200 response
 */
@GET
@Path("userlist/{searchText}")
public Response getUserList(@PathParam("searchText") final String searchText) {

    List<String> usersList = new ArrayList<>();
    List<String> rolesList = new ArrayList<>();
    try {
        GetUserList getUserListObj = new GetUserList();
        Collection realmsList = SecurityUtils.getRealmsList();
        if (realmsList != null) {
            for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext();) {
                Realm realm = iterator.next();
                String name = realm.getClass().getName();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("RealmClass.getName: " + name);
                }
                if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
                    usersList.addAll(getUserListObj.getUserList((IniRealm) realm));
                    rolesList.addAll(getUserListObj.getRolesList((IniRealm) realm));
                } else if (name.equals("org.apache.zeppelin.realm.LdapGroupRealm")) {
                    usersList.addAll(getUserListObj.getUserList((JndiLdapRealm) realm, searchText));
                } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
                    usersList.addAll(getUserListObj.getUserList((LdapRealm) realm, searchText));
                    rolesList.addAll(getUserListObj.getRolesList((LdapRealm) realm));
                } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
                    usersList.addAll(getUserListObj.getUserList((ActiveDirectoryGroupRealm) realm, searchText));
                } else if (name.equals("org.apache.shiro.realm.jdbc.JdbcRealm")) {
                    usersList.addAll(getUserListObj.getUserList((JdbcRealm) realm));
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Exception in retrieving Users from realms ", e);
    }
    List<String> autoSuggestUserList = new ArrayList<>();
    List<String> autoSuggestRoleList = new ArrayList<>();
    Collections.sort(usersList);
    Collections.sort(rolesList);
    Collections.sort(usersList, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1.matches(searchText + "(.*)") && o2.matches(searchText + "(.*)")) {
                return 0;
            } else if (o1.matches(searchText + "(.*)")) {
                return -1;
            }
            return 0;
        }
    });
    int maxLength = 0;
    for (String user : usersList) {
        if (StringUtils.containsIgnoreCase(user, searchText)) {
            autoSuggestUserList.add(user);
            maxLength++;
        }
        if (maxLength == 5) {
            break;
        }
    }

    for (String role : rolesList) {
        if (StringUtils.containsIgnoreCase(role, searchText)) {
            autoSuggestRoleList.add(role);
        }
    }

    Map<String, List> returnListMap = new HashMap<>();
    returnListMap.put("users", autoSuggestUserList);
    returnListMap.put("roles", autoSuggestRoleList);

    return new JsonResponse<>(Response.Status.OK, "", returnListMap).build();
}

From source file:org.apereo.openlrs.conditions.RedisEnabledCondition.java

@Override
public boolean matches(ConditionContext ctx, AnnotatedTypeMetadata atm) {
    String redis = ctx.getEnvironment().getProperty("xapi.statements.repository.twotier.write");
    return (redis != null && StringUtils.containsIgnoreCase(redis, "redis"));
}

From source file:org.apereo.openlrs.OpenLRSAuthenticationFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    if (!enabled) {
        log.warn("Authentication is disabled");
        filterChain.doFilter(request, response);
    } else {//from ww w. ja v  a  2s  . co m
        String authorizationHeader = request.getHeader("Authorization");

        if (log.isDebugEnabled()) {
            log.debug(String.format("Authorization Header: %s", authorizationHeader));
        }

        if (StringUtils.isNotBlank(authorizationHeader)) {
            if (StringUtils.containsIgnoreCase(authorizationHeader, "oauth")) {
                authenticateOAuth(authorizationHeader, request, response, filterChain);
            } else {
                authenticateBasic(authorizationHeader, request, response, filterChain);
            }
        } else if ("OPTIONS".equals(request.getMethod())) {
            log.warn("OPTIONS request - returning no content");
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            unauthorized(response, "Missing Authorization Header", "None");
        }
    }
}

From source file:org.asqatasun.crawler.CrawlerImpl.java

/**
 * Heritrix may return content with an unknow content-type. This content
 * may be Html and that's what we try to detect here. 
 * The raw content is first converted into UTF-8 and then we search the
 * $lt;html and $lt;/html$gt;. If present, we deduce it is html. If not, 
 * we do nothing, the content is trashed.
 * @param curi//w  ww .  ja  va 2 s . com
 * @param recis 
 */
private void lastChanceToQualifyUnknownContent(CrawlURI curi, RecordingInputStream recis) throws IOException {
    String charset = extractCharset(curi, recis);
    try {
        String data = CrawlUtils.convertSourceCodeIntoUtf8(recis, charset).trim();
        if (StringUtils.containsIgnoreCase(data, OPEN_HTML_TAG)
                && StringUtils.containsIgnoreCase(data, END_HTML_TAG)) {
            saveHtmlContent(curi, recis);
        }
    } catch (Exception e) {
        LOGGER.debug("Exception caught when trying to convert unknow Content " + curi.getURI()
                + " into UTF-8. We deduce this content is not of html type");
    }
}