org.hl7.fhir.r4.model.IdType Java Examples

The following examples show how to use org.hl7.fhir.r4.model.IdType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObservationDefinitionProvider.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Delete
public MethodOutcome delete
        (@IdParam IdType internalId) {
    resourcePermissionProvider.checkPermission("delete");
    MethodOutcome method = new MethodOutcome();

    try {
        OperationOutcome outcome = observationDefinitionDao.delete(ctx,internalId);
        method.setCreated(false);

        method.setResource(outcome);
    } catch (Exception ex) {
        log.info(ex.getMessage());
        ProviderResponseLibrary.handleException(method,ex);
    }

    return method;
}
 
Example #2
Source File: LibraryOperationsProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
@Operation(name = "$get-elm", idempotent = true, type = Library.class)
public Parameters getElm(@IdParam IdType theId, @OptionalParam(name="format") String format) {
    Library theResource = this.libraryResourceProvider.getDao().read(theId);
    // this.formatCql(theResource);

    ModelManager modelManager = this.getModelManager();
    LibraryManager libraryManager = this.getLibraryManager(modelManager);

    String elm = "";
    CqlTranslator translator = this.dataRequirementsProvider.getTranslator(theResource, libraryManager, modelManager);
    if (translator != null) {
        if (format.equals("json")) {
            elm = translator.toJson();
        }
        else {
            elm = translator.toXml();
        }
    }
    Parameters p = new Parameters();
    p.addParameter().setValue(new StringType(elm));
    return p;
}
 
Example #3
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private String describeTransformCCorC(StructureMapGroupRuleTargetComponent tgt) throws FHIRException {
  if (tgt.getParameter().size() < 2)
    return null;
  Type p1 = tgt.getParameter().get(0).getValue();
  Type p2 = tgt.getParameter().get(1).getValue();
  if (p1 instanceof IdType || p2 instanceof IdType)
    return null;
  if (!(p1 instanceof PrimitiveType) || !(p2 instanceof PrimitiveType))
    return null;
  String uri = ((PrimitiveType) p1).asStringValue();
  String code = ((PrimitiveType) p2).asStringValue();
  if (Utilities.noString(uri))
    throw new FHIRException("Describe Transform, but the uri is blank");
  if (Utilities.noString(code))
    throw new FHIRException("Describe Transform, but the code is blank");
  Coding c = buildCoding(uri, code);
  return NarrativeGenerator.describeSystem(c.getSystem())+"#"+c.getCode()+(c.hasDisplay() ? "("+c.getDisplay()+")" : "");
}
 
Example #4
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap) {
    List<IBase> values;
    for (BaseRuntimeChildDefinition child : this.measureResourceProvider.getContext().getResourceDefinition(resource).getChildren()) {
        values = child.getAccessor().getValues(resource);
        if (values == null || values.isEmpty()) {
            continue;
        }

        else if (values.get(0) instanceof Reference
                && ((Reference) values.get(0)).getReferenceElement().hasResourceType()
                && ((Reference) values.get(0)).getReferenceElement().hasIdPart()) {
            Resource fetchedResource = (Resource) registry
                    .getResourceDao(((Reference) values.get(0)).getReferenceElement().getResourceType())
                    .read(new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart()));

            if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue())) {
                parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
                        .setResource(fetchedResource));

                resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
            }
        }
    }
}
 
Example #5
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$data-requirements", idempotent = true, type = Measure.class)
public org.hl7.fhir.r4.model.Library dataRequirements(@IdParam IdType theId,
        @RequiredParam(name = "startPeriod") String startPeriod,
        @RequiredParam(name = "endPeriod") String endPeriod) throws InternalErrorException, FHIRException {
    
    Measure measure = this.measureResourceProvider.getDao().read(theId);
    return this.dataRequirementsProvider.getDataRequirements(measure, this.libraryResolutionProvider);
}
 
