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

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

Introduction

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

Prototype

public static boolean isNoneEmpty(final CharSequence... css) 

Source Link

Document

Checks if none of the CharSequences are empty ("") or null.

 StringUtils.isNoneEmpty(null)             = false StringUtils.isNoneEmpty(null, "foo")      = false StringUtils.isNoneEmpty("", "bar")        = false StringUtils.isNoneEmpty("bob", "")        = false StringUtils.isNoneEmpty("  bob  ", null)  = false StringUtils.isNoneEmpty(" ", "bar")       = true StringUtils.isNoneEmpty("foo", "bar")     = true 

Usage

From source file:org.apache.nifi.web.server.JettyServer.java

protected static void configureSslContextFactory(SslContextFactory contextFactory, NiFiProperties props) {
    // require client auth when not supporting login, Kerberos service, or anonymous access
    if (props.isClientAuthRequiredForRestApi()) {
        contextFactory.setNeedClientAuth(true);
    } else {/*from   ww  w .java 2  s.  co m*/
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
        contextFactory.setKeyStorePath(props.getProperty(NiFiProperties.SECURITY_KEYSTORE));
    }
    String keyStoreType = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    if (StringUtils.isNotBlank(keyStoreType)) {
        contextFactory.setKeyStoreType(keyStoreType);
        String keyStoreProvider = KeyStoreUtils.getKeyStoreProvider(keyStoreType);
        if (StringUtils.isNoneEmpty(keyStoreProvider)) {
            contextFactory.setKeyStoreProvider(keyStoreProvider);
        }
    }
    final String keystorePassword = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
    final String keyPassword = props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD);
    if (StringUtils.isNotBlank(keystorePassword)) {
        // if no key password was provided, then assume the keystore password is the same as the key password.
        final String defaultKeyPassword = (StringUtils.isBlank(keyPassword)) ? keystorePassword : keyPassword;
        contextFactory.setKeyStorePassword(keystorePassword);
        contextFactory.setKeyManagerPassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyManagerPassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
        contextFactory.setTrustStorePath(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));
    }
    String trustStoreType = props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    if (StringUtils.isNotBlank(trustStoreType)) {
        contextFactory.setTrustStoreType(trustStoreType);
        String trustStoreProvider = KeyStoreUtils.getKeyStoreProvider(trustStoreType);
        if (StringUtils.isNoneEmpty(trustStoreProvider)) {
            contextFactory.setTrustStoreProvider(trustStoreProvider);
        }
    }
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD))) {
        contextFactory.setTrustStorePassword(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    }
}

From source file:org.apache.rocketmq.client.consumer.rebalance.AllocateMachineRoomNearby.java

