Example usage for java.util HashSet size

List of usage examples for java.util HashSet size

Introduction

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

Prototype

public int size() 

Source Link

Document

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

Usage

From source file:org.batoo.jpa.core.impl.collections.ManagedList.java

/**
 * Default constructor.//w  ww.j  av a2  s  . co m
 * 
 * @param mapping
 *            the mapping
 * @param managedInstance
 *            the managed instance
 * @param values
 *            the initial values
 * 
 * @since 2.0.0
 */
public ManagedList(PluralMappingEx<?, ?, E> mapping, ManagedInstance<?> managedInstance,
        Collection<? extends E> values) {
    super(mapping, managedInstance);

    this.delegate = Lists.newArrayList();

    final HashSet<Object> uniqueSet = Sets.newHashSet();

    if (values instanceof List) {
        final List<? extends E> valuesList = (List<? extends E>) values;
        for (int i = 0; i < valuesList.size(); i++) {
            final E child = valuesList.get(i);
            if (child == null) {
                throw new NullPointerException("Instance " + this.getManagedInstance()
                        + " has null items in its collection " + this.getMapping().getPath());
            }

            this.delegate.add(child);
            uniqueSet.add(child);
        }
    } else {
        for (final E child : values) {
            if (child == null) {
                throw new NullPointerException("Instance " + this.getManagedInstance()
                        + " has null items in its collection " + this.getMapping().getPath());
            }

            this.delegate.add(child);
            uniqueSet.add(child);
        }
    }

    if (uniqueSet.size() != this.delegate.size()) {
        throw this.noDuplicates();
    }

    this.initialized = true;
}

From source file:com.quinsoft.zeidon.standardoe.ViewImpl.java

/**
 * This is used to look for memory leaks of EntityInstanceImpl.
 *
 * @return/*from   www.  ja va 2s . co m*/
 */
int countAllEntities() {
    int count = 0;
    HashSet<EntityInstanceImpl> allEntities = new HashSet<EntityInstanceImpl>();
    HashMap<String, Integer> entities = new HashMap<String, Integer>();
    for (EntityInstanceImpl ei = getObjectInstance().getRootEntityInstance(); ei != null; ei = ei
            .getNextHier()) {
        ei.countAllVersions(allEntities);
        for (EntityInstanceImpl linked : ei.getAllLinkedInstances(true)) {
            if (!allEntities.contains(linked))
                linked.countAllVersions(allEntities);
        }
    }

    for (EntityInstanceImpl ei : allEntities) {
        String name = (ei == null) ? "null" : ei.getEntityDef().getName();
        Integer ec = entities.get(name);
        if (ec == null)
            ec = 1;
        else
            ec = ec + 1;
        entities.put(name, ec);
    }

    count = allEntities.size();
    log().info("Entities = " + entities.toString());
    log().info("Total entities = " + count);
    return count;
}

From source file:org.mskcc.cbio.portal.servlet.QueryBuilder.java

/**
 * validate the portal web input form.// w w w .j a va2 s. co  m
 */