Example #6
Source File: ObservationDefinitionDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
   public ObservationDefinitionEntity readEntity(FhirContext ctx, IdType theId) {

       System.out.println("the id is " + theId.getIdPart());

       ObservationDefinitionEntity observationDefinitionEntity = null;
       // Only look up if the id is numeric else need to do a search
/*        if (daoutils.isNumeric(theId.getIdPart())) {
            observationDefinitionEntity =(ObservationDefinitionEntity) em.find(ObservationDefinitionEntity.class, theId.getIdPart());
        } */
       ObservationDefinitionEntity.class.getName();
       // if null try a search on strId

       CriteriaBuilder builder = em.getCriteriaBuilder();

       if (daoutilsR4.isNumeric(theId.getIdPart())) {

           CriteriaQuery<ObservationDefinitionEntity> criteria = builder.createQuery(ObservationDefinitionEntity.class);
           Root<ObservationDefinitionEntity> root = criteria.from(ObservationDefinitionEntity.class);
           List<Predicate> predList = new LinkedList<Predicate>();
           Predicate p = builder.equal(root.<String>get("id"), theId.getIdPart());
           predList.add(p);
           Predicate[] predArray = new Predicate[predList.size()];
           predList.toArray(predArray);
           if (predList.size() > 0) {
               criteria.select(root).where(predArray);

               List<ObservationDefinitionEntity> qryResults = em.createQuery(criteria).getResultList();

               for (ObservationDefinitionEntity cme : qryResults) {
                   observationDefinitionEntity = cme;
                   break;
               }
           }
       }
       // }
       return observationDefinitionEntity;
   }
 
Example #7
Source File: LibraryOperationsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$refresh-generated-content", type = Library.class)
  public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails,
          @IdParam IdType theId) {
      Library theResource = this.libraryResourceProvider.getDao().read(theId);
      //this.formatCql(theResource);

      ModelManager modelManager = this.getModelManager();
      LibraryManager libraryManager = this.getLibraryManager(modelManager);

      CqlTranslator translator = this.dataRequirementsProvider.getTranslator(theResource, libraryManager, modelManager);
      if (translator.getErrors().size() > 0) {
          throw new RuntimeException("Errors during library compilation.");
      }
      
      this.dataRequirementsProvider.ensureElm(theResource, translator);
      this.dataRequirementsProvider.ensureRelatedArtifacts(theResource, translator, this);
      this.dataRequirementsProvider.ensureDataRequirements(theResource, translator);

try {
	Narrative n = this.narrativeProvider.getNarrative(this.libraryResourceProvider.getContext(), theResource);
	theResource.setText(n);
} catch (Exception e) {
	//Ignore the exception so the resource still gets updated
}

      return this.libraryResourceProvider.update(theRequest, theResource, theId,
              theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
  }
 
Example #8
Source File: LibraryOperationsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$get-narrative", idempotent = true, type = Library.class)
public Parameters getNarrative(@IdParam IdType theId) {
    Library theResource = this.libraryResourceProvider.getDao().read(theId);
    Narrative n = this.narrativeProvider.getNarrative(this.libraryResourceProvider.getContext(), theResource);
    Parameters p = new Parameters();
    p.addParameter().setValue(new StringType(n.getDivAsString()));
    return p;
}
 
Example #9
Source File: LibraryOperationsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Override
public Library resolveLibraryById(String libraryId) {
    try {
        return this.libraryResourceProvider.getDao().read(new IdType(libraryId));
    }
    catch (Exception e) {
        throw new IllegalArgumentException(String.format("Could not resolve library id %s", libraryId));
    }
}
 
Example #10
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$get-narrative", idempotent = true, type = Measure.class)
public Parameters getNarrative(@IdParam IdType theId) {
    Measure theResource = this.measureResourceProvider.getDao().read(theId);
    CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider);
    Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
    Parameters p = new Parameters();
    p.addParameter().setValue(new StringType(n.getDivAsString()));
    return p;
}
 
