Example usage for org.springframework.util CollectionUtils isEmpty

List of usage examples for org.springframework.util CollectionUtils isEmpty

Introduction

In this page you can find the example usage for org.springframework.util CollectionUtils isEmpty.

Prototype

public static boolean isEmpty(@Nullable Map<?, ?> map) 

Source Link

Document

Return true if the supplied Map is null or empty.

Usage

From source file:de.tolina.common.validation.AnnotationValidation.java

/**
 * Validates the configured Annotations//from  w  w w  . j av a2 s.c o m
 *
 * @param annotatedObject can be a Class, a Method or a Field
 */
private void forClassOrMethodOrField(@Nonnull final Object annotatedObject) {
    final SoftAssertions softly = new SoftAssertions();
    final List<String> annotationsList = new ArrayList<>();
    for (final AnnotationDefinition annotationDefinition : annotationDefinitions) {
        // check if annotation is present
        final Annotation annotation = findAnnotationFor(annotatedObject, annotationDefinition.getAnnotation());
        softly.assertThat(annotation)
                .as("Expected Annotation %s not found", annotationDefinition.getAnnotation().getName())
                .isNotNull();

        if (annotation == null) {
            continue;
        }

        annotationsList.add(annotation.annotationType().getName());

        // check all methods defined in annotation definition against current annotation's methods
        final List<String> validatedMethods = validateAllMethodsOfAnnotationDefinition(softly,
                annotationDefinition, annotation);

        // check if there are undefined methods in annotation definition present in annotation
        checkForUndefinedMethodsInAnnotation(softly, annotation, validatedMethods);
    }

    softly.assertThat(!strictValidation && CollectionUtils.isEmpty(annotationDefinitions))
            .as("Please add at least one Annotation to assert or enable strict validation.").isFalse();

    if (strictValidation) {
        final Annotation[] allAnnotations = getAllAnnotationsFor(annotatedObject);
        softly.assertThat(allAnnotations).extracting(annotation -> annotation.annotationType().getName())
                .containsExactlyElementsOf(annotationsList);
    }
    try {
        softly.assertAll();
    } catch (final SoftAssertionError sae) {
        throw new SoftAssertionErrorWithObjectDetails(sae.getErrors(), annotatedObject);
    }
}

From source file:pe.gob.mef.gescon.service.impl.ConocimientoServiceImpl.java

