List of usage examples for java.util IdentityHashMap IdentityHashMap
public IdentityHashMap()
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 ww .j a v a2 s. c o m 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: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 ww . j av a 2s . 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:org.apache.hadoop.mapred.JobInProgress.java
/** * Create an almost empty JobInProgress, which can be used only for tests *///from w w w.j a v a2 s .c om protected JobInProgress(JobID jobid, JobConf conf, JobTracker tracker) throws IOException { this.conf = conf; this.jobId = jobid; this.numMapTasks = conf.getNumMapTasks(); this.numReduceTasks = conf.getNumReduceTasks(); this.maxLevel = NetworkTopology.DEFAULT_HOST_LEVEL; this.anyCacheLevel = this.maxLevel + 1; this.jobtracker = tracker; this.restartCount = 0; hasSpeculativeMaps = conf.getMapSpeculativeExecution(); hasSpeculativeReduces = conf.getReduceSpeculativeExecution(); this.nonLocalMaps = new LinkedList<TaskInProgress>(); this.failedMaps = new TreeSet<TaskInProgress>(failComparator); this.nonLocalRunningMaps = new LinkedHashSet<TaskInProgress>(); this.runningMapCache = new IdentityHashMap<Node, Set<TaskInProgress>>(); this.nonRunningReduces = new TreeSet<TaskInProgress>(failComparator); this.runningReduces = new LinkedHashSet<TaskInProgress>(); this.resourceEstimator = new ResourceEstimator(this); this.status = new JobStatus(jobid, 0.0f, 0.0f, JobStatus.PREP); this.status.setUsername(conf.getUser()); String queueName = conf.getQueueName(); this.profile = new JobProfile(conf.getUser(), jobid, "", "", conf.getJobName(), queueName); this.memoryPerMap = conf.getMemoryForMapTask(); this.memoryPerReduce = conf.getMemoryForReduceTask(); this.maxTaskFailuresPerTracker = conf.getMaxTaskFailuresPerTracker(); this.mapFailuresPercent = conf.getMaxMapTaskFailuresPercent(); this.reduceFailuresPercent = conf.getMaxReduceTaskFailuresPercent(); Queue queue = this.jobtracker.getQueueManager().getQueue(queueName); if (queue == null) { throw new IOException("Queue \"" + queueName + "\" does not exist"); } this.queueMetrics = queue.getMetrics(); // Check task limits checkTaskLimits(); this.taskCompletionEvents = new ArrayList<TaskCompletionEvent>(numMapTasks + numReduceTasks + 10); try { this.userUGI = UserGroupInformation.getCurrentUser(); } catch (IOException ie) { throw new RuntimeException(ie); } }
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); }/*w w w . ja v a 2s .c o m*/ 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.google.gwt.emultest.java.util.IdentityHashMapTest.java
public void testHashMapMap() { IdentityHashMap srcMap = new IdentityHashMap(); assertNotNull(srcMap);/* w ww .j ava 2 s . c om*/ checkEmptyHashMapAssumptions(srcMap); srcMap.put(INTEGER_1, INTEGER_11); srcMap.put(INTEGER_2, INTEGER_22); srcMap.put(INTEGER_3, INTEGER_33); IdentityHashMap hashMap = new IdentityHashMap(srcMap); assertFalse(hashMap.isEmpty()); assertTrue(hashMap.size() == SIZE_THREE); Collection valColl = hashMap.values(); assertTrue(valColl.contains(INTEGER_11)); assertTrue(valColl.contains(INTEGER_22)); assertTrue(valColl.contains(INTEGER_33)); Collection keyColl = hashMap.keySet(); assertTrue(keyColl.contains(INTEGER_1)); assertTrue(keyColl.contains(INTEGER_2)); assertTrue(keyColl.contains(INTEGER_3)); }
From source file:org.romaframework.aspect.view.ViewAspectAbstract.java
public void onSessionCreating(SessionInfo iSession) { objectsForms.put(iSession, new IdentityHashMap<Object, ViewComponent>()); }
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 . ja v a2 s . co m*/ 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:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
/** * Test that the implementation differs from a standard map in demanding * identity./*from ww w . j av a 2 s.c o m*/ */ public void testIdentity() { IdentityHashMap hashMap = new IdentityHashMap(); checkEmptyHashMapAssumptions(hashMap); Foo foo1 = new Foo(); assertNull(hashMap.get(foo1)); hashMap.put(foo1, VALUE_1); assertNotNull(hashMap.get(foo1)); assertSame(VALUE_1, hashMap.get(foo1)); Foo foo2 = new Foo(); assertNull(hashMap.get(foo2)); }
From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java
/** * Test that the implementation differs from a standard map in demanding * identity.//w w w . j a va 2 s.c o m */ public void testIdentityBasedEquality() { IdentityHashMap hashMap1 = new IdentityHashMap(); checkEmptyHashMapAssumptions(hashMap1); IdentityHashMap hashMap2 = new IdentityHashMap(); checkEmptyHashMapAssumptions(hashMap2); hashMap1.put(new Foo(), VALUE_1); hashMap2.put(new Foo(), VALUE_1); assertFalse(hashMap1.equals(hashMap2)); }