Example usage for java.util Set isEmpty

List of usage examples for java.util Set isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:com.espertech.esper.epl.spec.PatternStreamSpecRaw.java

private static int[] getIndexesForTags(LinkedHashSet<String> allTagNamesOrdered, Set<String> arrayTags) {
    if (arrayTags == null || arrayTags.isEmpty()) {
        return new int[0];
    }/*ww  w.j ava 2 s  .c o  m*/
    int[] indexes = new int[arrayTags.size()];
    int count = 0;
    for (String arrayTag : arrayTags) {
        int index = 0;
        int found = findTagNumber(arrayTag, allTagNamesOrdered);
        indexes[count] = found;
        count++;
    }
    return indexes;
}

From source file:org.jdbcluster.JDBClusterUtil.java

/**
 * returns the corresponding cluster id for a dao class
 * //  w  w w .j av  a 2s  .  c  o  m
 * @param clazz
 *            the dao class
 * @return the cluster id. Can be {@code null}
 */
static synchronized public String getClusterId(Class<? extends Dao> clazz) {
    if (dao2clusterId == null) {
        fillDao2ClusterId();
    }

    Set<String> clusterIds = dao2clusterId.get(clazz);
    if (clusterIds == null || clusterIds.isEmpty()) {
        return null;
    } else if (clusterIds.size() == 1) {
        return clusterIds.iterator().next();
    } else {
        throw new ConfigurationException(
                "several clusters defined using this dao [" + clazz.getName() + "]. Not supported yet");
    }
}

From source file:edu.wpi.checksims.algorithm.similaritymatrix.SimilarityMatrix.java

/**
 * Generate a Similarity Matrix with archive submissions.
 *
 * The result is not a square matrix. Only the input submissions are on the X axis, but the Y axis contains both
 * input and archive submissions.// w  ww .ja  va 2s . c  om
 *
 * @param inputSubmissions Submissions used to generate matrix
 * @param archiveSubmissions Archive submissions - only compared to input submissions, not to each other
 * @param results Results used to build matrix
 * @return Similarity matrix built from given results
 * @throws InternalAlgorithmError Thrown on missing results, or results containing a submission not in the input
 */
public static SimilarityMatrix generateMatrix(Set<Submission> inputSubmissions,
        Set<Submission> archiveSubmissions, Set<AlgorithmResults> results) throws InternalAlgorithmError {
    checkNotNull(inputSubmissions);
    checkNotNull(archiveSubmissions);
    checkNotNull(results);
    checkArgument(!inputSubmissions.isEmpty(), "Must provide at least 1 submission to build matrix from");
    checkArgument(!results.isEmpty(), "Must provide at least 1 AlgorithmResults to build matrix from!");

    Set<Submission> setOfBoth = new HashSet<>();
    setOfBoth.addAll(inputSubmissions);
    setOfBoth.addAll(archiveSubmissions);

    checkArgument(setOfBoth.size() == (archiveSubmissions.size() + inputSubmissions.size()),
            "Some submissions were found in both archive and input submissions!");

    // If there are no archive submissions, just generate using the other function
    if (archiveSubmissions.isEmpty()) {
        return generateMatrix(inputSubmissions, results);
    }

    List<Submission> xSubmissions = Ordering.natural().immutableSortedCopy(inputSubmissions);
    List<Submission> ySubmissions = new ArrayList<>();
    ySubmissions.addAll(Ordering.natural().immutableSortedCopy(inputSubmissions));
    ySubmissions.addAll(Ordering.natural().immutableSortedCopy(archiveSubmissions));

    MatrixEntry[][] matrix = new MatrixEntry[xSubmissions.size()][ySubmissions.size()];

    // Generate the matrix

    // First, handle identical submissions
    for (Submission xSub : xSubmissions) {
        // Get the X index
        int xIndex = xSubmissions.indexOf(xSub);
        int yIndex = ySubmissions.indexOf(xSub);

        matrix[xIndex][yIndex] = new MatrixEntry(xSub, xSub, xSub.getNumTokens());
    }

    // Now iterate through all given algorithm results
    for (AlgorithmResults result : results) {
        int aXCoord = xSubmissions.indexOf(result.a);
        int bXCoord = xSubmissions.indexOf(result.b);

        if (aXCoord == -1 && bXCoord == -1) {
            throw new InternalAlgorithmError("Neither submission \"" + result.a.getName() + "\" nor \""
                    + result.b.getName() + "\" were found in input submissions!");
        }

        if (aXCoord != -1) {
            int bYCoord = ySubmissions.indexOf(result.b);

            matrix[aXCoord][bYCoord] = new MatrixEntry(result.a, result.b, result.identicalTokensA);
        }

        if (bXCoord != -1) {
            int aYCoord = ySubmissions.indexOf(result.a);

            matrix[bXCoord][aYCoord] = new MatrixEntry(result.b, result.a, result.identicalTokensB);
        }
    }

    // Verification pass - ensure we built a matrix with no nulls
    for (int x = 0; x < xSubmissions.size(); x++) {
        for (int y = 0; y < ySubmissions.size(); y++) {
            if (matrix[x][y] == null) {
                throw new InternalAlgorithmError("Missing Algorithm Results for comparison of submissions \""
                        + xSubmissions.get(x).getName() + "\" and \"" + ySubmissions.get(y).getName() + "\"");
            }
        }
    }

    return new SimilarityMatrix(matrix, xSubmissions, ySubmissions, results);
}

