Example usage for org.apache.commons.collections4 CollectionUtils isNotEmpty

List of usage examples for org.apache.commons.collections4 CollectionUtils isNotEmpty

Introduction

In this page you can find the example usage for org.apache.commons.collections4 CollectionUtils isNotEmpty.

Prototype

public static boolean isNotEmpty(final Collection<?> coll) 

Source Link

Document

Null-safe check if the specified collection is not empty.

Usage

From source file:com.baifendian.swordfish.dao.mapper.ExecutionFlowMapperProvider.java

/**
 * , ???/*from  w ww  .  ja  v a 2  s. c o m*/
 */
public String selectByFlowIdAndTimesAndStatusLimit(Map<String, Object> parameter) {

    List<FlowStatus> flowStatuses = (List<FlowStatus>) parameter.get("status");

    List<String> workflowList = (List<String>) parameter.get("workflowList");

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

    Date startDate = (Date) parameter.get("startDate");
    Date endDate = (Date) parameter.get("endDate");

    if (CollectionUtils.isNotEmpty(workflowList)) {
        for (String workflow : workflowList) {
            workflowList2.add("p_f.name like '" + workflow + "%'");
        }
    }

    List<String> flowStatusStrList = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(flowStatuses)) {
        for (FlowStatus status : flowStatuses) {
            flowStatusStrList.add(String.valueOf(status.ordinal()));
        }
    }

    String where = String.join(",", flowStatusStrList);

    String sql = new SQL() {
        {
            SELECT("p_f.name as flow_name");
            SELECT("p.name as project_name");
            SELECT("u.name as owner");
            SELECT("e_f.*");

            FROM(TABLE_NAME + " e_f");

            JOIN("project_flows p_f on e_f.flow_id = p_f.id");
            JOIN("project p on p_f.project_id = p.id");
            JOIN("user u on p_f.owner = u.id");

            WHERE("p.name = #{projectName}");

            if (CollectionUtils.isNotEmpty(workflowList)) {
                WHERE(" ( " + String.join(" or ", workflowList2) + " ) ");
            }

            if (startDate != null && endDate != null) {
                WHERE("start_time >= #{startDate}");
                WHERE("start_time <= #{endDate}");
            }

            if (CollectionUtils.isNotEmpty(flowStatuses)) {
                WHERE("`status` in (" + where + ") ");
            }
        }
    }.toString();

    String sql2 = new SQL() {
        {
            SELECT("u.name as submit_user_name");
            SELECT("e_f.*");

            FROM("(" + sql + ") e_f");

            JOIN("user u on e_f.submit_user = u.id");
        }
    }.toString() + " order by start_time DESC limit #{start},#{limit}";

    return sql2;
}

From source file:com.epam.catgenome.dao.DaoHelper.java

/**
 * Creates a new temporary list of {@code Long} values. The created temporary list is
 * identified by the given ID. If a list has been created successfully, it will be filled
 * in by {@code Collection} of provided {@code Long} values.
 *
 * @param listId {@code Long} represents unique ID that is used to identify a temporary list
 * @param list   {@code Collection} specifies collection of {@code Long} values that should be
 *               associated with a temporary list if this call is succeeded
 * @return {@code Long} represents unique ID of a temporary list that has been created after
 * this call//from  w  w w  .  j ava  2  s.  c om
 * @throws IllegalArgumentException will be thrown if <tt>listId</tt> or <tt>list</tt> are
 *                                  <tt>null</tt>, or the given <tt>list</tt> is empty
 */
@Transactional(propagation = Propagation.MANDATORY)
public Long createTempLongList(final Long listId, final Collection<Long> list) {
    Assert.notNull(listId);
    Assert.isTrue(CollectionUtils.isNotEmpty(list));
    // creates a new local temporary table if it doesn't exists to handle temporary lists
    getJdbcTemplate().update(createTemporaryListQuery);
    // fills in a temporary list by given values
    int i = 0;
    final Iterator<Long> iterator = list.iterator();
    final MapSqlParameterSource[] batchArgs = new MapSqlParameterSource[list.size()];
    while (iterator.hasNext()) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue(HelperParameters.LIST_ID.name(), listId);
        params.addValue(HelperParameters.LIST_VALUE.name(), iterator.next());
        batchArgs[i] = params;
        i++;
    }
    getNamedParameterJdbcTemplate().batchUpdate(insertTemporaryListItemQuery, batchArgs);
    return listId;
}