Example #11
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$collect-data", idempotent = true, type = Measure.class)
public Parameters collectData(@IdParam IdType theId, @RequiredParam(name = "periodStart") String periodStart,
        @RequiredParam(name = "periodEnd") String periodEnd, @OptionalParam(name = "patient") String patientRef,
        @OptionalParam(name = "practitioner") String practitionerRef,
        @OptionalParam(name = "lastReceivedOn") String lastReceivedOn) throws FHIRException {
    // TODO: Spec says that the periods are not required, but I am not sure what to
    // do when they aren't supplied so I made them required
    MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, null,
            practitionerRef, lastReceivedOn, null, null, null);
    report.setGroup(null);

    Parameters parameters = new Parameters();

    parameters.addParameter(
            new Parameters.ParametersParameterComponent().setName("measurereport").setResource(report));

    if (report.hasContained()) {
        for (Resource contained : report.getContained()) {
            if (contained instanceof Bundle) {
                addEvaluatedResourcesToParameters((Bundle) contained, parameters);
            }
        }
    }

    // TODO: need a way to resolve referenced resources within the evaluated
    // resources
    // Should be able to use _include search with * wildcard, but HAPI doesn't
    // support that

    return parameters;
}
 
Example #12
Source File: ObservationDefinitionDao.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public OperationOutcome delete(FhirContext ctx, IdType theId) {
    log.trace("Delete OperationDefinition = " + theId.getValue());

    ObservationDefinitionEntity observationDefinitionEntity = readEntity(ctx, theId);

    if (observationDefinitionEntity == null) return null;

    for (ObservationDefinitionIdentifier identifier : observationDefinitionEntity.getIdentifiers()) {
        em.remove(identifier);
    }
    em.remove(observationDefinitionEntity);
    return new OperationOutcome();

}
 
Example #13
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$submit-data", idempotent = true, type = Measure.class)
public Resource submitData(RequestDetails details, @IdParam IdType theId,
        @OperationParam(name = "measure-report", min = 1, max = 1, type = MeasureReport.class) MeasureReport report,
        @OperationParam(name = "resource") List<IAnyResource> resources) {
    Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);

    /*
     * TODO - resource validation using $data-requirements operation (params are the
     * provided id and the measurement period from the MeasureReport)
     * 
     * TODO - profile validation ... not sure how that would work ... (get
     * StructureDefinition from URL or must it be stored in Ruler?)
     */

    transactionBundle.addEntry(createTransactionEntry(report));

    for (IAnyResource resource : resources) {
        Resource res = (Resource) resource;
        if (res instanceof Bundle) {
            for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) {
                transactionBundle.addEntry(entry);
            }
        } else {
            // Build transaction bundle
            transactionBundle.addEntry(createTransactionEntry(res));
        }
    }

    return (Resource) this.registry.getSystemDao().transaction(details, transactionBundle);
}
 
Example #14
Source File: CodeSystemUpdateProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
/***
 * Update existing CodeSystems with the codes in the specified ValueSet.
 *
 * This is for development environment purposes to enable ValueSet expansion and validation
 * without complete CodeSystems.
 *
 * @param theId the id of the ValueSet
 * @return FHIR OperationOutcome detailing the success or failure of the operation
 */
@Operation(name = "$updateCodeSystems", idempotent = true, type = ValueSet.class)
public OperationOutcome updateCodeSystems(@IdParam IdType theId)
{
    ValueSet vs = this.valueSetDao.read(theId);

    OperationOutcomeBuilder responseBuilder = new OperationOutcomeBuilder();
    if (vs == null)
    {
        return responseBuilder.buildIssue("error", "notfound", "Unable to find Resource: " + theId.getId()).build();
    }

    return performCodeSystemUpdate(vs);
}
 
Example #15
Source File: PlanDefinitionApplyProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Operation(name = "$apply", idempotent = true, type = PlanDefinition.class)
public CarePlan applyPlanDefinition(
        @IdParam IdType theId,
        @RequiredParam(name="patient") String patientId,
        @OptionalParam(name="encounter") String encounterId,
        @OptionalParam(name="practitioner") String practitionerId,
        @OptionalParam(name="organization") String organizationId,
        @OptionalParam(name="userType") String userType,
        @OptionalParam(name="userLanguage") String userLanguage,
        @OptionalParam(name="userTaskContext") String userTaskContext,
        @OptionalParam(name="setting") String setting,
        @OptionalParam(name="settingContext") String settingContext)
    throws IOException, JAXBException, FHIRException
{
    PlanDefinition planDefinition = this.planDefintionDao.read(theId);

    if (planDefinition == null) {
        throw new IllegalArgumentException("Couldn't find PlanDefinition " + theId);
    }

    logger.info("Performing $apply operation on PlanDefinition/" + theId);

    CarePlanBuilder builder = new CarePlanBuilder();

    builder
            .buildInstantiatesCanonical(planDefinition.getIdElement().getIdPart())
            .buildSubject(new Reference(patientId))
            .buildStatus(CarePlan.CarePlanStatus.DRAFT);

    if (encounterId != null) builder.buildEncounter(new Reference(encounterId));
    if (practitionerId != null) builder.buildAuthor(new Reference(practitionerId));
    if (organizationId != null) builder.buildAuthor(new Reference(organizationId));
    if (userLanguage != null) builder.buildLanguage(userLanguage);

    Session session =
            new Session(planDefinition, builder, patientId, encounterId, practitionerId,
                    organizationId, userType, userLanguage, userTaskContext, setting, settingContext);

    return resolveActions(session);
}
 
