Example usage for java.util Set size

List of usage examples for java.util Set size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:com.delicious.deliciousfeeds4J.DeliciousUtil.java

public static UserInfo deserializePublicUserInformationFromJson(String username, String json) throws Exception {

    logger.debug("Trying to deserialize JSON to UserInfo...");
    logger.trace("Deserializing JSON: " + json);

    //Check if empty or null
    if (json == null || json.isEmpty()) {
        logger.debug("Nothing to deserialize. JSON-string was empty!");
        return null;
    }//from   w w  w  .  j a v a 2 s  .  c  om

    //Actually deserialize
    final Set<UserInfoDetail> userInfoDetails = ((Set<UserInfoDetail>) objectMapper.readValue(json,
            new TypeReference<Set<UserInfoDetail>>() {
            }));

    if (userInfoDetails == null || userInfoDetails.isEmpty()) {
        logger.debug("No userInfoDetails found. Collection was empty.");
        return null;
    }

    logger.info("Successfully deserialized {} userInfoDetails!", userInfoDetails.size());

    //Now build a UserInfo-object
    final UserInfo userInfo = new UserInfo();
    userInfo.setUser(username);

    for (UserInfoDetail userInfoDetail : userInfoDetails) {

        if (userInfoDetail.getId().equals(UserInfoDetail.ITEMS_ID))
            userInfo.setItems(userInfoDetail.getCount());
        else if (userInfoDetail.getId().equals(UserInfoDetail.FOLLOWERS_ID))
            userInfo.setFollowers(userInfoDetail.getCount());
        else if (userInfoDetail.getId().equals(UserInfoDetail.FOLLOWING_ID))
            userInfo.setFollowing(userInfoDetail.getCount());

        userInfo.getUserInfoDetailSet().add(userInfoDetail);
    }

    return userInfo;
}

From source file:models.service.reminder.RemindService.java

/**
 * ????//from  w  w  w  . j  a va2 s  .  c  o  m
 * 
 * @param cfg json
 * @param items ??item
 * 
 * @return true:, false:
 */
public static boolean verifyCfg(JsonNode cfg, Item[] items) {
    if (null == cfg) {
        return false;
    }

    boolean isSuccess = true;
    int count = 0;
    for (Item item : items) {
        if (!item.isEnable) {
            continue;
        }

        String itemVal = item.getVal();

        // ??
        if (cfg.hasNonNull(itemVal) && cfg.get(itemVal).isArray()) {
            JsonNode optionsNode = cfg.get(itemVal);
            Iterator<JsonNode> optionsIt = optionsNode.elements();

            // ??
            Set<String> optionSet = new HashSet<>();
            while (optionsIt.hasNext()) {
                String optionString = optionsIt.next().asText();

                if (!Option.isContainVal(optionString)) {
                    isSuccess = false;
                    break;
                }

                optionSet.add(optionString);
            }
            if (!isSuccess) {
                break;
            }

            // ?????
            if (optionSet.size() != optionsNode.size()) {
                isSuccess = false;
                break;
            }

            count++;
        } else {
            isSuccess = false;
            break;
        }
    }

    // ?
    if (cfg.size() > count) {
        isSuccess = false;
    }

    return isSuccess;
}

From source file:org.grails.datastore.mapping.reflect.ReflectionUtils.java

/**
 * Retrieves all the properties of the given class for the given type
 *
 * @param clazz The class to retrieve the properties from
 * @param propertyType The type of the properties you wish to retrieve
 *
 * @return An array of PropertyDescriptor instances
 *//*from w w w  .j  a va  2s  . c o  m*/
public static PropertyDescriptor[] getPropertiesOfType(Class<?> clazz, Class<?> propertyType) {
    if (clazz == null || propertyType == null) {
        return new PropertyDescriptor[0];
    }

    Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>();
    try {
        for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(clazz)) {
            Class<?> currentPropertyType = descriptor.getPropertyType();
            if (isTypeInstanceOfPropertyType(propertyType, currentPropertyType)) {
                properties.add(descriptor);
            }
        }
    } catch (Exception e) {
        // if there are any errors in instantiating just return null for the moment
        return new PropertyDescriptor[0];
    }
    return properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:mobile.service.RNSService.java

/**
 * ?//  w w  w  . j av a2 s  . com
 *
 * @param serviceId ?Id??Idnull???
 * @param file      ??5
 * @param pos       ?1 - 5
 * @return
 */
