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

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

Introduction

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

Prototype

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

Source Link

Document

Null-safe check if the specified collection is empty.

Usage

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

@Override
public Map<String, Map<String, Object>> validateOnFailurePosition(
        List<Map<String, Map<String, Object>>> workFlowRawData, String execName,
        List<RuntimeException> errors) {
    Iterator<Map<String, Map<String, Object>>> stepsIterator = workFlowRawData.iterator();
    int onFailureCount = 0;
    String latestStepName = null;
    List<RuntimeException> onFailureErrors = new ArrayList<>();
    Map<String, Map<String, Object>> onFailureData = null;

    while (stepsIterator.hasNext()) {
        Map<String, Map<String, Object>> stepData = stepsIterator.next();
        latestStepName = stepData.keySet().iterator().next();
        if (latestStepName.equals(ON_FAILURE_KEY)) {
            if (onFailureCount == 1) {
                onFailureErrors.add(new RuntimeException(
                        "Flow: '" + execName + "' syntax is illegal.\n" + MULTIPLE_ON_FAILURE_MESSAGE_SUFFIX));
            }/*from w w w  .  ja  va2s.  c o  m*/
            ++onFailureCount;
            onFailureData = stepData;
            stepsIterator.remove();
        }
    }
    // exactly one on_failure -> need to be last step
    if (onFailureCount == 1) {
        if (!ON_FAILURE_KEY.equals(latestStepName)) {
            onFailureErrors.add(new RuntimeException(
                    "Flow: '" + execName + "' syntax is illegal.\n" + ON_FAILURE_LAST_STEP_MESSAGE_SUFFIX));
        }
    }

    if (CollectionUtils.isEmpty(onFailureErrors)) {
        return onFailureData;
    } else {
        errors.addAll(onFailureErrors);
        return null;
    }
}

From source file:com.mirth.connect.server.controllers.DefaultCodeTemplateController.java

@Override
public List<CodeTemplate> getCodeTemplates(Set<String> codeTemplateIds) throws ControllerException {
    logger.debug("Getting code templates, codeTemplateIds=" + String.valueOf(codeTemplateIds));
    if (CollectionUtils.isEmpty(codeTemplateIds)) {
        codeTemplateIds = null;/*  w  w  w . ja v  a 2  s.c  o  m*/
    }

    Map<String, CodeTemplate> codeTemplateMap = codeTemplateCache.getAllItems();
    List<CodeTemplate> codeTemplates = new ArrayList<CodeTemplate>();

    if (codeTemplateIds == null) {
        codeTemplates.addAll(codeTemplateMap.values());
    } else {
        for (String codeTemplateId : codeTemplateIds) {
            CodeTemplate codeTemplate = codeTemplateMap.get(codeTemplateId);
            if (codeTemplate == null) {
                logger.error("Cannot find code template, it may have been removed: " + codeTemplateId);
            } else {
                codeTemplates.add(codeTemplate);
            }
        }
    }

    return codeTemplates;
}

From source file:com.jkoolcloud.tnt4j.streams.StreamsAgent.java

/**
 * Configure streams and parsers, and run each stream in its own thread.
 *
 * @param cfg/*  w  ww . j av  a2 s. co m*/
 *            stream data source configuration
 * @param streamListener
 *            input stream listener
 * @param streamTasksListener
 *            stream tasks listener
 */
private static void initAndRun(StreamsConfigLoader cfg, InputStreamListener streamListener,
        StreamTasksListener streamTasksListener) throws Exception {
    if (cfg == null) {
        return;
    }

    Collection<TNTInputStream<?, ?>> streams;
    if (noStreamConfig) {
        streams = initPiping(cfg);
    } else {
        streams = cfg.getStreams();
    }
    if (CollectionUtils.isEmpty(streams)) {
        throw new IllegalStateException(StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "StreamsAgent.no.activity.streams"));
    }

    run(streams, streamListener, streamTasksListener);
}

From source file:com.kumarvv.setl.core.Loader.java

/**
 * build "exists" sql//from www.  ja v  a  2 s  .c  o  m
 *
 * @param load
 * @return
 */
protected String buildSqlExists(Load load) {
    if (load == null || StringUtils.isEmpty(load.getTable())) {
        return "";
    }

    final List<Column> nks = new ArrayList<>();
    load.getColumns().stream().filter(Column::getNk).forEach(nks::add);

    String cols = buildSelectColumns(load);

    StringBuilder sql = new StringBuilder();
    sql.append("SELECT ").append(cols);
    sql.append(" FROM ").append(load.getTable());
    sql.append(" WHERE ");

    if (CollectionUtils.isEmpty(nks)) {
        sql.append("1 > 2");
    } else {
        List<String> nkStr = nks.stream().filter(nk -> isNotEmpty(nk.getRef()))
                .map((nk) -> nk.getName() + " = :" + nk.getRef()).collect(Collectors.toList());
        sql.append(StringUtils.join(nkStr, " AND "));
    }

    Logger.debug("load={}, sqlExists={}", load.getTable(), sql.toString());
    return sql.toString();
}

