List of usage examples for java.util IdentityHashMap size
int size
To view the source code for java.util IdentityHashMap size.
Click Source Link
From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
/** * Test method for 'java.util.IdentityHashMap.putAll(Map)'. *///from w w w .j a va 2s .c om public void testPutAll() { IdentityHashMap srcMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(srcMap); srcMap.put(KEY_1, VALUE_1); srcMap.put(KEY_2, VALUE_2); srcMap.put(KEY_3, VALUE_3); // Make sure that the data is copied correctly IdentityHashMap dstMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(dstMap); dstMap.putAll(srcMap); assertEquals(srcMap.size(), dstMap.size()); assertTrue(dstMap.containsKey(KEY_1)); assertTrue(dstMap.containsValue(VALUE_1)); assertFalse(dstMap.containsKey(KEY_1.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_1.toUpperCase(Locale.ROOT))); assertTrue(dstMap.containsKey(KEY_2)); assertTrue(dstMap.containsValue(VALUE_2)); assertFalse(dstMap.containsKey(KEY_2.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_2.toUpperCase(Locale.ROOT))); assertTrue(dstMap.containsKey(KEY_3)); assertTrue(dstMap.containsValue(VALUE_3)); assertFalse(dstMap.containsKey(KEY_3.toUpperCase(Locale.ROOT))); assertFalse(dstMap.containsValue(VALUE_3.toUpperCase(Locale.ROOT))); // Check that an empty map does not blow away the contents of the // destination map IdentityHashMap emptyMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(emptyMap); dstMap.putAll(emptyMap); assertTrue(dstMap.size() == srcMap.size()); // Check that put all overwrite any existing mapping in the destination map srcMap.put(KEY_1, VALUE_2); srcMap.put(KEY_2, VALUE_3); srcMap.put(KEY_3, VALUE_1); dstMap.putAll(srcMap); assertEquals(dstMap.size(), srcMap.size()); assertEquals(dstMap.get(KEY_1), VALUE_2); assertEquals(dstMap.get(KEY_2), VALUE_3); assertEquals(dstMap.get(KEY_3), VALUE_1); // Check that a putAll does adds data but does not remove it srcMap.put(KEY_4, VALUE_4); dstMap.putAll(srcMap); assertEquals(dstMap.size(), srcMap.size()); assertTrue(dstMap.containsKey(KEY_4)); assertTrue(dstMap.containsValue(VALUE_4)); assertEquals(dstMap.get(KEY_1), VALUE_2); assertEquals(dstMap.get(KEY_2), VALUE_3); assertEquals(dstMap.get(KEY_3), VALUE_1); assertEquals(dstMap.get(KEY_4), VALUE_4); dstMap.putAll(dstMap); }
From source file:cdr.forms.FormController.java
@RequestMapping(value = "/{formId}.form", method = RequestMethod.POST) public String processForm(Model model, @PathVariable(value = "formId") String formId, @Valid @ModelAttribute("deposit") Deposit deposit, BindingResult errors, Principal user, SessionStatus sessionStatus,/*from w w w.j a va 2s .co m*/ @RequestParam(value = "deposit", required = false) String submitDepositAction, HttpServletRequest request, HttpServletResponse response) throws PermissionDeniedException { request.setAttribute("hasSupplementalObjectsStep", formId.equals(SUPPLEMENTAL_OBJECTS_FORM_ID)); // Check that the form submitted by the user matches the one in the session if (!deposit.getFormId().equals(formId)) throw new Error("Form ID in session doesn't match form ID in path"); // this.getAuthorizationHandler().checkPermission(formId, deposit.getForm(), request); // try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { LOG.error("Failed to set character encoding", e); } // if (user != null) deposit.getForm().setCurrentUser(user.getName()); // Remove entries set to null, append an entry for elements with append set for (DepositElement element : deposit.getElements()) { Iterator<DepositEntry> iterator = element.getEntries().iterator(); while (iterator.hasNext()) { if (iterator.next() == null) iterator.remove(); } if (element.getAppend() != null) { element.appendEntry(); element.setAppend(null); } } // Check the deposit's files for virus signatures IdentityHashMap<DepositFile, String> signatures = new IdentityHashMap<DepositFile, String>(); for (DepositFile depositFile : deposit.getAllFiles()) scanDepositFile(depositFile, signatures); // If the "submit deposit" button was pressed, run the validator. if (submitDepositAction != null) { Validator validator = new DepositValidator(); validator.validate(deposit, errors); } // If the deposit has validation errors and no virus signatures were detected, display errors if (errors.hasErrors() && signatures.size() == 0) { LOG.debug(errors.getErrorCount() + " errors"); return "form"; } // If the "submit deposit" button was not pressed, render the form again if (submitDepositAction == null) { return "form"; } // Otherwise, display one of the result pages: if we detected a virus signature, display // the virus warning; otherwise, try to submit the deposit and display results. In each // case, we want to do the same cleanup. String view; if (signatures.size() > 0) { model.addAttribute("signatures", signatures); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); view = "virus"; } else { // Redirect for supplemental objects special case if (formId.equals(SUPPLEMENTAL_OBJECTS_FORM_ID)) { return "redirect:/supplemental"; } // We're doing a regular deposit, so call the deposit handler DepositResult result = this.getDepositHandler().deposit(deposit); if (result.getStatus() == Status.FAILED) { LOG.error("deposit failed"); if (getNotificationHandler() != null) getNotificationHandler().notifyError(deposit, result); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); view = "failed"; } else { if (getNotificationHandler() != null) getNotificationHandler().notifyDeposit(deposit, result); view = "success"; } } // Clean up deposit.deleteAllFiles(); sessionStatus.setComplete(); request.setAttribute("formId", formId); request.setAttribute("administratorEmail", getAdministratorEmail()); return view; }
From source file:ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.java
private int validateConceptForStorage(TermConcept theConcept, TermCodeSystemVersion theCodeSystem, ArrayList<String> theConceptsStack, IdentityHashMap<TermConcept, Object> theAllConcepts) { ValidateUtil.isTrueOrThrowInvalidRequest(theConcept.getCodeSystem() != null, "CodesystemValue is null"); ValidateUtil.isTrueOrThrowInvalidRequest(theConcept.getCodeSystem() == theCodeSystem, "CodeSystems are not equal"); ValidateUtil.isNotBlankOrThrowInvalidRequest(theConcept.getCode(), "Codesystem contains a code with no code value"); if (theConceptsStack.contains(theConcept.getCode())) { throw new InvalidRequestException( "CodeSystem contains circular reference around code " + theConcept.getCode()); }/* w w w. j av a 2 s . c om*/ theConceptsStack.add(theConcept.getCode()); int retVal = 0; if (theAllConcepts.put(theConcept, theAllConcepts) == null) { if (theAllConcepts.size() % 1000 == 0) { ourLog.info("Have validated {} concepts", theAllConcepts.size()); } retVal = 1; } for (TermConceptParentChildLink next : theConcept.getChildren()) { next.setCodeSystem(theCodeSystem); retVal += validateConceptForStorage(next.getChild(), theCodeSystem, theConceptsStack, theAllConcepts); } theConceptsStack.remove(theConceptsStack.size() - 1); return retVal; }
From source file:cdr.forms.FormController.java
@RequestMapping(value = "/supplemental", method = { RequestMethod.POST, RequestMethod.GET }) public String collectSupplementalObjects(@Valid @ModelAttribute("deposit") Deposit deposit, BindingResult errors, SessionStatus sessionStatus, @RequestParam(value = "added", required = false) DepositFile[] addedDepositFiles, @RequestParam(value = "deposit", required = false) String submitDepositAction, HttpServletRequest request, HttpServletResponse response) { request.setAttribute("formattedMaxUploadSize", (getMaxUploadSize() / 1000000) + "MB"); request.setAttribute("maxUploadSize", getMaxUploadSize()); // Validate request and ensure character encoding is set this.getAuthorizationHandler().checkPermission(deposit.getFormId(), deposit.getForm(), request); try {// w w w. j av a 2 s. c om request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { LOG.error("Failed to set character encoding", e); } // Update supplemental objects Iterator<SupplementalObject> iterator = deposit.getSupplementalObjects().iterator(); while (iterator.hasNext()) { SupplementalObject file = iterator.next(); if (file == null) iterator.remove(); } if (addedDepositFiles != null) { for (DepositFile depositFile : addedDepositFiles) { if (depositFile != null) { depositFile.setExternal(true); SupplementalObject object = new SupplementalObject(); object.setDepositFile(depositFile); deposit.getSupplementalObjects().add(object); } } } Collections.sort(deposit.getSupplementalObjects(), new Comparator<SupplementalObject>() { public int compare(SupplementalObject sf1, SupplementalObject sf2) { return sf1.getDepositFile().getFilename().compareTo(sf2.getDepositFile().getFilename()); } }); // Check the deposit's files for virus signatures IdentityHashMap<DepositFile, String> signatures = new IdentityHashMap<DepositFile, String>(); for (DepositFile depositFile : deposit.getAllFiles()) scanDepositFile(depositFile, signatures); // Validate supplemental objects if (submitDepositAction != null) { Validator validator = new SupplementalObjectValidator(); int i = 0; for (SupplementalObject object : deposit.getSupplementalObjects()) { errors.pushNestedPath("supplementalObjects[" + i + "]"); validator.validate(object, errors); errors.popNestedPath(); i++; } } // Handle viruses, validation errors, and the deposit not having been finally submitted request.setAttribute("formId", deposit.getFormId()); request.setAttribute("administratorEmail", getAdministratorEmail()); if (signatures.size() > 0) { request.setAttribute("signatures", signatures); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); deposit.deleteAllFiles(true); sessionStatus.setComplete(); return "virus"; } if (errors.hasErrors()) { return "supplemental"; } if (submitDepositAction == null) { return "supplemental"; } // Try to deposit DepositResult result = this.getDepositHandler().deposit(deposit); if (result.getStatus() == Status.FAILED) { LOG.error("deposit failed"); if (getNotificationHandler() != null) { getNotificationHandler().notifyError(deposit, result); } response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); deposit.deleteAllFiles(true); sessionStatus.setComplete(); return "failed"; } else { if (getNotificationHandler() != null) { getNotificationHandler().notifyDeposit(deposit, result); } deposit.deleteAllFiles(false); sessionStatus.setComplete(); return "success"; } }
From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
public void testKeysConflict() { IdentityHashMap hashMap = new IdentityHashMap(); hashMap.put(STRING_ZERO_KEY, STRING_ZERO_VALUE); hashMap.put(INTEGER_ZERO_KEY, INTEGER_ZERO_VALUE); hashMap.put(ODD_ZERO_KEY, ODD_ZERO_VALUE); assertEquals(hashMap.get(INTEGER_ZERO_KEY), INTEGER_ZERO_VALUE); assertEquals(hashMap.get(ODD_ZERO_KEY), ODD_ZERO_VALUE); assertEquals(hashMap.get(STRING_ZERO_KEY), STRING_ZERO_VALUE); hashMap.remove(INTEGER_ZERO_KEY);/* w w w . j a va2 s. c o m*/ assertEquals(hashMap.get(ODD_ZERO_KEY), ODD_ZERO_VALUE); assertEquals(hashMap.get(STRING_ZERO_KEY), STRING_ZERO_VALUE); assertEquals(hashMap.get(INTEGER_ZERO_KEY), null); hashMap.remove(ODD_ZERO_KEY); assertEquals(hashMap.get(INTEGER_ZERO_KEY), null); assertEquals(hashMap.get(ODD_ZERO_KEY), null); assertEquals(hashMap.get(STRING_ZERO_KEY), STRING_ZERO_VALUE); hashMap.remove(STRING_ZERO_KEY); assertEquals(hashMap.get(INTEGER_ZERO_KEY), null); assertEquals(hashMap.get(ODD_ZERO_KEY), null); assertEquals(hashMap.get(STRING_ZERO_KEY), null); assertEquals(hashMap.size(), 0); }
From source file:org.apache.kylin.storage.cache.DynamicCacheTest.java
@Test public void basicTest() { final StorageContext context = new StorageContext(); final List<TblColRef> groups = StorageMockUtils.buildGroups(); final TblColRef partitionCol = groups.get(0); final List<FunctionDesc> aggregations = StorageMockUtils.buildAggregations(); final TupleInfo tupleInfo = StorageMockUtils.newTupleInfo(groups, aggregations); SQLDigest sqlDigest = new SQLDigest("default.test_kylin_fact", null, null, Lists.<TblColRef>newArrayList(), groups, Lists.newArrayList(partitionCol), Lists.<TblColRef>newArrayList(), aggregations, new ArrayList<MeasureDesc>(), new ArrayList<SQLDigest.OrderEnum>()); ITuple aTuple = new TsOnlyTuple(partitionCol, "2011-02-01"); ITuple bTuple = new TsOnlyTuple(partitionCol, "2012-02-01"); final List<ITuple> allTuples = Lists.newArrayList(aTuple, bTuple); //counts for verifying final AtomicInteger underlyingSEHitCount = new AtomicInteger(0); final List<Integer> returnedRowPerSearch = Lists.newArrayList(); CacheFledgedDynamicQuery dynamicCache = new CacheFledgedDynamicQuery(new ICachableStorageQuery() { @Override/*from w w w . j av a 2 s . c o m*/ public ITupleIterator search(StorageContext context, SQLDigest sqlDigest, TupleInfo returnTupleInfo) { Range<Long> tsRagneInQuery = TsConditionExtractor.extractTsCondition(partitionCol, sqlDigest.filter); List<ITuple> ret = Lists.newArrayList(); for (ITuple tuple : allTuples) { if (tsRagneInQuery.contains(Tuple.getTs(tuple, partitionCol))) { ret.add(tuple); } } underlyingSEHitCount.incrementAndGet(); returnedRowPerSearch.add(ret.size()); return new SimpleTupleIterator(ret.iterator()); } @Override public boolean isDynamic() { return true; } @Override public Range<Long> getVolatilePeriod() { return Ranges.greaterThan(DateFormat.stringToMillis("2011-02-01")); } @Override public String getStorageUUID() { return "111ca32a-a33e-4b69-12aa-0bb8b1f8c191"; } }, partitionCol); sqlDigest.filter = StorageMockUtils.buildTs2010Filter(groups.get(0)); ITupleIterator firstIterator = dynamicCache.search(context, sqlDigest, tupleInfo); IdentityHashMap<ITuple, Void> firstResults = new IdentityHashMap<>(); while (firstIterator.hasNext()) { firstResults.put(firstIterator.next(), null); } firstIterator.close(); sqlDigest.filter = StorageMockUtils.buildTs2011Filter(groups.get(0)); ITupleIterator secondIterator = dynamicCache.search(context, sqlDigest, tupleInfo); IdentityHashMap<ITuple, Void> secondResults = new IdentityHashMap<>(); while (secondIterator.hasNext()) { secondResults.put(secondIterator.next(), null); } secondIterator.close(); Assert.assertEquals(2, firstResults.size()); IdentityUtils.collectionReferenceEquals(firstResults.keySet(), secondResults.keySet()); Assert.assertEquals(2, underlyingSEHitCount.get()); Assert.assertEquals(new Integer(2), returnedRowPerSearch.get(0)); Assert.assertEquals(new Integer(1), returnedRowPerSearch.get(1)); }
From source file:org.apache.solr.handler.component.StatsField.java
/** * Computes a base {@link DocSet} for the current request to be used * when computing global stats for the local index. * * This is typically the same as the main DocSet for the {@link ResponseBuilder} * unless {@link CommonParams#TAG tag}ged filter queries have been excluded using * the {@link CommonParams#EXCLUDE ex} local param *//*from www.j a va 2 s . c om*/ public DocSet computeBaseDocSet() throws IOException { DocSet docs = rb.getResults().docSet; Map<?, ?> tagMap = (Map<?, ?>) rb.req.getContext().get("tags"); if (excludeTagList.isEmpty() || null == tagMap) { // either the exclude list is empty, or there // aren't any tagged filters to exclude anyway. return docs; } IdentityHashMap<Query, Boolean> excludeSet = new IdentityHashMap<Query, Boolean>(); for (String excludeTag : excludeTagList) { Object olst = tagMap.get(excludeTag); // tagMap has entries of List<String,List<QParser>>, but subject to change in the future if (!(olst instanceof Collection)) continue; for (Object o : (Collection<?>) olst) { if (!(o instanceof QParser)) continue; QParser qp = (QParser) o; try { excludeSet.put(qp.getQuery(), Boolean.TRUE); } catch (SyntaxError e) { // this shouldn't be possible since the request should have already // failed when attempting to execute the query, but just in case... throw new SolrException(ErrorCode.BAD_REQUEST, "Excluded query can't be parsed: " + originalParam + " due to: " + e.getMessage(), e); } } } if (excludeSet.size() == 0) return docs; List<Query> qlist = new ArrayList<Query>(); // add the base query if (!excludeSet.containsKey(rb.getQuery())) { qlist.add(rb.getQuery()); } // add the filters if (rb.getFilters() != null) { for (Query q : rb.getFilters()) { if (!excludeSet.containsKey(q)) { qlist.add(q); } } } // get the new base docset for this facet return searcher.getDocSet(qlist); }
From source file:org.apache.solr.request.SimpleFacets.java
License:asdf
protected DocSet computeDocSet(DocSet baseDocSet, List<String> excludeTagList) throws SyntaxError, IOException { Map<?, ?> tagMap = (Map<?, ?>) req.getContext().get("tags"); // rb can be null if facets are being calculated from a RequestHandler e.g. MoreLikeThisHandler if (tagMap == null || rb == null) { return baseDocSet; }// www. ja v a 2s .c o m IdentityHashMap<Query, Boolean> excludeSet = new IdentityHashMap<>(); for (String excludeTag : excludeTagList) { Object olst = tagMap.get(excludeTag); // tagMap has entries of List<String,List<QParser>>, but subject to change in the future if (!(olst instanceof Collection)) continue; for (Object o : (Collection<?>) olst) { if (!(o instanceof QParser)) continue; QParser qp = (QParser) o; excludeSet.put(qp.getQuery(), Boolean.TRUE); } } if (excludeSet.size() == 0) return baseDocSet; List<Query> qlist = new ArrayList<>(); // add the base query if (!excludeSet.containsKey(rb.getQuery())) { qlist.add(rb.getQuery()); } // add the filters if (rb.getFilters() != null) { for (Query q : rb.getFilters()) { if (!excludeSet.containsKey(q)) { qlist.add(q); } } } // get the new base docset for this facet DocSet base = searcher.getDocSet(qlist); if (rb.grouping() && rb.getGroupingSpec().isTruncateGroups()) { Grouping grouping = new Grouping(searcher, null, rb.getQueryCommand(), false, 0, false); grouping.setWithinGroupSort(rb.getGroupingSpec().getSortWithinGroup()); if (rb.getGroupingSpec().getFields().length > 0) { grouping.addFieldCommand(rb.getGroupingSpec().getFields()[0], req); } else if (rb.getGroupingSpec().getFunctions().length > 0) { grouping.addFunctionCommand(rb.getGroupingSpec().getFunctions()[0], req); } else { return base; } AllGroupHeadsCollector allGroupHeadsCollector = grouping.getCommands().get(0).createAllGroupCollector(); searcher.search(base.getTopFilter(), allGroupHeadsCollector); return new BitDocSet(allGroupHeadsCollector.retrieveGroupHeads(searcher.maxDoc())); } else { return base; } }
From source file:org.lilyproject.process.test.DecoratorTest.java
@Test public void test() throws Exception { LilyProxy lilyProxy = createLilyProxy(); LilyClient client = lilyProxy.getLilyServerProxy().getClient(); RepositoryModelImpl repositoryModel = new RepositoryModelImpl( lilyProxy.getLilyServerProxy().getZooKeeper()); repositoryModel.create("repo1"); assertTrue(repositoryModel.waitUntilRepositoryInState("repo1", RepositoryLifecycleState.ACTIVE, 60000L)); repositoryModel.create("repo2"); assertTrue(repositoryModel.waitUntilRepositoryInState("repo2", RepositoryLifecycleState.ACTIVE, 60000L)); repositoryModel.close();//from ww w . ja va 2 s .com // Make a schema TypeManager typeMgr = client.getDefaultRepository().getTypeManager(); QName field1 = new QName("ns", "f1"); FieldType fieldType1 = typeMgr.newFieldType(typeMgr.getValueType("STRING"), field1, Scope.NON_VERSIONED); fieldType1 = typeMgr.createFieldType(fieldType1); QName field2 = new QName("ns", "f2"); FieldType fieldType2 = typeMgr.newFieldType(typeMgr.getValueType("STRING"), field2, Scope.NON_VERSIONED); fieldType2 = typeMgr.createFieldType(fieldType2); QName typeName = new QName("ns", "rt1"); RecordType recordType = typeMgr.newRecordType(typeName); recordType.addFieldTypeEntry(fieldType1.getId(), false); recordType.addFieldTypeEntry(fieldType2.getId(), false); recordType = typeMgr.createRecordType(recordType); DecoratingRepositoryManager repositoryMgr = (DecoratingRepositoryManager) lilyProxy.getLilyServerProxy() .getLilyServerTestingUtility().getRuntime().getModuleById("repository").getApplicationContext() .getBean("repositoryManager"); IdentityHashMap<Object, Object> chains = new IdentityHashMap<Object, Object>(); // Test the decorator is applied for each repository and each table for (String repositoryName : new String[] { "default", "repo1", "repo2" }) { LRepository repository = client.getRepository(repositoryName); repository.getTableManager().createTable("table1"); repository.getTableManager().createTable("table2"); for (String tableName : new String[] { "record", "table1", "table2" }) { LTable table = repository.getTable(tableName); Record record = table.newRecord(); record.setRecordType(typeName); record.setField(field1, "foobar"); record = table.create(record); assertEquals("foo", record.getField(field2)); assertEquals("foo", table.read(record.getId()).getField(field2)); // Test we can get access to our test decorator: this is something that is occasionally useful // in test cases to check certain conditions, e.g. if the decorator would have async side effects. RepositoryDecoratorChain chain = repositoryMgr.getRepositoryDecoratorChain(repositoryName, tableName); assertNotNull(chain); assertNotNull(chain.getDecorator(TestRepositoryDecoratorFactory.NAME)); chains.put(chain.getDecorator(TestRepositoryDecoratorFactory.NAME), null); assertEquals(2, chain.getEntries().size()); } } // There should be one instance of the decorator created for each repository-table combination (that // was accessed) assertEquals(3 * 3, chains.size()); // Check that if we ask the same table twice, we get the same instance (verifies cache works) assertTrue(client.getRepository("repo1").getTable("table1") == client.getRepository("repo1") .getTable("table1")); lilyProxy.stop(); // Check each of the decorators was properly closed assertEquals(9, TestRepositoryDecoratorFactory.CLOSE_COUNT.get()); }