Example #16
Source File: Example01_PatientResourceProvider.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Simple implementation of the "read" method
 */
@Read()
public Patient read(@IdParam IdType theId) {
   Patient retVal = myPatients.get(theId.getIdPart());
   if (retVal == null) {
      throw new ResourceNotFoundException(theId);
   }
   return retVal;
}
 
Example #17
Source File: Hints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Simple implementation of the "read" method */
@Read(version = false)
public Patient read(@IdParam IdType theId) {
	Patient retVal = myPatients.get(theId.getIdPart());
	if (retVal == null) {
		throw new ResourceNotFoundException(theId);
	}
	return retVal;
}
 
Example #18
Source File: Hints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Create
public MethodOutcome create(@ResourceParam Patient thePatient) {
	// Give the resource the next sequential ID
	int id = myNextId++;
	thePatient.setId(new IdType(id));

	// Store the resource in memory
	myPatients.put(Integer.toString(id), thePatient);

	// Inform the server of the ID for the newly stored resource
	return new MethodOutcome().setId(thePatient.getIdElement());
}
 
Example #19
Source File: Example03_AuthorizationInterceptor.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<IAuthRule> buildRuleList(RequestDetails theRequestDetails) {

   // Process this header
   String authHeader = theRequestDetails.getHeader("Authorization");

   RuleBuilder builder = new RuleBuilder();
   builder
      .allow().metadata().andThen()
      .allow().read().allResources().withAnyId().andThen()
      .allow().write().resourcesOfType(Observation.class).inCompartment("Patient", new IdType("Patient/123"));

   return builder.build();
}
 
Example #20
Source File: ObservationDefinitionProvider.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Read
public ObservationDefinition get
        (@IdParam IdType internalId) {
    resourcePermissionProvider.checkPermission("read");
    ObservationDefinition observationDefinition = observationDefinitionDao.read( ctx, internalId);

    if ( observationDefinition == null) {
        throw OperationOutcomeFactory.buildOperationOutcomeException(
                new ResourceNotFoundException("No ObservationDefinition/" + internalId.getIdPart()),
                 OperationOutcome.IssueType.NOTFOUND);
    }

    return observationDefinition;
}
 
Example #21
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void parseParameter(StructureMapGroupRuleTargetComponent target, FHIRLexer lexer) throws FHIRLexerException, FHIRFormatError {
	if (!lexer.isConstant()) {
		target.addParameter().setValue(new IdType(lexer.take()));
	} else if (lexer.isStringConstant())
		target.addParameter().setValue(new StringType(lexer.readConstant("??")));
	else {
		target.addParameter().setValue(readConstant(lexer.take(), lexer));
	}
}
 
Example #22
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private Base getParam(Variables vars, StructureMapGroupRuleTargetParameterComponent parameter) throws DefinitionException {
	Type p = parameter.getValue();
	if (!(p instanceof IdType))
		return p;
	else { 
		String n = ((IdType) p).asStringValue();
     Base b = vars.get(VariableMode.INPUT, n);
		if (b == null)
			b = vars.get(VariableMode.OUTPUT, n);
		if (b == null)
       throw new DefinitionException("Variable "+n+" not found ("+vars.summary()+")");
		return b;
	}
}
 