From source file:net.sf.morph.util.TransformerUtils.java

/**
 * Get the set of source classes available from the specified Transformer for the specified destination type.
 * @param transformer// w  w w .ja v  a2  s . c om
 * @param destinationType
 * @return Class[]
 */
public static Class[] getSourceClasses(Transformer transformer, Class destinationType) {
    if (!ClassUtils.inheritanceContains(transformer.getDestinationClasses(), destinationType)) {
        return CLASS_NONE;
    }
    Class[] sourceTypes = transformer.getSourceClasses();
    if (transformer instanceof ExplicitTransformer) {
        Set result = ContainerUtils.createOrderedSet();
        for (int i = 0; i < sourceTypes.length; i++) {
            if (((ExplicitTransformer) transformer).isTransformable(destinationType, sourceTypes[i])) {
                result.add(sourceTypes[i]);
            }
        }
        return result.isEmpty() ? CLASS_NONE : (Class[]) result.toArray(new Class[result.size()]);
    }
    return sourceTypes;
}

From source file:com.google.android.gcm.GCMRegistrar.java

/**
 * Checks that the application manifest is properly configured.
 * <p>/*from  w  w w .ja v  a 2s  .c  o  m*/
 * A proper configuration means:
 * <ol>
 *    <li>It creates a custom permission called
 *      {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
 *    <li>It defines at least one {@link BroadcastReceiver} with category
 *      {@code PACKAGE_NAME}.
 *    <li>The {@link BroadcastReceiver}(s) uses the
 *      {@value GCMConstants#PERMISSION_GCM_INTENTS} permission.
 *    <li>The {@link BroadcastReceiver}(s) handles the 3 GCM intents
 *      ({@value GCMConstants#INTENT_FROM_GCM_MESSAGE},
 *      {@value GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK},
 *      and {@value GCMConstants#INTENT_FROM_GCM_LIBRARY_RETRY}).
 * </ol>
 * ...where {@code PACKAGE_NAME} is the application package.
 * <p>
 * This method should be used during development time to verify that the
 * manifest is properly set up, but it doesn't need to be called once the
 * application is deployed to the users' devices.
 *
 * @param context application context.
 * @throws IllegalStateException if any of the conditions above is not met.
 */
public static void checkManifest(Context context) {
    PackageManager packageManager = context.getPackageManager();
    String packageName = context.getPackageName();
    String permissionName = packageName + ".permission.C2D_MESSAGE";
    // check permission
    try {
        packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS);
    } catch (NameNotFoundException e) {
        throw new IllegalStateException("Application does not define permission " + permissionName);
    }
    // check receivers
    PackageInfo receiversInfo;
    try {
        receiversInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        throw new IllegalStateException("Could not get receivers for package " + packageName);
    }
    ActivityInfo[] receivers = receiversInfo.receivers;
    if (receivers == null || receivers.length == 0) {
        throw new IllegalStateException("No receiver for package " + packageName);
    }
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "number of receivers for " + packageName + ": " + receivers.length);
    }
    Set<String> allowedReceivers = new HashSet<String>();
    for (ActivityInfo receiver : receivers) {
        if (GCMConstants.PERMISSION_GCM_INTENTS.equals(receiver.permission)) {
            allowedReceivers.add(receiver.name);
        }
    }
    if (allowedReceivers.isEmpty()) {
        throw new IllegalStateException(
                "No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS);
    }
    checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
    checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE);
}

From source file:net.lldp.checksims.algorithm.similaritymatrix.SimilarityMatrix.java

/**
 * Generate a Similarity Matrix with archive submissions.
 *
 * The result is not a square matrix. Only the input submissions are on the X axis, but the Y axis contains both
 * input and archive submissions.//from   w w  w. jav a  2  s.c om
 *
 * @param inputSubmissions Submissions used to generate matrix
 * @param archiveSubmissions Archive submissions - only compared to input submissions, not to each other
 * @param results Results used to build matrix
 * @return Similarity matrix built from given results
 * @throws InternalAlgorithmError Thrown on missing results, or results containing a submission not in the input
 */
public static SimilarityMatrix generateMatrix(Set<Submission> inputSubmissions,
        Set<Submission> archiveSubmissions, Set<AlgorithmResults> results) throws InternalAlgorithmError {
    checkNotNull(inputSubmissions);
    checkNotNull(archiveSubmissions);
    checkNotNull(results);
    checkArgument(!inputSubmissions.isEmpty(), "Must provide at least 1 submission to build matrix from");
    checkArgument(!results.isEmpty(), "Must provide at least 1 AlgorithmResults to build matrix from!");

    Set<Submission> setOfBoth = new HashSet<>();
    setOfBoth.addAll(inputSubmissions);
    setOfBoth.addAll(archiveSubmissions);

    checkArgument(setOfBoth.size() == (archiveSubmissions.size() + inputSubmissions.size()),
            "Some submissions were found in both archive and input submissions!");

    // If there are no archive submissions, just generate using the other function
    if (archiveSubmissions.isEmpty()) {
        return generateMatrix(inputSubmissions, results);
    }

    List<Submission> xSubmissions = Ordering.natural().immutableSortedCopy(inputSubmissions);
    List<Submission> ySubmissions = new ArrayList<>();
    ySubmissions.addAll(Ordering.natural().immutableSortedCopy(inputSubmissions));
    ySubmissions.addAll(Ordering.natural().immutableSortedCopy(archiveSubmissions));

    AlgorithmResults[][] matrix = new AlgorithmResults[xSubmissions.size()][ySubmissions.size()];

    // Generate the matrix

    // First, handle identical submissions
    for (Submission xSub : xSubmissions) {
        // Get the X index
        int xIndex = xSubmissions.indexOf(xSub);
        int yIndex = ySubmissions.indexOf(xSub);

        matrix[xIndex][yIndex] = new AlgorithmResults(Pair.of(xSub, xSub), Real.ONE, Real.ONE);
    }

    // Now iterate through all given algorithm results
    for (AlgorithmResults result : results) {
        int aXCoord = xSubmissions.indexOf(result.a);
        int bXCoord = xSubmissions.indexOf(result.b);

        if (aXCoord == -1 && bXCoord == -1) {
            throw new InternalAlgorithmError("Neither submission \"" + result.a.getName() + "\" nor \""
                    + result.b.getName() + "\" were found in input submissions!");
        }

        if (aXCoord != -1) {
            int bYCoord = ySubmissions.indexOf(result.b);

            matrix[aXCoord][bYCoord] = result.inverse();
        }

        if (bXCoord != -1) {
            int aYCoord = ySubmissions.indexOf(result.a);

            matrix[bXCoord][aYCoord] = result;
        }
    }

    // Verification pass - ensure we built a matrix with no nulls
    for (int x = 0; x < xSubmissions.size(); x++) {
        for (int y = 0; y < ySubmissions.size(); y++) {
            if (matrix[x][y] == null) {
                throw new InternalAlgorithmError("Missing Algorithm Results for comparison of submissions \""
                        + xSubmissions.get(x).getName() + "\" and \"" + ySubmissions.get(y).getName() + "\"");
            }
        }
    }

    return new SimilarityMatrix(matrix, xSubmissions, ySubmissions, results);
}

From source file:com.netflix.genie.server.repository.jpa.ClusterSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param commandId The id of the command that is registered with this cluster
 * @param statuses The status of the cluster
 * @return The specification/*ww  w  . j  a v a2  s.c om*/
 */
public static Specification<Cluster> findClustersForCommand(final String commandId,
        final Set<ClusterStatus> statuses) {
    return new Specification<Cluster>() {
        @Override
        public Predicate toPredicate(final Root<Cluster> root, final CriteriaQuery<?> cq,
                final CriteriaBuilder cb) {
            final List<Predicate> predicates = new ArrayList<>();
            final Join<Cluster, Command> commands = root.join(Cluster_.commands);

            predicates.add(cb.equal(commands.get(Command_.id), commandId));

            if (statuses != null && !statuses.isEmpty()) {
                //Could optimize this as we know size could use native array
                final List<Predicate> orPredicates = new ArrayList<>();
                for (final ClusterStatus status : statuses) {
                    orPredicates.add(cb.equal(root.get(Cluster_.status), status));
                }
                predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
            }

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}

From source file:net.sf.morph.util.TransformerUtils.java

/**
 * Get the set of destination classes available from the specified Transformer for the specified source type.
 * @param transformer/*from  w w w.j  av a 2  s.c om*/
 * @param sourceType
 * @return Class[]
 * @since Morph 1.1
 */
public static Class[] getDestinationClasses(Transformer transformer, Class sourceType) {
    if (!ClassUtils.inheritanceContains(transformer.getSourceClasses(), sourceType)) {
        return CLASS_NONE;
    }
    Class[] destinationTypes = transformer.getDestinationClasses();
    if (transformer instanceof ExplicitTransformer) {
        Set result = ContainerUtils.createOrderedSet();
        for (int i = 0; i < destinationTypes.length; i++) {
            if (((ExplicitTransformer) transformer).isTransformable(destinationTypes[i], sourceType)) {
                result.add(destinationTypes[i]);
            }
        }
        return result.isEmpty() ? CLASS_NONE : (Class[]) result.toArray(new Class[result.size()]);
    }
    return destinationTypes;
}

From source file:com.reactivetechnologies.platform.utils.EntityFinder.java

/**
 * Scans for JAX RS classes under given (comma delimited) packages
 * @param basePkg//from w w  w  .ja v  a  2  s . c  o  m
 * @return
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 */
public static List<Class<?>> findJaxRsClasses(String basePkg)
        throws ClassNotFoundException, IllegalAccessException {
    if (basePkg.contains(",")) {
        List<Class<?>> allPkgClasses = new ArrayList<>();
        String[] pkgs = basePkg.split(",");
        for (String pkg : pkgs) {
            allPkgClasses.addAll(findJaxRsClasses(pkg));
        }
        return allPkgClasses;
    }
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            AnnotationMetadata aMeta = metadataReader.getAnnotationMetadata();
            return aMeta.hasAnnotation(Path.class.getName()) || (aMeta.hasAnnotatedMethods(GET.class.getName())
                    || aMeta.hasAnnotatedMethods(POST.class.getName())
                    || aMeta.hasAnnotatedMethods(DELETE.class.getName())
                    || aMeta.hasAnnotatedMethods(Path.class.getName()));
        }
    });

    Set<BeanDefinition> beans = null;
    try {
        beans = provider.findCandidateComponents(StringUtils.hasText(basePkg) ? basePkg
                : EntityFinder.class.getName().substring(0, EntityFinder.class.getName().lastIndexOf(".")));
    } catch (Exception e) {
        throw new BeanInitializationException("Unable to scan for JAX-RS annotated classes under base package",
                e);
    }
    List<Class<?>> classes = new ArrayList<Class<?>>();
    if (beans != null && !beans.isEmpty()) {
        Class<?> restletClass;
        for (BeanDefinition bd : beans) {
            restletClass = Class.forName(bd.getBeanClassName());
            classes.add(restletClass);
        }
    } else {
        log.warn("** Did not find any JAX-RS annotated classes under the given base scan package [" + basePkg
                + "]. No REST requests will be served **");
    }
    return classes;

}

From source file:com.bibisco.manager.SceneTagsManager.java

/**
**
 * @return a Map as// w  w  w  . jav a2 s .  c  om
 * 
 *                 Chapter.1 Chapter.2 Chapter.3
 * - location.1 -     X         X
 * - location.2 -               X
 * - location.3 -     X         X          
 * 
 */
public static Map<String, List<Boolean>> getLocationsChaptersPresence() {

    Map<String, List<Boolean>> lMapLocationChapterPresence = new HashMap<String, List<Boolean>>();

    mLog.debug("Start getLocationsChaptersDistribution()");

    List<com.bibisco.bean.LocationDTO> lListLocationDTO = LocationManager.loadAll();
    List<ChapterDTO> lListChapters = ChapterManager.loadAll();

    if (CollectionUtils.isEmpty(lListLocationDTO) || CollectionUtils.isEmpty(lListChapters)) {
        mLog.debug("End getStrandsChaptersDistribution()");
        return lMapLocationChapterPresence;
    }

    SqlSessionFactory lSqlSessionFactory = SqlSessionFactoryManager.getInstance().getSqlSessionFactoryProject();
    SqlSession lSqlSession = lSqlSessionFactory.openSession();
    try {

        VSceneTagsMapper lVSceneTagsMapper = lSqlSession.getMapper(VSceneTagsMapper.class);
        VSceneTagsExample lVSceneTagsExample = new VSceneTagsExample();
        lVSceneTagsExample.setOrderByClause("chapter_position, id_location");
        List<VSceneTags> lListVSceneTags = lVSceneTagsMapper.selectByExample(lVSceneTagsExample);

        if (lListVSceneTags != null && lListVSceneTags.size() > 0) {

            Map<Integer, Set<Integer>> lMapLocationsChaptersDistribution = new HashMap<Integer, Set<Integer>>();
            int lIntLastChapter = -1;
            Set<Integer> lSetChapterLocations = null;

            // filter duplicate items using a set
            for (VSceneTags lVSceneTags : lListVSceneTags) {
                if (lVSceneTags.getChapterPosition().intValue() != lIntLastChapter) {
                    lSetChapterLocations = new HashSet<Integer>();
                    lMapLocationsChaptersDistribution.put(lVSceneTags.getChapterPosition(),
                            lSetChapterLocations);
                    lIntLastChapter = lVSceneTags.getChapterPosition();
                }
                if (lVSceneTags.getIdLocation() != null) {
                    lSetChapterLocations.add(lVSceneTags.getIdLocation().intValue());
                }

            }

            // populate result map
            for (LocationDTO lLocationDTO : lListLocationDTO) {
                List<Boolean> lListLocationChapterPresence = new ArrayList<Boolean>();
                lMapLocationChapterPresence.put(lLocationDTO.getIdLocation().toString(),
                        lListLocationChapterPresence);
                for (ChapterDTO lChapterDTO : lListChapters) {
                    Set<Integer> lSetLocations = lMapLocationsChaptersDistribution
                            .get(lChapterDTO.getPosition());
                    if (lSetLocations != null && !lSetLocations.isEmpty()
                            && lSetLocations.contains(lLocationDTO.getIdLocation())) {
                        lListLocationChapterPresence.add(Boolean.TRUE);
                    } else {
                        lListLocationChapterPresence.add(Boolean.FALSE);
                    }
                }
            }
        }

    } catch (Throwable t) {
        mLog.error(t);
        throw new BibiscoException(t, BibiscoException.SQL_EXCEPTION);
    } finally {
        lSqlSession.close();
    }

    mLog.debug("End getLocationsChaptersDistribution()");

    return lMapLocationChapterPresence;
}