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:com.daimler.spm.b2bacceleratoraddon.controllers.pages.checkout.steps.PaymentTypeCheckoutStepController.java

protected PaymentTypeForm preparePaymentTypeForm(final CartData cartData) {
    final PaymentTypeForm paymentTypeForm = new PaymentTypeForm();

    // set payment type
    if (cartData.getPaymentType() != null && StringUtils.isNotBlank(cartData.getPaymentType().getCode())) {
        paymentTypeForm.setPaymentType(cartData.getPaymentType().getCode());
    } else {/* w  w  w . j ava 2s .  c om*/
        paymentTypeForm.setPaymentType(CheckoutPaymentType.ACCOUNT.getCode());
    }

    // set cost center
    if (cartData.getCostCenter() != null && StringUtils.isNotBlank(cartData.getCostCenter().getCode())) {
        paymentTypeForm.setCostCenterId(cartData.getCostCenter().getCode());
    } else if (!CollectionUtils.isEmpty(getVisibleActiveCostCenters())
            && getVisibleActiveCostCenters().size() == 1) {
        paymentTypeForm.setCostCenterId(getVisibleActiveCostCenters().get(0).getCode());
    }

    // set purchase order number
    paymentTypeForm.setPurchaseOrderNumber(cartData.getPurchaseOrderNumber());
    return paymentTypeForm;
}

From source file:com.turbospaces.spaces.tx.TransactionModificationContext.java

private void sync(final SpaceStore memoryManager, final Set<NotificationContext> notificationContext,
        final boolean applyDiscard) {
    LOGGER.debug("synchronizing {} wih offheap cache store. commit/rollback = {}", this,
            applyDiscard ? "COMMIT" : "ROLLBACK");
    try {/*from  w  w w .j  a v a2 s.com*/
        memoryManager.sync(this, applyDiscard);
        if (!CollectionUtils.isEmpty(notificationContext))
            for (NotificationContext item : notificationContext) {
                SpaceNotificationListener listener = item.getListener();
                boolean matchById = SpaceModifiers.isMatchById(item.getModifier());
                boolean returnAsBytes = SpaceModifiers.isReturnAsBytes(item.getModifier());
                CacheStoreEntryWrapper template = item.getTemplateEntry();

                if (matchById) {
                    notifyById(getWrites(), template.getId(), listener, memoryManager, template.getBean(),
                            returnAsBytes);
                    notifyById(getTakes(), template.getId(), listener, memoryManager, template.getBean(),
                            returnAsBytes);
                } else {
                    notifyByTemplate(getWrites(), listener, template, memoryManager, returnAsBytes);
                    notifyByTemplate(getTakes(), listener, template, memoryManager, returnAsBytes);
                }
            }
    } finally {
        clear();
    }
}

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