Example #23
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private boolean allParametersFixed(StructureMapGroupRuleTargetComponent tgt) {
  for (StructureMapGroupRuleTargetParameterComponent p : tgt.getParameter()) {
    Type pr = p.getValue();
    if (pr instanceof IdType)
      return false;
  }
  return true;
}
 
Example #24
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private String getParamString(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
  Type p = parameter.getValue();
  if (p == null || p instanceof IdType)
    return null;
  if (!p.hasPrimitiveValue())
    return null;
  return p.primitiveValue();
}
 
Example #25
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private TypeDetails getParam(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) throws DefinitionException {
  Type p = parameter.getValue();
  if (!(p instanceof IdType))
    return new TypeDetails(CollectionStatus.SINGLETON, ProfileUtilities.sdNs(p.fhirType(), worker.getOverrideVersionNs()));
  else { 
    String n = ((IdType) p).asStringValue();
    VariableForProfiling b = vars.get(VariableMode.INPUT, n);
    if (b == null)
      b = vars.get(VariableMode.OUTPUT, n);
    if (b == null)
      throw new DefinitionException("Variable "+n+" not found ("+vars.summary()+")");
    return b.getProperty().getTypes();
  }
}
 
Example #26
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 4 votes vote down vote up
@Operation(name = "$evaluate-measure", idempotent = true, type = Measure.class)
public MeasureReport evaluateMeasure(@IdParam IdType theId, @RequiredParam(name = "periodStart") String periodStart,
        @RequiredParam(name = "periodEnd") String periodEnd, @OptionalParam(name = "measure") String measureRef,
        @OptionalParam(name = "reportType") String reportType, @OptionalParam(name = "patient") String patientRef,
        @OptionalParam(name = "productLine") String productLine,
        @OptionalParam(name = "practitioner") String practitionerRef,
        @OptionalParam(name = "lastReceivedOn") String lastReceivedOn,
        @OptionalParam(name = "source") String source, @OptionalParam(name = "user") String user,
        @OptionalParam(name = "pass") String pass) throws InternalErrorException, FHIRException {
    LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);
    MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResolutionProvider);
    Measure measure = this.measureResourceProvider.getDao().read(theId);

    if (measure == null) {
        throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
    }

    seed.setup(measure, periodStart, periodEnd, productLine, source, user, pass);

    // resolve report type
    MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod());
    if (reportType != null) {
        switch (reportType) {
        case "patient":
            return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
        case "patient-list":
            return evaluator.evaluateSubjectListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef);
        case "population":
            return  evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext());
        default:
            throw new IllegalArgumentException("Invalid report type: " + reportType);
        }
    }

    // default report type is patient
    MeasureReport report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
    if (productLine != null)
    {
        Extension ext = new Extension();
        ext.setUrl("http://hl7.org/fhir/us/cqframework/cqfmeasures/StructureDefinition/cqfm-productLine");
        ext.setValue(new StringType(productLine));
        report.addExtension(ext);
    }

    return report;
}
 
Example #27
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private boolean isParamId(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
  Type p = parameter.getValue();
  if (p == null || !(p instanceof IdType))
    return false;
  return vars.get(null, p.primitiveValue()) != null;
}
 
Example #28
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private String getParamId(VariablesForProfiling vars, StructureMapGroupRuleTargetParameterComponent parameter) {
  Type p = parameter.getValue();
  if (p == null || !(p instanceof IdType))
    return null;
  return p.primitiveValue();
}
 