public static ServiceVOResult<CommonVO> uploadServicePic(Long serviceId, File file) {
    Service service = null;
    if (null != serviceId) {
        service = Service.queryServiceById(serviceId);
        if (null == service) {
            return ServiceVOResult.error("1008", "??");
        }
        if (!service.getOwner().getId().equals(MobileUtil.getCurrentUser().getId())) {
            return ServiceVOResult.error("1004", "???");
        }
        if (service.getCaseAttachs().size() >= 5) {
            return ServiceVOResult.error("1005", "???");
        }
    }

    ServiceVOResult<CommonVO> uploadResult = FileService.uploadAttatch(file, "mobile.jpg",
            FileService.AttatchType.SERVICE);
    if (!uploadResult.isSuccess()) {
        return ServiceVOResult.error(uploadResult.getErrorCode(), uploadResult.getErrorContent());
    }

    if (null != service) {
        synchronized (uploadServicePicLock) {
            JPA.em().refresh(service);
            Set<AttachOfService> caseAttachs = service.getCaseAttachs();
            if (caseAttachs.size() >= 5) {
                return ServiceVOResult.error("1005", "???");
            }

            // ?Json
            ArrayNode attachArray = Json.newObject().arrayNode();
            for (AttachOfService attachOfService : caseAttachs) {
                ObjectNode attachNode = Json.newObject();
                attachNode.put("attachId", attachOfService.id);
                attachArray.add(attachNode);
            }
            ObjectNode attachNode = Json.newObject();
            attachNode.put("attachId", uploadResult.getVo().getLong("attachId"));
            attachArray.add(attachNode);

            ObjectNode data = Json.newObject();
            data.put("id", serviceId);
            data.set("attachs", attachArray);

            ServiceResult updateResult = createOrUpdateService(data, null);
            if (!updateResult.isSuccess()) {
                return ServiceVOResult.create(updateResult);
            }
        }
    }

    CommonVO vo = CommonVO.create();
    vo.set("url", uploadResult.getVo().getString("url"));
    vo.set("attachId", uploadResult.getVo().getLong("attachId"));

    return ServiceVOResult.success(vo);
}

From source file:net.lldp.checksims.ChecksimsCommandLine.java

/**
 * Parse flags which require submissions to be built.
 *
 * TODO unit tests/*ww w .j  av  a  2 s  . c  om*/
 *
 * @param cli Parse CLI options
 * @param baseConfig Base configuration to work off
 * @return Modified baseConfig with submissions (and possibly common code and archive submissions) changed
 * @throws ChecksimsException Thrown on bad argument
 * @throws IOException Thrown on error building submissions
 */
static ChecksimsConfig parseFileFlags(CommandLine cli, ChecksimsConfig baseConfig)
        throws ChecksimsException, IOException {
    checkNotNull(cli);
    checkNotNull(baseConfig);

    ChecksimsConfig toReturn = new ChecksimsConfig(baseConfig);

    // Get glob match pattern
    // Default to *
    String globPattern = cli.getOptionValue("g", "*");

    // Check if we are recursively building
    boolean recursive = cli.hasOption("r");

    // Check if we are retaining empty submissions
    boolean retainEmpty = cli.hasOption("e");

    // Get submission directories
    if (!cli.hasOption("s")) {
        throw new ChecksimsException("Must provide at least one submission directory!");
    }

    String[] submissionDirsString = cli.getOptionValues("s");

    // Make a Set<File> from those submission directories
    // Map to absolute file, to ensure no dups
    Set<File> submissionDirs = Arrays.stream(submissionDirsString).map(File::new).map(File::getAbsoluteFile)
            .collect(Collectors.toSet());

    if (submissionDirs.isEmpty()) {
        throw new ChecksimsException("Must provide at least one submission directory!");
    }

    // Generate submissions
    Set<Submission> submissions = getSubmissions(submissionDirs, globPattern, recursive, retainEmpty);

    logs.debug("Generated " + submissions.size() + " submissions to process.");

    if (submissions.isEmpty()) {
        throw new ChecksimsException("Could build any submissions to operate on!");
    }

    toReturn = toReturn.setSubmissions(submissions);

    // Check if we need to perform common code removal
    if (cli.hasOption("c")) {
        // Get the directory containing the common code
        String commonCodeDirString = cli.getOptionValue("c");

        List<SubmissionPreprocessor> procs = new ArrayList<>(toReturn.getPreprocessors());
        try {
            procs.add(getCommonCodeRemoval(commonCodeDirString, submissionDirs, globPattern));
        } catch (IOException | ChecksimsException e) {
            logs.debug(e.getMessage());
        }
        toReturn = toReturn.setPreprocessors(procs);
    }

    // Check if we need to add archive directories
    if (cli.hasOption("archive")) {
        String[] archiveDirsString = cli.getOptionValues("archive");

        // Convert them into a set of files, again using getAbsoluteFile
        Set<File> archiveDirs = Arrays.stream(archiveDirsString).map(File::new).map(File::getAbsoluteFile)
                .collect(Collectors.toSet());

        archiveDirs = extractTurninFiles(archiveDirs);

        // Ensure that none of them are also submission directories
        for (File archiveDir : archiveDirs) {
            if (submissionDirs.contains(archiveDir)) {
                throw new ChecksimsException("Directory is both an archive directory and submission directory: "
                        + archiveDir.getAbsolutePath());
            }
        }

        // Get set of archive submissions
        Set<Submission> archiveSubmissions = getSubmissions(archiveDirs, globPattern, recursive, retainEmpty);

        logs.debug("Generated " + archiveSubmissions.size() + " archive submissions to process");

        if (archiveSubmissions.isEmpty()) {
            logs.warn("Did not find any archive submissions to test with!");
        }

        toReturn = toReturn.setArchiveSubmissions(archiveSubmissions);
    }

    return toReturn;
}

