Search in sources :

Example 56 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project dpc-app by CMSgov.

the class OrganizationRegistration method run.

@Override
public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception {
    System.out.println("Registering Organization");
    // Read the file and parse it
    final Path filePath = FileSystems.getDefault().getPath(namespace.getString(ORG_FILE)).normalize().toAbsolutePath();
    Bundle organization;
    try (FileInputStream fileInputStream = new FileInputStream(new File(filePath.toUri()))) {
        final IParser parser = ctx.newJsonParser();
        organization = (Bundle) parser.parseResource(fileInputStream);
    }
    final boolean noToken = Boolean.parseBoolean(namespace.getString("no-token"));
    final String apiService = namespace.getString("api-service");
    registerOrganization(organization, namespace.getString(ATTR_HOSTNAME), noToken, apiService);
}
Also used : Path(java.nio.file.Path) Bundle(org.hl7.fhir.dstu3.model.Bundle) File(java.io.File) FileInputStream(java.io.FileInputStream) IParser(ca.uhn.fhir.parser.IParser)

Example 57 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project dpc-app by CMSgov.

the class ParamResourceFactoryTest method testUnnamedResource.

@Test
void testUnnamedResource() throws IOException {
    final Parameters parameters = new Parameters();
    final Patient dummyPatient = new Patient();
    parameters.addParameter().setResource(dummyPatient);
    final HttpServletRequest mock = Mockito.mock(HttpServletRequest.class);
    final ServletInputStream mockStream = Mockito.mock(ServletInputStream.class);
    final IParser parser = Mockito.mock(IParser.class);
    Mockito.when(parser.parseResource(Mockito.eq(Parameters.class), Mockito.any(InputStream.class))).thenReturn(parameters);
    final Injector mockInjector = Mockito.mock(Injector.class);
    Mockito.when(mockInjector.getInstance(HttpServletRequest.class)).thenReturn(mock);
    Mockito.when(mock.getInputStream()).thenReturn(mockStream);
    final Parameter parameter = Mockito.mock(Parameter.class);
    final FHIRParameter annotation = Mockito.mock(FHIRParameter.class);
    Mockito.when(annotation.name()).thenReturn("");
    Mockito.when(parameter.getAnnotation(FHIRParameter.class)).thenReturn(annotation);
    Mockito.when(parameter.getRawType()).thenAnswer(answer -> Patient.class);
    final ParamResourceFactory factory = new ParamResourceFactory(mockInjector, parameter, parser);
    assertTrue(dummyPatient.equalsDeep((Patient) factory.provide()), "Should have returned dummy patient");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Parameters(org.hl7.fhir.dstu3.model.Parameters) ServletInputStream(javax.servlet.ServletInputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) Injector(com.google.inject.Injector) FHIRParameter(gov.cms.dpc.fhir.annotations.FHIRParameter) Patient(org.hl7.fhir.dstu3.model.Patient) FHIRParameter(gov.cms.dpc.fhir.annotations.FHIRParameter) Parameter(org.glassfish.jersey.server.model.Parameter) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.jupiter.api.Test)

Example 58 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project dpc-app by CMSgov.

the class ParamResourceFactoryTest method testMismatchedParameterType.

