public Throwable fhir(SparseArray<GlucoseRecord> records) {

    try {
      Patient p = getPatient();
      Log.d(TAG, "converting glucoserecrods to observations now");

      Device d = initializeDevice(p);
      // do conditional update here so the device is updated if needed

      String ident = getConditionalUrl(d, d.getIdentifierFirstRep());
      String a = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(d);
      IdDt id = (IdDt) client.update().resource(d).conditionalByUrl(ident).execute().getId();
      d.setId(id);

      DeviceMetric metric = initializeDeviceMetric(d);
      metric.setId(
          client
              .create()
              .resource(metric)
              .conditionalByUrl(getConditionalUrl(metric, metric.getIdentifier()))
              .execute()
              .getId());

      for (int i = 0; i < records.size(); i++) {
        int j = records.keyAt(i);
        GlucoseRecord r = records.get(j);

        Log.d(TAG, "creating quantity");

        QuantityDt qdt = initializeQuantityDt(r);

        Observation o = initializeObservation(p, metric, r, qdt);

        Log.d(TAG, "submitting to server...");
        // client.update().resource(o).conditionalByUrl("Observation?identifier=http://...%7Cid").encodedJson().execute();
        IdDt did =
            (IdDt)
                client
                    .update()
                    .resource(o)
                    .conditionalByUrl(getConditionalUrl(o, o.getIdentifierFirstRep()))
                    .execute()
                    .getId();

        o.setId(did);

        String s = ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(o);

        Log.d(TAG, "... done");
      }
    } catch (Throwable e) {
      return e;
    }

    return null;
  }
  /**
   * Invokes the given search Url and writes the results to a file in the specified job folder.
   *
   * @param searchUrl
   * @param serverBase
   * @param jobDir
   * @param fileName
   * @throws IOException
   */
  private int retrieveAndStoreData(
      String searchUrl, String serverBase, File jobDir, String fileName) throws IOException {

    int numRecords = 0;

    final String url = urlEncodeQueryParams(searchUrl);

    LOG.info(
        "retrieveAndStoreData, serverBase: {}  searchUrl: {} encoded query: {}",
        serverBase,
        searchUrl,
        url);

    final ServerAuthorization serverAuthorization =
        AuthorizationUtil.findServerAuthorization(serverAuthorizations, serverBase);

    BearerTokenAuthInterceptor authInterceptor = null;
    if (serverAuthorization != null) {
      // register authorization interceptor with the client
      LOG.info("assigning bearing token interceptor, {}", serverAuthorization.getAccessToken());
      authInterceptor = new BearerTokenAuthInterceptor(serverAuthorization.getAccessToken());
      fhirRestClient.registerInterceptor(authInterceptor);
    }
    try {
      // Perform a search
      final Bundle searchResults =
          fhirRestClient.search().byUrl(url).returnBundle(Bundle.class).execute();

      // Split the bundle into its component resources
      final SearchResultSplitter resultSplitter = new SearchResultSplitter();
      final List<Resource> resources = resultSplitter.splitBundle(searchResults);

      final File dataFile = createDataSourceFile(jobDir, fileName);
      writeData(dataFile, resources, serverBase, true);
      numRecords = resources.size();

      // retrieve other pages of search results
      Bundle nextResults = searchResults;
      while (nextResults.getLink(Bundle.LINK_NEXT) != null) {
        nextResults = fhirRestClient.loadPage().next(nextResults).execute();
        List<Resource> nextResources = resultSplitter.splitBundle(nextResults);
        writeData(dataFile, nextResources, serverBase, false);
        numRecords += nextResources.size();
      }
    } finally {
      if (authInterceptor != null) {
        // unregister authorization interceptor with the client
        fhirRestClient.unregisterInterceptor(authInterceptor);
      }
    }
    return numRecords;
  }
  /**
   * gets Patient from the server if existing. else creates a new one.
   *
   * @return
   */
  private Patient getPatient() {
    Log.d(TAG, "looking for patient");
    Patient p =
        this.newPatient(patient.getLastname(), patient.getFirstName(), patient.getDateOfBirth());
    p.setText(getNarrative(p));
    p.setIdentifier(
        Arrays.asList(
            new IdentifierDt()
                .setSystem(SYSTEM_URL.concat("/patients/"))
                .setValue(
                    patient
                        .getLastname()
                        .concat(patient.getFirstName())
                        .concat(
                            SimpleDateFormat.getDateInstance(DateFormat.SHORT)
                                .format(patient.getDateOfBirth())))));

    IdDt patientId =
        (IdDt)
            client
                .create()
                .resource(p)
                .conditionalByUrl(getConditionalUrl(p, p.getIdentifierFirstRep()))
                .execute()
                .getId();
    p.setId(patientId);

    return p;
  }
  @Test
  public void testSearchByIdUsingClient() throws Exception {
    IGenericClient client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort);

    Bundle bundle =
        client
            .search()
            .forResource("Patient")
            .where(BaseResource.RES_ID.matches().value("aaa"))
            .execute();
    assertEquals(1, bundle.getEntries().size());

    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals("idaaa", p.getNameFirstRep().getFamilyAsSingleString());
    assertEquals("IDAAA (identifier123)", bundle.getEntries().get(0).getTitle().getValue());
  }
  public void process(Bundle bundle) {
    Bundle response = null;
    RecordMatchResultsBuilder respBuilder;

    if (BundleType.MESSAGE.equals(bundle.getType())) {
      // Create a CSV data source for FRIL
      final File jobDir = newRunDir(workDir);

      final List<BundleEntryComponent> bundleEntries = bundle.getEntry();
      try {
        // The first entry is supposed to be the MessageHeader
        // This will force an exception if not true.
        final MessageHeader msgHdr = (MessageHeader) bundleEntries.get(0).getResource();
        // This log statement keeps above from getting optimized out
        LOG.trace("msg hdr id {}", msgHdr.getId());

        Parameters masterQryParams = null;
        Parameters queryQryParams = null;
        String masterSearchUrl = null;
        String querySearchUrl = null;
        String masterServerBase = null;
        String queryServerBase = null;
        String resourceType = "Patient";
        boolean isDeduplication = true;

        // Find the Parameters resources that contain the search parameters
        // and use those to construct search Urls
        for (BundleEntryComponent entry : bundleEntries) {
          Resource r = entry.getResource();
          LOG.debug("Found Resource type: " + r.getResourceType().toString());
          if (ResourceType.Parameters.equals(r.getResourceType())) {
            Parameters params = (Parameters) r;
            List<ParametersParameterComponent> paramList = params.getParameter();
            // Now look for the parameter with name, resourceType.
            ParametersParameterComponent p = ParametersUtil.findByName(paramList, RESOURCE_TYPE);
            if (p != null) {
              resourceType = p.getValue().toString();
            }
            // Find parameter that distinguishes between master and query sets
            p = ParametersUtil.findByName(paramList, "type");
            if (p != null) {
              String val = p.getValue().toString();
              if (val.equalsIgnoreCase(MASTER)) {
                masterQryParams = params;
                masterSearchUrl = buildSearchUrl(params);
                masterServerBase = getServerBase(resourceType, masterQryParams);
              } else if (val.equalsIgnoreCase(QUERY)) {
                queryQryParams = params;
                querySearchUrl = buildSearchUrl(params);
                queryServerBase = getServerBase(resourceType, queryQryParams);
              }
            }
          }
        }

        if (masterSearchUrl == null) {
          final String errMsg =
              "Required Parameter for master record set is missing, bundle: " + bundle.getId();
          LOG.warn(errMsg);
          // Construct and return an error result
          respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.FATALERROR);
          respBuilder.outcomeIssueDiagnostics(errMsg);
          response = respBuilder.build();
          getProducer().sendBody(getProducerEndpointUri(), response);
          return;
        }

        LoggingInterceptor loggingInterceptor = null;
        if (LOG.isDebugEnabled()) {
          loggingInterceptor = new LoggingInterceptor(true);
          fhirRestClient.registerInterceptor(loggingInterceptor);
        }

        int numMasterRecs = 0;
        try {
          // Retrieve the data associated with the search urls
          numMasterRecs = retrieveAndStoreData(masterSearchUrl, masterServerBase, jobDir, "master");

          if (querySearchUrl != null) {
            isDeduplication = false;
            retrieveAndStoreData(querySearchUrl, queryServerBase, jobDir, "query");
          }

        } catch (BaseServerResponseException e) {
          final String errMsg =
              String.format(
                  "Error response from server.  code: %d, %s", e.getStatusCode(), e.getMessage());
          LOG.warn(errMsg);
          // Construct and return an error result
          respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.FATALERROR);
          respBuilder.outcomeIssueDiagnostics(errMsg);
          response = respBuilder.build();
          getProducer().sendBody(getProducerEndpointUri(), response);
          return;
        } catch (Exception e) {
          final String errMsg = String.format("Unable to retrieve messages: %s", e.getMessage());
          LOG.warn(errMsg, e);
          // Construct and return an error result
          respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.FATALERROR);
          respBuilder.outcomeIssueDiagnostics(errMsg);
          response = respBuilder.build();
          getProducer().sendBody(getProducerEndpointUri(), response);
          return;
        } finally {
          if (loggingInterceptor != null) {
            fhirRestClient.unregisterInterceptor(loggingInterceptor);
          }
        }

        // if no records were returned for the master record set query
        if (numMasterRecs == 0) {
          respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.OK);
          respBuilder.outcomeDetailText("No Records Found in Master Record Set");
          response = respBuilder.build();
        } else {
          final File configFile = prepareMatchingRuleConfiguration(isDeduplication, jobDir);

          // Perform the Match Operation
          LOG.debug("About to Start FRIL w/ config {}", configFile.getAbsolutePath());
          final int numMatches = findMatches(isDeduplication, configFile);
          LOG.info("FRIL Number of Matches: {}", numMatches);

          if (numMatches == 0) {
            respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.OK);
            respBuilder.outcomeDetailText("No Matches Found");
            response = respBuilder.build();

          } else if (numMatches > 0) {
            // Find the name of the file containing duplicates from the config
            // file
            final File dupsFile = getDuplicatesFile(configFile);
            // Ensure the duplicates file exists
            if (!dupsFile.exists()) {
              final String errMsg = "Unable to find duplicates file";
              LOG.error(errMsg + " at " + dupsFile.getAbsolutePath());
              throw new FileNotFoundException(errMsg);
            }

            // Construct results
            respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.OK);
            respBuilder.outcomeDetailText("Deduplication Complete");
            respBuilder.duplicates(dupsFile);
            response = respBuilder.build();

          } else {
            final String errMsg = "Unknown Processing Error";
            LOG.error("{} bundleId: {}", errMsg, bundle.getId());

            // Construct an error result
            respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.FATALERROR);
            respBuilder.outcomeIssueDiagnostics(errMsg);
            response = respBuilder.build();
          }
        }

      } catch (Exception e) {
        final String errMsg = "Unexpected Error";
        LOG.error("Processing bundle: {}", bundle.getId(), e);

        // Construct an error result
        respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.FATALERROR);
        respBuilder.outcomeIssueDiagnostics(errMsg);
        try {
          response = respBuilder.build();
        } catch (IOException ioe) {
          // only so many times we can attempt to send a response; log error
          LOG.error("Unable to Send Error Response. request bundle: {}", bundle.getId(), ioe);
        }
      }

      if (deleteJobResults) {
        // Delete the Job Results folder and content
        deleteFolder(jobDir);
      }
    } else {
      final String errMsg = "Unsupported Bundle type: " + bundle.getType().toString();
      LOG.info("{} msgId: {}", errMsg, bundle.getId());

      // Construct an error result
      respBuilder = new RecordMatchResultsBuilder(bundle, ResponseType.FATALERROR);
      respBuilder.outcomeIssueDiagnostics(errMsg);
      try {
        response = respBuilder.build();
      } catch (IOException e) {
        // only so many times we can attempt to send a response; log error
        LOG.error("Unable to Send Error Response. request bundle: {}", bundle.getId());
      }
    }

    // Send the response back to the requester
    if (response != null) {
      getProducer().sendBody(getProducerEndpointUri(), response);
    } else {
      LOG.error("Null Response for request! bundleId: {}", bundle.getId());
    }
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Before
  public void before() throws Exception {
    myFhirCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
    myFhirCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);

    if (ourServer == null) {
      ourPort = RandomServerPortProvider.findFreePort();

      ourRestServer = new RestfulServer(myFhirCtx);

      ourServerBase = "http://localhost:" + ourPort + "/fhir/context";

      ourRestServer.setResourceProviders((List) myResourceProviders);

      ourRestServer
          .getFhirContext()
          .setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator());

      myTerminologyUploaderProvider = myAppCtx.getBean(TerminologyUploaderProviderDstu3.class);

      ourRestServer.setPlainProviders(mySystemProvider, myTerminologyUploaderProvider);

      JpaConformanceProviderDstu3 confProvider =
          new JpaConformanceProviderDstu3(ourRestServer, mySystemDao, myDaoConfig);
      confProvider.setImplementationDescription("THIS IS THE DESC");
      ourRestServer.setServerConformanceProvider(confProvider);

      ourRestServer.setPagingProvider(myAppCtx.getBean(DatabaseBackedPagingProvider.class));

      Server server = new Server(ourPort);

      ServletContextHandler proxyHandler = new ServletContextHandler();
      proxyHandler.setContextPath("/");

      ServletHolder servletHolder = new ServletHolder();
      servletHolder.setServlet(ourRestServer);
      proxyHandler.addServlet(servletHolder, "/fhir/context/*");

      ourWebApplicationContext = new GenericWebApplicationContext();
      ourWebApplicationContext.setParent(myAppCtx);
      ourWebApplicationContext.refresh();
      //			ContextLoaderListener loaderListener = new ContextLoaderListener(webApplicationContext);
      //			loaderListener.initWebApplicationContext(mock(ServletContext.class));
      //
      proxyHandler
          .getServletContext()
          .setAttribute(
              WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
              ourWebApplicationContext);

      DispatcherServlet dispatcherServlet = new DispatcherServlet();
      //			dispatcherServlet.setApplicationContext(webApplicationContext);
      dispatcherServlet.setContextClass(AnnotationConfigWebApplicationContext.class);
      ServletHolder subsServletHolder = new ServletHolder();
      subsServletHolder.setServlet(dispatcherServlet);
      subsServletHolder.setInitParameter(
          ContextLoader.CONFIG_LOCATION_PARAM, WebsocketDstu3Config.class.getName());
      proxyHandler.addServlet(subsServletHolder, "/*");

      // Register a CORS filter
      CorsConfiguration config = new CorsConfiguration();
      CorsInterceptor corsInterceptor = new CorsInterceptor(config);
      config.addAllowedHeader("x-fhir-starter");
      config.addAllowedHeader("Origin");
      config.addAllowedHeader("Accept");
      config.addAllowedHeader("X-Requested-With");
      config.addAllowedHeader("Content-Type");
      config.addAllowedHeader("Access-Control-Request-Method");
      config.addAllowedHeader("Access-Control-Request-Headers");
      config.addAllowedOrigin("*");
      config.addExposedHeader("Location");
      config.addExposedHeader("Content-Location");
      config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
      ourRestServer.registerInterceptor(corsInterceptor);

      server.setHandler(proxyHandler);
      server.start();

      WebApplicationContext wac =
          WebApplicationContextUtils.getWebApplicationContext(
              subsServletHolder.getServlet().getServletConfig().getServletContext());
      myValidationSupport = wac.getBean(JpaValidationSupportChainDstu3.class);

      ourClient = myFhirCtx.newRestfulGenericClient(ourServerBase);
      ourClient.registerInterceptor(new LoggingInterceptor(true));

      PoolingHttpClientConnectionManager connectionManager =
          new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
      HttpClientBuilder builder = HttpClientBuilder.create();
      builder.setConnectionManager(connectionManager);
      ourHttpClient = builder.build();

      ourServer = server;
    }
  }