From source file:io.kodokojo.service.marathon.MarathonBrickManager.java

@Override
public void configure(ProjectConfiguration projectConfiguration, BrickType brickType)
        throws ProjectConfigurationException {
    if (projectConfiguration == null) {
        throw new IllegalArgumentException("projectConfiguration must be defined.");
    }//from   w  w w  . j a v  a  2  s  . co  m
    if (brickType == null) {
        throw new IllegalArgumentException("brickType must be defined.");
    }

    Iterator<BrickConfiguration> brickConfigurations = projectConfiguration.getDefaultBrickConfigurations();
    BrickConfiguration brickConfiguration = getBrickConfiguration(brickType, brickConfigurations);

    if (brickConfiguration == null) {
        throw new IllegalStateException("Unable to find brickConfiguration for " + brickType);
    }
    String name = projectConfiguration.getName().toLowerCase();
    String type = brickType.name().toLowerCase();
    BrickConfigurer configurer = brickConfigurerProvider.provideFromBrick(brickConfiguration.getBrick());
    if (configurer != null) {
        Set<Service> services = marathonServiceLocator.getService(type, name);
        if (CollectionUtils.isNotEmpty(services)) {
            String entrypoint = getEntryPoint(services);
            if (StringUtils.isBlank(entrypoint)) {
                LOGGER.error("Unable to find a valid entrypoint for brick '{}' on project {}", type, name);
            } else {
                List<User> users = IteratorUtils.toList(projectConfiguration.getUsers());
                try {
                    BrickConfigurerData brickConfigurerData = configurer
                            .configure(new BrickConfigurerData(projectConfiguration.getName(),
                                    projectConfiguration.getDefaultStackConfiguration().getName(), entrypoint,
                                    domain, IteratorUtils.toList(projectConfiguration.getAdmins()), users));
                    brickConfigurerData = configurer.addUsers(brickConfigurerData, users);
                    projectStore.setContextToBrickConfiguration(projectConfiguration.getIdentifier(),
                            brickConfiguration, brickConfigurerData.getContext());

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Adding users {} to brick {}", StringUtils.join(users, ","), brickType);
                    }
                } catch (BrickConfigurationException e) {
                    throw new ProjectConfigurationException("En error occur while trying to configure brick "
                            + brickType.name() + " on project " + projectConfiguration.getName(), e);
                }
            }
        } else {
            LOGGER.error("Unable to find http service for brick '{}' on project {}.", type, name);
        }
    } else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Configurer Not defined for brick {}", brickType);
    }

}

From source file:com.jkoolcloud.tnt4j.streams.custom.dirStream.DirStreamingManager.java

private synchronized void shutdownExecutors() {
    if (executorService == null || executorService.isShutdown()) {
        return;// w  w  w  .  j a  v  a 2 s.  c  om
    }

    executorService.shutdown();
    try {
        executorService.awaitTermination(executorsTerminationTimeout, TimeUnit.SECONDS);
    } catch (InterruptedException exc) {
    } finally {
        List<Runnable> droppedJobs = executorService.shutdownNow();

        if (CollectionUtils.isNotEmpty(droppedJobs)) {
            for (Runnable job : droppedJobs) {
                notifyStreamingJobDropOff(job);
            }
        }
    }
}

From source file:io.cloudslang.lang.compiler.validator.CompileValidatorImpl.java

