List of usage examples for java.util IdentityHashMap put
public V put(K key, V value)
From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
public void testEntrySet() { IdentityHashMap hashMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(hashMap); Set entrySet = hashMap.entrySet(); assertNotNull(entrySet);//from w w w . j av a 2s . c o m // Check that the entry set looks right hashMap.put(KEY_TEST_ENTRY_SET, VALUE_TEST_ENTRY_SET_1); entrySet = hashMap.entrySet(); assertEquals(entrySet.size(), SIZE_ONE); Iterator itSet = entrySet.iterator(); Map.Entry entry = (Map.Entry) itSet.next(); assertEquals(entry.getKey(), KEY_TEST_ENTRY_SET); assertEquals(entry.getValue(), VALUE_TEST_ENTRY_SET_1); // Check that entries in the entrySet are update correctly on overwrites hashMap.put(KEY_TEST_ENTRY_SET, VALUE_TEST_ENTRY_SET_2); entrySet = hashMap.entrySet(); assertEquals(entrySet.size(), SIZE_ONE); itSet = entrySet.iterator(); entry = (Map.Entry) itSet.next(); assertEquals(entry.getKey(), KEY_TEST_ENTRY_SET); assertEquals(entry.getValue(), VALUE_TEST_ENTRY_SET_2); // Check that entries are updated on removes hashMap.remove(KEY_TEST_ENTRY_SET); checkEmptyHashMapAssumptions(hashMap); }
From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
public void testKeySet() { IdentityHashMap hashMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(hashMap); Set keySet = hashMap.keySet(); assertNotNull(keySet);/*from w w w . ja v a 2 s. co m*/ assertTrue(keySet.isEmpty()); assertTrue(keySet.size() == 0); hashMap.put(KEY_TEST_KEY_SET, VALUE_TEST_KEY_SET); assertTrue(keySet.size() == SIZE_ONE); assertTrue(keySet.contains(KEY_TEST_KEY_SET)); assertFalse(keySet.contains(VALUE_TEST_KEY_SET)); assertFalse(keySet.contains(KEY_TEST_KEY_SET.toUpperCase(Locale.ROOT))); }
From source file:ca.uhn.fhir.util.FhirTerser.java
private void visit(IdentityHashMap<Object, Object> theStack, IBaseResource theResource, IBase theElement, List<String> thePathToElement, BaseRuntimeChildDefinition theChildDefinition, BaseRuntimeElementDefinition<?> theDefinition, IModelVisitor theCallback) { List<String> pathToElement = addNameToList(thePathToElement, theChildDefinition); if (theStack.put(theElement, theElement) != null) { return;//from ww w . j av a2 s. c om } theCallback.acceptElement(theResource, theElement, pathToElement, theChildDefinition, theDefinition); BaseRuntimeElementDefinition<?> def = theDefinition; if (def.getChildType() == ChildTypeEnum.CONTAINED_RESOURCE_LIST) { def = myContext.getElementDefinition(theElement.getClass()); } if (theElement instanceof IBaseReference) { IBaseResource target = ((IBaseReference) theElement).getResource(); if (target != null) { if (target.getIdElement().hasIdPart() == false || target.getIdElement().isLocal()) { RuntimeResourceDefinition targetDef = myContext.getResourceDefinition(target); visit(theStack, target, target, pathToElement, null, targetDef, theCallback); } } } switch (def.getChildType()) { case ID_DATATYPE: case PRIMITIVE_XHTML_HL7ORG: case PRIMITIVE_XHTML: case PRIMITIVE_DATATYPE: // These are primitive types break; case RESOURCE: case RESOURCE_BLOCK: case COMPOSITE_DATATYPE: { BaseRuntimeElementCompositeDefinition<?> childDef = (BaseRuntimeElementCompositeDefinition<?>) def; for (BaseRuntimeChildDefinition nextChild : childDef.getChildrenAndExtension()) { List<?> values = nextChild.getAccessor().getValues(theElement); if (values != null) { for (Object nextValueObject : values) { IBase nextValue; try { nextValue = (IBase) nextValueObject; } catch (ClassCastException e) { String s = "Found instance of " + nextValueObject.getClass() + " - Did you set a field value to the incorrect type? Expected " + IBase.class.getName(); throw new ClassCastException(s); } if (nextValue == null) { continue; } if (nextValue.isEmpty()) { continue; } BaseRuntimeElementDefinition<?> childElementDef; childElementDef = nextChild.getChildElementDefinitionByDatatype(nextValue.getClass()); if (childElementDef == null) { childElementDef = myContext.getElementDefinition(nextValue.getClass()); } if (nextChild instanceof RuntimeChildDirectResource) { // Don't descend into embedded resources theCallback.acceptElement(theResource, nextValue, null, nextChild, childElementDef); } else { visit(theStack, theResource, nextValue, pathToElement, nextChild, childElementDef, theCallback); } } } } break; } case CONTAINED_RESOURCES: { BaseContainedDt value = (BaseContainedDt) theElement; for (IResource next : value.getContainedResources()) { def = myContext.getResourceDefinition(next); visit(theStack, next, next, pathToElement, null, def, theCallback); } break; } case CONTAINED_RESOURCE_LIST: case EXTENSION_DECLARED: case UNDECL_EXT: { throw new IllegalStateException("state should not happen: " + def.getChildType()); } } theStack.remove(theElement); }
From source file:ca.uhn.fhir.jpa.dao.FhirSystemDaoDstu2.java
@SuppressWarnings("unchecked") private Bundle transaction(ServletRequestDetails theRequestDetails, Bundle theRequest, String theActionName) { BundleTypeEnum transactionType = theRequest.getTypeElement().getValueAsEnum(); if (transactionType == BundleTypeEnum.BATCH) { return batch(theRequestDetails, theRequest); }// w w w . ja va 2 s . c o m if (transactionType == null) { String message = "Transactiion Bundle did not specify valid Bundle.type, assuming " + BundleTypeEnum.TRANSACTION.getCode(); ourLog.warn(message); transactionType = BundleTypeEnum.TRANSACTION; } if (transactionType != BundleTypeEnum.TRANSACTION) { throw new InvalidRequestException( "Unable to process transaction where incoming Bundle.type = " + transactionType.getCode()); } ourLog.info("Beginning {} with {} resources", theActionName, theRequest.getEntry().size()); long start = System.currentTimeMillis(); Date updateTime = new Date(); Set<IdDt> allIds = new LinkedHashSet<IdDt>(); Map<IdDt, IdDt> idSubstitutions = new HashMap<IdDt, IdDt>(); Map<IdDt, DaoMethodOutcome> idToPersistedOutcome = new HashMap<IdDt, DaoMethodOutcome>(); /* * We want to execute the transaction request bundle elements in the order * specified by the FHIR specification (see TransactionSorter) so we save the * original order in the request, then sort it. * * Entries with a type of GET are removed from the bundle so that they * can be processed at the very end. We do this because the incoming resources * are saved in a two-phase way in order to deal with interdependencies, and * we want the GET processing to use the final indexing state */ Bundle response = new Bundle(); List<Entry> getEntries = new ArrayList<Entry>(); IdentityHashMap<Entry, Integer> originalRequestOrder = new IdentityHashMap<Bundle.Entry, Integer>(); for (int i = 0; i < theRequest.getEntry().size(); i++) { originalRequestOrder.put(theRequest.getEntry().get(i), i); response.addEntry(); if (theRequest.getEntry().get(i).getRequest().getMethodElement().getValueAsEnum() == HTTPVerbEnum.GET) { getEntries.add(theRequest.getEntry().get(i)); } } Collections.sort(theRequest.getEntry(), new TransactionSorter()); List<IIdType> deletedResources = new ArrayList<IIdType>(); List<DeleteConflict> deleteConflicts = new ArrayList<DeleteConflict>(); Map<Entry, ResourceTable> entriesToProcess = new IdentityHashMap<Entry, ResourceTable>(); Set<ResourceTable> nonUpdatedEntities = new HashSet<ResourceTable>(); /* * Loop through the request and process any entries of type * PUT, POST or DELETE */ for (int i = 0; i < theRequest.getEntry().size(); i++) { if (i % 100 == 0) { ourLog.info("Processed {} non-GET entries out of {}", i, theRequest.getEntry().size()); } Entry nextReqEntry = theRequest.getEntry().get(i); IResource res = nextReqEntry.getResource(); IdDt nextResourceId = null; if (res != null) { nextResourceId = res.getId(); if (nextResourceId.hasIdPart() == false) { if (isNotBlank(nextReqEntry.getFullUrl())) { nextResourceId = new IdDt(nextReqEntry.getFullUrl()); } } if (nextResourceId.hasIdPart() && nextResourceId.getIdPart().matches("[a-zA-Z]+\\:.*") && !isPlaceholder(nextResourceId)) { throw new InvalidRequestException("Invalid placeholder ID found: " + nextResourceId.getIdPart() + " - Must be of the form 'urn:uuid:[uuid]' or 'urn:oid:[oid]'"); } if (nextResourceId.hasIdPart() && !nextResourceId.hasResourceType() && !isPlaceholder(nextResourceId)) { nextResourceId = new IdDt(toResourceName(res.getClass()), nextResourceId.getIdPart()); res.setId(nextResourceId); } /* * Ensure that the bundle doesn't have any duplicates, since this causes all kinds of weirdness */ if (isPlaceholder(nextResourceId)) { if (!allIds.add(nextResourceId)) { throw new InvalidRequestException( getContext().getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionContainsMultipleWithDuplicateId", nextResourceId)); } } else if (nextResourceId.hasResourceType() && nextResourceId.hasIdPart()) { IdDt nextId = nextResourceId.toUnqualifiedVersionless(); if (!allIds.add(nextId)) { throw new InvalidRequestException(getContext().getLocalizer().getMessage( BaseHapiFhirSystemDao.class, "transactionContainsMultipleWithDuplicateId", nextId)); } } } HTTPVerbEnum verb = nextReqEntry.getRequest().getMethodElement().getValueAsEnum(); if (verb == null) { throw new InvalidRequestException( getContext().getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionEntryHasInvalidVerb", nextReqEntry.getRequest().getMethod())); } String resourceType = res != null ? getContext().getResourceDefinition(res).getName() : null; Entry nextRespEntry = response.getEntry().get(originalRequestOrder.get(nextReqEntry)); switch (verb) { case POST: { // CREATE @SuppressWarnings("rawtypes") IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass()); res.setId((String) null); DaoMethodOutcome outcome; outcome = resourceDao.create(res, nextReqEntry.getRequest().getIfNoneExist(), false, theRequestDetails); handleTransactionCreateOrUpdateOutcome(idSubstitutions, idToPersistedOutcome, nextResourceId, outcome, nextRespEntry, resourceType, res); entriesToProcess.put(nextRespEntry, outcome.getEntity()); if (outcome.getCreated() == false) { nonUpdatedEntities.add(outcome.getEntity()); } break; } case DELETE: { // DELETE String url = extractTransactionUrlOrThrowException(nextReqEntry, verb); UrlParts parts = UrlUtil.parseUrl(url); ca.uhn.fhir.jpa.dao.IFhirResourceDao<? extends IBaseResource> dao = toDao(parts, verb.getCode(), url); int status = Constants.STATUS_HTTP_204_NO_CONTENT; if (parts.getResourceId() != null) { ResourceTable deleted = dao.delete(new IdDt(parts.getResourceType(), parts.getResourceId()), deleteConflicts, theRequestDetails); if (deleted != null) { deletedResources.add(deleted.getIdDt().toUnqualifiedVersionless()); } } else { List<ResourceTable> allDeleted = dao.deleteByUrl( parts.getResourceType() + '?' + parts.getParams(), deleteConflicts, theRequestDetails); for (ResourceTable deleted : allDeleted) { deletedResources.add(deleted.getIdDt().toUnqualifiedVersionless()); } if (allDeleted.isEmpty()) { status = Constants.STATUS_HTTP_404_NOT_FOUND; } } nextRespEntry.getResponse().setStatus(toStatusString(status)); break; } case PUT: { // UPDATE @SuppressWarnings("rawtypes") IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass()); DaoMethodOutcome outcome; String url = extractTransactionUrlOrThrowException(nextReqEntry, verb); UrlParts parts = UrlUtil.parseUrl(url); if (isNotBlank(parts.getResourceId())) { res.setId(new IdDt(parts.getResourceType(), parts.getResourceId())); outcome = resourceDao.update(res, null, false, theRequestDetails); } else { res.setId((String) null); outcome = resourceDao.update(res, parts.getResourceType() + '?' + parts.getParams(), false, theRequestDetails); } handleTransactionCreateOrUpdateOutcome(idSubstitutions, idToPersistedOutcome, nextResourceId, outcome, nextRespEntry, resourceType, res); entriesToProcess.put(nextRespEntry, outcome.getEntity()); break; } } } /* * Make sure that there are no conflicts from deletions. E.g. we can't delete something * if something else has a reference to it.. Unless the thing that has a reference to it * was also deleted as a part of this transaction, which is why we check this now at the * end. */ for (Iterator<DeleteConflict> iter = deleteConflicts.iterator(); iter.hasNext();) { DeleteConflict next = iter.next(); if (deletedResources.contains(next.getTargetId().toVersionless())) { iter.remove(); } } validateDeleteConflictsEmptyOrThrowException(deleteConflicts); /* * Perform ID substitutions and then index each resource we have saved */ FhirTerser terser = getContext().newTerser(); for (DaoMethodOutcome nextOutcome : idToPersistedOutcome.values()) { IResource nextResource = (IResource) nextOutcome.getResource(); if (nextResource == null) { continue; } List<BaseResourceReferenceDt> allRefs = terser.getAllPopulatedChildElementsOfType(nextResource, BaseResourceReferenceDt.class); for (BaseResourceReferenceDt nextRef : allRefs) { IdDt nextId = nextRef.getReference(); if (!nextId.hasIdPart()) { continue; } if (idSubstitutions.containsKey(nextId)) { IdDt newId = idSubstitutions.get(nextId); ourLog.info(" * Replacing resource ref {} with {}", nextId, newId); nextRef.setReference(newId); } else { ourLog.debug(" * Reference [{}] does not exist in bundle", nextId); } } InstantDt deletedInstantOrNull = ResourceMetadataKeyEnum.DELETED_AT.get(nextResource); Date deletedTimestampOrNull = deletedInstantOrNull != null ? deletedInstantOrNull.getValue() : null; boolean shouldUpdate = !nonUpdatedEntities.contains(nextOutcome.getEntity()); updateEntity(nextResource, nextOutcome.getEntity(), deletedTimestampOrNull, true, shouldUpdate, updateTime); } myEntityManager.flush(); /* * Double check we didn't allow any duplicates we shouldn't have */ for (Entry nextEntry : theRequest.getEntry()) { if (nextEntry.getRequest().getMethodElement().getValueAsEnum() == HTTPVerbEnum.POST) { String matchUrl = nextEntry.getRequest().getIfNoneExist(); if (isNotBlank(matchUrl)) { IFhirResourceDao<?> resourceDao = getDao(nextEntry.getResource().getClass()); Set<Long> val = resourceDao.processMatchUrl(matchUrl); if (val.size() > 1) { throw new InvalidRequestException("Unable to process " + theActionName + " - Request would cause multiple resources to match URL: \"" + matchUrl + "\". Does transaction request contain duplicates?"); } } } } for (IdDt next : allIds) { IdDt replacement = idSubstitutions.get(next); if (replacement == null) { continue; } if (replacement.equals(next)) { continue; } ourLog.info("Placeholder resource ID \"{}\" was replaced with permanent ID \"{}\"", next, replacement); } /* * Loop through the request and process any entries of type GET */ for (int i = 0; i < getEntries.size(); i++) { Entry nextReqEntry = getEntries.get(i); Integer originalOrder = originalRequestOrder.get(nextReqEntry); Entry nextRespEntry = response.getEntry().get(originalOrder); ServletSubRequestDetails requestDetails = new ServletSubRequestDetails(); requestDetails.setServletRequest(theRequestDetails.getServletRequest()); requestDetails.setRequestType(RequestTypeEnum.GET); requestDetails.setServer(theRequestDetails.getServer()); String url = extractTransactionUrlOrThrowException(nextReqEntry, HTTPVerbEnum.GET); int qIndex = url.indexOf('?'); ArrayListMultimap<String, String> paramValues = ArrayListMultimap.create(); requestDetails.setParameters(new HashMap<String, String[]>()); if (qIndex != -1) { String params = url.substring(qIndex); List<NameValuePair> parameters = translateMatchUrl(params); for (NameValuePair next : parameters) { paramValues.put(next.getName(), next.getValue()); } for (java.util.Map.Entry<String, Collection<String>> nextParamEntry : paramValues.asMap() .entrySet()) { String[] nextValue = nextParamEntry.getValue() .toArray(new String[nextParamEntry.getValue().size()]); requestDetails.getParameters().put(nextParamEntry.getKey(), nextValue); } url = url.substring(0, qIndex); } requestDetails.setRequestPath(url); requestDetails.setFhirServerBase(theRequestDetails.getFhirServerBase()); theRequestDetails.getServer().populateRequestDetailsFromRequestPath(requestDetails, url); BaseMethodBinding<?> method = theRequestDetails.getServer().determineResourceMethod(requestDetails, url); if (method == null) { throw new IllegalArgumentException("Unable to handle GET " + url); } if (isNotBlank(nextReqEntry.getRequest().getIfMatch())) { requestDetails.addHeader(Constants.HEADER_IF_MATCH, nextReqEntry.getRequest().getIfMatch()); } if (isNotBlank(nextReqEntry.getRequest().getIfNoneExist())) { requestDetails.addHeader(Constants.HEADER_IF_NONE_EXIST, nextReqEntry.getRequest().getIfNoneExist()); } if (isNotBlank(nextReqEntry.getRequest().getIfNoneMatch())) { requestDetails.addHeader(Constants.HEADER_IF_NONE_MATCH, nextReqEntry.getRequest().getIfNoneMatch()); } if (method instanceof BaseResourceReturningMethodBinding) { try { ResourceOrDstu1Bundle responseData = ((BaseResourceReturningMethodBinding) method) .doInvokeServer(theRequestDetails.getServer(), requestDetails); IBaseResource resource = responseData.getResource(); if (paramValues.containsKey(Constants.PARAM_SUMMARY) || paramValues.containsKey(Constants.PARAM_CONTENT)) { resource = filterNestedBundle(requestDetails, resource); } nextRespEntry.setResource((IResource) resource); nextRespEntry.getResponse().setStatus(toStatusString(Constants.STATUS_HTTP_200_OK)); } catch (NotModifiedException e) { nextRespEntry.getResponse().setStatus(toStatusString(Constants.STATUS_HTTP_304_NOT_MODIFIED)); } } else { throw new IllegalArgumentException("Unable to handle GET " + url); } } ourLog.info("Flushing context after {}", theActionName); myEntityManager.flush(); for (java.util.Map.Entry<Entry, ResourceTable> nextEntry : entriesToProcess.entrySet()) { nextEntry.getKey().getResponse().setLocation(nextEntry.getValue().getIdDt().toUnqualified().getValue()); nextEntry.getKey().getResponse().setEtag(nextEntry.getValue().getIdDt().getVersionIdPart()); } long delay = System.currentTimeMillis() - start; int numEntries = theRequest.getEntry().size(); long delayPer = delay / numEntries; ourLog.info("{} completed in {}ms ({} entries at {}ms per entry)", new Object[] { theActionName, delay, numEntries, delayPer }); response.setType(BundleTypeEnum.TRANSACTION_RESPONSE); return response; }
From source file:ca.uhn.fhir.jpa.dao.dstu3.FhirSystemDaoDstu3.java
@SuppressWarnings("unchecked") private Bundle transaction(ServletRequestDetails theRequestDetails, Bundle theRequest, String theActionName) { BundleType transactionType = theRequest.getTypeElement().getValue(); if (transactionType == BundleType.BATCH) { return batch(theRequestDetails, theRequest); }//from w w w .j a va2 s . com if (transactionType == null) { String message = "Transactiion Bundle did not specify valid Bundle.type, assuming " + BundleType.TRANSACTION.toCode(); ourLog.warn(message); transactionType = BundleType.TRANSACTION; } if (transactionType != BundleType.TRANSACTION) { throw new InvalidRequestException( "Unable to process transaction where incoming Bundle.type = " + transactionType.toCode()); } ourLog.info("Beginning {} with {} resources", theActionName, theRequest.getEntry().size()); long start = System.currentTimeMillis(); Date updateTime = new Date(); Set<IdType> allIds = new LinkedHashSet<IdType>(); Map<IdType, IdType> idSubstitutions = new HashMap<IdType, IdType>(); Map<IdType, DaoMethodOutcome> idToPersistedOutcome = new HashMap<IdType, DaoMethodOutcome>(); // Do all entries have a verb? for (int i = 0; i < theRequest.getEntry().size(); i++) { BundleEntryComponent nextReqEntry = theRequest.getEntry().get(i); HTTPVerb verb = nextReqEntry.getRequest().getMethodElement().getValue(); if (verb == null) { throw new InvalidRequestException( getContext().getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionEntryHasInvalidVerb", nextReqEntry.getRequest().getMethod(), i)); } } /* * We want to execute the transaction request bundle elements in the order * specified by the FHIR specification (see TransactionSorter) so we save the * original order in the request, then sort it. * * Entries with a type of GET are removed from the bundle so that they * can be processed at the very end. We do this because the incoming resources * are saved in a two-phase way in order to deal with interdependencies, and * we want the GET processing to use the final indexing state */ Bundle response = new Bundle(); List<BundleEntryComponent> getEntries = new ArrayList<BundleEntryComponent>(); IdentityHashMap<BundleEntryComponent, Integer> originalRequestOrder = new IdentityHashMap<Bundle.BundleEntryComponent, Integer>(); for (int i = 0; i < theRequest.getEntry().size(); i++) { originalRequestOrder.put(theRequest.getEntry().get(i), i); response.addEntry(); if (theRequest.getEntry().get(i).getRequest().getMethodElement().getValue() == HTTPVerb.GET) { getEntries.add(theRequest.getEntry().get(i)); } } Collections.sort(theRequest.getEntry(), new TransactionSorter()); Set<String> deletedResources = new HashSet<String>(); List<DeleteConflict> deleteConflicts = new ArrayList<DeleteConflict>(); Map<BundleEntryComponent, ResourceTable> entriesToProcess = new IdentityHashMap<BundleEntryComponent, ResourceTable>(); Set<ResourceTable> nonUpdatedEntities = new HashSet<ResourceTable>(); /* * Loop through the request and process any entries of type * PUT, POST or DELETE */ for (int i = 0; i < theRequest.getEntry().size(); i++) { if (i % 100 == 0) { ourLog.info("Processed {} non-GET entries out of {}", i, theRequest.getEntry().size()); } BundleEntryComponent nextReqEntry = theRequest.getEntry().get(i); Resource res = nextReqEntry.getResource(); IdType nextResourceId = null; if (res != null) { nextResourceId = res.getIdElement(); if (nextResourceId.hasIdPart() == false) { if (isNotBlank(nextReqEntry.getFullUrl())) { nextResourceId = new IdType(nextReqEntry.getFullUrl()); } } if (nextResourceId.hasIdPart() && nextResourceId.getIdPart().matches("[a-zA-Z]+\\:.*") && !isPlaceholder(nextResourceId)) { throw new InvalidRequestException("Invalid placeholder ID found: " + nextResourceId.getIdPart() + " - Must be of the form 'urn:uuid:[uuid]' or 'urn:oid:[oid]'"); } if (nextResourceId.hasIdPart() && !nextResourceId.hasResourceType() && !isPlaceholder(nextResourceId)) { nextResourceId = new IdType(toResourceName(res.getClass()), nextResourceId.getIdPart()); res.setId(nextResourceId); } /* * Ensure that the bundle doesn't have any duplicates, since this causes all kinds of weirdness */ if (isPlaceholder(nextResourceId)) { if (!allIds.add(nextResourceId)) { throw new InvalidRequestException( getContext().getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionContainsMultipleWithDuplicateId", nextResourceId)); } } else if (nextResourceId.hasResourceType() && nextResourceId.hasIdPart()) { IdType nextId = nextResourceId.toUnqualifiedVersionless(); if (!allIds.add(nextId)) { throw new InvalidRequestException(getContext().getLocalizer().getMessage( BaseHapiFhirSystemDao.class, "transactionContainsMultipleWithDuplicateId", nextId)); } } } HTTPVerb verb = nextReqEntry.getRequest().getMethodElement().getValue(); String resourceType = res != null ? getContext().getResourceDefinition(res).getName() : null; BundleEntryComponent nextRespEntry = response.getEntry().get(originalRequestOrder.get(nextReqEntry)); switch (verb) { case POST: { // CREATE @SuppressWarnings("rawtypes") IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass()); res.setId((String) null); DaoMethodOutcome outcome; outcome = resourceDao.create(res, nextReqEntry.getRequest().getIfNoneExist(), false, theRequestDetails); handleTransactionCreateOrUpdateOutcome(idSubstitutions, idToPersistedOutcome, nextResourceId, outcome, nextRespEntry, resourceType, res); entriesToProcess.put(nextRespEntry, outcome.getEntity()); if (outcome.getCreated() == false) { nonUpdatedEntities.add(outcome.getEntity()); } break; } case DELETE: { // DELETE String url = extractTransactionUrlOrThrowException(nextReqEntry, verb); UrlParts parts = UrlUtil.parseUrl(url); ca.uhn.fhir.jpa.dao.IFhirResourceDao<? extends IBaseResource> dao = toDao(parts, verb.toCode(), url); int status = Constants.STATUS_HTTP_204_NO_CONTENT; if (parts.getResourceId() != null) { IdType deleteId = new IdType(parts.getResourceType(), parts.getResourceId()); if (!deletedResources.contains(deleteId.getValueAsString())) { ResourceTable deleted = dao.delete(deleteId, deleteConflicts, theRequestDetails); if (deleted != null) { deletedResources.add(deleteId.getValueAsString()); } } } else { List<ResourceTable> allDeleted = dao.deleteByUrl( parts.getResourceType() + '?' + parts.getParams(), deleteConflicts, theRequestDetails); for (ResourceTable deleted : allDeleted) { deletedResources.add(deleted.getIdDt().toUnqualifiedVersionless().getValueAsString()); } if (allDeleted.isEmpty()) { status = Constants.STATUS_HTTP_204_NO_CONTENT; } } nextRespEntry.getResponse().setStatus(toStatusString(status)); break; } case PUT: { // UPDATE @SuppressWarnings("rawtypes") IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass()); String url = extractTransactionUrlOrThrowException(nextReqEntry, verb); DaoMethodOutcome outcome; UrlParts parts = UrlUtil.parseUrl(url); if (isNotBlank(parts.getResourceId())) { res.setId(new IdType(parts.getResourceType(), parts.getResourceId())); outcome = resourceDao.update(res, null, false, theRequestDetails); } else { res.setId((String) null); outcome = resourceDao.update(res, parts.getResourceType() + '?' + parts.getParams(), false, theRequestDetails); } handleTransactionCreateOrUpdateOutcome(idSubstitutions, idToPersistedOutcome, nextResourceId, outcome, nextRespEntry, resourceType, res); entriesToProcess.put(nextRespEntry, outcome.getEntity()); break; } } } /* * Make sure that there are no conflicts from deletions. E.g. we can't delete something * if something else has a reference to it.. Unless the thing that has a reference to it * was also deleted as a part of this transaction, which is why we check this now at the * end. */ for (Iterator<DeleteConflict> iter = deleteConflicts.iterator(); iter.hasNext();) { DeleteConflict next = iter.next(); if (deletedResources.contains(next.getTargetId().toUnqualifiedVersionless().getValue())) { iter.remove(); } } validateDeleteConflictsEmptyOrThrowException(deleteConflicts); /* * Perform ID substitutions and then index each resource we have saved */ FhirTerser terser = getContext().newTerser(); for (DaoMethodOutcome nextOutcome : idToPersistedOutcome.values()) { IBaseResource nextResource = nextOutcome.getResource(); if (nextResource == null) { continue; } List<IBaseReference> allRefs = terser.getAllPopulatedChildElementsOfType(nextResource, IBaseReference.class); for (IBaseReference nextRef : allRefs) { IIdType nextId = nextRef.getReferenceElement(); if (!nextId.hasIdPart()) { continue; } if (idSubstitutions.containsKey(nextId)) { IdType newId = idSubstitutions.get(nextId); ourLog.info(" * Replacing resource ref {} with {}", nextId, newId); nextRef.setReference(newId.getValue()); } else if (nextId.getValue().startsWith("urn:")) { throw new InvalidRequestException("Unable to satisfy placeholder ID: " + nextId.getValue()); } else { ourLog.debug(" * Reference [{}] does not exist in bundle", nextId); } } IPrimitiveType<Date> deletedInstantOrNull = ResourceMetadataKeyEnum.DELETED_AT .get((IAnyResource) nextResource); Date deletedTimestampOrNull = deletedInstantOrNull != null ? deletedInstantOrNull.getValue() : null; boolean shouldUpdate = !nonUpdatedEntities.contains(nextOutcome.getEntity()); updateEntity(nextResource, nextOutcome.getEntity(), deletedTimestampOrNull, shouldUpdate, shouldUpdate, updateTime); } myEntityManager.flush(); /* * Double check we didn't allow any duplicates we shouldn't have */ for (BundleEntryComponent nextEntry : theRequest.getEntry()) { if (nextEntry.getRequest().getMethodElement().getValue() == HTTPVerb.POST) { String matchUrl = nextEntry.getRequest().getIfNoneExist(); if (isNotBlank(matchUrl)) { IFhirResourceDao<?> resourceDao = getDao(nextEntry.getResource().getClass()); Set<Long> val = resourceDao.processMatchUrl(matchUrl); if (val.size() > 1) { throw new InvalidRequestException("Unable to process " + theActionName + " - Request would cause multiple resources to match URL: \"" + matchUrl + "\". Does transaction request contain duplicates?"); } } } } for (IdType next : allIds) { IdType replacement = idSubstitutions.get(next); if (replacement == null) { continue; } if (replacement.equals(next)) { continue; } ourLog.info("Placeholder resource ID \"{}\" was replaced with permanent ID \"{}\"", next, replacement); } /* * Loop through the request and process any entries of type GET */ for (int i = 0; i < getEntries.size(); i++) { BundleEntryComponent nextReqEntry = getEntries.get(i); Integer originalOrder = originalRequestOrder.get(nextReqEntry); BundleEntryComponent nextRespEntry = response.getEntry().get(originalOrder); ServletSubRequestDetails requestDetails = new ServletSubRequestDetails(); requestDetails.setServletRequest(theRequestDetails.getServletRequest()); requestDetails.setRequestType(RequestTypeEnum.GET); requestDetails.setServer(theRequestDetails.getServer()); String url = extractTransactionUrlOrThrowException(nextReqEntry, HTTPVerb.GET); int qIndex = url.indexOf('?'); ArrayListMultimap<String, String> paramValues = ArrayListMultimap.create(); requestDetails.setParameters(new HashMap<String, String[]>()); if (qIndex != -1) { String params = url.substring(qIndex); List<NameValuePair> parameters = translateMatchUrl(params); for (NameValuePair next : parameters) { paramValues.put(next.getName(), next.getValue()); } for (java.util.Map.Entry<String, Collection<String>> nextParamEntry : paramValues.asMap() .entrySet()) { String[] nextValue = nextParamEntry.getValue() .toArray(new String[nextParamEntry.getValue().size()]); requestDetails.getParameters().put(nextParamEntry.getKey(), nextValue); } url = url.substring(0, qIndex); } requestDetails.setRequestPath(url); requestDetails.setFhirServerBase(theRequestDetails.getFhirServerBase()); theRequestDetails.getServer().populateRequestDetailsFromRequestPath(requestDetails, url); BaseMethodBinding<?> method = theRequestDetails.getServer().determineResourceMethod(requestDetails, url); if (method == null) { throw new IllegalArgumentException("Unable to handle GET " + url); } if (isNotBlank(nextReqEntry.getRequest().getIfMatch())) { requestDetails.addHeader(Constants.HEADER_IF_MATCH, nextReqEntry.getRequest().getIfMatch()); } if (isNotBlank(nextReqEntry.getRequest().getIfNoneExist())) { requestDetails.addHeader(Constants.HEADER_IF_NONE_EXIST, nextReqEntry.getRequest().getIfNoneExist()); } if (isNotBlank(nextReqEntry.getRequest().getIfNoneMatch())) { requestDetails.addHeader(Constants.HEADER_IF_NONE_MATCH, nextReqEntry.getRequest().getIfNoneMatch()); } if (method instanceof BaseResourceReturningMethodBinding) { try { ResourceOrDstu1Bundle responseData = ((BaseResourceReturningMethodBinding) method) .doInvokeServer(theRequestDetails.getServer(), requestDetails); IBaseResource resource = responseData.getResource(); if (paramValues.containsKey(Constants.PARAM_SUMMARY) || paramValues.containsKey(Constants.PARAM_CONTENT)) { resource = filterNestedBundle(requestDetails, resource); } nextRespEntry.setResource((Resource) resource); nextRespEntry.getResponse().setStatus(toStatusString(Constants.STATUS_HTTP_200_OK)); } catch (NotModifiedException e) { nextRespEntry.getResponse().setStatus(toStatusString(Constants.STATUS_HTTP_304_NOT_MODIFIED)); } } else { throw new IllegalArgumentException("Unable to handle GET " + url); } } for (Entry<BundleEntryComponent, ResourceTable> nextEntry : entriesToProcess.entrySet()) { nextEntry.getKey().getResponse().setLocation(nextEntry.getValue().getIdDt().toUnqualified().getValue()); nextEntry.getKey().getResponse().setEtag(nextEntry.getValue().getIdDt().getVersionIdPart()); } long delay = System.currentTimeMillis() - start; ourLog.info(theActionName + " completed in {}ms", new Object[] { delay }); response.setType(BundleType.TRANSACTIONRESPONSE); return response; }
From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java
public boolean visitNode(EntityPreserveIdFlagPair entityPreserveIdFlagPair, GraphTraverser<EntityPreserveIdFlagPair, IdentityHashMap<Object, Object>> graphTraverser, IdentityHashMap<Object, Object> entityClones) { if (!(graphTraverser instanceof HibernateEntityGraphCloner)) { throw new IllegalArgumentException( graphTraverser + " is not an instance of HibernateEntityGraphCloner"); }//ww w. java2 s . c o m Object entity = entityPreserveIdFlagPair.getEntity(); Object clone; try { // ensure the "real" class is instantiated if the current instance is a CGLIB class clone = getEntityClass(entity).newInstance(); for (String targetedFieldName : getTargetedFieldNames(entity, entityPreserveIdFlagPair.isPreserveId())) { cloneProperty(entity, clone, targetedFieldName, (HibernateEntityGraphCloner) graphTraverser); } } catch (Exception exception) { throw new AssertionError("Unable to clone entity " + entity + " due to " + exception.getClass().getSimpleName() + ": " + exception.getMessage()); } entityClones.put(entity, clone); return true; }
From source file:org.apache.pig.pen.LineageTrimmingVisitor.java
private Map<LOLoad, DataBag> PruneBaseDataConstrainedCoverage(Map<LOLoad, DataBag> baseData, LineageTracer lineage, Collection<IdentityHashSet<Tuple>> equivalenceClasses) { IdentityHashMap<Tuple, Collection<Tuple>> membershipMap = lineage.getMembershipMap(); IdentityHashMap<Tuple, Double> lineageGroupWeights = lineage.getWeightedCounts(2f, 1); // compute a mapping from lineage group to the set of equivalence // classes covered by it // IdentityHashMap<Tuple, Set<Integer>> lineageGroupToEquivClasses = new // IdentityHashMap<Tuple, Set<Integer>>(); IdentityHashMap<Tuple, Set<IdentityHashSet<Tuple>>> lineageGroupToEquivClasses = new IdentityHashMap<Tuple, Set<IdentityHashSet<Tuple>>>(); for (IdentityHashSet<Tuple> equivClass : equivalenceClasses) { for (Object t : equivClass) { Tuple lineageGroup = lineage.getRepresentative((Tuple) t); // Set<Integer> entry = // lineageGroupToEquivClasses.get(lineageGroup); Set<IdentityHashSet<Tuple>> entry = lineageGroupToEquivClasses.get(lineageGroup); if (entry == null) { // entry = new HashSet<Integer>(); entry = new HashSet<IdentityHashSet<Tuple>>(); lineageGroupToEquivClasses.put(lineageGroup, entry); }/* www . ja v a2 s. c o m*/ // entry.add(equivClassId); entry.add(equivClass); } } // select lineage groups such that we cover all equivalence classes IdentityHashSet<Tuple> selectedLineageGroups = new IdentityHashSet<Tuple>(); while (!lineageGroupToEquivClasses.isEmpty()) { // greedily find the lineage group with the best "score", where // score = # equiv classes covered / group weight double bestWeight = -1; Tuple bestLineageGroup = null; Set<IdentityHashSet<Tuple>> bestEquivClassesCovered = null; int bestNumEquivClassesCovered = 0; for (Tuple lineageGroup : lineageGroupToEquivClasses.keySet()) { double weight = lineageGroupWeights.get(lineageGroup); Set<IdentityHashSet<Tuple>> equivClassesCovered = lineageGroupToEquivClasses.get(lineageGroup); int numEquivClassesCovered = equivClassesCovered.size(); if ((numEquivClassesCovered > bestNumEquivClassesCovered) || (numEquivClassesCovered == bestNumEquivClassesCovered && weight < bestWeight)) { if (selectedLineageGroups.contains(lineageGroup)) { bestLineageGroup = lineageGroup; bestEquivClassesCovered = equivClassesCovered; continue; } bestWeight = weight; bestLineageGroup = lineageGroup; bestNumEquivClassesCovered = numEquivClassesCovered; bestEquivClassesCovered = equivClassesCovered; } } // add the best-scoring lineage group to the set of ones we plan to // retain selectedLineageGroups.add(bestLineageGroup); // make copy of bestEquivClassesCovered (or else the code that // follows won't work correctly, because removing from the reference // set) Set<IdentityHashSet<Tuple>> toCopy = bestEquivClassesCovered; bestEquivClassesCovered = new HashSet<IdentityHashSet<Tuple>>(); bestEquivClassesCovered.addAll(toCopy); // remove the classes we've now covered Collection<Tuple> toRemove = new LinkedList<Tuple>(); for (Tuple lineageGroup : lineageGroupToEquivClasses.keySet()) { Set<IdentityHashSet<Tuple>> equivClasses = lineageGroupToEquivClasses.get(lineageGroup); for (Iterator<IdentityHashSet<Tuple>> it = equivClasses.iterator(); it.hasNext();) { IdentityHashSet<Tuple> equivClass = it.next(); if (bestEquivClassesCovered.contains(equivClass)) { it.remove(); } } if (equivClasses.size() == 0) toRemove.add(lineageGroup); } for (Tuple removeMe : toRemove) lineageGroupToEquivClasses.remove(removeMe); } // revise baseData to only contain the tuples that are part of // selectedLineageGroups IdentityHashSet<Tuple> tuplesToRetain = new IdentityHashSet<Tuple>(); for (Tuple lineageGroup : selectedLineageGroups) { Collection<Tuple> members = membershipMap.get(lineageGroup); for (Tuple t : members) tuplesToRetain.add(t); } Map<LOLoad, DataBag> newBaseData = new HashMap<LOLoad, DataBag>(); for (LOLoad loadOp : baseData.keySet()) { DataBag data = baseData.get(loadOp); // DataBag newData = new DataBag(); DataBag newData = BagFactory.getInstance().newDefaultBag(); for (Iterator<Tuple> it = data.iterator(); it.hasNext();) { Tuple t = it.next(); if (tuplesToRetain.contains(t)) newData.add(t); } newBaseData.put(loadOp, newData); } return newBaseData; }
From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
public void testClone() { IdentityHashMap srcMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(srcMap); // Check empty clone behavior IdentityHashMap dstMap = (IdentityHashMap) srcMap.clone(); assertNotNull(dstMap);/*from w ww.ja v a2 s .com*/ assertEquals(dstMap.size(), srcMap.size()); // assertTrue(dstMap.values().toArray().equals(srcMap.values().toArray())); assertTrue(dstMap.keySet().equals(srcMap.keySet())); assertTrue(dstMap.entrySet().equals(srcMap.entrySet())); // Check non-empty clone behavior srcMap.put(KEY_1, VALUE_1); srcMap.put(KEY_2, VALUE_2); srcMap.put(KEY_3, VALUE_3); dstMap = (IdentityHashMap) srcMap.clone(); assertNotNull(dstMap); assertEquals(dstMap.size(), srcMap.size()); assertTrue(dstMap.keySet().equals(srcMap.keySet())); assertTrue(dstMap.entrySet().equals(srcMap.entrySet())); }
From source file:sf.net.experimaestro.manager.plans.Operator.java
/** * Recursion through the structure//w w w .j ava 2s . c o m * * @see #getTaskOperatorMap(sf.net.experimaestro.manager.experiments.Experiment) * @param experiment * @param map The current map * @param descendant The current descendant */ private void getTaskOperatorMap(Experiment experiment, IdentityHashMap<TaskOperator, TaskReference> map, TaskReference descendant) { if (this instanceof TaskOperator) { TaskOperator task = (TaskOperator) this; TaskReference reference = map.get(task); if (descendant != null) { descendant.addParent(reference); } if (reference != null) { // If we already were in the map, no need to go higher return; } reference = new TaskReference(experiment, task.getPlan().getFactory().getId()); map.put(task, reference); descendant = reference; } for (Operator parent : getParents()) { parent.getTaskOperatorMap(experiment, map, descendant); } }
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()); }/*from w w w .j a va 2 s . c o m*/ 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; }