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:co.runrightfast.core.security.cert.X509V3CertRequest.java

private void checkConstraints(final Collection<X509CertExtension> extensions) {
    if (CollectionUtils.isEmpty(extensions)) {
        return;//w  w  w  .  java  2 s .c om
    }

    final Extensions exts = new Extensions(
            extensions.stream().map(X509CertExtension::toExtension).toArray(Extension[]::new));
    checkArgument(BasicConstraints.fromExtensions(exts) == null,
            "BasicConstraints must not be specified as an extension - it is added automatically");
    checkArgument(SubjectKeyIdentifier.fromExtensions(exts) == null,
            "SubjectKeyIdentifier must not be specified as an extension - it is added automatically");
}

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 w  w .j a v  a2s  .  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:com.evolveum.midpoint.model.common.expression.evaluator.FunctionExpressionEvaluator.java

@Override
public PrismValueDeltaSetTriple<V> evaluate(ExpressionEvaluationContext context)
        throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException,
        ConfigurationException, SecurityViolationException {

    List<ExpressionType> expressions;

    ObjectReferenceType functionLibraryRef = functionEvaluatorType.getLibraryRef();

    if (functionLibraryRef == null) {
        throw new SchemaException("No functions library defined");
    }/*w  w w.ja va 2 s  . c  o  m*/

    OperationResult result = context.getResult().createMinorSubresult(
            FunctionExpressionEvaluator.class.getSimpleName() + ".resolveFunctionLibrary");
    Task task = context.getTask();

    FunctionLibraryType functionLibraryType = objectResolver.resolve(functionLibraryRef,
            FunctionLibraryType.class, null, "resolving value policy reference in generateExpressionEvaluator",
            task, result);
    expressions = functionLibraryType.getFunction();

    if (CollectionUtils.isEmpty(expressions)) {
        throw new ObjectNotFoundException(
                "No functions defined in referenced function library: " + functionLibraryType);
    }

    String functionName = functionEvaluatorType.getName();

    if (StringUtils.isEmpty(functionName)) {
        throw new SchemaException("Missing function name in " + functionEvaluatorType);
    }

    List<ExpressionType> filteredExpressions = expressions.stream()
            .filter(expression -> functionName.equals(expression.getName())).collect(Collectors.toList());
    if (filteredExpressions.size() == 0) {
        String possibleFunctions = "";
        for (ExpressionType expression : expressions) {
            possibleFunctions += expression.getName() + ", ";
        }
        possibleFunctions = possibleFunctions.substring(0, possibleFunctions.lastIndexOf(","));
        throw new ObjectNotFoundException("No function with name " + functionName + " found in "
                + functionEvaluatorType + ". Function defined are: " + possibleFunctions);
    }

    ExpressionType functionToExecute = determineFunctionToExecute(filteredExpressions);

    OperationResult functionExpressionResult = result
            .createMinorSubresult(FunctionExpressionEvaluator.class.getSimpleName() + ".makeExpression");
    ExpressionFactory factory = context.getExpressionFactory();

    Expression<V, D> expression;
    try {
        expression = factory.makeExpression(functionToExecute, outputDefinition, "function execution", task,
                functionExpressionResult);
        functionExpressionResult.recordSuccess();
    } catch (SchemaException | ObjectNotFoundException e) {
        functionExpressionResult.recordFatalError(
                "Cannot make expression for " + functionToExecute + ". Reason: " + e.getMessage(), e);
        throw e;
    }

    ExpressionVariables originVariables = context.getVariables();

    ExpressionEvaluationContext functionContext = context.shallowClone();
    ExpressionVariables functionVariables = new ExpressionVariables();

    for (ExpressionParameterType param : functionEvaluatorType.getParameter()) {
        ExpressionType valueExpression = param.getExpression();
        OperationResult variableResult = result
                .createMinorSubresult(FunctionExpressionEvaluator.class.getSimpleName() + ".resolveVariable");
        try {
            variableResult.addArbitraryObjectAsParam("valueExpression", valueExpression);
            D variableOutputDefinition = determineVariableOutputDefinition(functionToExecute, param.getName(),
                    context);
            ExpressionUtil.evaluateExpression(originVariables, variableOutputDefinition, valueExpression,
                    context.getExpressionFactory(), "resolve variable", task, variableResult);
            variableResult.recordSuccess();
        } catch (SchemaException | ExpressionEvaluationException | ObjectNotFoundException
                | CommunicationException | ConfigurationException | SecurityViolationException e) {
            variableResult.recordFatalError(
                    "Failed to resolve variable: " + valueExpression + ". Reason: " + e.getMessage());
            throw e;
        }
    }

    functionContext.setVariables(functionVariables);

    return expression.evaluate(context);
}