Esempio n. 7
0
  public static void establishScene() {
    initScrollData();
    Main.hLeft = new VBox(20);
    Main.hLeft.setEffect(new DropShadow());
    Main.hLeft.setAlignment(Pos.CENTER);
    Main.hLeft.setBackground(new Background(Main.myBG));
    Main.hLeft.setMinHeight(Main.height);
    Main.hLeft.setMinWidth(Main.width / 2 - 100);

    Main.hRight = new VBox(18);
    Main.hRight.setAlignment(Pos.TOP_CENTER);
    Main.hRight.setMinHeight(Main.height);
    Main.hRight.setMinWidth(Main.width / 2 + 100);
    Main.hRight.setPadding(new Insets(20, 0, 0, 20));

    // Create Dividers
    VBox stats = new VBox(10);
    stats.setAlignment(Pos.CENTER);

    // Patient Portal
    Image pp = new Image("file:src/docketdoc/res/PD_Logo.png");
    ImageView pap = new ImageView(pp);
    VBox patientPortal = new VBox();
    patientPortal.setAlignment(Pos.CENTER);
    patientPortal.setPadding(new Insets(10, 10, 10, 10));

    // Label
    Label lp = new Label("Patient Portal");
    lp.setStyle("-fx-font: 25px Futura;" + "-fx-text-fill: #66CDAA;");

    patientPortal.getChildren().addAll(pap, lp);

    // Search Patient
    TextField searchTF = new TextField();
    searchTF.setStyle(
        "-fx-max-height: 50px;"
            + "-fx-max-width: 200px;"
            + "-fx-text-fill: #505050;"
            + "-fx-font: 12px Futura;"
            + "-fx-prompt-text-fill: #505050;");
    searchTF.setPromptText("First Name");

    TextField searchTFlast = new TextField();
    searchTFlast.setStyle(
        "-fx-max-height: 50px;"
            + "-fx-max-width: 200px;"
            + "-fx-text-fill: #505050;"
            + "-fx-font: 12px Futura;"
            + "-fx-prompt-text-fill: #505050;");
    searchTFlast.setPromptText("Last Name");

    // Interact Button
    Button searchName = new Button("Search Name");
    searchName.setStyle(
        "-fx-background-radius: 0;"
            + "-fx-font: 16px Futura;"
            + "-fx-font-weight: bold;"
            + "-fx-text-fill: white;"
            + "-fx-background-color: #FF7F50;");

    // Hover animation.
    searchName.setOnMouseEntered(
        e -> {
          searchName.setOpacity(.5);
        });
    searchName.setOnMouseExited(
        e -> {
          searchName.setOpacity(2);
        });

    // Button Search for Name
    searchName.setOnAction(
        e -> {
          /* ------------------------------------ */
          /* Search patiend directory by FHIR API */
          /* ------------------------------------ */
          new FhirContext();
          // Create a client (only needed once)
          FhirContext ctx = FhirContext.forDstu2();
          IGenericClient client =
              ctx.newRestfulGenericClient("http://fhir2.healthintersections.com.au/open");

          String search = new String(searchTF.getText() + " " + searchTFlast.getText());

          // Invoke the client
          Bundle bundle =
              client
                  .search()
                  .forResource(Patient.class)
                  .where(Patient.NAME.matchesExactly().value(search))
                  .encodedJson()
                  .execute();

          System.out.println("patients count=" + bundle.size());
          List<Patient> list = bundle.getResources(Patient.class);
          for (Patient p : list) {
            namess = p.getNameFirstRep().getText();
            agess = p.getBirthDateElement().toHumanDisplay();
            sexess = p.getGender();
          }
          // Add to grid then display

          // Update Name
          nameShow = new Label(namess.toUpperCase());
          namePat.getChildren().remove(nameShow);
          patientData.getChildren().remove(namePat);
          nameShow.setStyle("-fx-font: 15px Futura;" + "-fx-text-fill: #ff0080;");
          namePat.getChildren().addAll(nameShow);
          patientData.getChildren().add(namePat);

          // Update Age
          ageShow = new Label(agess.toUpperCase());
          agePat.getChildren().remove(ageShow);
          patientData.getChildren().remove(agePat);
          ageShow.setStyle("-fx-font: 15px Futura;" + "-fx-text-fill: #ff0080;");
          agePat.getChildren().addAll(ageShow);
          patientData.getChildren().add(agePat);

          // Update Sex
          sexShow = new Label(sexess.toUpperCase());
          sexPat.getChildren().remove(sexShow);
          patientData.getChildren().remove(sexPat);
          sexShow.setStyle("-fx-font: 15px Futura;" + "-fx-text-fill: #ff0080;");
          sexPat.getChildren().addAll(sexShow);
          patientData.getChildren().add(sexPat);

          addScrollData();
          searchTF.setText(null);
          searchTFlast.setText(null);
        });

    /* ----------------------------------------- */
    /* Right Side contained within a scroll Pane */
    /* ----------------------------------------- */
    patientData = new VBox(10);

    // Name Divisors
    pname = new Label("NAME:\t");
    pname.setStyle("-fx-font: 15px Futura;" + "-fx-text-fill: #66CDAA;" + "-fx-font-weight: bold;");
    namePat = new HBox(10);
    namePat.getChildren().addAll(pname, nameShow);

    // Age Divisors
    page = new Label("DOB:\t");
    page.setStyle("-fx-font: 15px Futura;" + "-fx-text-fill: #66CDAA;" + "-fx-font-weight: bold;");
    agePat = new HBox(10);
    agePat.getChildren().addAll(page, ageShow);

    // Gender Divisors
    psex = new Label("SEX:\t\t");
    psex.setStyle("-fx-font: 15px Futura;" + "-fx-text-fill: #66CDAA;" + "-fx-font-weight: bold;");
    sexPat = new HBox(10);
    sexPat.getChildren().addAll(psex, sexShow);

    patientData.getChildren().addAll(namePat, agePat, sexPat);

    // Scrolls
    scrollSocial.setContent(soScroll);
    scrollMedical.setContent(medScroll);
    scrollHistory.setContent(hisScroll);

    // Add search results to right side
    Main.hRight.getChildren().addAll(patientData, scrollMedical, scrollSocial, hisScroll);

    // Add elements to Left Side
    stats.getChildren().addAll(patientPortal, searchTF, searchTFlast, searchName);

    // Set Main stage to home scene

    Main.hLeft.getChildren().addAll(stats);
    Main.containHome = new HBox();
    Main.containHome.getChildren().addAll(Main.hLeft, Main.hRight);
    Main.homeScene = new Scene(Main.containHome);
  }