private boolean validateForm(String action, ArrayList<GeneticProfile> profileList,
        HashSet<String> geneticProfileIdSet, String sampleSetId, String sampleIds,
        HttpServletRequest httpServletRequest) throws DaoException {
    boolean errorsExist = false;
    String tabIndex = httpServletRequest.getParameter(QueryBuilder.TAB_INDEX);
    if (action != null) {
        if (action.equals(ACTION_SUBMIT)) {
            // is user authorized for the study
            String cancerStudyIdentifier = (String) httpServletRequest.getAttribute(CANCER_STUDY_ID);
            cancerStudyIdentifier = StringEscapeUtils.escapeJavaScript(cancerStudyIdentifier);

            if (accessControl.isAccessibleCancerStudy(cancerStudyIdentifier).size() != 1) {
                httpServletRequest.setAttribute(STEP1_ERROR_MSG,
                        "You are not authorized to view the cancer study with id: '" + cancerStudyIdentifier
                                + "'. ");
                errorsExist = true;
            } else {
                UserDetails ud = accessControl.getUserDetails();
                if (ud != null) {
                    LOG.info("QueryBuilder.validateForm: Query initiated by user: " + ud.getUsername());
                }
            }

            if (geneticProfileIdSet.size() == 0) {
                if (tabIndex == null || tabIndex.equals(QueryBuilder.TAB_DOWNLOAD)) {
                    httpServletRequest.setAttribute(STEP2_ERROR_MSG, "Please select a genetic profile below. ");
                } else {
                    httpServletRequest.setAttribute(STEP2_ERROR_MSG,
                            "Please select one or more genetic profiles below. ");
                }
                errorsExist = true;
            }

            // user-defined patient set
            if (sampleIds != null && sampleSetId != null && sampleSetId.equals("-1")) {
                // empty patient list
                if (sampleIds.trim().length() == 0) {
                    httpServletRequest.setAttribute(STEP3_ERROR_MSG, "Please enter at least one ID below. ");

                    errorsExist = true;
                } else {
                    List<String> invalidSamples = SampleSetUtil.validateSampleSet(cancerStudyIdentifier,
                            sampleIds);

                    String sampleSetErrMsg = "Invalid samples(s) for the selected cancer study:";

                    // non-empty list, but contains invalid patient IDs
                    if (invalidSamples.size() > 0) {
                        // append patient ids to the message
                        for (String sampleId : invalidSamples) {
                            sampleSetErrMsg += " " + sampleId;
                        }

                        httpServletRequest.setAttribute(STEP3_ERROR_MSG, sampleSetErrMsg);

                        errorsExist = true;
                    }
                }
            }

            //  Additional validation rules
            //  If we have selected mRNA Expression Data Check Box, but failed to
            //  select an mRNA profile, this is an error.
            String mRNAProfileSelected = httpServletRequest.getParameter(QueryBuilder.MRNA_PROFILES_SELECTED);
            if (mRNAProfileSelected != null && mRNAProfileSelected.equalsIgnoreCase("on")) {

                //  Make sure that at least one of the mRNA profiles is selected
                boolean mRNAProfileRadioSelected = false;
                for (int i = 0; i < profileList.size(); i++) {
                    GeneticProfile geneticProfile = profileList.get(i);
                    if (geneticProfile.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION
                            && geneticProfileIdSet.contains(geneticProfile.getStableId())) {
                        mRNAProfileRadioSelected = true;
                    }
                }
                if (mRNAProfileRadioSelected == false) {
                    httpServletRequest.setAttribute(STEP2_ERROR_MSG, "Please select an mRNA profile.");
                    errorsExist = true;
                }
            }
        }
    }

    return errorsExist;
}

From source file:com.yahoo.ycsb.workloads.MailAppCassandraWorkload.java

public void doTransactionPopDelete(DB db) throws WorkloadException {
    printDebug("------------POP Delete Transaction-------------");
    //choose a random key
    int keynum = nextKeynum();

    String keynameInbox = buildKeyName(keynum, inboxSuffix);

    HashSet<String> fields = null;

    HashSet<String> counterColumnNames = new HashSet<String>();
    counterColumnNames.add(messagecountfieldkey);
    counterColumnNames.add(mailboxsizefieldkey);

    HashMap<String, ByteIterator> counterResult = new HashMap<String, ByteIterator>();
    HashMap<String, ByteIterator> uidlResult = new HashMap<String, ByteIterator>();
    HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();

    HashSet<String> uidlKeySet = new HashSet<String>();

    long st = System.nanoTime();

    //read counter Table (POP3 STAT Command)
    db.read(incrementTag + countertable, keynameInbox, counterColumnNames, counterResult);

    int statCount = Integer.valueOf(counterResult.get(messagecountfieldkey).toString());
    if (statCount <= 0) {
        long en = System.nanoTime();
        printDebug("POP Delete: Inbox empty, closing...");
        Measurements.getMeasurements().measure("POP_DELETE-Transaction", (int) ((en - st) / 1000));
        return;/* w  w  w.  j a v  a  2  s.  c om*/
    }
    //get UIDL/LIST-List
    printDebug("POP Delete: reading uidl-List");
    db.read(sizetable, keynameInbox, fields, uidlResult);

    //DELE d-times
    //delete Messages. DB.delete() only allows deletion of whole rows, so  columnNames are appended with delimiter
    //min. deletion: 1, max. deletion: messagecount in Mailbox

    uidlKeySet.addAll(uidlResult.keySet());
    printDebug("POP Read: setting up delete count generator...");
    int deleteCount = getMessageDeleteCountGenerator(0, uidlKeySet.size()).nextInt();
    printDebug("POP Read: deleting " + deleteCount + " messages from " + keynameInbox);
    if (deleteCount > 0) {

        Iterator<String> retrievedIdsIterator = uidlResult.keySet().iterator();
        for (int i = 0; i < deleteCount; i++) {

            String columnNameDelete = hashAndRangeKeyDelimiter + retrievedIdsIterator.next();
            //System.out.println("deleting column: "+columnNameDelete);
            db.delete(mailboxtable, keynameInbox + columnNameDelete);
            db.delete(sizetable, keynameInbox + columnNameDelete);
        }

        //Update Counter
        HashMap<String, ByteIterator> countUpdateValue = new HashMap<String, ByteIterator>();
        countUpdateValue.put(messagecountfieldkey, new StringByteIterator("-" + deleteCount));
        countUpdateValue.put(mailboxsizefieldkey, new StringByteIterator("-" + deleteCount * 100));//100: dummy size

        //indicate use of counterColumns with incremetTag in from of tablename
        db.update(incrementTag + countertable, keynameInbox, countUpdateValue);

    }

    //---

    long en = System.nanoTime();
    Measurements.getMeasurements().measure("POP_DELETE-Transaction", (int) ((en - st) / 1000));

}

