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:org.tdar.core.bean.resource.InformationResource.java

@Field(store = Store.NO)
@FieldBridge(impl = PersistentReaderBridge.class)
@Analyzer(impl = LowercaseWhiteSpaceStandardAnalyzer.class)
@Transient/*from ww w  .ja  v  a 2s.c o  m*/
// @Boost(0.5f)
@XmlTransient
public List<InformationResourceFileVersion> getContent() {
    logger.trace("getContent");
    List<InformationResourceFile> files = getPublicFiles();
    if (CollectionUtils.isEmpty(files)) {
        return null;
    }
    // List<InputStream> streams = new ArrayList<InputStream>();
    List<InformationResourceFileVersion> fileURIs = new ArrayList<InformationResourceFileVersion>();
    for (InformationResourceFile irFile : files) {
        try {
            if (irFile.getRestriction().isRestricted()) {
                continue;
            }
            InformationResourceFileVersion indexableVersion = irFile.getIndexableVersion();
            fileURIs.add(indexableVersion);
        } catch (Exception e) {
            logger.trace("an exception occurred while reading file: {} ", e);
        }
    }
    return fileURIs;
}

From source file:org.tdar.core.configuration.TdarConfiguration.java

public Set<String> getStopWords() {
    if (CollectionUtils.isEmpty(stopWords)) {
        initializeStopWords();
    }
    return stopWords;
}

From source file:org.tdar.core.configuration.TdarConfiguration.java

public List<String> getCouponCodes() {
    if (CollectionUtils.isEmpty(couponCodes)) {
        intializeCouponCodes();
    }
    return couponCodes;
}

From source file:org.tdar.core.service.resource.ResourceService.java

@Transactional
/**// ww w. ja  v a 2 s  . c o  m
 * Given a collection of hibernate-managed beans (the 'current' collection)  and another collection of transient beans (the 'incoming' collection),
 * update the current collection to match the contents of the incoming collection. This method will associate all elements in the incoming collection 
 * with the specified resource.  Contents of both collections should satisfy the HasResource interface.
 * 
 * @param resource  the 'owner' of the elements in the incoming collection.  This method will associate all elements of the incoming collection with this resource.
 * @param shouldSave if true,  this method will persist elements of the incoming collection.
 * @param validateMethod determines what validation steps (if any) to perform on each element of the incoming collection
 * @param incoming_ the incoming collection of HasResource elements.  
 * @param current the current collection of HasResource elements.  This method will modify collection to contain the same elements as the incoming collection.
 * @param cls type of the collection elements.
 */