From source file:io.kodokojo.service.DefaultProjectManager.java

@Override
public Project start(ProjectConfiguration projectConfiguration) throws ProjectAlreadyExistException {
    if (projectConfiguration == null) {
        throw new IllegalArgumentException("projectConfiguration must be defined.");
    }/*from  w w w  .  ja va  2  s.  co  m*/
    if (CollectionUtils.isEmpty(projectConfiguration.getStackConfigurations())) {
        throw new IllegalArgumentException("Unable to create a project without stack.");
    }

    String projectName = projectConfiguration.getName();

    Set<DnsEntry> dnsEntries = new HashSet<>();
    List<BrickStartContext> contexts = new ArrayList<>();
    Set<Stack> stacks = new HashSet<>();
    for (StackConfiguration stackConfiguration : projectConfiguration.getStackConfigurations()) {
        String lbHost = stackConfiguration.getLoadBalancerHost();
        DnsEntry.Type dnsType = getDnsType(lbHost);
        for (BrickConfiguration brickConfiguration : stackConfiguration.getBrickConfigurations()) {
            Brick brick = brickConfiguration.getBrick();
            BrickType brickType = brick.getType();
            if (brickType.isRequiredHttpExposed()) {
                String brickDomainName = brickUrlFactory.forgeUrl(projectConfiguration,
                        stackConfiguration.getName(), brickConfiguration);
                dnsEntries.add(new DnsEntry(brickDomainName, dnsType, lbHost));
            }
            BrickStartContext context = new BrickStartContext(projectConfiguration, stackConfiguration,
                    brickConfiguration, domain, lbHost);
            contexts.add(context);
        }

        Stack stack = new Stack(stackConfiguration.getName(), stackConfiguration.getType(), new HashSet<>());
        stacks.add(stack);

    }
    dnsManager.createOrUpdateDnsEntries(dnsEntries);
    contexts.forEach(brickConfigurationStarter::start);
    Project project = new Project(projectConfiguration.getIdentifier(), projectName, new Date(), stacks);
    return project;
}

From source file:io.cloudslang.maven.compiler.CloudSlangMavenCompiler.java

private List<CompilerMessage> compileFile(String sourceFile, String[] sourceFiles,
        Map<String, byte[]> dependenciesSourceFiles) {
    ExecutableModellingResult executableModellingResult;
    List<CompilerMessage> compilerMessages = new ArrayList<>();

    try {//from w  w  w.  j av  a2 s  .c o  m
        SlangSource slangSource = SlangSource.fromFile(new File(sourceFile));
        executableModellingResult = slangCompiler.preCompileSource(slangSource);
        if (!CollectionUtils.isEmpty(executableModellingResult.getErrors())) {
            for (RuntimeException runtimeException : executableModellingResult.getErrors()) {
                compilerMessages.add(
                        new CompilerMessage(sourceFile + ": " + runtimeException.getMessage(), errorLevel));
            }
        } else {
            if (compileWithDependencies) {
                compilerMessages.addAll(validateSlangModelWithDependencies(executableModellingResult,
                        sourceFiles, dependenciesSourceFiles, sourceFile));
            }
        }
    } catch (Exception e) {
        compilerMessages.add(new CompilerMessage(sourceFile + ": " + e.getMessage(), errorLevel));
    }

    return compilerMessages;
}

From source file:com.movies.entities.Movie.java