From source file:com.mirth.connect.plugins.httpauth.HttpAuthConnectorPropertiesPanel.java

private void setProperties(ConnectorProperties connectorProperties, ConnectorPluginProperties properties) {
    if (properties instanceof BasicHttpAuthProperties) {
        BasicHttpAuthProperties props = (BasicHttpAuthProperties) properties;

        basicRealmField.setText(props.getRealm());

        Object[][] data = new Object[props.getCredentials().size()][2];
        int i = 0;
        for (Entry<String, String> entry : props.getCredentials().entrySet()) {
            data[i][0] = entry.getKey();
            data[i][1] = entry.getValue();
            i++;/*  w w  w  . ja  v a 2  s .  co m*/
        }
        ((RefreshTableModel) basicCredentialsTable.getModel()).refreshDataVector(data);
    } else if (properties instanceof DigestHttpAuthProperties) {
        DigestHttpAuthProperties props = (DigestHttpAuthProperties) properties;

        digestRealmField.setText(props.getRealm());

        if (props.getAlgorithms().contains(Algorithm.MD5)
                && props.getAlgorithms().contains(Algorithm.MD5_SESS)) {
            digestAlgorithmBothRadio.setSelected(true);
        } else if (props.getAlgorithms().contains(Algorithm.MD5)) {
            digestAlgorithmMD5Radio.setSelected(true);
        } else if (props.getAlgorithms().contains(Algorithm.MD5_SESS)) {
            digestAlgorithmMD5SessRadio.setSelected(true);
        }

        digestQOPAuthCheckBox.setSelected(props.getQopModes().contains(QOPMode.AUTH));
        digestQOPAuthIntCheckBox.setSelected(props.getQopModes().contains(QOPMode.AUTH_INT));
        digestOpaqueField.setText(props.getOpaque());

        Object[][] data = new Object[props.getCredentials().size()][2];
        int i = 0;
        for (Entry<String, String> entry : props.getCredentials().entrySet()) {
            data[i][0] = entry.getKey();
            data[i][1] = entry.getValue();
            i++;
        }
        ((RefreshTableModel) digestCredentialsTable.getModel()).refreshDataVector(data);
    } else if (properties instanceof JavaScriptHttpAuthProperties) {
        JavaScriptHttpAuthProperties props = (JavaScriptHttpAuthProperties) properties;
        jsScript = props.getScript();
        updateJSScriptField();
    } else if (properties instanceof CustomHttpAuthProperties) {
        CustomHttpAuthProperties props = (CustomHttpAuthProperties) properties;

        customClassNameField.setText(props.getAuthenticatorClass());

        Object[][] data = new Object[props.getProperties().size()][2];
        int i = 0;
        for (Entry<String, String> entry : props.getProperties().entrySet()) {
            data[i][0] = entry.getKey();
            data[i][1] = entry.getValue();
            i++;
        }
        ((RefreshTableModel) customPropertiesTable.getModel()).refreshDataVector(data);
    } else if (properties instanceof OAuth2HttpAuthProperties) {
        OAuth2HttpAuthProperties props = (OAuth2HttpAuthProperties) properties;
        oauth2TokenLocationComboBox.setSelectedItem(props.getTokenLocation());
        oauth2TokenField.setText(props.getLocationKey());
        oauth2VerificationURLField.setText(props.getVerificationURL());
        if (connectorPropertiesPanel != null) {
            Set<ConnectorPluginProperties> connectorPluginProperties = props.getConnectorPluginProperties();
            if (CollectionUtils.isEmpty(connectorPluginProperties)) {
                connectorPluginProperties = new HashSet<ConnectorPluginProperties>();
                connectorPluginProperties.add(connectorPropertiesPanel.getDefaults());
            }
            ConnectorPluginProperties pluginProperties = connectorPluginProperties.iterator().next();
            if (!(pluginProperties instanceof InvalidConnectorPluginProperties)) {
                connectorPropertiesPanel.setProperties(connectorProperties, pluginProperties, Mode.DESTINATION,
                        new HttpDispatcherProperties().getName());
            }
        }
    }
}

From source file:com.ccserver.digital.service.LOSService.java