public void setSelectedRow(ActionEvent event) {
    try {//from   w  w  w  .j  a  va2s.c  o m
        if (event != null) {
            int index = Integer.parseInt((String) JSFUtils.getRequestParameter("index"));
            if (!CollectionUtils.isEmpty(this.getFilteredListaAlerta())) {
                this.setSelectedAlerta(this.getFilteredListaAlerta().get(index));
            } else {
                this.setSelectedAlerta(this.getListaAlerta().get(index));
            }
            this.setFilteredListaAlerta(new ArrayList());
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

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

@Override
public List<Consulta> getNotificationsPublicPanelByUser(User user) {
    List<Consulta> lista = new ArrayList<Consulta>();
    try {//from   w ww  .  j ava 2 s .co m
        Mtuser mtuser = new Mtuser();
        BeanUtils.copyProperties(mtuser, user);
        AsignacionDao asignacionDao = (AsignacionDao) ServiceFinder.findBean("AsignacionDao");
        List<HashMap> consulta = asignacionDao.getNotificationsPublicPanelByMtuser(mtuser);
        if (!CollectionUtils.isEmpty(consulta)) {
            for (HashMap map : consulta) {
                Consulta c = new Consulta();
                c.setIdconocimiento((BigDecimal) map.get("ID"));
                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:org.wallride.service.PostService.java

/**
 *
 * @param blogLanguage//from  w  w  w .  ja  va  2  s .  c  o m
 * @param type
 * @param maxRank
 * @see PostService#getPopularPosts(String, PopularPost.Type)
 */
@CacheEvict(value = WallRideCacheConfiguration.POPULAR_POST_CACHE, key = "'list.type.' + #blogLanguage.language + '.' + #type")
public void updatePopularPosts(BlogLanguage blogLanguage, PopularPost.Type type, int maxRank) {
    logger.info("Start update of the popular posts");

    GoogleAnalytics googleAnalytics = blogLanguage.getBlog().getGoogleAnalytics();
    if (googleAnalytics == null) {
        logger.info("Configuration of Google Analytics can not be found");
        return;
    }

    Analytics analytics = GoogleAnalyticsUtils.buildClient(googleAnalytics);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        logger.info("GuestServlet is not ready yet");
        return;
    }

    final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

    Map<Post, Long> posts = new LinkedHashMap<>();

    int startIndex = 1;
    int currentRetry = 0;
    int totalResults = 0;

    do {
        try {
            LocalDate now = LocalDate.now();
            LocalDate startDate;
            switch (type) {
            case DAILY:
                startDate = now.minusDays(1);
                break;
            case WEEKLY:
                startDate = now.minusWeeks(1);
                break;
            case MONTHLY:
                startDate = now.minusMonths(1);
                break;
            default:
                throw new ServiceException();
            }

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Analytics.Data.Ga.Get get = analytics.data().ga()
                    .get(googleAnalytics.getProfileId(), startDate.format(dateTimeFormatter),
                            now.format(dateTimeFormatter), "ga:sessions")
                    .setDimensions(String.format("ga:pagePath", googleAnalytics.getCustomDimensionIndex()))
                    .setSort(String.format("-ga:sessions", googleAnalytics.getCustomDimensionIndex()))
                    .setStartIndex(startIndex).setMaxResults(GoogleAnalyticsUtils.MAX_RESULTS);
            if (blogLanguage.getBlog().isMultiLanguage()) {
                get.setFilters("ga:pagePath=~/" + blogLanguage.getLanguage() + "/");
            }

            logger.info(get.toString());
            final GaData gaData = get.execute();
            if (CollectionUtils.isEmpty(gaData.getRows())) {
                break;
            }

            for (List row : gaData.getRows()) {
                UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) row.get(0)).build();

                MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
                request.setRequestURI(uriComponents.getPath());
                request.setQueryString(uriComponents.getQuery());
                MockHttpServletResponse response = new MockHttpServletResponse();

                BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService);
                BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request,
                        response);
                try {
                    rewriteMatch.execute(request, response);
                } catch (ServletException e) {
                    throw new ServiceException(e);
                } catch (IOException e) {
                    throw new ServiceException(e);
                }

                request.setRequestURI(rewriteMatch.getMatchingUrl());

                HandlerExecutionChain handler;
                try {
                    handler = mapping.getHandler(request);
                } catch (Exception e) {
                    throw new ServiceException(e);
                }

                if (!(handler.getHandler() instanceof HandlerMethod)) {
                    continue;
                }

                HandlerMethod method = (HandlerMethod) handler.getHandler();
                if (!method.getBeanType().equals(ArticleDescribeController.class)
                        && !method.getBeanType().equals(PageDescribeController.class)) {
                    continue;
                }

                // Last path mean code of post
                String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1);
                Post post = postRepository.findOneByCodeAndLanguage(code,
                        rewriteMatch.getBlogLanguage().getLanguage());
                if (post == null) {
                    logger.debug("Post not found [{}]", code);
                    continue;
                }

                if (!posts.containsKey(post)) {
                    posts.put(post, Long.parseLong((String) row.get(1)));
                }
                if (posts.size() >= maxRank) {
                    break;
                }
            }

            if (posts.size() >= maxRank) {
                break;
            }

            startIndex += GoogleAnalyticsUtils.MAX_RESULTS;
            totalResults = gaData.getTotalResults();
        } catch (IOException e) {
            logger.warn("Failed to synchronize with Google Analytics", e);
            if (currentRetry >= GoogleAnalyticsUtils.MAX_RETRY) {
                throw new GoogleAnalyticsException(e);
            }

            currentRetry++;
            logger.info("{} ms to sleep...", GoogleAnalyticsUtils.RETRY_INTERVAL);
            try {
                Thread.sleep(GoogleAnalyticsUtils.RETRY_INTERVAL);
            } catch (InterruptedException ie) {
                throw new GoogleAnalyticsException(e);
            }
            logger.info("Retry for the {} time", currentRetry);
        }
    } while (startIndex <= totalResults);

    popularPostRepository.deleteByType(blogLanguage.getLanguage(), type);

    int rank = 1;
    for (Map.Entry<Post, Long> entry : posts.entrySet()) {
        PopularPost popularPost = new PopularPost();
        popularPost.setLanguage(blogLanguage.getLanguage());
        popularPost.setType(type);
        popularPost.setRank(rank);
        popularPost.setViews(entry.getValue());
        popularPost.setPost(entry.getKey());
        popularPostRepository.saveAndFlush(popularPost);
        rank++;
    }

    logger.info("Complete the update of popular posts");
}

From source file:com.stormpath.spring.security.authz.CustomDataPermissionsEditor.java

@Override
public PermissionsEditor remove(String perm) {
    if (StringUtils.hasText(perm)) {
        Collection<String> perms = lookupPermissionStrings();
        if (!CollectionUtils.isEmpty(perms)) {
            if (perms instanceof List) {
                //hasn't yet been converted to a set that we maintain:
                String attrName = getFieldName();
                perms = asSet(attrName, (List) perms);
                CUSTOM_DATA.put(attrName, perms);
            }/*  ww  w .j  a va  2 s.  c  om*/
            perms.remove(perm);
        }
    }
    return this;
}

From source file:com.deloitte.smt.service.SignalDetectionService.java

/**
 * @param signalDetection/*ww w .j a  va2s .  c o m*/
 * @param soc
 */
private void saveHlt(SignalDetection signalDetection, Soc soc) {
    List<Hlt> hlts = soc.getHlts();
    if (!CollectionUtils.isEmpty(hlts)) {
        for (Hlt hlt : hlts) {
            hlt.setSocId(soc.getId());
            hlt.setDetectionId(signalDetection.getId());
        }
        hltRepository.save(hlts);
    }
}

From source file:com.vip.saturn.job.console.service.impl.ServerDimensionServiceImpl.java

@Override
public void removeOffLineExecutor(String executor) {
    CuratorRepository.CuratorFrameworkOp curatorFrameworkOp = curatorRepository.inSessionClient();
    curatorFrameworkOp.deleteRecursive(ExecutorNodePath.getExecutorNodePath(executor));
    List<String> jobNames = new ArrayList<>();
    try {/*  w w  w  .  j  a va  2 s .  c om*/
        jobNames = jobDimensionService.getAllJobs(curatorFrameworkOp);
    } catch (SaturnJobConsoleException e) {
        logger.error(e.getMessage(), e);
    }
    if (CollectionUtils.isEmpty(jobNames)) {
        return;
    }
    for (String jobName : jobNames) {
        String executorNode = JobNodePath.getServerNodePath(jobName, executor);
        if (!curatorFrameworkOp.checkExists(executorNode)) {
            continue;
        }
        curatorFrameworkOp.deleteRecursive(executorNode);
    }
}

From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java

@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws Exception {
    // TODO need blocking cache stuff from CachingFilter
    initContext();//from  ww  w  . ja  v a  2s  .c o  m

    try {

        Object controller = lookupController(getContext().getControllerClass());
        if (controller == null) {
            log.debug("Not a controller request {}:{} {}",
                    new Object[] { request.getMethod(), request.getRequestURI(), getContext() });
            chain.doFilter(request, response);
            return;
        }

        Class<?> controllerClass = AopProxyUtils.ultimateTargetClass(controller);
        if (controllerClass == null) {
            controllerClass = controller.getClass();
        }
        Method method = getContext().getMethod();
        if (method == null) {
            log.debug("No cacheable method found for {}:{} {}",
                    new Object[] { request.getMethod(), request.getRequestURI(), getContext() });
            chain.doFilter(request, response);
            return;
        }
        Collection<CacheOperation> cacheOperations = cacheOperationSource.getCacheOperations(method,
                controllerClass, true);

        if (CollectionUtils.isEmpty(cacheOperations)) {
            log.debug("No cacheable annotation found for {}:{} {}",
                    new Object[] { request.getMethod(), request.getRequestURI(), getContext() });
            chain.doFilter(request, response);
            return;
        }

        Map<String, Collection<CacheOperationContext>> operationsByType = createOperationContext(
                cacheOperations, method, controllerClass, request);

        // start with evictions
        if (inspectBeforeCacheEvicts(operationsByType.get(EVICT))) {
            chain.doFilter(request, response);
            return;
        }

        // follow up with cacheable
        CacheStatus status = inspectCacheables(operationsByType.get(CACHEABLE));

        Map<CacheOperationContext, Object> updates = inspectCacheUpdates(operationsByType.get(UPDATE));

        if (status != null) {
            if (status.updateRequired) {
                updates.putAll(status.updates);
            }
            // render cached response
            else {
                logRequestDetails(request, getContext(), "Caching enabled for request");
                PageInfo pageInfo = buildCachedPageInfo(request, response, status);
                writeResponse(request, response, pageInfo);
                return;
            }
        }

        logRequestDetails(request, getContext(), "Caching enabled for request");
        PageInfo pageInfo = buildNewPageInfo(request, response, chain, status, operationsByType);
        writeResponse(request, response, pageInfo);

        inspectAfterCacheEvicts(operationsByType.get(EVICT));

        if (!updates.isEmpty()) {
            Collection<Cache> caches = new ArrayList<Cache>();
            for (Map.Entry<CacheOperationContext, Object> entry : updates.entrySet()) {
                for (Cache cache : entry.getKey().getCaches()) {
                    caches.add(cache);
                }
            }
            update(caches, pageInfo, status, calculateKey(request));
        }
    } finally {
        destroyContext();
    }
}

From source file:com.gst.portfolio.client.api.ClientChargesApiResource.java

@GET
@Path("{chargeId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveClientCharge(@PathParam("clientId") final Long clientId,
        @PathParam("chargeId") final Long chargeId, @Context final UriInfo uriInfo) {

    this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME);
    ClientChargeData clientCharge = this.clientChargeReadPlatformService.retrieveClientCharge(clientId,
            chargeId);/*from w  ww  .j a v  a 2  s .c o  m*/
    // extract associations
    final Set<String> associationParameters = ApiParameterHelper
            .extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters());
    if (!associationParameters.isEmpty()) {
        if (associationParameters.contains("all")) {
            associationParameters
                    .addAll(Arrays.asList(ClientApiConstants.CLIENT_CHARGE_ASSOCIATIONS_TRANSACTIONS));
        }
        ApiParameterHelper.excludeAssociationsForResponseIfProvided(uriInfo.getQueryParameters(),
                associationParameters);
        if (associationParameters.contains(ClientApiConstants.CLIENT_CHARGE_ASSOCIATIONS_TRANSACTIONS)) {
            Collection<ClientTransactionData> clientTransactionDatas = this.clientTransactionReadPlatformService
                    .retrieveAllTransactions(clientId, chargeId);
            if (!CollectionUtils.isEmpty(clientTransactionDatas)) {
                clientCharge = ClientChargeData.addAssociations(clientCharge, clientTransactionDatas);
            }
        }
    }
    final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper
            .process(uriInfo.getQueryParameters());
    return this.toApiJsonSerializer.serialize(settings, clientCharge,
            ClientApiConstants.CLIENT_CHARGES_RESPONSE_DATA_PARAMETERS);
}