From source file:com.espertech.esper.epl.join.plan.NStreamOuterQueryPlanBuilder.java

private static void addNotYetNavigated(int streamNo, int numStreams,
        LinkedHashMap<Integer, int[]> substreamsPerStream, NStreamQueryPlanBuilder.BestChainResult bestChain) {
    // sum up all substreams (the query plan for each stream: nested iteration or cardinal)
    Set<Integer> streams = new HashSet<Integer>();
    streams.add(streamNo);/*from w ww .  j a va  2  s .  c  o m*/
    recursiveAdd(streamNo, streamNo, substreamsPerStream, streams, false);

    // we are done, all have navigated
    if (streams.size() == numStreams) {
        return;
    }

    int previous = streamNo;
    for (int stream : bestChain.getChain()) {

        if (streams.contains(stream)) {
            previous = stream;
            continue;
        }

        // add node as a nested join to the previous stream
        int[] substreams = substreamsPerStream.get(previous);
        if (substreams == null) {
            substreams = new int[0];
        }
        int[] added = CollectionUtil.addValue(substreams, stream);
        substreamsPerStream.put(previous, added);

        if (!substreamsPerStream.containsKey(stream)) {
            substreamsPerStream.put(stream, new int[0]);
        }

        previous = stream;
    }
}

From source file:mobile.service.RNSService.java

/**
 * /*from w  w  w . j  av  a 2s  . c o  m*/
 *
 * @param requireId Id
 * @param file      
 * @param filename  ??
 * @return
 */
public static ServiceVOResult<CommonVO> updateRequireAttachment(Long requireId, File file, String filename) {
    if (StringUtils.isBlank(filename)) {
        throw new IllegalArgumentException("filename can not be blank.");
    }

    Require require = null;
    if (null != requireId) {
        require = Require.queryRequireById(requireId);
        if (null == require) {
            return ServiceVOResult.error("1007", "?");
        }
        if (!require.getOwner().getId().equals(MobileUtil.getCurrentUser().getId())) {
            return ServiceVOResult.error("1003", "??");
        }
        if (require.getCaseAttachs().size() >= 5) {
            return ServiceVOResult.error("1006", "??");
        }
    }

    ServiceVOResult<CommonVO> uploadResult = FileService.uploadAttatch(file, filename,
            FileService.AttatchType.REQUIRE);
    if (!uploadResult.isSuccess()) {
        return ServiceVOResult.error(uploadResult.getErrorCode(), uploadResult.getErrorContent());
    }

    if (null != require) {
        synchronized (updateRequireAttachmentLock) {
            JPA.em().refresh(require);

            Set<AttachOfRequire> caseAttachs = require.getCaseAttachs();
            if (caseAttachs.size() >= 5) {
                return ServiceVOResult.error("1006", "??");
            }

            // ?Json
            ArrayNode attachArray = Json.newObject().arrayNode();
            for (AttachOfRequire attachOfRequire : caseAttachs) {
                ObjectNode attachNode = Json.newObject();
                attachNode.put("attachId", attachOfRequire.id);
                attachArray.add(attachNode);
            }
            ObjectNode attachNode = Json.newObject();
            attachNode.put("attachId", uploadResult.getVo().getLong("attachId"));
            attachArray.add(attachNode);

            ObjectNode data = Json.newObject();
            data.put("id", requireId);
            data.set("attachs", attachArray);

            ServiceResult updateResult = createOrUpdateRequire(data, null);
            if (!updateResult.isSuccess()) {
                return ServiceVOResult.create(updateResult);
            }

        }
    }

    CommonVO vo = CommonVO.create();
    vo.set("url", uploadResult.getVo().getString("url"));
    vo.set("attachId", uploadResult.getVo().getLong("attachId"));

    return ServiceVOResult.success(vo);
}

From source file:com.aurel.track.admin.customize.category.filter.execute.loadItems.LoadItemLinksUtil.java

/**
 * Loads all dependent items in allItemIDSet
 * @param baseWorkItemBeans/*from   www.  ja v  a  2  s .  c om*/
 * @param archived
 * @param deleted
 * @param allItemIDSet
 */
