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.james.mailbox.cassandra.mail.CassandraMailboxMapper.java

private void manageException(CompletionException e) throws MailboxException {
    if (e.getCause() instanceof InvalidQueryException) {
        String errorMessage = e.getCause().getMessage();
        if (StringUtils.containsIgnoreCase(errorMessage, VALUES_MAY_NOT_BE_LARGER_THAN_64_K)
                || StringUtils.containsIgnoreCase(errorMessage, CLUSTERING_COLUMNS_IS_TOO_LONG)) {
            throw new TooLongMailboxNameException("too long mailbox name");
        }/* w  w  w.  j av a2s  .  co m*/
        throw new MailboxException("It has error with cassandra storage", e.getCause());
    }
    throw e;
}

From source file:org.apache.marmotta.kiwi.persistence.h2.H2Dialect.java

@Override
public String getRegexp(String text, String pattern, String flags) {
    if (StringUtils.containsIgnoreCase(flags, "i")) {
        return String.format("lower(%s) REGEXP lower(%s)", text, pattern);
    } else {/*from w  ww .  j  a  v a  2s.co  m*/
        return text + " REGEXP " + pattern;
    }
}

From source file:org.apache.marmotta.kiwi.persistence.h2.H2Dialect.java

/**
 * Return true in case the SPARQL RE flags contained in the given string are supported.
 *
 * @param flags//  ww w  .  j a  va2  s .c o  m
 * @return
 */
@Override
public boolean isRegexpSupported(String flags) {
    if (StringUtils.containsIgnoreCase(flags, "s")) {
        return false;
    }
    if (StringUtils.containsIgnoreCase(flags, "m")) {
        return false;
    }
    if (StringUtils.containsIgnoreCase(flags, "x")) {
        return false;
    }

    return true;
}

From source file:org.apache.marmotta.kiwi.persistence.mysql.MySQLDialect.java

@Override
public String getRegexp(String text, String pattern, String flags) {
    if (StringUtils.containsIgnoreCase(flags, "i")) {
        return String.format("lower(%s) RLIKE lower(%s)", text, pattern);
    } else {//from w  w  w.  jav a2  s  .co m
        return text + " RLIKE " + pattern;
    }
}

From source file:org.apache.marmotta.kiwi.persistence.pgsql.PostgreSQLDialect.java

@Override
public String getRegexp(String text, String pattern, String flags) {
    StringBuilder flagList = new StringBuilder();
    if (StringUtils.containsIgnoreCase(flags, "i")) {
        flagList.append("i");
    }//  w ww.j  a v  a 2 s  .  co m
    if (flagList.length() == 0) {
        return text + " ~ " + pattern;
    } else {
        return String.format("%s ~ (?%s)%s", text, flagList.toString(), pattern);
    }
}

From source file:org.apache.marmotta.kiwi.sparql.builder.eval.ValueExpressionEvaluator.java

/**
 * Test if the regular expression given in the pattern can be simplified to a LIKE SQL statement; these are
 * considerably more efficient to evaluate in most databases, so in case we can simplify, we return a LIKE.
 *
 * @param value/* www  .  jav a  2  s. c  o  m*/
 * @param pattern
 * @return
 */
private String optimizeRegexp(String value, String pattern, ValueExpr flags) {
    String _flags = flags != null && flags instanceof ValueConstant
            ? ((ValueConstant) flags).getValue().stringValue()
            : null;

    String simplified = pattern;

    // apply simplifications

    // remove SQL quotes at beginning and end
    simplified = simplified.replaceFirst("^'", "");
    simplified = simplified.replaceFirst("'$", "");

    // remove .* at beginning and end, they are the default anyways
    simplified = simplified.replaceFirst("^\\.\\*", "");
    simplified = simplified.replaceFirst("\\.\\*$", "");

    // replace all occurrences of % with \% and _ with \_, as they are special characters in SQL
    simplified = simplified.replaceAll("%", "\\%");
    simplified = simplified.replaceAll("_", "\\_");

    // if pattern now does not start with a ^, we put a "%" in front
    if (!simplified.startsWith("^")) {
        simplified = "%" + simplified;
    } else {
        simplified = simplified.substring(1);
    }

    // if pattern does not end with a "$", we put a "%" at the end
    if (!simplified.endsWith("$")) {
        simplified = simplified + "%";
    } else {
        simplified = simplified.substring(0, simplified.length() - 1);
    }

    // replace all non-escaped occurrences of .* with %
    simplified = simplified.replaceAll("(?<!\\\\)\\.\\*", "%");

    // replace all non-escaped occurrences of .+ with _%
    simplified = simplified.replaceAll("(?<!\\\\)\\.\\+", "_%");

    // the pattern is not simplifiable if the simplification still contains unescaped regular expression constructs
    Pattern notSimplifiable = Pattern.compile("(?<!\\\\)[\\.\\*\\+\\{\\}\\[\\]\\|]");

    if (notSimplifiable.matcher(simplified).find()) {
        return parent.getDialect().getRegexp(value, pattern, _flags);
    } else {
        if (!simplified.startsWith("%") && !simplified.endsWith("%")) {
            if (StringUtils.containsIgnoreCase(_flags, "i")) {
                return String.format("lower(%s) = lower('%s')", value, simplified);
            } else {
                return String.format("%s = '%s'", value, simplified);
            }
        } else {
            if (StringUtils.containsIgnoreCase(_flags, "i")) {
                return parent.getDialect().getILike(value, "'" + simplified + "'");
            } else {
                return value + " LIKE '" + simplified + "'";
            }
        }
    }

}

