Example usage for java.util Collection isEmpty

List of usage examples for java.util Collection isEmpty

Introduction

In this page you can find the example usage for java.util Collection isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

From source file:com.samsung.sjs.theorysolver.TheorySolver.java

/**
 * Given a fixing set finder, a solver for some particular theory, and some constraints,
 * this procedure either finds a model or it finds a minimum set of constraints
 * which, if broken, make the system satisfiable (a "fixing set").
 *
 * <p>A <em>theory</em> is a solver that solves simple conjunctions of constraints.
 * The performance of this algorithm highly depends on the ability of the theory to
 * produce small unsatisfiable cores./*from   w  ww .ja  v  a  2 s. c  o  m*/
 *
 * @param <Constraint>    the type of constraint solved by the theory
 * @param <Model>         the type of model produced by the theory
 * @param theorySolver    a solver for some theory
 * @param fixingSetFinder a strategy for finding a fixing set
 * @param hardConstraints the hard constraints which MUST be satisfied
 * @param softConstraints the labeled soft constraints from which the fixing set is drawn
 * @return A pair (m,l) where l is the fixing set (a minimum set of constraints which had
 *   to be weakened to satisfy the system), and m is the resulting model after weakening.
 *   Note that <code>l.isEmpty()</code> means the entire set of constraints is satisfiable.
 * @see SatSolver
 * @see Theory
 */
public static <Constraint, Model> Pair<Model, Collection<Constraint>> solve(
        Theory<Constraint, Model> theorySolver, FixingSetFinder<Constraint> fixingSetFinder,
        List<Constraint> hardConstraints, List<Constraint> softConstraints) {

    FixingSetListener<Constraint, Model> listener = NOISY ? loggingListener()
            : FixingSetListener.dummyListener();

    fixingSetFinder.setup(softConstraints);

    // These two are complements of each other:
    //    - fixingSet is the constraints we are going to remove
    //    - positive  is the constraints we are going to keep
    //      (i.e. all those not in the fixing set)
    Collection<Constraint> fixingSet = new ArrayList<>();
    Collection<Constraint> positive = new LinkedHashSet<>();
    for (;;) {

        // Be polite---interruptions mean that someone else wants
        // this thread to stop what it's doing.
        if (Thread.currentThread().isInterrupted()) {
            throw new RuntimeException("thread was interrupted");
        }

        positive.addAll(hardConstraints);
        positive.addAll(softConstraints);
        positive.removeAll(fixingSet);

        // Check the proposed fixing set against the theory.
        Either<Model, Collection<Constraint>> result = timed(() -> theorySolver.check(positive),
                "CHECKING THEORY");

        if (result.right == null) {
            // The proposed fixing set works! We are done!
            if (NOISY)
                System.out.println("VALID MODEL");
            listener.onFixingSet(result.left, fixingSet);
            return Pair.of(result.left, fixingSet);
        } else {
            // The proposed fixing set didn't work. We will use the core
            // to adjust what fixing set gets returned next.

            // Inform the listener
            listener.onCore(result.right);

            // The fixing set finder shouldn't care about hard constraints
            Collection<Constraint> softCore = result.right.stream().filter(c -> !hardConstraints.contains(c))
                    .collect(Collectors.toList());

            if (softCore.isEmpty()) {
                throw new IllegalStateException("Hard clauses are unsat!");
            }

            // Push the core to the fixing set finder
            fixingSet.clear();
            fixingSetFinder.addCore(softCore);
            timed(() -> fixingSetFinder.currentFixingSet(fixingSet, listener), "FINDING FIXING SET");
            System.out.println("  --> PROPOSAL SIZE = " + fixingSet.size());
        }

    }

}

From source file:de.iteratec.iteraplan.common.GeneralHelper.java