@Override
public List<MessageQueue> allocate(String consumerGroup, String currentCID, List<MessageQueue> mqAll,
        List<String> cidAll) {
    if (currentCID == null || currentCID.length() < 1) {
        throw new IllegalArgumentException("currentCID is empty");
    }// ww  w  . ja v a 2 s.  c  om
    if (mqAll == null || mqAll.isEmpty()) {
        throw new IllegalArgumentException("mqAll is null or mqAll empty");
    }
    if (cidAll == null || cidAll.isEmpty()) {
        throw new IllegalArgumentException("cidAll is null or cidAll empty");
    }

    List<MessageQueue> result = new ArrayList<MessageQueue>();
    if (!cidAll.contains(currentCID)) {
        log.info("[BUG] ConsumerGroup: {} The consumerId: {} not in cidAll: {}", consumerGroup, currentCID,
                cidAll);
        return result;
    }

    //group mq by machine room
    Map<String/*machine room */, List<MessageQueue>> mr2Mq = new TreeMap<String, List<MessageQueue>>();
    for (MessageQueue mq : mqAll) {
        String brokerMachineRoom = machineRoomResolver.brokerDeployIn(mq);
        if (StringUtils.isNoneEmpty(brokerMachineRoom)) {
            if (mr2Mq.get(brokerMachineRoom) == null) {
                mr2Mq.put(brokerMachineRoom, new ArrayList<MessageQueue>());
            }
            mr2Mq.get(brokerMachineRoom).add(mq);
        } else {
            throw new IllegalArgumentException("Machine room is null for mq " + mq);
        }
    }

    //group consumer by machine room
    Map<String/*machine room */, List<String/*clientId*/>> mr2c = new TreeMap<String, List<String>>();
    for (String cid : cidAll) {
        String consumerMachineRoom = machineRoomResolver.consumerDeployIn(cid);
        if (StringUtils.isNoneEmpty(consumerMachineRoom)) {
            if (mr2c.get(consumerMachineRoom) == null) {
                mr2c.put(consumerMachineRoom, new ArrayList<String>());
            }
            mr2c.get(consumerMachineRoom).add(cid);
        } else {
            throw new IllegalArgumentException("Machine room is null for consumer id " + cid);
        }
    }

    List<MessageQueue> allocateResults = new ArrayList<MessageQueue>();

    //1.allocate the mq that deploy in the same machine room with the current consumer
    String currentMachineRoom = machineRoomResolver.consumerDeployIn(currentCID);
    List<MessageQueue> mqInThisMachineRoom = mr2Mq.remove(currentMachineRoom);
    List<String> consumerInThisMachineRoom = mr2c.get(currentMachineRoom);
    if (mqInThisMachineRoom != null && !mqInThisMachineRoom.isEmpty()) {
        allocateResults.addAll(allocateMessageQueueStrategy.allocate(consumerGroup, currentCID,
                mqInThisMachineRoom, consumerInThisMachineRoom));
    }

    //2.allocate the rest mq to each machine room if there are no consumer alive in that machine room
    for (String machineRoom : mr2Mq.keySet()) {
        if (!mr2c.containsKey(machineRoom)) { // no alive consumer in the corresponding machine room, so all consumers share these queues
            allocateResults.addAll(allocateMessageQueueStrategy.allocate(consumerGroup, currentCID,
                    mr2Mq.get(machineRoom), cidAll));
        }
    }

    return allocateResults;
}

From source file:org.apache.samza.execution.JobNode.java

/**
 * Generate the configs for a job/*w  ww  .  j a  va2s . c  o  m*/
 * @param executionPlanJson JSON representation of the execution plan
 * @return config of the job
 */
public JobConfig generateConfig(String executionPlanJson) {
    Map<String, String> configs = new HashMap<>();
    configs.put(JobConfig.JOB_NAME(), jobName);

    final List<String> inputs = new ArrayList<>();
    final List<String> broadcasts = new ArrayList<>();
    for (StreamEdge inEdge : inEdges) {
        String formattedSystemStream = inEdge.getFormattedSystemStream();
        if (inEdge.getStreamSpec().isBroadcast()) {
            broadcasts.add(formattedSystemStream + "#0");
        } else {
            inputs.add(formattedSystemStream);
        }
    }
    configs.put(TaskConfig.INPUT_STREAMS(), Joiner.on(',').join(inputs));
    if (!broadcasts.isEmpty()) {
        // TODO: remove this once we support defining broadcast input stream in high-level
        // task.broadcast.input should be generated by the planner in the future.
        final String taskBroadcasts = config.get(TaskConfigJava.BROADCAST_INPUT_STREAMS);
        if (StringUtils.isNoneEmpty(taskBroadcasts)) {
            broadcasts.add(taskBroadcasts);
        }
        configs.put(TaskConfigJava.BROADCAST_INPUT_STREAMS, Joiner.on(',').join(broadcasts));
    }

    // set triggering interval if a window or join is defined
    if (streamGraph.hasWindowOrJoins()) {
        if ("-1".equals(config.get(TaskConfig.WINDOW_MS(), "-1"))) {
            long triggerInterval = computeTriggerInterval();
            log.info("Using triggering interval: {} for jobName: {}", triggerInterval, jobName);

            configs.put(TaskConfig.WINDOW_MS(), String.valueOf(triggerInterval));
        }
    }

    streamGraph.getAllOperatorSpecs().forEach(opSpec -> {
        if (opSpec instanceof StatefulOperatorSpec) {
            ((StatefulOperatorSpec) opSpec).getStoreDescriptors()
                    .forEach(sd -> configs.putAll(sd.getStorageConfigs()));
            // store key and message serdes are configured separately in #addSerdeConfigs
        }
    });

    configs.put(CONFIG_INTERNAL_EXECUTION_PLAN, executionPlanJson);

    // write input/output streams to configs
    inEdges.stream().filter(StreamEdge::isIntermediate).forEach(edge -> configs.putAll(edge.generateConfig()));

    // write serialized serde instances and stream serde configs to configs
    addSerdeConfigs(configs);

    tables.forEach(tableSpec -> {
        // Table provider factory
        configs.put(String.format(JavaTableConfig.TABLE_PROVIDER_FACTORY, tableSpec.getId()),
                tableSpec.getTableProviderFactoryClassName());

        // Note: no need to generate config for Serde's, as they are already produced by addSerdeConfigs()

        // Generate additional configuration
        TableProviderFactory tableProviderFactory = Util.getObj(tableSpec.getTableProviderFactoryClassName(),
                TableProviderFactory.class);
        TableProvider tableProvider = tableProviderFactory.getTableProvider(tableSpec);
        configs.putAll(tableProvider.generateConfig(configs));
    });

    log.info("Job {} has generated configs {}", jobName, configs);

    String configPrefix = String.format(CONFIG_JOB_PREFIX, jobName);

    // Disallow user specified job inputs/outputs. This info comes strictly from the user application.
    Map<String, String> allowedConfigs = new HashMap<>(config);
    if (allowedConfigs.containsKey(TaskConfig.INPUT_STREAMS())) {
        log.warn("Specifying task inputs in configuration is not allowed with Fluent API. "
                + "Ignoring configured value for " + TaskConfig.INPUT_STREAMS());
        allowedConfigs.remove(TaskConfig.INPUT_STREAMS());
    }

    log.debug("Job {} has allowed configs {}", jobName, allowedConfigs);
    return new JobConfig(Util.rewriteConfig(
            extractScopedConfig(new MapConfig(allowedConfigs), new MapConfig(configs), configPrefix)));
}