@Override
public List<Consulta> getConcimientosVinculados(HashMap filters) {
    List<Consulta> lista = new ArrayList<Consulta>();
    try {/*  ww w  . j  a  v a 2 s . c o m*/
        ConocimientoDao conocimientoDao = (ConocimientoDao) ServiceFinder.findBean("ConocimientoDao");
        List<HashMap> consulta = conocimientoDao.getConcimientosVinculados(filters);
        if (!CollectionUtils.isEmpty(consulta)) {
            for (HashMap map : consulta) {
                Consulta c = new Consulta();
                c.setId((BigDecimal) map.get("ID"));
                c.setIdconocimiento((BigDecimal) map.get("IDCONOCIMIENTO"));
                c.setCodigo((String) map.get("NUMERO"));
                c.setNombre((String) map.get("NOMBRE"));
                c.setSumilla((String) map.get("SUMILLA"));
                c.setFechaPublicacion((Date) map.get("FECHA"));
                c.setIdCategoria((BigDecimal) map.get("IDCATEGORIA"));
                c.setCategoria((String) map.get("CATEGORIA"));
                c.setIdTipoConocimiento((BigDecimal) map.get("IDTIPOCONOCIMIENTO"));
                c.setTipoConocimiento((String) map.get("TIPOCONOCIMIENTO"));
                c.setIdEstado((BigDecimal) map.get("IDESTADO"));
                c.setEstado((String) map.get("ESTADO"));
                lista.add(c);
            }
        }
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return lista;
}

From source file:nl.surfnet.coin.teams.domain.Invitation.java

/**
 * @return latest {@link InvitationMessage} or {@literal null} if none is set
 *//*  www .  ja  v  a2s  .c  o  m*/
public InvitationMessage getLatestInvitationMessage() {
    if (CollectionUtils.isEmpty(invitationMessages)) {
        return null;
    }
    return invitationMessages.get(invitationMessages.size() - 1);
}

From source file:com.sinet.gage.provision.controller.DomainController.java

/**
 * Returns all content providers domains
 * /*from www .  j  a v  a2 s  . c o  m*/
 * @return
 */
@RequestMapping(value = "/list/providers", method = RequestMethod.GET)
@ResponseBody
public Message getAllContentProviderDomains(@RequestHeader(value = "token", required = false) String token)
        throws InterruptedException {
    List<DomainResponse> listOfDomainResponse = domainService.findAllContentDomains(token, 0);
    if (!CollectionUtils.isEmpty(listOfDomainResponse)) {
        LOGGER.debug("Found " + listOfDomainResponse.size() + " content domains ");
        return messageUtil.createMessageWithPayload(MessageConstants.DOMAINS_FOUND, listOfDomainResponse,
                Collections.singletonMap("dataModels", "domains"), DomainResponse.class);
    } else {
        LOGGER.debug("No course catalog domains available");
        return messageUtil.createMessage(MessageConstants.DOMAINS_NOT_FOUND, Boolean.FALSE);
    }
}

From source file:org.whitesource.teamcity.agent.WhitesourceLifeCycleListener.java

@Override
public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
    super.runnerFinished(runner, status);

    AgentRunningBuild build = runner.getBuild();
    Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT,
            "runner finished " + build.getProjectName() + " type " + runner.getName()));

    if (!shouldUpdate(runner)) {
        return;/*from w  w  w.j  av  a  2  s  . c  o  m*/
    } // no need to update white source...

    final BuildProgressLogger buildLogger = build.getBuildLogger();
    buildLogger.message("Updating White Source");

    // make sure we have an organization token
    Map<String, String> runnerParameters = runner.getRunnerParameters();
    String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
    if (StringUtil.isEmptyOrSpaces(orgToken)) {
        orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
    }
    if (StringUtil.isEmptyOrSpaces(orgToken)) {
        stopBuildOnError((AgentRunningBuildEx) build, new IllegalStateException(
                "Empty organization token. Please make sure an organization token is defined for this runner."));
        return;
    }

    // should we check policies first ?
    boolean shouldCheckPolicies;
    String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
    if (StringUtil.isEmptyOrSpaces(overrideCheckPolicies) || "global".equals(overrideCheckPolicies)) {
        shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
    } else {
        shouldCheckPolicies = "enable".equals(overrideCheckPolicies);
    }

    String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
    String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);

    // collect OSS usage information
    buildLogger.message("Collecting OSS usage information");
    Collection<AgentProjectInfo> projectInfos;
    if (WssUtils.isMavenRunType(runner.getRunType())) {
        MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
        projectInfos = extractor.extract();
        if (StringUtil.isEmptyOrSpaces(product)) {
            product = extractor.getTopMostProjectName();
        }
    } else {
        GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
        projectInfos = extractor.extract();
    }
    debugAgentProjectInfos(projectInfos);

    // send to white source
    if (CollectionUtils.isEmpty(projectInfos)) {
        buildLogger.message("No open source information found.");
    } else {
        WhitesourceService service = createServiceClient(runner);
        try {
            if (shouldCheckPolicies) {
                buildLogger.message("Checking policies");
                CheckPoliciesResult result = service.checkPolicies(orgToken, product, productVersion,
                        projectInfos);
                policyCheckReport(runner, result);
                if (result.hasRejections()) {
                    stopBuild((AgentRunningBuildEx) build, "Open source rejected by organization policies.");
                } else {
                    buildLogger.message("All dependencies conform with open source policies.");
                    sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
                }
            } else {
                sendUpdate(orgToken, product, productVersion, projectInfos, service, buildLogger);
            }
        } catch (WssServiceException e) {
            stopBuildOnError((AgentRunningBuildEx) build, e);
        } catch (IOException e) {
            stopBuildOnError((AgentRunningBuildEx) build, e);
        } catch (RuntimeException e) {
            Loggers.AGENT.error(WssUtils.logMsg(LOG_COMPONENT, "Runtime Error"), e);
            stopBuildOnError((AgentRunningBuildEx) build, e);
        } finally {
            service.shutdown();
        }
    }
}