/**
 * Returns a String made from the concatenation of value strings of the given Collection of Attribute Values,
 * separated by the standard {@link Constants#BUILDINGBLOCKSEP}.
 * @param avs//from   w  w w . j a  va 2  s. c  o  m
 *          Collection of Attribute Values
 * @return Concatenated value strings of the Attribute Values
 */
public static String makeConcatenatedNameStringForAvCollection(Collection<? extends AttributeValue> avs) {
    if (avs == null || avs.isEmpty()) {
        return " ";
    }

    Function<AttributeValue, String> toNameFuntion = new Function<AttributeValue, String>() {
        public String apply(AttributeValue av) {
            if (av == null) {
                return "null";
            }
            return av.getValueString();
        }
    };
    return Joiner.on(Constants.BUILDINGBLOCKSEP).join(Iterables.transform(avs, toNameFuntion));
}

From source file:org.auraframework.test.AuraTestingUtil.java

/**
 * Clear cached defs from the system. When mocking a def, if the def has already been cached, as itself, or as part
 * of a preloaded set, the mock will not be effective, so it's safer to clear any cached defs after setting up mocks
 * but before executing a test. This relies on source change notifications to get the servlets to clear their
 * caches.//from w w  w .  ja  v a 2s  .  c  o m
 * 
 * @param defs the Definitions to be cleared from any caches
 * @throws InterruptedException
 */
public static <T extends Definition> void clearCachedDefs(Collection<T> defs) throws Exception {
    if (defs == null || defs.isEmpty()) {
        return;
    }

    // Get the Descriptors for the provided Definitions
    final DefinitionService definitionService = Aura.getDefinitionService();
    final Set<DefDescriptor<?>> cached = Sets.newHashSet();
    for (T def : defs) {
        if (def != null) {
            cached.add(def.getDescriptor());
        }
    }

    // Wait for the change notifications to get processed. We expect listeners to get processed in the order in
    // which they subscribe.
    final CountDownLatch latch = new CountDownLatch(cached.size());
    SourceListener listener = new SourceListener() {
        private Set<DefDescriptor<?>> descriptors = Sets.newHashSet(cached);

        @Override
        public void onSourceChanged(DefDescriptor<?> source, SourceMonitorEvent event, String filePath) {
            if (descriptors.remove(source)) {
                latch.countDown();
            }
            if (descriptors.isEmpty()) {
                definitionService.unsubscribeToChangeNotification(this);
            }
        }
    };
    definitionService.subscribeToChangeNotification(listener);
    for (DefDescriptor<?> desc : cached) {
        definitionService.onSourceChanged(desc, SourceMonitorEvent.CHANGED, null);
    }
    if (!latch.await(CACHE_CLEARING_TIMEOUT_SECS, TimeUnit.SECONDS)) {
        throw new AuraRuntimeException(
                String.format("Timed out after %s seconds waiting for cached Aura definitions to clear: %s",
                        CACHE_CLEARING_TIMEOUT_SECS, defs));
    }
}

From source file:com.frame.base.repository.jpa.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override/* ww  w .  j  a v a 2 s  .c om*/
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (filters != null && !filters.isEmpty()) {
                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName,
                    // ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, ".");
                    Path expression = root.get(names[0]);
                    for (int i = 1; i < names.length; i++) {
                        expression = expression.get(names[i]);
                    }

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case NE:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                    case IN:
                        predicates.add(
                                builder.in(expression).in(Arrays.asList(filter.value.toString().split(","))));
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}

From source file:javadepchecker.Main.java

/**
 * Check if a dependency is needed by a given package
 *
 * @param pkg Gentoo package name/*  ww w.ja  va2  s  .  com*/
 * @param deps collection of dependencies for the package
 * @return boolean if the dependency is needed or not
 * @throws IOException
 */
private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    Collection<String> jars = getPackageJars(pkg);

    // We have a virtual with VM provider here
    if (jars.isEmpty()) {
        return true;
    }
    for (String jarName : jars) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }
        }
    }
    return false;
}