From source file:org.apache.samza.execution.JobPlanner.java

private Map<String, String> getGeneratedConfig(String runId) {
    Map<String, String> generatedConfig = new HashMap<>();
    if (StringUtils.isNoneEmpty(runId)) {
        generatedConfig.put(ApplicationConfig.APP_RUN_ID, runId);
    }//from  w  w  w . j  a va2s .c o m

    StreamConfig streamConfig = new StreamConfig(userConfig);
    Set<String> inputStreamIds = new HashSet<>(appDesc.getInputStreamIds());
    inputStreamIds.removeAll(appDesc.getOutputStreamIds()); // exclude intermediate streams
    ApplicationConfig.ApplicationMode mode = inputStreamIds.stream().allMatch(streamConfig::getIsBounded)
            ? ApplicationConfig.ApplicationMode.BATCH
            : ApplicationConfig.ApplicationMode.STREAM;
    generatedConfig.put(ApplicationConfig.APP_MODE, mode.name());

    Map<String, String> systemStreamConfigs = generateSystemStreamConfigs(appDesc);
    generatedConfig.putAll(systemStreamConfigs);

    // adding app.class in the configuration, unless it is LegacyTaskApplication
    if (!LegacyTaskApplication.class.getName().equals(appDesc.getAppClass().getName())) {
        generatedConfig.put(ApplicationConfig.APP_CLASS, appDesc.getAppClass().getName());
    }
    return generatedConfig;
}

From source file:org.apache.samza.runtime.AbstractApplicationRunner.java

ExecutionPlan getExecutionPlan(StreamApplication app, String runId) throws Exception {
    // build stream graph
    StreamGraphImpl streamGraph = new StreamGraphImpl(this, config);
    app.init(streamGraph, config);// ww  w  .  j  av  a  2 s  . c  o  m

    // create the physical execution plan
    Map<String, String> cfg = new HashMap<>(config);
    if (StringUtils.isNoneEmpty(runId)) {
        cfg.put(ApplicationConfig.APP_RUN_ID, runId);
    }

    Set<StreamSpec> inputStreams = new HashSet<>(streamGraph.getInputOperators().keySet());
    inputStreams.removeAll(streamGraph.getOutputStreams().keySet());
    ApplicationMode mode = inputStreams.stream().allMatch(StreamSpec::isBounded) ? ApplicationMode.BATCH
            : ApplicationMode.STREAM;
    cfg.put(ApplicationConfig.APP_MODE, mode.name());

    ExecutionPlanner planner = new ExecutionPlanner(new MapConfig(cfg), streamManager);
    return planner.plan(streamGraph);
}