public List<Genre> getGenresList() {
    if (CollectionUtils.isEmpty(genresList) && CollectionUtils.isNotEmpty(genres)) {
        genresList = new ArrayList<>(genres);
    }/*from  w  w w. j  a v a  2 s  .c om*/
    return genresList;
}

From source file:com.haulmont.cuba.core.global.QueryParserAstBased.java

@Override
public boolean isEntitySelect(String targetEntity) {
    List<PathNode> returnedPathNodes = getQueryAnalyzer().getReturnedPathNodes();
    if (CollectionUtils.isEmpty(returnedPathNodes) || returnedPathNodes.size() > 1) {
        return false;
    }/* w  w  w .  j a  v  a2  s. c  o  m*/

    PathNode pathNode = returnedPathNodes.get(0);
    String targetEntityAlias = getQueryAnalyzer().getRootEntityVariableName(targetEntity);
    return targetEntityAlias.equals(pathNode.getEntityVariableName())
            && CollectionUtils.isEmpty(pathNode.getChildren());
}

From source file:nc.noumea.mairie.appock.viewmodel.EditDemandeATraiterViewModel.java

private void changeEtatArticleSelected(String action, EtatArticleDemande etatArticleDemande) {
    if (CollectionUtils.isEmpty(selectedListeArticleDemande)) {
        Messagebox.show("Vous devez slectionner au moins un article pour pouvoir le " + action,
                "Erreur changement d'tat", Messagebox.OK, Messagebox.INFORMATION);
        return;/*from   w  w  w. ja  v a2 s  . c  o m*/
    }

    for (ArticleDemande articleDemande : selectedListeArticleDemande) {
        articleDemande.setEtatArticleDemande(etatArticleDemande);
        articleDemandeRepository.save(articleDemande);
    }

    rechargeOnglet(entity, "/layout/editDemandeATraiter.zul", null);
    rechargeOngletListeReferentAchat();
    showNotificationStandard("tat mise  jour");
}

From source file:io.github.valters.xsdiff.format.SemanticDiffFormatter.java

public void printPartAdded(final String text, final SemanticNodeChanges changes, final DiffOutput output) {
    final TrieBuilder trie = Trie.builder().removeOverlaps();
    for (final String part : changes.getAddedNodes()) {
        trie.addKeyword(part);//w  w w  .j ava  2  s.  c  o m
    }
    for (final String part : changes.getNodesWithAddedAttributes()) {
        trie.addKeyword(part);
    }
    final Collection<Emit> emits = trie.build().parseText(text);

    int prevFragment = 0;
    for (final Emit emit : emits) {
        final String clearPartBefore = text.substring(prevFragment, emit.getStart());
        output.clearPart(clearPartBefore);
        final String nodeText = emit.getKeyword();
        // check if we need to go deeper
        final Set<String> attrFragments = changes.getAddedAttributesForNode(nodeText);

        if (CollectionUtils.isEmpty(attrFragments)) {
            output.addedPart(nodeText);
        } else {
            printAttributeHighlights(nodeText, attrFragments, fragment -> output.addedPart(fragment));
        }

        prevFragment = emit.getEnd() + 1;
    }

    final String clearPartAfter = text.substring(prevFragment, text.length());
    output.clearPart(clearPartAfter);
}

From source file:de.micromata.genome.util.runtime.jndi.SimpleNamingContext.java

/**
 * Convert a {@link Collection} to a delimited {@code String} (e.g. CSV).
 * <p>/* w  ww.j a  v  a2s. co m*/
 * Useful for {@code toString()} implementations.
 * 
 * @param coll the {@code Collection} to convert
 * @param delim the delimiter to use (typically a ",")
 * @param prefix the {@code String} to start each element with
 * @param suffix the {@code String} to end each element with
 * @return the delimited {@code String}
 */
public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix,
        String suffix) {
    if (CollectionUtils.isEmpty(coll)) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    Iterator<?> it = coll.iterator();
    while (it.hasNext()) {
        sb.append(prefix).append(it.next()).append(suffix);
        if (it.hasNext()) {
            sb.append(delim);
        }
    }
    return sb.toString();
}