private void validateResultNamesAndNavigationSection(Flow flow, Step step, String refId, Executable reference,
        List<RuntimeException> errors) {
    List<String> stepNavigationKeys = getMapKeyList(step.getNavigationStrings());
    List<String> refResults = mapResultsToNames(reference.getResults());
    List<String> possibleResults;

    possibleResults = getPossibleResults(step, refResults);

    List<String> stepNavigationKeysWithoutMatchingResult = ListUtils.subtract(stepNavigationKeys,
            possibleResults);/*www  .  j  av  a  2  s . c  om*/
    List<String> refResultsWithoutMatchingNavigation = ListUtils.subtract(possibleResults, stepNavigationKeys);

    if (CollectionUtils.isNotEmpty(refResultsWithoutMatchingNavigation)) {
        if (step.isParallelLoop()) {
            errors.add(new IllegalArgumentException(
                    getErrorMessagePrefix(flow, step) + " the parallel loop results "
                            + refResultsWithoutMatchingNavigation + " have no matching navigation."));
        } else {
            errors.add(new IllegalArgumentException(
                    getErrorMessagePrefix(flow, step) + " the results " + refResultsWithoutMatchingNavigation
                            + " of its dependency '" + refId + "' have no matching navigation."));
        }
    }
    if (CollectionUtils.isNotEmpty(stepNavigationKeysWithoutMatchingResult)) {
        if (step.isParallelLoop()) {
            errors.add(new IllegalArgumentException(getErrorMessagePrefix(flow, step) + " the navigation keys "
                    + stepNavigationKeysWithoutMatchingResult + " have no matching results."
                    + " The parallel loop depending on '" + refId + "' can have the following results: "
                    + possibleResults + "."));
        } else {
            errors.add(new IllegalArgumentException(getErrorMessagePrefix(flow, step) + " the navigation keys "
                    + stepNavigationKeysWithoutMatchingResult + " have no matching results in its dependency '"
                    + refId + "'."));
        }
    }
}

From source file:com.baifendian.swordfish.dao.mapper.StreamingResultMapperProvider.java

/**
 * //from w  w  w  . j ava 2s  .  c o  m
 *
 * @param parameter
 * @return
 */
public String findCountByMultiCondition(Map<String, Object> parameter) {
    List<Integer> status = (List<Integer>) parameter.get("status");
    String name = (String) parameter.get("name");

    Date startDate = (Date) parameter.get("startDate");
    Date endDate = (Date) parameter.get("endDate");

    return new SQL() {
        {
            SELECT("count(0)");

            FROM(TABLE_NAME + " r");

            JOIN("streaming_job s on r.streaming_id = s.id");

            if (startDate != null) {
                WHERE("schedule_time >= #{startDate}");
            }

            if (endDate != null) {
                WHERE("schedule_time < #{endDate}");
            }

            WHERE("s.project_id=#{projectId}");

            // ?
            if (StringUtils.isNotEmpty(name)) {
                WHERE("s.name like '" + name + "%'");
            }

            if (CollectionUtils.isNotEmpty(status)) {
                WHERE("`status` in (" + StringUtils.join(status, ",") + ")");
            }

        }
    }.toString();
}

From source file:fr.landel.utils.assertor.helper.HelperMessage.java

/**
 * Get the message and define that the current condition uses a personalized
 * message, not the default one//from   ww  w. jav  a 2 s.  c  o  m
 * 
 * @param key
 *            The message key (required, not null)
 * @param precondition
 *            If 'precondition' suffix has to be appended
 * @param not
 *            If 'not' suffix has to be appended
 * @param values
 *            the message values
 * @param parameters
 *            The parameters
 * @return The loaded property
 */
public static String getDefaultMessage(final CharSequence key, final boolean precondition, final boolean not,
        final CharSequence[] values, final List<ParameterAssertor<?>> parameters) {

    Objects.requireNonNull(key, MISSING_DEFAULT_MESSAGE_KEY);

    final StringBuilder keyProperty = new StringBuilder(key);

    if (precondition) {
        if (!MSG.INVALID_WITHOUT_MESSAGE.equals(key)) {
            keyProperty.append(MSG.PRE);
        }
    } else if (not) {
        // NOT is ignored if precondition mode
        // precondition is the same with or without not
        keyProperty.append(MSG.NOT);
    }

    if (CollectionUtils.isNotEmpty(parameters)) {
        final CharSequence[] arguments = new CharSequence[parameters.size()];
        for (int i = 0; i < parameters.size(); i++) {
            arguments[i] = HelperMessage.getParam(i + 1, parameters.get(i).getType());
        }

        return getProperty(keyProperty, values, arguments);
    } else {
        return getProperty(keyProperty, values);
    }
}