public <H extends HasResource<R>, R extends Resource> void saveHasResources(R resource, boolean shouldSave,
        ErrorHandling validateMethod, Collection<H> incoming_, Set<H> current, Class<H> cls) {
    if (CollectionUtils.isEmpty(incoming_) && CollectionUtils.isEmpty(current)) {
        // skip a complete no-op
        return;
    }

    if (incoming_ == null) {
        incoming_ = new ArrayList<H>();
    }
    Collection<H> incoming = incoming_;
    // there are cases where current and incoming_ are the same object, if that's the case
    // then we need to copy incoming_ before
    if ((incoming_ == current) && !CollectionUtils.isEmpty(incoming_)) {
        incoming = new ArrayList<H>();
        incoming.addAll(incoming_);
        current.clear();
    }

    // assume everything that's incoming is valid or deduped and tied back into tDAR entities/beans
    logger.debug("Current Collection of {}s ({}) : {} ",
            new Object[] { cls.getSimpleName(), current.size(), current });

    /*
     * Because we're using ID for the equality and hashCode, we have no way to avoid deleting everything and re-adding it.
     * This is an issue as what'll end up happening otherwise is something like editing a Date results in no persisted change because the
     * "retainAll" below keeps the older version
     */

    current.retainAll(incoming);
    Map<Long, H> idMap = PersistableUtils.createIdMap(current);
    if (CollectionUtils.isNotEmpty(incoming)) {
        logger.debug("Incoming Collection of {}s ({})  : {} ",
                new Object[] { cls.getSimpleName(), incoming.size(), incoming });
        Iterator<H> incomingIterator = incoming.iterator();
        while (incomingIterator.hasNext()) {
            H hasResource_ = incomingIterator.next();

            if (hasResource_ != null) {

                // attach the incoming notes to a hibernate session
                logger.trace("adding {} to {} ", hasResource_, current);
                H existing = idMap.get(hasResource_.getId());
                /*
                 * If we're not transient, compare the two beans on all of their local properties (non-recursive) -- if there are differences
                 * copy. otherwise, move on. Question -- it may be more work to compare than to just "copy"... is it worth it?
                 */
                if (PersistableUtils.isNotNullOrTransient(existing)
                        && !EqualsBuilder.reflectionEquals(existing, hasResource_)) {
                    try {
                        logger.trace("copying bean properties for entry in existing set");
                        BeanUtils.copyProperties(existing, hasResource_);
                    } catch (Exception e) {
                        logger.error("exception setting bean property", e);
                    }
                }

                if (validateMethod != ErrorHandling.NO_VALIDATION) {
                    boolean isValid = false;
                    if (hasResource_ instanceof ResourceCreator) {
                        isValid = ((ResourceCreator) hasResource_).isValidForResource(resource);
                    } else {
                        isValid = hasResource_.isValid();
                    }

                    if (!isValid) {
                        logger.debug("skipping: {} - INVALID", hasResource_);
                        if (validateMethod == ErrorHandling.VALIDATE_WITH_EXCEPTION) {
                            throw new TdarRecoverableRuntimeException(hasResource_ + " is not valid");
                        }
                        continue;
                    }
                }

                current.add(hasResource_);

                // if (shouldSave) {
                // getGenericDao().saveOrUpdate(hasResource_);
                // }
            }
        }
    }
    logger.debug("Resulting Collection of {}s ({}) : {} ",
            new Object[] { cls.getSimpleName(), current.size(), current });
}

From source file:org.tdar.struts.action.resource.AbstractInformationResourceController.java

protected List<FileProxy> handleSingleFileUpload(List<FileProxy> toProcess) {
    /*//from w  ww.j av  a 2 s  .c om
     * FIXME: in Jar, hopefully, this goes away
     */

    FileProxy singleFileProxy = CollectionUtils.isEmpty(fileProxies) ? new FileProxy() : fileProxies.get(0);
    if (CollectionUtils.isEmpty(uploadedFiles)) {
        // check for metadata change iff this resource has an existing file.
        InformationResourceFile file = getPersistable().getFirstInformationResourceFile();
        if (file != null && singleFileProxy.isDifferentFromFile(file)) {
            singleFileProxy.setAction(FileAction.MODIFY_METADATA);
            singleFileProxy.setFileId(file.getId());
            toProcess.add(singleFileProxy);
        }
    } else {
        // process a new uploaded file (either ADD or REPLACE)
        setFileProxyAction(singleFileProxy);
        singleFileProxy.setFilename(uploadedFilesFileNames.get(0));
        singleFileProxy.setFile(uploadedFiles.get(0));
        toProcess.add(singleFileProxy);
    }
    return toProcess;
}

From source file:org.tdar.struts.action.resource.AbstractInformationResourceController.java

public List<File> getUploadedFiles() {
    if (CollectionUtils.isEmpty(uploadedFiles)) {
        uploadedFiles = createListWithSingleNull();
    }//w w  w  . j av a  2 s  . co  m
    return uploadedFiles;
}

From source file:org.tdar.struts.action.resource.AbstractInformationResourceController.java