From source file:edu.mit.mobile.android.locast.data.TaggableItem.java

/**
 * Given a base content URI of a taggable item and a list of tags, constructs a URI
 * representing all the items of the baseUri that match all the listed tags.
 *
 * @param baseUri a content URI of a TaggableItem
 * @param tags a collection of tags//ww w. j a v a2s .c  o m
 * @return a URI representing all the items that match all the given tags
 */
public static Uri getTagUri(Uri baseUri, Collection<String> tags) {
    if (tags.isEmpty()) {
        return baseUri;
    }

    final List<String> path = baseUri.getPathSegments();
    // AUTHORITY/casts/tags
    if (path.size() >= 2 && Tag.PATH.equals(path.get(path.size() - 1))) {
        baseUri = ProviderUtils.removeLastPathSegment(baseUri);
    }

    return baseUri.buildUpon().appendQueryParameter(SERVER_QUERY_PARAMETER, Tag.toTagQuery(tags)).build();
}

From source file:com.smartitengineering.version.api.factory.VersionAPI.java

/**
 * Create a versioned resource from revisions. If revisions is not empty
 * then head revision's resource will be pointed accordingly.
 * @param revisions Revisions of a resource
 * @return VersionedResource of the revisions.
 *///  www  .  jav a  2  s  .  com
public static VersionedResource createVersionedResource(Collection<Revision> revisions) {
    if (revisions == null) {
        revisions = Collections.emptyList();
    }
    VersionedResourceImpl versionedResourceImpl = new VersionedResourceImpl();
    if (!revisions.isEmpty()) {
        try {
            versionedResourceImpl.setHeadVersionResource(revisions.iterator().next().getResource());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    versionedResourceImpl.setRevisions(revisions);
    return versionedResourceImpl;
}

From source file:cn.imethan.common.repository.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override//ww  w  . j av  a 2  s  .  c  o  m
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (filters != null && !filters.isEmpty()) {

                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, ".");
                    Path expression = root.get(names[0]);
                    try {
                        for (int i = 1; i < names.length; i++) {
                            expression = expression.get(names[i]);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case IN:
                        In in = builder.in(expression);
                        String[] valueStrings = StringUtils.split(filter.value.toString(), ",");
                        List<Long> list = new ArrayList<Long>();
                        for (String value : valueStrings) {
                            list.add(Long.valueOf(value.trim()));
                        }
                        in.value(list);

                        predicates.add(in);

                        break;
                    case NOTIN:
                        In in1 = builder.in(expression);
                        String[] valueStrings1 = StringUtils.split(filter.value.toString(), ",");
                        List<Long> list1 = new ArrayList<Long>();
                        for (String value : valueStrings1) {
                            list1.add(Long.valueOf(value.trim()));
                        }
                        in1.value(list1);

                        predicates.add(builder.not(in1));
                        break;
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            //            //hibernate
            //            //org.hibernate.ejb.criteria.CriteriaQueryImpl
            //            if(query instanceof org.hibernate.ejb.QueryImpl) {  
            //               @SuppressWarnings("rawtypes")
            //               org.hibernate.ejb.QueryImpl hibernateQuery = (org.hibernate.ejb.QueryImpl)query;  
            //               org.hibernate.Query hQuery = hibernateQuery.getHibernateQuery();
            //               hQuery.setCacheable(true);
            //            }

            return builder.conjunction();
        }
    };
}

From source file:com.easou.common.util.CommonUtils.java

/**
 * Check whether the collection is null or empty. If it is, throw an
 * exception and display the message.//from  w w  w.  jav a 2  s. co m
 * 
 * @param c
 *            the collecion to check.
 * @param message
 *            the message to display if the object is null.
 */
public static void assertNotEmpty(final Collection<?> c, final String message) {
    assertNotNull(c, message);
    if (c.isEmpty()) {
        throw new IllegalArgumentException(message);
    }
}