From source file:org.apache.servicecomb.swagger.generator.core.processor.annotation.AnnotationUtils.java

protected static void processApiParam(ApiParam param, AbstractSerializableParameter<?> p) {
    if (param.required()) {
        p.setRequired(true);//  ww w .  j  a  v a  2  s  .com
    }
    if (param.readOnly()) {
        p.setReadOnly(true);
    }
    if (param.allowEmptyValue()) {
        p.setAllowEmptyValue(true);
    }
    if (StringUtils.isNotEmpty(param.name())) {
        p.setName(param.name());
    }
    if (StringUtils.isNotEmpty(param.value())) {
        p.setDescription(param.value());
    }
    if (StringUtils.isNotEmpty(param.example())) {
        p.setExample(param.example());
    }
    if (StringUtils.isNotEmpty(param.access())) {
        p.setAccess(param.access());
    }
    if (StringUtils.isNoneEmpty(param.collectionFormat())) {
        p.setCollectionFormat(param.collectionFormat());
    }
    if (StringUtils.isNotEmpty(param.type())) {
        if ("java.io.File".equalsIgnoreCase(param.type())) {
            p.setProperty(new FileProperty());
        } else if ("long".equalsIgnoreCase(param.type())) {
            p.setProperty(new LongProperty());
        } else {
            p.setType(param.type());
        }
    }
}

From source file:org.apache.syncope.client.console.status.ResourceStatusDirectoryPanel.java

public void updateResultTable(final String type, final AjaxRequestTarget target) {
    this.type = type;

    if (StringUtils.isNoneEmpty(type)) {
        switch (type) {
        case "USER":
            this.restClient = new UserRestClient();
            break;
        case "GROUP":
            this.restClient = new GroupRestClient();
            break;
        default:/*from w  ww  .j av a2s  . c o m*/
            this.restClient = new AnyObjectRestClient();
        }
    }

    super.updateResultTable(target);
}

From source file:org.apache.syncope.client.console.wicket.ajax.markup.html.LabelInfo.java

public LabelInfo(final String id, final Collection<String> title) {
    super(id, StringUtils.EMPTY);
    if (CollectionUtils.isEmpty(title)) {
        this.title = StringUtils.EMPTY;
    } else {//from   ww w  .  j  a  v  a 2  s  .  c  om
        StringBuilder titleBuilder = new StringBuilder();
        for (String el : title) {
            if (titleBuilder.length() > 0) {
                titleBuilder.append("; ");
            }
            if (StringUtils.isNoneEmpty(el)) {
                titleBuilder.append(el);
            }
        }
        this.title = StringUtils.abbreviate(titleBuilder.toString(), 50);
    }
}

From source file:org.apache.zeppelin.elasticsearch.client.HttpBasedClient.java