public List<Pair<InformationResourceFile, ExceptionWrapper>> getHistoricalFileErrors() {
    List<Pair<InformationResourceFile, ExceptionWrapper>> toReturn = new ArrayList<>();
    try {//from w  w  w.ja va2 s  .  co  m
        if (isHasFileProxyChanges()) {
            return toReturn;
        }

        if (getPersistable() == null
                || CollectionUtils.isEmpty(getPersistable().getFilesWithFatalProcessingErrors())) {
            return toReturn;
        }

        for (InformationResourceFile file : getPersistable().getFilesWithProcessingErrors()) {
            if (file.isDeleted()) {
                continue;
            }
            String message = file.getErrorMessage();
            String stackTrace = file.getErrorMessage();
            if (StringUtils.contains(message, ExceptionWrapper.SEPARATOR)) {
                message = message.substring(0, message.indexOf(ExceptionWrapper.SEPARATOR));
                stackTrace = stackTrace.substring(stackTrace.indexOf(ExceptionWrapper.SEPARATOR) + 2);
            }
            Pair<InformationResourceFile, ExceptionWrapper> pair = Pair.create(file,
                    new ExceptionWrapper(message, stackTrace));
            toReturn.add(pair);
        }
    } catch (LazyInitializationException lae) {
        getLogger().trace(
                "lazy initializatione exception -- ignore in this case, likely session has been actively closed by SessionSecurityInterceptor");
    } catch (Exception e) {
        getLogger().error("got an exception while evaluating whether we should show one, should we?", e);
    }
    return toReturn;
}

From source file:org.tdar.struts.action.TdarActionSupport.java

public void addActionErrors(List<String> errors) {
    if (CollectionUtils.isEmpty(errors)) {
        return;/*from  w  w  w. ja v a  2  s . c om*/
    }
    for (String error : errors) {
        addActionError(error);
    }
}

From source file:pl.hycom.pip.messanger.handler.processor.GenerateMessageProcessor.java

@Override
public int runProcess(PipelineContext ctx) throws PipelineException {

    log.info("Started process of GenerateMessageProcessor");

    @SuppressWarnings("unchecked")
    List<Product> products = ctx.get(LoadBestMatchingProductsProcessor.PRODUCTS, List.class);
    String senderId = ctx.get(PipelineMessageHandler.SENDER_ID, String.class);

    if (CollectionUtils.isEmpty(products)) {
        sendTextMessage(senderId, "No products found.");
        return 1;
    }/*from  www . j  a v  a2 s. c o m*/

    sendStructuredMessage(senderId, getStructuredMessage(products));
    return 1;
}

From source file:reconf.server.services.product.UpsertProductService.java

@RequestMapping(value = "/product/{prod}", method = RequestMethod.PUT)
@Transactional/*w ww  . ja  va  2 s. co m*/
public ResponseEntity<ProductResult> doIt(@PathVariable("prod") String product,
        @RequestParam(value = "user", required = false) List<String> users,
        @RequestParam(value = "desc", required = false) String description, HttpServletRequest request,
        Authentication auth) {

    if (!ApplicationSecurity.isRoot(auth)) {
        return new ResponseEntity<ProductResult>(HttpStatus.FORBIDDEN);
    }

    Product reqProduct = new Product(product, description);
    ResponseEntity<ProductResult> errorResponse = checkForErrors(auth, reqProduct, users);
    if (errorResponse != null) {
        return errorResponse;
    }

    HttpStatus status = null;
    Product dbProduct = products.findOne(reqProduct.getName());
    if (dbProduct != null) {
        userProducts.deleteByKeyProduct(reqProduct.getName());
        dbProduct.setDescription(description);
        status = HttpStatus.OK;

    } else {
        dbProduct = new Product(reqProduct.getName(), reqProduct.getDescription());
        dbProduct.setDescription(description);
        products.save(dbProduct);
        status = HttpStatus.CREATED;
    }

    dbProduct.setUsers(users);
    users = CollectionUtils.isEmpty(users) ? Collections.EMPTY_LIST : users;
    for (String user : users) {
        if (ApplicationSecurity.isRoot(user)) {
            continue;
        }
        userProducts.save(new UserProduct(new UserProductKey(user, reqProduct.getName())));
    }
    return new ResponseEntity<ProductResult>(new ProductResult(dbProduct, CrudServiceUtils.getBaseUrl(request)),
            status);
}