public LosResponseDTO submitCreditCardDocument(Long creditCardId) {

    AtomicReference<Object> refError = new AtomicReference<Object>("");

    CreditCardApplication app = repository.findOne(creditCardId);

    LosResponseDTO losResponseDTO = new LosResponseDTO();

    if (app == null
            || !Arrays.asList(new Status[] { Status.SubmittedApp, Status.Processing, Status.No_wf_initiated })
                    .contains(app.getStatus())) {
        losResponseDTO.setValidationError(new ValidationErrorDTO(Constants.APPLICATION_FIELD_INVALID,
                "The application status is invalid!"));
        return losResponseDTO;
    }/*from  w  w  w. ja v a  2 s  .  com*/

    if (app.getSubmittedDocTime() != null) {
        losResponseDTO.setValidationError(new ValidationErrorDTO(Constants.MODIFYING_SUBMITTED_DOCUMENT,
                "The application's document submitted already"));
        return losResponseDTO;
    }

    List<CreditCardApplicationDocumentThumbNailDTO> entities = docService
            .getDocumentsThumbNailByApplicationId(creditCardId);

    if (CollectionUtils.isEmpty(entities)) {
        losResponseDTO.setValidationError(
                new ValidationErrorDTO(Constants.OBJECT_REQUIRED, "The application's documents are required!"));
        return losResponseDTO;
    }

    configLos = utilService.getConfigurations();

    String messageId = java.util.UUID.randomUUID().toString();
    com.vpbank.entity.vn.ba251.bd324.documentservice.configuredocumenthandlingoperationcreditcard._1.ObjectFactory objectFactory = new com.vpbank.entity.vn.ba251.bd324.documentservice.configuredocumenthandlingoperationcreditcard._1.ObjectFactory();
    JAXBElement<ConfigureDocumentHandlingOperationCreditCardRequestType> jaxbRequest = objectFactory
            .createConfigureDocumentHandlingOperationCreditCardRequest(
                    getRequestOfDoc(app, entities, messageId, refError));

    if (refError.get().toString() != "") {
        losResponseDTO.setValidationError(
                new ValidationErrorDTO(Constants.FILE_SIZE_LIMIT_ERROR, "File Size is exceeded!"));
        return losResponseDTO;
    }
    Object result = null;
    try {
        result = new ExternalGatewaySupport(LOS_DOCUMENT_PACKAGE).getWebServiceTemplate()
                .marshalSendAndReceive(losConfig.getUrlDoc(), jaxbRequest, null);
    } catch (Exception ex) {
        logger.error(Utils.getErrorFormatLog("LOSService", "submitCreditCardDocument", "",
                "Can not call webservice", losConfig.getUrlDoc(), ex));
    }
    if (result != null) {
        ConfigureDocumentHandlingOperationCreditCardResponseType resultResponse = ((JAXBElement<ConfigureDocumentHandlingOperationCreditCardResponseType>) result)
                .getValue();
        String status = resultResponse.getResponseStatus().getStatus();
        losResponseDTO.setStatus(status);
        ApplicationLOSDTO losApplicationDTO = mapper.applicationLOSToDTO(app.getApplicationLOS());
        losApplicationDTO.setMessageDocId(messageId);
        if (status.equals("0")) {
            losApplicationDTO.setDocErrorCode(StringUtils.EMPTY);
            losApplicationDTO.setDocErrorMessage(StringUtils.EMPTY);
            CreditCardApplicationDTO dto = applicationService.updateLosDocStatus(app.getId(), Status.Processing,
                    losApplicationDTO);
            losResponseDTO.setAppDTO(dto);
        } else {
            losApplicationDTO.setDocErrorCode(resultResponse.getResponseStatus().getGlobalErrorCode());
            losApplicationDTO.setDocErrorMessage(getErrorDescription(resultResponse.getResponseStatus()));
            applicationService.updateLosDocStatus(app.getId(), null, losApplicationDTO);
        }
        losResponseDTO.setResponseStatusType(resultResponse.getResponseStatus());
        return losResponseDTO;
    }
    losResponseDTO.setValidationError(
            new ValidationErrorDTO(Constants.APPLICATION_DOC_UNEXPECT_ERROR, "Unexpect error!"));
    return losResponseDTO;
}

From source file:com.ejisto.event.listener.SessionRecorderManager.java