From source file:org.wallride.repository.ArticleRepositoryImpl.java

private FullTextQuery buildFullTextQuery(ArticleSearchRequest request, Pageable pageable, Criteria criteria) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Article.class)
            .get();/*from ww  w. j a v a  2s . c  o m*/

    @SuppressWarnings("rawtypes")
    BooleanJunction<BooleanJunction> junction = qb.bool();
    junction.must(qb.all().createQuery());

    junction.must(qb.keyword().onField("drafted").ignoreAnalyzer().matching("_null_").createQuery());

    if (StringUtils.hasText(request.getKeyword())) {
        Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
        String[] fields = new String[] { "title", "body", "categories.name", "tags.name",
                "customFieldValues.value" };
        MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
        parser.setDefaultOperator(QueryParser.Operator.AND);
        Query query = null;
        try {
            query = parser.parse(request.getKeyword());
        } catch (ParseException e1) {
            try {
                query = parser.parse(QueryParser.escape(request.getKeyword()));
            } catch (ParseException e2) {
                throw new RuntimeException(e2);
            }
        }
        junction.must(query);
    }
    if (request.getStatus() != null) {
        junction.must(qb.keyword().onField("status").matching(request.getStatus()).createQuery());
    }
    if (StringUtils.hasText(request.getLanguage())) {
        junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
    }

    if (request.getDateFrom() != null) {
        junction.must(qb.range().onField("date").above(request.getDateFrom()).createQuery());
    }
    if (request.getDateTo() != null) {
        junction.must(qb.range().onField("date").below(request.getDateTo()).createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getCategoryIds())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (long categoryId : request.getCategoryIds()) {
            subJunction.should(qb.keyword().onField("categories.id").matching(categoryId).createQuery());
        }
        junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getCategoryCodes())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (String categoryCode : request.getCategoryCodes()) {
            subJunction.should(qb.keyword().onField("categories.code").matching(categoryCode).createQuery());
        }
        junction.must(subJunction.createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getTagIds())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (long tagId : request.getTagIds()) {
            subJunction.should(qb.keyword().onField("tags.id").matching(tagId).createQuery());
        }
        junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getTagNames())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (String tagName : request.getTagNames()) {
            subJunction.should(qb.phrase().onField("tags.name").sentence(tagName).createQuery());
        }
        junction.must(subJunction.createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getCustomFields())) {
        javax.persistence.Query query = entityManager.createQuery(
                "from CustomField where language = :language and code in (:codes)", CustomField.class);
        query.setParameter("language", request.getLanguage()).setParameter("codes",
                request.getCustomFields().keySet());
        List<CustomField> customFields = query.getResultList();

        if (!CollectionUtils.isEmpty(customFields)) {
            Map<String, CustomField> customFieldMap = customFields.stream()
                    .collect(Collectors.toMap(CustomField::getCode, Function.identity()));

            BooleanJunction<BooleanJunction> subJunction = qb.bool();
            for (String key : request.getCustomFields().keySet()) {
                List<Object> values = (List<Object>) request.getCustomFields().get(key);
                CustomField target = customFieldMap.get(key);
                BooleanJunction<BooleanJunction> customFieldJunction = qb.bool();
                switch (target.getFieldType()) {
                case TEXT:
                case TEXTAREA:
                case HTML:
                    for (Object value : values) {
                        customFieldJunction.must(qb.keyword().onField("customFieldValues." + key)
                                .ignoreFieldBridge().matching(value.toString()).createQuery());
                    }
                    break;
                default:
                    for (Object value : values) {
                        customFieldJunction.must(qb.phrase().onField("customFieldValues." + key)
                                .ignoreFieldBridge().sentence(value.toString()).createQuery());
                    }
                }
                subJunction.must(customFieldJunction.createQuery());
            }
            junction.must(subJunction.createQuery());
        }
    }

    if (request.getAuthorId() != null) {
        junction.must(qb.keyword().onField("author.id").matching(request.getAuthorId()).createQuery());
    }

    Query searchQuery = junction.createQuery();

    Sort sort = new Sort(new SortField("sortDate", SortField.Type.STRING, true),
            new SortField("sortId", SortField.Type.LONG, true));

    FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Article.class)
            .setCriteriaQuery(criteria).setSort(sort);
    if (pageable != null) {
        persistenceQuery.setFirstResult(pageable.getOffset());
        persistenceQuery.setMaxResults(pageable.getPageSize());
    }
    return persistenceQuery;
}