@Override
public ActionResponse search(String[] indices, String[] types, String query, int size) {
    ActionResponse response = null;//from  w w w  .  j  a  v  a 2 s  . co m

    if (!StringUtils.isEmpty(query)) {
        // The query can be either JSON-formatted, nor a Lucene query
        // So, try to parse as a JSON => if there is an error, consider the query a Lucene one
        try {
            gson.fromJson(query, Map.class);
        } catch (final JsonParseException e) {
            // This is not a JSON (or maybe not well formatted...)
            query = QUERY_STRING_TEMPLATE.replace("_Q_", query);
        }
    }

    try {
        final HttpRequestWithBody request = Unirest.post(getUrl(indices, types) + "/_search?size=" + size)
                .header("Content-Type", "application/json");

        if (StringUtils.isNoneEmpty(query)) {
            request.header("Accept", "application/json").body(query);
        }

        if (StringUtils.isNotEmpty(username)) {
            request.basicAuth(username, password);
        }

        final HttpResponse<JsonNode> result = request.asJson();
        final JSONObject body = result.getBody() != null ? result.getBody().getObject() : null;

        if (isSucceeded(result)) {
            final long total = getFieldAsLong(result, "hits/total");

            response = new ActionResponse().succeeded(true).totalHits(total);

            if (containsAggs(result)) {
                JSONObject aggregationsMap = body.getJSONObject("aggregations");
                if (aggregationsMap == null) {
                    aggregationsMap = body.getJSONObject("aggs");
                }

                for (final String key : aggregationsMap.keySet()) {
                    final JSONObject aggResult = aggregationsMap.getJSONObject(key);
                    if (aggResult.has("buckets")) {
                        // Multi-bucket aggregations
                        final Iterator<Object> buckets = aggResult.getJSONArray("buckets").iterator();
                        while (buckets.hasNext()) {
                            response.addAggregation(
                                    new AggWrapper(AggregationType.MULTI_BUCKETS, buckets.next().toString()));
                        }
                    } else {
                        response.addAggregation(
                                new AggWrapper(AggregationType.SIMPLE, aggregationsMap.toString()));
                    }
                    break; // Keep only one aggregation
                }
            } else if (size > 0 && total > 0) {
                final JSONArray hits = getFieldAsArray(body, "hits/hits");
                final Iterator<Object> iter = hits.iterator();

                while (iter.hasNext()) {
                    final JSONObject hit = (JSONObject) iter.next();
                    final Object data = hit.opt("_source") != null ? hit.opt("_source") : hit.opt("fields");
                    response.addHit(new HitWrapper(hit.getString("_index"), hit.getString("_type"),
                            hit.getString("_id"), data.toString()));
                }
            }
        } else {
            throw new ActionException(body.get("error").toString());
        }
    } catch (final UnirestException e) {
        throw new ActionException(e);
    }

    return response;
}

From source file:org.craftercms.studio.impl.v1.web.security.access.StudioGroupAPIAccessDecisionVoter.java

@Override
public int vote(Authentication authentication, Object o, Collection collection) {
    int toRet = ACCESS_ABSTAIN;
    String requestUri = "";
    if (o instanceof FilterInvocation) {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        HttpServletRequest request = filterInvocation.getRequest();
        requestUri = request.getRequestURI().replace(request.getContextPath(), "");
        String siteParam = request.getParameter("site_id");
        String userParam = request.getParameter("username");
        User currentUser = null;//  w w  w.  j  a v a  2 s  .  com
        try {
            currentUser = (User) authentication.getPrincipal();
        } catch (ClassCastException e) {
            // anonymous user
            if (!authentication.getPrincipal().toString().equals("anonymousUser")) {
                logger.error("Error getting current user", e);
                return ACCESS_ABSTAIN;
            }
        }
        if (StringUtils.isEmpty(userParam)
                && StringUtils.equalsIgnoreCase(request.getMethod(), HttpMethod.POST.name())
                && !ServletFileUpload.isMultipartContent(request)) {
            try {
                InputStream is = request.getInputStream();
                is.mark(0);
                String jsonString = IOUtils.toString(is);
                if (StringUtils.isNoneEmpty(jsonString)) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonString);
                    if (jsonObject.has("username")) {
                        userParam = jsonObject.getString("username");
                    }
                    if (jsonObject.has("site_id")) {
                        siteParam = jsonObject.getString("site_id");
                    }
                }
                is.reset();
            } catch (IOException | JSONException e) {
                // TODO: ??
                logger.debug("Failed to extract username from POST request");
            }
        }
        switch (requestUri) {
        case ADD_USER:
        case CREATE:
        case DELETE:
        case GET_ALL:
        case REMOVE_USER:
        case UPDATE:
            if (currentUser != null && (isSiteAdmin(
                    studioConfiguration.getProperty(StudioConfiguration.CONFIGURATION_GLOBAL_SYSTEM_SITE),
                    currentUser) || isSiteAdmin(siteParam, currentUser))) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case GET:
        case GET_PER_SITE:
        case USERS:
            if (currentUser != null
                    && (isSiteAdmin(siteParam, currentUser) || isSiteMember(siteParam, currentUser))) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        default:
            toRet = ACCESS_ABSTAIN;
            break;
        }
    }
    logger.debug("Request: " + requestUri + " - Access: " + toRet);
    return toRet;
}