private void tryToSave(final String contextPath) {
    final Set<CollectedData> data = RECORDED_DATA.replace(contextPath, new HashSet<>());
    if (CollectionUtils.isEmpty(data)) {
        log.debug("Nothing to save, exiting");
        return;//from  w  w  w  .j av a2s .c  o m
    }
    String name;
    do {
        name = showInputDialog(null, getMessage("session.record.save.as"),
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));

    } while (StringUtils.isEmpty(name) && !GuiUtils.showWarning(null, getMessage("warning.message")));

    if (StringUtils.isNotEmpty(name)) {
        final CollectedData collectedData;
        if (data.size() > 1) {
            final Stream<CollectedData> stream = data.stream();
            CollectedData aggregated = CollectedData.empty(stream.findFirst().get().getRequestURI(),
                    contextPath);
            collectedData = stream.reduce(aggregated, CollectedData::join);
        } else {
            collectedData = data.iterator().next();
        }
        collectedDataRepository.saveRecordedSession(name, collectedData);

        eventManager.publishEvent(
                new SessionRecorded(this, name, getMessage("session.recorded.status.message", name)));
    }
}

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

@Override
@SuppressWarnings("unchecked")
public List<AlarmDefinition> find(String tenantId, String name, Map<String, String> dimensions,
        List<AlarmSeverity> severities, List<String> sortBy, String offset, int limit) {
    logger.trace(ORM_LOG_MARKER, "find(...) entering...");

    Session session = null;/*from ww w .ja va 2 s.c om*/
    List<AlarmDefinition> resultSet = Lists.newArrayList();

    final StringBuilder sbWhere = new StringBuilder();
    final StringBuilder limitOffset = new StringBuilder();
    final StringBuilder orderByPart = new StringBuilder();

    if (name != null) {
        sbWhere.append(" and ad.name = :name");
    }

    if (CollectionUtils.isNotEmpty(severities)) {
        if (severities.size() == 1) {
            sbWhere.append(" and ad.severity = :severity");
        } else {
            sbWhere.append(" and (");
            for (int i = 0; i < severities.size(); i++) {
                sbWhere.append("ad.severity = :severity_").append(i);
                if (i < severities.size() - 1) {
                    sbWhere.append(" or ");
                }
            }
            sbWhere.append(")");
        }
    }

    if (limit > 0) {
        limitOffset.append(" limit :limit");
    }

    if (offset != null) {
        limitOffset.append(" offset :offset ");
    }

    if (sortBy != null && !sortBy.isEmpty()) {
        orderByPart.append(" order by ").append(COMMA_JOINER.join(sortBy));
        if (!sortBy.contains("id")) {
            orderByPart.append(",id");
        }
    } else {
        orderByPart.append(" order by id ");
    }

    final String sql = String.format(FIND_ALARM_DEF_SQL,
            SubAlarmDefinitionQueries.buildJoinClauseFor(dimensions), sbWhere, limitOffset, orderByPart);

    try {
        session = sessionFactory.openSession();

        final Query qAlarmDefinition = session.createSQLQuery(sql).setString("tenantId", tenantId)
                .setReadOnly(true).setResultTransformer(ALARM_DEF_RESULT_TRANSFORMER);

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

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

        if (limit > 0) {
            qAlarmDefinition.setInteger("limit", limit + 1);
        }

        if (offset != null) {
            qAlarmDefinition.setInteger("offset", Integer.parseInt(offset));
        }

        this.bindDimensionsToQuery(qAlarmDefinition, dimensions);

        final List<Map<?, ?>> alarmDefinitionDbList = qAlarmDefinition.list();

        resultSet = CollectionUtils.isEmpty(alarmDefinitionDbList) ? Lists.<AlarmDefinition>newArrayList()
                : this.createAlarmDefinitions(alarmDefinitionDbList);

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

    return resultSet;
}

From source file:com.thoughtworks.go.server.service.UserService.java

private boolean validateUserSelection(List<String> userNames, BulkUpdateUsersOperationResult result) {
    if (CollectionUtils.isEmpty(userNames)) {
        result.badRequest("No users selected.");
        return false;
    }/*w ww.  j  av  a  2 s .  c om*/
    return true;
}

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

private List<RuntimeException> validateMandatoryInputsAreWired(Flow flow, Step step, Executable reference) {
    List<RuntimeException> errors = new ArrayList<>();
    List<String> mandatoryInputNames = getMandatoryInputNames(reference);
    List<String> stepInputNames = getStepInputNamesWithNonEmptyValue(step);
    List<String> inputsNotWired = getInputsNotWired(mandatoryInputNames, stepInputNames);
    if (!CollectionUtils.isEmpty(inputsNotWired)) {
        errors.add(new IllegalArgumentException(
                prepareErrorMessageValidateInputNamesEmpty(inputsNotWired, flow, step, reference)));
    }/*from w  ww  .j  a v a2  s .c  o  m*/
    return errors;
}