From source file:com.gst.portfolio.group.service.GroupReadPlatformServiceImpl.java

@Override
public GroupGeneralData retrieveTemplate(final Long officeId, final boolean isCenterGroup,
        final boolean staffInSelectedOfficeOnly) {

    final Long defaultOfficeId = defaultToUsersOfficeIfNull(officeId);

    Collection<CenterData> centerOptions = null;
    if (isCenterGroup) {
        centerOptions = this.centerReadPlatformService.retrieveAllForDropdown(defaultOfficeId);
    }/*from  w  ww . j a  va  2s.c  o  m*/

    final Collection<OfficeData> officeOptions = this.officeReadPlatformService.retrieveAllOfficesForDropdown();

    final boolean loanOfficersOnly = false;
    Collection<StaffData> staffOptions = null;
    if (staffInSelectedOfficeOnly) {
        staffOptions = this.staffReadPlatformService.retrieveAllStaffForDropdown(defaultOfficeId);
    } else {
        staffOptions = this.staffReadPlatformService
                .retrieveAllStaffInOfficeAndItsParentOfficeHierarchy(defaultOfficeId, loanOfficersOnly);
    }

    if (CollectionUtils.isEmpty(staffOptions)) {
        staffOptions = null;
    }

    final Collection<CodeValueData> availableRoles = this.codeValueReadPlatformService
            .retrieveCodeValuesByCode(GroupingTypesApiConstants.GROUP_ROLE_NAME);

    final Long centerId = null;
    final String accountNo = null;
    final String centerName = null;
    final Long staffId = null;
    final String staffName = null;
    final Collection<ClientData> clientOptions = null;

    return GroupGeneralData.template(defaultOfficeId, centerId, accountNo, centerName, staffId, staffName,
            centerOptions, officeOptions, staffOptions, clientOptions, availableRoles);
}

From source file:at.pagu.soldockr.core.QueryParser.java

private void appendFilterQuery(SolrQuery solrQuery, List<FilterQuery> filterQueries) {
    if (CollectionUtils.isEmpty(filterQueries)) {
        return;/*w  w w .j  a v  a2  s  .com*/
    }
    List<String> filterQueryStrings = getFilterQueryStrings(filterQueries);

    if (!filterQueryStrings.isEmpty()) {
        solrQuery.setFilterQueries(convertStringListToArray(filterQueryStrings));
    }
}

From source file:pe.gob.mef.gescon.web.ui.PoliticaMB.java

public void save(ActionEvent event) {
    try {/* ww w.ja  va  2 s  . c  o m*/
        if (CollectionUtils.isEmpty(this.getListaPolitica())) {
            this.setListaPolitica(Collections.EMPTY_LIST);
        }
        Politica politica = new Politica();
        politica.setNmoduloid(this.getModuloid());
        politica.setVnombre(this.getNombre());
        politica.setVdescripcion(this.getDescripcion());
        if (!errorValidation(politica)) {
            politica.setVnombre(StringUtils.upperCase(this.getNombre().trim()));
            politica.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim()));
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();
            PoliticaService service = (PoliticaService) ServiceFinder.findBean("PoliticaService");
            politica.setNpoliticaid(service.getNextPK());
            politica.setNactivo(BigDecimal.ONE);
            politica.setDfechacreacion(new Date());
            politica.setVusuariocreacion(user.getVlogin());
            service.saveOrUpdate(politica);
            this.setListaPolitica(service.getPoliticas());
            this.cleanAttributes();
            RequestContext.getCurrentInstance().execute("PF('newDialog').hide();");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private void loadSpringProfiles(SpringApplicationService config) {
    final SpringProfiles springProfiles = config.getSpringProfiles();
    if (springProfiles != null) {
        final List<String> profiles = springProfiles.getProfile();
        if (!CollectionUtils.isEmpty(profiles)) {
            this.springProfiles = profiles.toArray(new String[profiles.size()]);
        }//w  w w. j  a v  a 2  s  . c om
    }
}