ca.uhn.fhir.rest.api.EncodingEnum Java Examples

The following examples show how to use ca.uhn.fhir.rest.api.EncodingEnum. 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: HapiProperties.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 5 votes vote down vote up
public static EncodingEnum getDefaultEncoding() {
  String defaultEncodingString = HapiProperties.getProperty(DEFAULT_ENCODING);

  if (defaultEncodingString != null && defaultEncodingString.length() > 0) {
    return EncodingEnum.valueOf(defaultEncodingString);
  }

  return EncodingEnum.JSON;
}
 
Example #2
Source File: HapiProperties.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
public static EncodingEnum getDefaultEncoding() {
    String defaultEncodingString = HapiProperties.getProperty(DEFAULT_ENCODING);

    if (defaultEncodingString != null && defaultEncodingString.length() > 0) {
        return EncodingEnum.valueOf(defaultEncodingString);
    }

    return EncodingEnum.JSON;
}
 
Example #3
Source File: HapiProperties.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
public static EncodingEnum getDefaultEncoding() {
    String defaultEncodingString = HapiProperties.getProperty(DEFAULT_ENCODING);

    if (defaultEncodingString != null && defaultEncodingString.length() > 0) {
        return EncodingEnum.valueOf(defaultEncodingString);
    }

    return EncodingEnum.JSON;
}
 
Example #4
Source File: ExampleServerDstu3IT.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebsocketSubscription() throws Exception {
	/*
	 * Create subscription
	 */
	Subscription subscription = new Subscription();
	subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
	subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
	subscription.setCriteria("Observation?status=final");

	Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
	channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
	channel.setPayload("application/json");
	subscription.setChannel(channel);

	MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
	IIdType mySubscriptionId = methodOutcome.getId();

	// Wait for the subscription to be activated
	waitForSize(1, () -> ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size());

	/*
	 * Attach websocket
	 */

	WebSocketClient myWebSocketClient = new WebSocketClient();
	SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);

	myWebSocketClient.start();
	URI echoUri = new URI("ws://localhost:" + ourPort + "/hapi-fhir-jpaserver/websocket");
	ClientUpgradeRequest request = new ClientUpgradeRequest();
	ourLog.info("Connecting to : {}", echoUri);
	Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
	Session session = connection.get(2, TimeUnit.SECONDS);

	ourLog.info("Connected to WS: {}", session.isOpen());

	/*
	 * Create a matching resource
	 */
	Observation obs = new Observation();
	obs.setStatus(Observation.ObservationStatus.FINAL);
	ourClient.create().resource(obs).execute();

	// Give some time for the subscription to deliver
	Thread.sleep(2000);

	/*
	 * Ensure that we receive a ping on the websocket
	 */
	waitForSize(1, () -> mySocketImplementation.myPingCount);

	/*
	 * Clean up
	 */
	ourClient.delete().resourceById(mySubscriptionId).execute();
}
 
Example #5
Source File: ExampleServerR4IT.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebsocketSubscription() throws Exception {
    /*
     * Create subscription
     */
    Subscription subscription = new Subscription();
    subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
    subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
    subscription.setCriteria("Observation?status=final");

    Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
    channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
    channel.setPayload("application/json");
    subscription.setChannel(channel);

    MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
    IIdType mySubscriptionId = methodOutcome.getId();

    // Wait for the subscription to be activated
    waitForSize(1, () -> ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size());

    /*
     * Attach websocket
     */

    WebSocketClient myWebSocketClient = new WebSocketClient();
    SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);

    myWebSocketClient.start();
    URI echoUri = new URI("ws://localhost:" + ourPort + "/hapi-fhir-jpaserver/websocket");
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    ourLog.info("Connecting to : {}", echoUri);
    Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
    Session session = connection.get(2, TimeUnit.SECONDS);

    ourLog.info("Connected to WS: {}", session.isOpen());

    /*
     * Create a matching resource
     */
    Observation obs = new Observation();
    obs.setStatus(Observation.ObservationStatus.FINAL);
    ourClient.create().resource(obs).execute();

    // Give some time for the subscription to deliver
    Thread.sleep(2000);

    /*
     * Ensure that we receive a ping on the websocket
     */
    waitForSize(1, () -> mySocketImplementation.myPingCount);

    /*
     * Clean up
     */
    ourClient.delete().resourceById(mySubscriptionId).execute();
}
 