@Test
void testMismatchedParameterType() throws IOException {
    final Parameters parameters = new Parameters();
    final Patient dummyPatient = new Patient();
    parameters.addParameter().setResource(dummyPatient);
    final HttpServletRequest mock = Mockito.mock(HttpServletRequest.class);
    final ServletInputStream mockStream = Mockito.mock(ServletInputStream.class);
    final IParser parser = Mockito.mock(IParser.class);
    Mockito.when(parser.parseResource(Mockito.eq(Parameters.class), Mockito.any(InputStream.class))).thenReturn(parameters);
    final Injector mockInjector = Mockito.mock(Injector.class);
    Mockito.when(mockInjector.getInstance(HttpServletRequest.class)).thenReturn(mock);
    Mockito.when(mock.getInputStream()).thenReturn(mockStream);
    final Parameter parameter = Mockito.mock(Parameter.class);
    final FHIRParameter annotation = Mockito.mock(FHIRParameter.class);
    Mockito.when(annotation.name()).thenReturn("");
    Mockito.when(parameter.getAnnotation(FHIRParameter.class)).thenReturn(annotation);
    Mockito.when(parameter.getRawType()).thenAnswer(answer -> Practitioner.class);
    final ParamResourceFactory factory = new ParamResourceFactory(mockInjector, parameter, parser);
    final WebApplicationException exception = assertThrows(WebApplicationException.class, factory::provide, "Should throw an exception");
    assertAll(() -> assertEquals(HttpStatus.BAD_REQUEST_400, exception.getResponse().getStatus(), "Should be a bad request"), () -> assertEquals("Provided resource must be: `Practitioner`, not `Patient`", exception.getMessage(), "Should have useful message"));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Parameters(org.hl7.fhir.dstu3.model.Parameters) ServletInputStream(javax.servlet.ServletInputStream) WebApplicationException(javax.ws.rs.WebApplicationException) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) Injector(com.google.inject.Injector) FHIRParameter(gov.cms.dpc.fhir.annotations.FHIRParameter) Patient(org.hl7.fhir.dstu3.model.Patient) FHIRParameter(gov.cms.dpc.fhir.annotations.FHIRParameter) Parameter(org.glassfish.jersey.server.model.Parameter) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.jupiter.api.Test)

Example 59 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project dpc-app by CMSgov.

the class FHIRHelpers method registerOrganization.

/**
 * Register an organization with the Attribution Service
 * Organizations are pulled from the `organization_bundle.json` file and filtered based on the provided resource ID
 *
 * @param client         - {@link IGenericClient} client to communicate to attribution service
 * @param parser         - {@link IParser} to use for reading {@link Bundle} JSON
 * @param organizationID - {@link String} organization ID to filter for
 * @param adminURL       - {@link String} Base url for executing admin tasks
 * @return - {@link String} Access token generated for the {@link Organization}
 * @throws IOException - Throws if HTTP client fails
 */