From source file:org.apache.marmotta.kiwi.sparql.function.string.NReplace.java

/**
 * Return a string representing how this function is translated into SQL in the given dialect
 *
 * @param dialect/*from   ww  w . ja v a 2s. c  om*/
 * @param args
 * @return
 */
@Override
public String getNative(KiWiDialect dialect, String... args) {
    if (dialect instanceof PostgreSQLDialect) {
        if (args.length == 3) {
            // no flags
            return String.format("regexp_replace(%s, %s, %s, 'g')", args[0], args[1], args[2]);
        } else if (args.length == 4) {
            // flags
            StringBuilder psqlFlags = new StringBuilder();
            if (StringUtils.containsIgnoreCase(args[3], "i")) {
                psqlFlags.append("i");
            }

            return String.format("regexp_replace(%s, %s, %s, 'g%s')", args[0], args[1], args[2],
                    psqlFlags.toString());
        }
    } else if (dialect instanceof H2Dialect) {
        // no flags
        return String.format("REGEXP_REPLACE(%s, %s, %s)", args[0], args[1], args[2]);
    }
    throw new UnsupportedOperationException("REPLACE not supported in dialect " + dialect);
}

From source file:org.apache.nifi.processors.attributes.UpdateAttribute.java

@Override
public Collection<SearchResult> search(final SearchContext context) {
    final String term = context.getSearchTerm();

    final Collection<SearchResult> results = new ArrayList<>();
    if (StringUtils.isBlank(context.getAnnotationData())) {
        return results;
    }/*from  ww  w .ja  v  a2s.c om*/

    try {
        // parse the annotation data
        final Criteria criteria = CriteriaSerDe.deserialize(context.getAnnotationData());

        // ensure there are some rules
        if (criteria.getRules() != null) {
            final FlowFilePolicy flowFilePolicy = criteria.getFlowFilePolicy();
            if (flowFilePolicy != null && StringUtils.containsIgnoreCase(flowFilePolicy.name(), term)) {
                results.add(new SearchResult.Builder().label("FlowFile policy").match(flowFilePolicy.name())
                        .build());
            }

            for (final Rule rule : criteria.getRules()) {
                if (StringUtils.containsIgnoreCase(rule.getName(), term)) {
                    results.add(new SearchResult.Builder().label("Rule name").match(rule.getName()).build());
                }

                // ensure there are some conditions
                if (rule.getConditions() != null) {
                    for (final Condition condition : rule.getConditions()) {
                        if (StringUtils.containsIgnoreCase(condition.getExpression(), term)) {
                            results.add(new SearchResult.Builder()
                                    .label(String.format("Condition in rule '%s'", rule.getName()))
                                    .match(condition.getExpression()).build());
                        }
                    }
                }

                // ensure there are some actions
                if (rule.getActions() != null) {
                    for (final Action action : rule.getActions()) {
                        if (StringUtils.containsIgnoreCase(action.getAttribute(), term)) {
                            results.add(new SearchResult.Builder()
                                    .label(String.format("Action in rule '%s'", rule.getName()))
                                    .match(action.getAttribute()).build());
                        }
                        if (StringUtils.containsIgnoreCase(action.getValue(), term)) {
                            results.add(new SearchResult.Builder()
                                    .label(String.format("Action in rule '%s'", rule.getName()))
                                    .match(action.getValue()).build());
                        }
                    }
                }
            }
        }

        return results;
    } catch (Exception e) {
        return results;
    }
}