Example #29
Source File: PlanDefinitionApplyProvider.java    From cqf-ruler with Apache License 2.0 4 votes vote down vote up
private void resolveDefinition(Session session, PlanDefinition.PlanDefinitionActionComponent action) {
    if (action.hasDefinition()) {
        logger.debug("Resolving definition "+ action.getDefinitionCanonicalType().getValue());
        String definition = action.getDefinitionCanonicalType().getValue();
        if (definition.startsWith(session.getPlanDefinition().fhirType())) {
            logger.error("Currently cannot resolve nested PlanDefinitions");
            throw new NotImplementedException("Plan Definition refers to sub Plan Definition, this is not yet supported");
        }

        else {
            Resource result;
            try {
                if (action.getDefinitionCanonicalType().getValue().startsWith("#")) {
                    result = this.activityDefinitionApplyProvider.resolveActivityDefinition(
                            (ActivityDefinition) resolveContained(session.getPlanDefinition(),
                                    action.getDefinitionCanonicalType().getValue()),
                            session.getPatientId(), session.getPractionerId(), session.getOrganizationId()
                    );
                }
                else {
                    result = this.activityDefinitionApplyProvider.apply(
                            new IdType(CanonicalHelper.getId(action.getDefinitionCanonicalType())),
                            session.getPatientId(),
                            session.getEncounterId(),
                            session.getPractionerId(),
                            session.getOrganizationId(),
                            null,
                            session.getUserLanguage(),
                            session.getUserTaskContext(),
                            session.getSetting(),
                            session.getSettingContext()
                    );
                }

                if (result.getId() == null) {
                    logger.warn("ActivityDefinition %s returned resource with no id, setting one", action.getDefinitionCanonicalType().getId());
                    result.setId( UUID.randomUUID().toString() );
                }
                session.getCarePlanBuilder()
                        .buildContained(result)
                        .buildActivity(
                                new CarePlanActivityBuilder()
                                        .buildReference( new Reference("#"+result.getId()) )
                                        .build()
                        );
            } catch (Exception e) {
                logger.error("ERROR: ActivityDefinition %s could not be applied and threw exception %s", action.getDefinition(), e.toString());
            }
        }
    }
}
 
Example #30
Source File: StructureMapUtilities.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private void analyseTarget(String ruleId, TransformContext context, VariablesForProfiling vars, StructureMap map, StructureMapGroupRuleTargetComponent tgt, String tv, TargetWriter tw, List<StructureDefinition> profiles, String sliceName) throws FHIRException {
  VariableForProfiling var = null;
  if (tgt.hasContext()) {
    var = vars.get(VariableMode.OUTPUT, tgt.getContext());
    if (var == null)
      throw new FHIRException("Rule \""+ruleId+"\": target context not known: "+tgt.getContext());
    if (!tgt.hasElement())
      throw new FHIRException("Rule \""+ruleId+"\": Not supported yet");
  }

  
  TypeDetails type = null;
  if (tgt.hasTransform()) {
    type = analyseTransform(context, map, tgt, var, vars);
      // profiling: dest.setProperty(tgt.getElement().hashCode(), tgt.getElement(), v);
  } else {
    Property vp = var.property.baseProperty.getChild(tgt.getElement(),  tgt.getElement());
    if (vp == null)
      throw new FHIRException("Unknown Property "+tgt.getElement()+" on "+var.property.path);
    
    type = new TypeDetails(CollectionStatus.SINGLETON, vp.getType(tgt.getElement()));
  }

  if (tgt.getTransform() == StructureMapTransform.CREATE) {
    String s = getParamString(vars, tgt.getParameter().get(0));
    if (worker.getResourceNames().contains(s))
      tw.newResource(tgt.getVariable(), s);
  } else { 
    boolean mapsSrc = false;
    for (StructureMapGroupRuleTargetParameterComponent p : tgt.getParameter()) {
      Type pr = p.getValue();
      if (pr instanceof IdType && ((IdType) pr).asStringValue().equals(tv)) 
        mapsSrc = true;
    }
    if (mapsSrc) { 
      if (var == null)
        throw new Error("Rule \""+ruleId+"\": Attempt to assign with no context");
      tw.valueAssignment(tgt.getContext(), var.property.getPath()+"."+tgt.getElement()+getTransformSuffix(tgt.getTransform()));
    } else if (tgt.hasContext()) {
      if (isSignificantElement(var.property, tgt.getElement())) {
        String td = describeTransform(tgt);
        if (td != null)
          tw.keyAssignment(tgt.getContext(), var.property.getPath()+"."+tgt.getElement()+" = "+td);
      }
    }
  }
  Type fixed = generateFixedValue(tgt);
  
  PropertyWithType prop = updateProfile(var, tgt.getElement(), type, map, profiles, sliceName, fixed, tgt);
  if (tgt.hasVariable())
    if (tgt.hasElement())
      vars.add(VariableMode.OUTPUT, tgt.getVariable(), prop); 
    else
      vars.add(VariableMode.OUTPUT, tgt.getVariable(), prop); 
}