From source file:com.astamuse.asta4d.util.annotation.AnnotatedPropertyUtil.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static AnnotatedPropertyInfoMap retrievePropertiesMap(Class cls) {
    String cacheKey = cls.getName();
    AnnotatedPropertyInfoMap map = propertiesMapCache.get(cacheKey);
    if (map == null) {
        List<AnnotatedPropertyInfo> infoList = new LinkedList<>();
        Set<String> beanPropertyNameSet = new HashSet<>();

        Method[] mtds = cls.getMethods();
        for (Method method : mtds) {
            List<Annotation> annoList = ConvertableAnnotationRetriever
                    .retrieveAnnotationHierarchyList(AnnotatedProperty.class, method.getAnnotations());

            if (CollectionUtils.isEmpty(annoList)) {
                continue;
            }//from  w  ww.  j  a  va  2 s.  c o  m

            AnnotatedPropertyInfo info = new AnnotatedPropertyInfo();
            info.setAnnotations(annoList);

            boolean isGet = false;
            boolean isSet = false;
            String propertySuffixe = method.getName();
            if (propertySuffixe.startsWith("set")) {
                propertySuffixe = propertySuffixe.substring(3);
                isSet = true;
            } else if (propertySuffixe.startsWith("get")) {
                propertySuffixe = propertySuffixe.substring(3);
                isGet = true;
            } else if (propertySuffixe.startsWith("is")) {
                propertySuffixe = propertySuffixe.substring(2);
                isSet = true;
            } else {
                String msg = String.format("Method [%s]:[%s] can not be treated as a getter or setter method.",
                        cls.getName(), method.toGenericString());
                throw new RuntimeException(msg);
            }

            char[] cs = propertySuffixe.toCharArray();
            cs[0] = Character.toLowerCase(cs[0]);
            info.setBeanPropertyName(new String(cs));

            AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by
            String name = ap.name();
            if (StringUtils.isEmpty(name)) {
                name = info.getBeanPropertyName();
            }

            info.setName(name);

            if (isGet) {
                info.setGetter(method);
                info.setType(method.getReturnType());
                String setterName = "set" + propertySuffixe;
                Method setter = null;
                try {
                    setter = cls.getMethod(setterName, method.getReturnType());
                } catch (NoSuchMethodException | SecurityException e) {
                    String msg = "Could not find setter method:[{}({})] in class[{}] for annotated getter:[{}]";
                    logger.warn(msg, new Object[] { setterName, method.getReturnType().getName(), cls.getName(),
                            method.getName() });
                }
                info.setSetter(setter);
            }

            if (isSet) {
                info.setSetter(method);
                info.setType(method.getParameterTypes()[0]);
                String getterName = "get" + propertySuffixe;
                Method getter = null;
                try {
                    getter = cls.getMethod(getterName);
                } catch (NoSuchMethodException | SecurityException e) {
                    String msg = "Could not find getter method:[{}:{}] in class[{}] for annotated setter:[{}]";
                    logger.warn(msg, new Object[] { getterName, method.getReturnType().getName(), cls.getName(),
                            method.getName() });
                }
                info.setGetter(getter);
            }

            infoList.add(info);
            beanPropertyNameSet.add(info.getBeanPropertyName());
        }

        List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(cls));
        Iterator<Field> it = list.iterator();

        while (it.hasNext()) {
            Field f = it.next();
            List<Annotation> annoList = ConvertableAnnotationRetriever
                    .retrieveAnnotationHierarchyList(AnnotatedProperty.class, f.getAnnotations());
            if (CollectionUtils.isNotEmpty(annoList)) {
                AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by

                String beanPropertyName = f.getName();
                if (beanPropertyNameSet.contains(beanPropertyName)) {
                    continue;
                }

                String name = ap.name();
                if (StringUtils.isEmpty(name)) {
                    name = f.getName();
                }

                AnnotatedPropertyInfo info = new AnnotatedPropertyInfo();
                info.setAnnotations(annoList);
                info.setBeanPropertyName(beanPropertyName);
                info.setName(name);
                info.setField(f);
                info.setGetter(null);
                info.setSetter(null);
                info.setType(f.getType());
                infoList.add(info);
            }
        }

        map = new AnnotatedPropertyInfoMap(infoList);
        if (Configuration.getConfiguration().isCacheEnable()) {
            propertiesMapCache.put(cacheKey, map);
        }
    }
    return map;
}