From source file:org.apache.nifi.update.attributes.api.RuleResource.java

@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("/rules/search-results")
public Response searchRules(@QueryParam("processorId") final String processorId,
        @QueryParam("q") final String term) {

    // get the web context
    final NiFiWebConfigurationContext configurationContext = (NiFiWebConfigurationContext) servletContext
            .getAttribute("nifi-web-configuration-context");

    // build the web context config
    final NiFiWebRequestContext requestContext = getRequestContext(processorId);

    // load the criteria
    final Criteria criteria = getCriteria(configurationContext, requestContext);
    final List<Rule> rules = criteria.getRules();

    // generate the rules
    List<RuleDTO> ruleDtos = null;
    if (rules != null) {
        ruleDtos = new ArrayList<>(rules.size());
        for (final Rule rule : rules) {
            if (StringUtils.containsIgnoreCase(rule.getName(), term)) {
                final RuleDTO ruleDto = DtoFactory.createRuleDTO(rule);
                ruleDtos.add(ruleDto);/*from  w  w  w .  j a  v  a  2 s . c o m*/
            }
        }
    }

    // sort the rules
    Collections.sort(ruleDtos, new Comparator<RuleDTO>() {
        @Override
        public int compare(RuleDTO r1, RuleDTO r2) {
            final Collator collator = Collator.getInstance(Locale.US);
            return collator.compare(r1.getName(), r2.getName());
        }
    });

    // create the response entity
    final RulesEntity responseEntity = new RulesEntity();
    responseEntity.setProcessorId(processorId);
    responseEntity.setRules(ruleDtos);

    // generate the response
    final ResponseBuilder response = Response.ok(responseEntity);
    return noCache(response).build();
}

From source file:org.apache.nifi.web.api.ClusterResource.java

/**
 * Searches the cluster for a node with a given address.
 *
 * @param value Search value that will be matched against a node's address
 * @return Nodes that match the specified criteria
 *//*from   w w w  .j  a v a2  s  .co m*/
@GET
@Consumes(MediaType.WILDCARD)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/search-results")
@PreAuthorize("hasAnyRole('ROLE_MONITOR', 'ROLE_DFM', 'ROLE_ADMIN')")
@ApiOperation(value = "Searches the cluster for a node with the specified address", response = ClusterSearchResultsEntity.class, authorizations = {
        @Authorization(value = "Read Only", type = "ROLE_MONITOR"),
        @Authorization(value = "DFM", type = "ROLE_DFM"),
        @Authorization(value = "Admin", type = "ROLE_ADMIN") })
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
        @ApiResponse(code = 401, message = "Client could not be authenticated."),
        @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
        @ApiResponse(code = 404, message = "The specified resource could not be found."),
        @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response searchCluster(
        @ApiParam(value = "Node address to search for.", required = true) @QueryParam("q") @DefaultValue(StringUtils.EMPTY) String value) {

    // ensure this is the cluster manager
    if (properties.isClusterManager()) {
        final List<NodeSearchResultDTO> nodeMatches = new ArrayList<>();

        // get the nodes in the cluster
        final ClusterDTO cluster = serviceFacade.getCluster();

        // check each to see if it matches the search term
        for (NodeDTO node : cluster.getNodes()) {
            // ensure the node is connected
            if (!Node.Status.CONNECTED.toString().equals(node.getStatus())) {
                continue;
            }

            // determine the current nodes address
            final String address = node.getAddress() + ":" + node.getApiPort();

            // count the node if there is no search or it matches the address
            if (StringUtils.isBlank(value) || StringUtils.containsIgnoreCase(address, value)) {
                final NodeSearchResultDTO nodeMatch = new NodeSearchResultDTO();
                nodeMatch.setId(node.getNodeId());
                nodeMatch.setAddress(address);
                nodeMatches.add(nodeMatch);
            }
        }

        // build the response
        ClusterSearchResultsEntity results = new ClusterSearchResultsEntity();
        results.setNodeResults(nodeMatches);

        // generate an 200 - OK response
        return noCache(Response.ok(results)).build();
    }

    throw new IllegalClusterResourceRequestException("Only a cluster manager can process the request.");
}