public static String registerOrganization(IGenericClient client, IParser parser, String organizationID, String organizationNPI, String adminURL) throws IOException {
    // Random number generator for Org NPI
    // Register an organization, and a token
    // Read in the test file
    String macaroon;
    try (InputStream inputStream = FHIRHelpers.class.getClassLoader().getResourceAsStream("organization.tmpl.json")) {
        final Bundle orgBundle = (Bundle) parser.parseResource(inputStream);
        // Update the Organization resource and set a random NPI
        final Organization origOrg = (Organization) orgBundle.getEntryFirstRep().getResource();
        origOrg.getIdentifierFirstRep().setValue(organizationNPI);
        origOrg.setId(organizationID);
        final Parameters parameters = new Parameters();
        parameters.addParameter().setResource(orgBundle).setName("resource");
        client.operation().onType(Organization.class).named("submit").withParameters(parameters).returnResourceType(Organization.class).encodedJson().execute();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            final URIBuilder uriBuilder = new URIBuilder(String.format("%s/generate-token", adminURL));
            uriBuilder.setParameter("organization", organizationID);
            // Now, create a Macaroon
            final HttpPost tokenPost = new HttpPost(uriBuilder.build());
            try (CloseableHttpResponse response = httpClient.execute(tokenPost)) {
                if (response.getStatusLine().getStatusCode() != HttpStatus.OK_200) {
                    throw new IllegalStateException(String.format("Unable to generate token: %s", response.getStatusLine().getReasonPhrase()));
                }
                macaroon = EntityUtils.toString(response.getEntity());
            }
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Cannot parse URI", e);
        }
    }
    return macaroon;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) Organization(org.hl7.fhir.dstu3.model.Organization) Parameters(org.hl7.fhir.dstu3.model.Parameters) InputStream(java.io.InputStream) Bundle(org.hl7.fhir.dstu3.model.Bundle) URISyntaxException(java.net.URISyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 60 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project dpc-app by CMSgov.

the class PractitionerResourceTest method ensurePractitionersExist.

@Test
void ensurePractitionersExist() throws IOException, URISyntaxException, GeneralSecurityException {
    final IParser parser = ctx.newJsonParser();
    final IGenericClient attrClient = APITestHelpers.buildAttributionClient(ctx);
    IGenericClient client = APIAuthHelpers.buildAuthenticatedClient(ctx, getBaseURL(), ORGANIZATION_TOKEN, PUBLIC_KEY_ID, PRIVATE_KEY);
    APITestHelpers.setupPractitionerTest(client, parser);
    // Find everything attributed
    final Bundle practitioners = client.search().forResource(Practitioner.class).returnBundle(Bundle.class).encodedJson().execute();
    assertEquals(4, practitioners.getTotal(), "Should have all the providers");
    final Bundle specificSearch = client.search().forResource(Practitioner.class).where(Practitioner.IDENTIFIER.exactly().code("1232131239")).returnBundle(Bundle.class).encodedJson().execute();
    assertEquals(1, specificSearch.getTotal(), "Should have a specific provider");
    // Fetch the provider directly
    final Practitioner foundProvider = (Practitioner) specificSearch.getEntryFirstRep().getResource();
    final IReadExecutable<Practitioner> clientQuery = client.read().resource(Practitioner.class).withId(foundProvider.getIdElement()).encodedJson();
    final Practitioner queriedProvider = clientQuery.execute();
    assertTrue(foundProvider.equalsDeep(queriedProvider), "Search and GET should be identical");
    // Try to delete the practitioner
    client.delete().resourceById(queriedProvider.getIdElement()).encodedJson().execute();
    // Try again, should be not found
    assertThrows(AuthenticationException.class, clientQuery::execute, "Should not have practitioner");
    // Create a new org and make sure it has no providers
    final String m2 = FHIRHelpers.registerOrganization(attrClient, parser, OTHER_ORG_ID, "1112111111", getAdminURL());
    // Submit a new public key to use for JWT flow
    final String keyLabel = "new-key";
    final Pair<UUID, PrivateKey> uuidPrivateKeyPair = APIAuthHelpers.generateAndUploadKey(keyLabel, OTHER_ORG_ID, GOLDEN_MACAROON, getBaseURL());
    // Update the authenticated client to use the new organization
    client = APIAuthHelpers.buildAuthenticatedClient(ctx, getBaseURL(), m2, uuidPrivateKeyPair.getLeft(), uuidPrivateKeyPair.getRight());
    final Bundle otherPractitioners = client.search().forResource(Practitioner.class).returnBundle(Bundle.class).encodedJson().execute();
    assertEquals(0, otherPractitioners.getTotal(), "Should not have any practitioners");
    // Try to look for one of the other practitioners
    final Bundle otherSpecificSearch = client.search().forResource(Practitioner.class).where(Practitioner.IDENTIFIER.exactly().identifier(foundProvider.getIdentifierFirstRep().getValue())).returnBundle(Bundle.class).encodedJson().execute();
    assertEquals(0, otherSpecificSearch.getTotal(), "Should not have a specific provider");
// Try to search for our fund provider
}
Also used : Practitioner(org.hl7.fhir.dstu3.model.Practitioner) PrivateKey(java.security.PrivateKey) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) Bundle(org.hl7.fhir.dstu3.model.Bundle) UUID(java.util.UUID) IParser(ca.uhn.fhir.parser.IParser) AbstractSecureApplicationTest(gov.cms.dpc.api.AbstractSecureApplicationTest) Test(org.junit.jupiter.api.Test)

Aggregations

IParser (ca.uhn.fhir.parser.IParser)89 FhirContext (ca.uhn.fhir.context.FhirContext)43 IOException (java.io.IOException)35 ByteArrayOutputStream (java.io.ByteArrayOutputStream)30 Test (org.junit.Test)24 InputStream (java.io.InputStream)22 IParser (org.hl7.fhir.r5.formats.IParser)19 JsonParser (org.hl7.fhir.r5.formats.JsonParser)18 Test (org.junit.jupiter.api.Test)18 FHIRException (org.hl7.fhir.exceptions.FHIRException)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 File (java.io.File)16 FileInputStream (java.io.FileInputStream)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 Bundle (org.hl7.fhir.r4.model.Bundle)14 FileOutputStream (java.io.FileOutputStream)12 Bundle (org.hl7.fhir.dstu3.model.Bundle)12 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)12 XmlParser (org.hl7.fhir.r5.formats.XmlParser)12 ArrayList (java.util.ArrayList)11