From source file:cz.cas.lib.proarc.webapp.server.rest.DigitalObjectResource.java

/**
 * Deletes object members from digital object.
 * @param parentPid digital object ID//  www .j a  va  2  s  . c om
 * @param toRemovePids member IDs to remove
 * @param batchId optional batch import ID
 * @return list of removed IDs
 */
@DELETE
@Path(DigitalObjectResourceApi.MEMBERS_PATH)
@Produces({ MediaType.APPLICATION_JSON })
public SmartGwtResponse<Item> deleteMembers(
        @QueryParam(DigitalObjectResourceApi.MEMBERS_ITEM_PARENT) String parentPid,
        @QueryParam(DigitalObjectResourceApi.MEMBERS_ITEM_PID) List<String> toRemovePids,
        @QueryParam(DigitalObjectResourceApi.MEMBERS_ITEM_BATCHID) Integer batchId)
        throws IOException, DigitalObjectException {

    if (parentPid == null) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing parent parameter!");
    }
    if (toRemovePids == null || toRemovePids.isEmpty()) {
        throw RestException.plainText(Status.BAD_REQUEST, "Missing pid parameter!");
    }
    if (toRemovePids.contains(parentPid)) {
        throw RestException.plainText(Status.BAD_REQUEST, "parent and pid are same!");
    }

    HashSet<String> toRemovePidSet = new HashSet<String>(toRemovePids);
    if (toRemovePidSet.isEmpty()) {
        return new SmartGwtResponse<Item>(Collections.<Item>emptyList());
    }

    DigitalObjectHandler parent = findHandler(parentPid, batchId, false);
    deleteMembers(parent, toRemovePidSet);
    parent.commit();

    ArrayList<Item> removed = new ArrayList<Item>(toRemovePidSet.size());
    for (String removePid : toRemovePidSet) {
        Item item = new Item(removePid);
        item.setParentPid(parentPid);
        removed.add(item);
    }

    return new SmartGwtResponse<Item>(removed);
}

From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java

/**
 * Fetch all tags/*from  ww w.  j a v  a  2s  . c om*/
 * @param serverTime
 * @return new serverTime
 */
public int fetchTags(int serverTime) throws JSONException, IOException {
    if (!checkForToken())
        return 0;

    JSONObject result = actFmInvoker.invoke("tag_list", "token", token, "modified_after", serverTime);
    JSONArray tags = result.getJSONArray("list");
    HashSet<Long> remoteIds = new HashSet<Long>(tags.length());
    for (int i = 0; i < tags.length(); i++) {
        JSONObject tagObject = tags.getJSONObject(i);
        actFmDataService.saveTagData(tagObject);
        remoteIds.add(tagObject.getLong("id"));
    }

    if (serverTime == 0) {
        Long[] remoteIdArray = remoteIds.toArray(new Long[remoteIds.size()]);
        tagDataService.deleteWhere(Criterion.not(TagData.REMOTE_ID.in(remoteIdArray)));
    }

    return result.optInt("time", 0);
}

From source file:com.smartitengineering.dao.impl.hibernate.AbstractDAOTest.java

private int getDistinctNumOfEmployeeNum() {
    HashSet<Integer> numbers = new HashSet<Integer>();
    for (Publisher publisher : getAllPublishers()) {
        numbers.add(publisher.getNumOfEmployees());
    }//  w  w  w . j a v a  2 s.c  om
    return numbers.size();
}

From source file:api.behindTheName.BehindTheNameApi.java

private void Search(final HashSet<String> set, int counter, final PeopleNameOption option,
        final ProgressCallback callback) {
    final int c = counter;
    callback.onProgressUpdate(behindTheNameProgressValues[c]);
    if (!set.isEmpty())
        callback.onProgress(new TreeSet<>(set));

    Platform.runLater(new Runnable() {

        @Override//from   www .  j  ava 2  s . c  om
        public void run() {
            String nation = genres.get(option.genre);
            String gender = getGenderKey(option.gender);
            String url = "http://www.behindthename.com/api/random.php?number=6&usage=" + nation + "&gender="
                    + gender + "&key=" + BEHIND_THE_NAME_KEY;

            final File file = new File("Temp.xml");
            try {
                URL u = new URL(url);
                FileUtils.copyURLToFile(u, file);

                List<String> lines = FileUtils.readLines(file);
                for (String s : lines) {
                    if (s.contains("<name>")) {
                        s = s.substring(s.indexOf(">") + 1, s.lastIndexOf("</"));
                        set.add(s);
                    }
                }

            } catch (MalformedURLException ex) {
                Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
                Thread.sleep(250);
            } catch (InterruptedException ex) {
                Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (set.size() == MAX_SIZE || c == MAX_SEARCH - 1 || set.isEmpty()) {
                callback.onProgressUpdate(1.0f);

                return;
            }

            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    Search(set, c + 1, option, callback);
                }
            });

        }
    });

}