Example #6
Source File: SocketImplementation.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 4 votes vote down vote up
public SocketImplementation(String theCriteria, EncodingEnum theEncoding) {
	myCriteria = theCriteria;
}
 
Example #7
Source File: ExampleServerR5IT.java    From hapi-fhir-jpaserver-starter with Apache License 2.0 4 votes vote down vote up
@Test
public void testWebsocketSubscription() throws Exception {

    /*
     * Create topic
     */
    SubscriptionTopic topic = new SubscriptionTopic();
    topic.getResourceTrigger().getQueryCriteria().setCurrent("Observation?status=final");

    /*
     * Create subscription
     */
    Subscription subscription = new Subscription();
    subscription.getTopic().setResource(topic);
    subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
    subscription.setStatus(Enumerations.SubscriptionState.REQUESTED);
    subscription.getChannelType()
            .setSystem("http://terminology.hl7.org/CodeSystem/subscription-channel-type")
            .setCode("websocket");
    subscription.setContentType("application/json");

    MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
    IIdType mySubscriptionId = methodOutcome.getId();

    // Wait for the subscription to be activated
    waitForSize(1, () -> ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size());

    /*
     * Attach websocket
     */

    WebSocketClient myWebSocketClient = new WebSocketClient();
    SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);

    myWebSocketClient.start();
    URI echoUri = new URI("ws://localhost:" + ourPort + "/hapi-fhir-jpaserver/websocket");
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    ourLog.info("Connecting to : {}", echoUri);
    Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
    Session session = connection.get(2, TimeUnit.SECONDS);

    ourLog.info("Connected to WS: {}", session.isOpen());

    /*
     * Create a matching resource
     */
    Observation obs = new Observation();
    obs.setStatus(Enumerations.ObservationStatus.FINAL);
    ourClient.create().resource(obs).execute();

    // Give some time for the subscription to deliver
    Thread.sleep(2000);

    /*
     * Ensure that we receive a ping on the websocket
     */
    waitForSize(1, () -> mySocketImplementation.myPingCount);

    /*
     * Clean up
     */
    ourClient.delete().resourceById(mySubscriptionId).execute();
}
 
Example #8
Source File: CCRequestValidatingInterceptor.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
public boolean incomingRequestPostProcessed(RequestDetails theRequestDetails, HttpServletRequest theRequest, HttpServletResponse theResponse) throws AuthenticationException {
    EncodingEnum encoding = RestfulServerUtils.determineRequestEncodingNoDefault(theRequestDetails);

    if (encoding == null || theRequestDetails.getOperation() != null) {
        log.trace("Incoming request does not appear to be FHIR, not going to validate");
        return true;
    } else {
        Charset charset = ResourceParameter.determineRequestCharset(theRequestDetails);
        String requestText = new String(theRequestDetails.loadRequestContents(), charset);
        if (StringUtils.isBlank(requestText)) {
            log.trace("Incoming request does not have a body");
            return true;
        } else {
            //log.info(theRequest.getMethod());
            if ((theRequest.getMethod().equals("POST") && !theRequest.getRequestURI().contains("$validate") ) || theRequest.getMethod().equals("PUT")) {


                IBaseResource resource = null;
                switch (encoding) {
                    case JSON:
                        resource = ctx.newJsonParser().parseResource(requestText);
                        break;
                    case XML:
                        resource = ctx.newXmlParser().parseResource(requestText);
                        break;
                }
                if (resource instanceof Bundle) {
                    Bundle bundle = (Bundle) resource;
                    for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
                       entry.setResource((Resource) setProfile(entry.getResource()));
                    }
                } else {
                    resource = setProfile(resource);
                }

                // Should not need to convert in the interceptor.


                try {

                    results = this.fhirValidator.validateWithResult(resource);
                } catch (Exception val) {
                    log.error(val.getMessage());
                    return true;
                }

                //OperationOutcome outcomeR4 = ;

                OperationOutcome outcome = null;
                if (results.toOperationOutcome() instanceof org.hl7.fhir.r4.model.OperationOutcome) {OperationOutcomeFactory.removeUnsupportedIssues((org.hl7.fhir.r4.model.OperationOutcome) results.toOperationOutcome(), null);
                    outcome = OperationOutcomeFactory.removeUnsupportedIssues((org.hl7.fhir.r4.model.OperationOutcome) results.toOperationOutcome(), null);
                } else {
                    outcome = OperationOutcomeFactory.removeUnsupportedIssues((OperationOutcome) results.toOperationOutcome());
                }


                if (!pass(outcome)) {
                    log.info("VALIDATION FAILED");
                    System.out.println(ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(outcome));
                    throw new UnprocessableEntityException(theRequestDetails.getServer().getFhirContext(), outcome);
                }
            }
            return true;
        }
    }
}
 