public static void loadAllDependentItems(List<TWorkItemBean> baseWorkItemBeans, Integer archived,
        Integer deleted, Set<Integer> allItemIDSet) {
    Set<Integer> linkedItemIDsSet = loadAncestorDescendantAndDirectLinkedItems(baseWorkItemBeans, archived,
            deleted, allItemIDSet);
    int i = 0;
    LOGGER.debug("Number of linked items at level " + i);
    while (linkedItemIDsSet != null && linkedItemIDsSet.size() > 0) {
        List<TWorkItemBean> linkedItemBeans = ItemBL
                .loadByWorkItemKeys(GeneralUtils.createIntArrFromSet(linkedItemIDsSet));
        i++;
        linkedItemIDsSet = loadAncestorDescendantAndDirectLinkedItems(linkedItemBeans, archived, deleted,
                allItemIDSet);
        LOGGER.debug("Number of linked items at level " + i);
    }
}

From source file:com.microsoft.tfs.client.eclipse.ui.actions.ActionHelpers.java

/**
 * Returns the {@link IProject}s that are contained in this selection.
 *
 * @param selection/* w  w w.  j a  va  2  s  .c om*/
 *        The selected resources (not <code>null</code>)
 * @return All {@link IProject}s contained by the selection (never
 *         <code>null</code>)
 */
public static IProject[] getProjectsFromSelection(final ISelection selection) {
    Check.notNull(selection, "selection"); //$NON-NLS-1$

    if (!(selection instanceof IStructuredSelection)) {
        return new IProject[0];
    }

    final Set<IProject> projectSet = new HashSet<IProject>();

    @SuppressWarnings("rawtypes")
    final Iterator i;

    for (i = ((IStructuredSelection) selection).iterator(); i.hasNext();) {
        final IResource resource = (IResource) i.next();

        final IProject project = resource.getProject();

        if (project != null) {
            projectSet.add(project);
        }
    }

    return projectSet.toArray(new IProject[projectSet.size()]);
}

From source file:edu.ksu.cis.indus.staticanalyses.concurrency.escape.MethodContext.java

/**
 * Fixes up the field maps of the alias sets in the given map. When alias sets are cloned, the field maps are cloned.
 * Hence, they are shallow copied. This method clones the relation between the alias sets among their clones.
 * //from   w ww.j a va2  s. c  om
 * @param src2clone maps an representative alias set to it's clone. This is also an out parameter that will contain new
 *            mappings.
 * @throws CloneNotSupportedException when <code>clone()</code> fails.
 */
private static void fixUpFieldMapsOfClone(final Map<AliasSet, AliasSet> src2clone)
        throws CloneNotSupportedException {
    final IWorkBag<AliasSet> _wb = new HistoryAwareLIFOWorkBag<AliasSet>(new HashSet<AliasSet>());

    _wb.addAllWork(src2clone.keySet());

    while (_wb.hasWork()) {
        final AliasSet _src = _wb.getWork();
        final AliasSet _clone = src2clone.get(_src);
        final Map<String, AliasSet> _srcASFieldMap = _src.getFieldMap();
        final Set<String> _srcASFields = _srcASFieldMap.keySet();
        final Iterator<String> _i = _srcASFields.iterator();
        final int _iEnd = _srcASFields.size();

        for (int _iIndex = 0; _iIndex < _iEnd; _iIndex++) {
            final String _field = _i.next();

            /*
             * We use the representative alias set as it is possible that a field may have 2 alias sets in different
             * contexts but the same representative alias set in both contexts. We don't do the same for clones as they
             * are the representatives until they are unified, which happens in the following block.
             */
            final AliasSet _srcFieldAS = _src.getASForField(_field).find();
            final AliasSet _cloneFieldAS;

            _cloneFieldAS = getCloneOf(src2clone, _srcFieldAS);
            // if the clone is different from the src only then we need to further process src.
            if (_cloneFieldAS != _srcFieldAS) {
                _wb.addWork(_srcFieldAS);
            }
            _clone.putASForField(_field, _cloneFieldAS);
        }
    }

    // Unify the clones to reflect the relation between their originators.
    for (final Iterator<AliasSet> _i = src2clone.keySet().iterator(); _i.hasNext();) {
        final AliasSet _k1 = _i.next();

        for (final Iterator<AliasSet> _j = src2clone.keySet().iterator(); _j.hasNext();) {
            final AliasSet _k2 = _j.next();

            if (_k1 != _k2 && _k1.find() == _k2.find()) {
                final AliasSet _v1 = src2clone.get(_k1);
                final AliasSet _v2 = src2clone.get(_k2);
                _v1.unifyAliasSetHelper(_v2, false);
            }
        }
    }
    return;
}