From source file:org.processmining.analysis.petrinet.cpnexport.HLToCPNTranslator.java

/**
 * Gets for the given transitions all the other transitions that are
 * involved in the same choice based on frequencies.
 * /*from  w  ww.  j a  v a2 s.co m*/
 * @param transitionsFreqDep
 *            HashSet. A hashset in which we only have one transition and
 *            for which we want to obtain all the other transitions that are
 *            involved in the same choice based on frequencies.
 */
private void getTransitionsForChoiceOnFrequencies(HashSet<ColoredTransition> transitionsFreqDep) {
    int oldSizeTransitions = transitionsFreqDep.size();
    HashSet<ColoredPlace> places = new HashSet<ColoredPlace>();
    Iterator<ColoredTransition> transitionsFreqDepIt = transitionsFreqDep.iterator();
    while (transitionsFreqDepIt.hasNext()) {
        ColoredTransition transition = transitionsFreqDepIt.next();
        places.addAll(transition.getPredecessors());
    }
    // get the outgoing transitions for each place in places
    Iterator<ColoredPlace> placesIt = places.iterator();
    while (placesIt.hasNext()) {
        ColoredPlace place = placesIt.next();
        transitionsFreqDep.addAll(place.getSuccessors());
    }

    if (transitionsFreqDep.size() > oldSizeTransitions) {
        getTransitionsForChoiceOnFrequencies(transitionsFreqDep);
    }
}

From source file:org.kuali.ext.mm.context.DataDictionaryConfigurationTest.java

@Test
public void testAllDataDicitionaryDocumentTypesExistInWorkflowDocumentTypeTable() throws Exception {
    HashSet<String> workflowDocumentTypeNames = new HashSet<String>();
    DataSource mySource = (DataSource) SpringContext.getBean("dataSource");
    Connection dbCon = null;/*from   w ww.j  av a 2 s . co m*/
    try {

        dbCon = mySource.getConnection();
        Statement dbAsk = dbCon.createStatement();
        ResultSet dbAnswer = dbAsk.executeQuery("select DOC_TYP_NM from KREW_DOC_TYP_T where CUR_IND = 1");
        while (dbAnswer.next()) {
            String docName = dbAnswer.getString(1);
            if (StringUtils.isNotBlank(docName)) {
                workflowDocumentTypeNames.add(docName);
            }
        }

    } catch (Exception e) {
        throw (e);
    }
    // Using HashSet since duplicate objects would otherwise be returned
    HashSet<DocumentEntry> documentEntries = new HashSet(dataDictionary.getDocumentEntries().values());
    List<String> ddEntriesWithMissingTypes = new ArrayList<String>();
    for (DocumentEntry documentEntry : documentEntries) {
        String name = documentEntry.getDocumentTypeName();
        String testName = new String(" ");
        // if (documentEntry instanceof StoresMaintenanceDocumentEntry){
        // testName=((StoresMaintenanceDocumentEntry)documentEntry).getBusinessObjectClass().getName();
        // }else{
        // testName=documentEntry.getDocumentClass().getName();
        // }
        if (!workflowDocumentTypeNames.contains(name) && !"RiceUserMaintenanceDocument".equals(name)
                && !testName.contains("rice")) {
            ddEntriesWithMissingTypes.add(name);
        } else {
            workflowDocumentTypeNames.remove(name);
        }
    }

    if (workflowDocumentTypeNames.size() > 0) {
        try {
            // If documents are parent docs, then they aren't superfluous.
            String queryString = "select distinct doc_typ_nm from krew_doc_typ_t"
                    + " where doc_typ_id in (select parnt_id from krew_doc_typ_t" + " where actv_ind = 1"
                    + " and cur_ind = 1)";
            Statement dbAsk = dbCon.createStatement();
            ResultSet dbAnswer = dbAsk.executeQuery(queryString);
            while (dbAnswer.next()) {
                String docName = dbAnswer.getString(1);
                if (StringUtils.isNotBlank(docName)) {
                    workflowDocumentTypeNames.remove(docName);
                }
            }
        } catch (Exception e) {
            throw (e);
        }

        System.err.print("superfluousTypesDefinedInWorkflowDatabase: " + workflowDocumentTypeNames);
    }
    assertEquals("documentTypesNotDefinedInWorkflowDatabase: " + ddEntriesWithMissingTypes, 0,
            ddEntriesWithMissingTypes.size());
}