Example #9
Source File: JpaRestfulServerR4.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void initialize() throws ServletException {
    super.initialize();
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    // Get the spring context from the web container (it's declared in web.xml)
    FhirVersionEnum fhirVersion = FhirVersionEnum.R4;
    setFhirContext(new FhirContext(fhirVersion));
    String serverBase = HapiProperties.getServerAddress();
    if (serverBase != null && !serverBase.isEmpty()) {
        setServerAddressStrategy(new HardcodedServerAddressStrategy(serverBase));
    }

    if (applicationContext == null ) log.info("Context is null");

    AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    autowireCapableBeanFactory.autowireBean(this);

    List<IResourceProvider> permissionlist = new ArrayList<>();
    Class<?> classType = null;
    try {
        classType = Class.forName("uk.nhs.careconnect.ccri.fhirserver.r4.provider.ObservationDefinitionProvider");
        log.info("class methods " + classType.getMethods()[4].getName() );
    } catch (ClassNotFoundException  e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }

    permissionlist.add((IResourceProvider) applicationContext.getBean(classType));
    setResourceProviders(permissionlist);

    // Replace built in conformance provider (CapabilityStatement)
    setServerConformanceProvider(new CareConnectServerConformanceR4Provider());

    setServerName(HapiProperties.getServerName());
    setServerVersion(HapiProperties.getSoftwareVersion());
    setImplementationDescription(HapiProperties.getSoftwareImplementationDesc());


    ServerInterceptor loggingInterceptor = new ServerInterceptor(log);
    registerInterceptor(loggingInterceptor);




    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedHeader("x-fhir-starter");
    config.addAllowedHeader("Origin");
    config.addAllowedHeader("Accept");
    config.addAllowedHeader("X-Requested-With");
    config.addAllowedHeader("Content-Type");

    config.addAllowedOrigin("*");

    config.addExposedHeader("Location");
    config.addExposedHeader("Content-Location");
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));

    // Create the interceptor and register it
    CorsInterceptor interceptor = new CorsInterceptor(config);
    registerInterceptor(interceptor);

    ServerInterceptor gatewayInterceptor = new ServerInterceptor(log);
    if (HapiProperties.getSecurityOauth()) {
        registerInterceptor(new OAuth2Interceptor());  // Add OAuth2 Security Filter
    }
    registerInterceptor(gatewayInterceptor);

    FifoMemoryPagingProvider pp = new FifoMemoryPagingProvider(10);
    pp.setDefaultPageSize(10);
    pp.setMaximumPageSize(100);
    setPagingProvider(pp);

    setDefaultPrettyPrint(true);
    setDefaultResponseEncoding(EncodingEnum.JSON);

    ctx = getFhirContext();


    registerInterceptor( new ResponseHighlighterInterceptor());

    // Remove as believe due to issues on docker ctx.setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator());
}