From source file:monasca.api.infrastructure.persistence.hibernate.AlarmSqlRepoImpl.java

@SuppressWarnings("unchecked")
@Override/*from w w  w.  j av a 2 s  .  c o  m*/
public List<Alarm> find(final String tenantId, final String alarmDefId, final String metricName,
        final Map<String, String> metricDimensions, final AlarmState state,
        final List<AlarmSeverity> severities, final String lifecycleState, final String link,
        final DateTime stateUpdatedStart, final List<String> sortBy, final String offset, final int limit,
        final boolean enforceLimit) {
    logger.trace(ORM_LOG_MARKER, "find(...) entering");

    Preconditions.checkNotNull(tenantId, "TenantId is required");

    Session session = null;

    List<Alarm> alarms = new LinkedList<>();

    try {
        final Query query;

        final String sortByClause = ALARM_SORT_BY_FUNCTION.apply(sortBy);
        final String alarmsSubQuery = this.getFindAlarmsSubQuery(alarmDefId, metricName, metricDimensions,
                state, severities, lifecycleState, link, stateUpdatedStart, sortBy, offset, limit,
                enforceLimit);

        final String sql = String.format(FIND_ALARMS_SQL, alarmsSubQuery, sortByClause);

        try {
            query = new Function<Session, Query>() {

                @Nullable
                @Override
                public Query apply(@Nullable final Session input) {
                    assert input != null;
                    final Query query = input.createSQLQuery(sql).setReadOnly(true);

                    query.setString("tenantId", tenantId);

                    if (alarmDefId != null) {
                        query.setString("alarmDefId", alarmDefId);
                    }

                    if (metricName != null) {
                        query.setString("metricName", metricName);
                    }

                    if (state != null) {
                        query.setString("state", state.name());
                    }

                    if (CollectionUtils.isNotEmpty(severities)) {
                        if (severities.size() == 1) {
                            query.setString("severity", severities.get(0).name());
                        } else {
                            for (int it = 0; it < severities.size(); it++) {
                                query.setString(String.format("severity_%d", it), severities.get(it).name());
                            }
                        }
                    }

                    if (link != null) {
                        query.setString("link", link);
                    }

                    if (lifecycleState != null) {
                        query.setString("lifecycleState", lifecycleState);
                    }

                    if (stateUpdatedStart != null) {
                        query.setDate("stateUpdatedStart",
                                stateUpdatedStart.toDateTime(DateTimeZone.UTC).toDate());
                    }

                    if (enforceLimit && limit > 0) {
                        query.setInteger("limit", limit + 1);
                    }

                    bindDimensionsToQuery(query, metricDimensions);

                    return query;
                }

            }.apply((session = sessionFactory.openSession()));
        } catch (Exception e) {
            logger.error("Failed to bind query {}, error is {}", sql, e.getMessage());
            throw new RuntimeException("Failed to bind query", e);
        }

        List<Object[]> alarmList = (List<Object[]>) query.list();

        if (alarmList.isEmpty()) {
            return Collections.emptyList();
        }

        alarms = createAlarms(alarmList);

    } finally {
        if (session != null) {
            session.close();
        }
    }
    return alarms;

}

From source file:com.epam.catgenome.dao.reference.ReferenceGenomeDao.java

/**
 * Loads a persisted {@code Reference} entity from the database by a specified ID
 * @param referenceId {@code Reference} ID to load
 * @return loaded {@code Reference} instance
 *///from ww  w .  j av a 2s .  com
@Transactional(propagation = Propagation.MANDATORY)
public Reference loadReferenceGenome(final Long referenceId) {
    final List<Reference> list = getNamedParameterJdbcTemplate().query(loadReferenceGenomeByIdQuery,
            new MapSqlParameterSource(GenomeParameters.REFERENCE_GENOME_ID.name(), referenceId),
            GenomeParameters.getReferenceGenomeMapper());
    return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
}