下面列出了javax.ws.rs.client.Entity#entity ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testPost() {
Assume.assumeTrue(databaseConfigured);
String url = contextRoot + testDatabase;
System.out.println("Testing " + url);
JsonObject data = Json.createObjectBuilder().add("weather", "sunny").build();
String dataString = data.toString();
Entity<String> ent = Entity.entity(dataString, MediaType.APPLICATION_JSON);
Response response = sendRequest(url, RequestType.POST, ent);
String responseString = response.readEntity(String.class);
int responseCode = response.getStatus();
response.close();
System.out.println("Returned " + responseString);
assertTrue("Incorrect response code: " + responseCode + " Response string is " + responseString,
responseCode == 200);
}
@Test
public void testJAXBClientPut() throws InterruptedException {
WebTarget webTarget = createDefaultTarget().path("create");
registerAddon(new TestJAXBAddon());
Product p = new Product();
p.description = "Description: BAR";
p.id = 10023;
p.name = "BAR";
p.price = 100;
Entity<Product> entity = Entity.entity(p, MediaType.APPLICATION_XML_TYPE);
Response response = webTarget.request(MediaType.APPLICATION_XML).put(entity);
assertEquals(200, response.getStatus());
assertEquals(p.id + "", response.readEntity(String.class));
}
@Test
public void testCreatePatient3() throws Exception {
WebTarget target = getWebTarget();
// Build a new Patient and then call the 'create' API.
Patient patient = TestUtil.readLocalResource("patient-example-a.json");
Entity<Patient> entity = Entity.entity(patient, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
// Get the patient's logical id value.
patientId = getLocationLogicalId(response);
// Next, call the 'read' API to retrieve the new patient and verify it.
response =
target.path("Patient/" + patientId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
Patient responsePatient = response.readEntity(Patient.class);
TestUtil.assertResourceEquals(patient, responsePatient);
}
@Test(groups = { "batch" }, dependsOnMethods = { "testBatchUpdates" })
public void testBatchReads() throws Exception {
String method = "testBatchReads";
WebTarget target = getWebTarget();
assertNotNull(locationB1);
// Perform a 'read' and a 'vread'.
Bundle bundle = buildBundle(BundleType.BATCH);
bundle = addRequestToBundle(null, bundle, HTTPVerb.GET, "Patient/" + patientB2.getId(), null, null);
bundle = addRequestToBundle(null, bundle, HTTPVerb.GET, locationB1, null, null);
printBundle(method, "request", bundle);
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.request().post(entity, Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
Bundle responseBundle = getEntityWithExtraWork(response,method);
assertResponseBundle(responseBundle, BundleType.BATCH_RESPONSE, 2);
assertGoodGetResponse(responseBundle.getEntry().get(0), Status.OK.getStatusCode());
assertGoodGetResponse(responseBundle.getEntry().get(1), Status.OK.getStatusCode());
}
@Test(groups = { "batch" })
public void testInvalidResource() throws Exception {
WebTarget target = getWebTarget();
JsonObjectBuilder bundleObject = TestUtil.getEmptyBundleJsonObjectBuilder();
JsonObject PatientJsonObject = TestUtil.readJsonObject("InvalidPatient.json");
JsonObject requestJsonObject = TestUtil.getRequestJsonObject("POST", "Patient");
JsonObjectBuilder resourceObject = Json.createBuilderFactory(null).createObjectBuilder();
resourceObject.add( "resource", PatientJsonObject).add("request", requestJsonObject);
bundleObject.add("Entry", Json.createBuilderFactory(null).createArrayBuilder().add(resourceObject));
Entity<JsonObject> entity = Entity.entity(bundleObject.build(), FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.request().post(entity, Response.class);
assertTrue(response.getStatus() >= 400);
}
@Test(groups = { "batch" })
public void testIncorrectMethod() throws Exception {
// If the "delete" operation is supported by the server, then we can't use
// DELETE
// to test out an incorrect method in a bundle request entry :)
if (deleteSupported) {
return;
}
String method = "testIncorrectMethod";
WebTarget target = getWebTarget();
Bundle bundle = buildBundle(BundleType.BATCH);
bundle = addRequestToBundle(null, bundle, HTTPVerb.DELETE, "placeholder", null, null);
printBundle(method, "request", bundle);
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.request().post(entity, Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
Bundle responseBundle = response.readEntity(Bundle.class);
assertResponseBundle(responseBundle, BundleType.BATCH_RESPONSE, 1);
printBundle(method, "response", responseBundle);
assertBadResponse(responseBundle.getEntry().get(0), Status.BAD_REQUEST.getStatusCode(),
"Bundle.Entry.request contains unsupported HTTP method");
}
/**
* Create a Patient, then make sure we can retrieve it.
*/
@Test(groups = { "websocket-notifications" })
public void testCreatePatient() throws Exception {
if (!ON) {
System.out.println("skipping this test ");
} else {
// Build a new Patient and then call the 'create' API.
Patient patient = TestUtil.readLocalResource("Patient_JohnDoe.json");
Entity<Patient> entity = Entity.entity(patient, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
// Get the patient's logical id value.
String patientId = getLocationLogicalId(response);
System.out.println(">>> [CREATE] Patient Resource -> Id: " + patientId);
// Next, call the 'read' API to retrieve the new patient and verify it.
response = target.path("Patient/"
+ patientId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
Patient responsePatient = response.readEntity(Patient.class);
savedCreatedPatient = responsePatient;
FHIRNotificationEvent event = getEvent(responsePatient.getId());
assertEquals(event.getResourceId(), responsePatient.getId());
TestUtil.assertResourceEquals(patient, responsePatient);
}
}
public void loadCareteam() throws Exception {
WebTarget target = getWebTarget();
CareTeam careTeam = TestUtil.readExampleResource("json/spec/careteam-example.json");
Entity<CareTeam> entity = Entity.entity(careTeam, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("CareTeam").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
careTeamId = getLocationLogicalId(response);
response = target.path("CareTeam/" + careTeamId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
@Override
public FHIRResponse invoke(String resourceType, String operationName, Resource resource, FHIRRequestHeader... headers) throws Exception {
if (resourceType == null) {
throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
}
if (operationName == null) {
throw new IllegalArgumentException("The 'operationName' argument is required but was null.");
}
WebTarget endpoint = getWebTarget();
Entity<Parameters> entity = Entity.entity((Parameters)resource, getDefaultMimeType());
Invocation.Builder builder = endpoint.path(resourceType).path(operationName).request();
builder = addRequestHeaders(builder, headers);
Response response = builder.post(entity);
return new FHIRResponseImpl(response);
}
public void loadProvider() throws Exception {
WebTarget target = getWebTarget();
Practitioner practitioner = TestUtil.readExampleResource("json/spec/practitioner-example.json");
Entity<Practitioner> entity = Entity.entity(practitioner, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Practitioner").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
practitionerId = getLocationLogicalId(response);
response = target.path("Practitioner/" + practitionerId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
}
/**
* Test "update" command of updateResourceIdealState.
* @throws Exception
*/
@Test(dependsOnMethods = "deleteFromResourceConfig")
public void updateResourceIdealState() throws Exception {
// Get IdealState ZNode
String zkPath = PropertyPathBuilder.idealState(CLUSTER_NAME, RESOURCE_NAME);
ZNRecord record = _baseAccessor.get(zkPath, null, AccessOption.PERSISTENT);
// 1. Add these fields by way of "update"
Entity entity =
Entity.entity(OBJECT_MAPPER.writeValueAsString(record), MediaType.APPLICATION_JSON_TYPE);
post("clusters/" + CLUSTER_NAME + "/resources/" + RESOURCE_NAME + "/idealState",
Collections.singletonMap("command", "update"), entity, Response.Status.OK.getStatusCode());
// Check that the fields have been added
ZNRecord newRecord = _baseAccessor.get(zkPath, null, AccessOption.PERSISTENT);
Assert.assertEquals(record.getSimpleFields(), newRecord.getSimpleFields());
Assert.assertEquals(record.getListFields(), newRecord.getListFields());
Assert.assertEquals(record.getMapFields(), newRecord.getMapFields());
String newValue = "newValue";
// 2. Modify the record and update
for (int i = 0; i < 3; i++) {
String key = "k" + i;
record.getSimpleFields().put(key, newValue);
record.getMapFields().put(key, ImmutableMap.of(key, newValue));
record.getListFields().put(key, Arrays.asList(key, newValue));
}
entity =
Entity.entity(OBJECT_MAPPER.writeValueAsString(record), MediaType.APPLICATION_JSON_TYPE);
post("clusters/" + CLUSTER_NAME + "/resources/" + RESOURCE_NAME + "/idealState",
Collections.singletonMap("command", "update"), entity, Response.Status.OK.getStatusCode());
// Check that the fields have been modified
newRecord = _baseAccessor.get(zkPath, null, AccessOption.PERSISTENT);
Assert.assertEquals(record.getSimpleFields(), newRecord.getSimpleFields());
Assert.assertEquals(record.getListFields(), newRecord.getListFields());
Assert.assertEquals(record.getMapFields(), newRecord.getMapFields());
System.out.println("End test :" + TestHelper.getTestMethodName());
}
@Test(groups = { "fhir-operation" }, dependsOnMethods = { "testCreateObservation" })
public void testCreateComposition() throws Exception {
String practitionerId = savedCreatedPractitioner.getId();
String patientId = savedCreatedPatient.getId();
String observationId = savedCreatedObservation.getId();
String conditionId = savedCreatedCondition.getId();
String allergyIntoleranceId = savedCreatedAllergyIntolerance.getId();
WebTarget target = getWebTarget();
// Build a new Composition and then call the 'create' API.
Composition composition = buildComposition(practitionerId, patientId, observationId, conditionId,
allergyIntoleranceId);
Entity<Composition> entity = Entity.entity(composition, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Composition").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
// Get the composition's logical id value.
String compositionId = getLocationLogicalId(response);
// Next, call the 'read' API to retrieve the new composition and verify it.
response = target.path("Composition/" + compositionId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
Composition responseComposition = response.readEntity(Composition.class);
savedCreatedComposition = responseComposition;
TestUtil.assertResourceEquals(composition, responseComposition);
}
/**
* Create an Observation and make sure we can retrieve it.
*/
@Test(groups = { "websocket-notifications" }, dependsOnMethods = { "testCreatePatient" })
public void testCreateObservation() throws Exception {
if (!ON) {
System.out.println("skipping this test ");
} else {
// Next, create an Observation belonging to the new patient.
String patientId = savedCreatedPatient.getId();
Observation observation = TestUtil.buildPatientObservation(patientId, "Observation1.json");
Entity<Observation> obs =
Entity.entity(observation, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Observation").request().post(obs, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
String observationId = getLocationLogicalId(response);
// Next, retrieve the new Observation with a read operation and verify it.
response = target.path("Observation/"
+ observationId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
Observation responseObs = response.readEntity(Observation.class);
savedCreatedObservation = responseObs;
FHIRNotificationEvent event = getEvent(savedCreatedObservation.getId());
assertEquals(event.getResourceId(), responseObs.getId());
TestUtil.assertResourceEquals(observation, responseObs);
}
}
@Test(groups = { "transaction" }, dependsOnMethods = { "testTransactionDeletes" })
public void testTransactionReadDeletedResources() throws Exception {
if (!deleteSupported) {
return;
}
String method = "testTransactionReadDeletedResources";
WebTarget target = getWebTarget();
Bundle bundle = buildBundle(BundleType.TRANSACTION);
String url1 = "Patient/" + patientTD1.getId();
String url2 = "Patient/" + patientTD1.getId() + "/_history/1";
String url3 = "Patient/" + patientTD1.getId() + "/_history/2";
String url4 = "Patient/" + patientTD1.getId() + "/_history";
bundle = addRequestToBundle(null, bundle, HTTPVerb.GET, url1, null, null);
bundle = addRequestToBundle(null, bundle, HTTPVerb.GET, url2, null, null);
bundle = addRequestToBundle(null, bundle, HTTPVerb.GET, url3, null, null);
bundle = addRequestToBundle(null, bundle, HTTPVerb.GET, url4, null, null);
printBundle(method, "request", bundle);
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.request().post(entity, Response.class);
assertResponse(response, Response.Status.BAD_REQUEST.getStatusCode());
OperationOutcome oo = response.readEntity(OperationOutcome.class);
assertNotNull(oo);
assertEquals(oo.getIssue().get(0).getCode().getValueAsEnumConstant(), IssueType.ValueSet.DELETED);
}
@Test( groups = { "server-basic" })
public void testCreateObservationWithUnrecognizedElements_lenient_minimal() throws Exception {
WebTarget target = getWebTarget();
JsonObject jsonObject = TestUtil.readJsonObject("testdata/observation-unrecognized-elements.json");
Entity<JsonObject> entity = Entity.entity(jsonObject, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Observation").request()
.header("Prefer", "handling=lenient")
.post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
}
@Test(groups = { "batch" })
public void testBatchCreatesForVersionAwareUpdates() throws Exception {
String method = "testBatchCreatesForVersionAwareUpdates";
WebTarget target = getWebTarget();
Bundle bundle = buildBundle(BundleType.BATCH);
bundle = addRequestToBundle(null, bundle, HTTPVerb.POST, "Patient", null,
TestUtil.readLocalResource("Patient_DavidOrtiz.json"));
bundle = addRequestToBundle(null, bundle, HTTPVerb.POST, "Patient", null,
TestUtil.readLocalResource("Patient_JohnDoe.json"));
printBundle(method, "request", bundle);
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.request()
.header(PREFER_HEADER_NAME, PREFER_HEADER_RETURN_REPRESENTATION)
.post(entity, Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
Bundle responseBundle = getEntityWithExtraWork(response,method);
assertResponseBundle(responseBundle, BundleType.BATCH_RESPONSE, 2);
assertGoodPostPutResponse(responseBundle.getEntry().get(0), Status.CREATED.getStatusCode());
assertGoodPostPutResponse(responseBundle.getEntry().get(1), Status.CREATED.getStatusCode());
// Save off the two patients for the update test.
patientBVA1 = (Patient) responseBundle.getEntry().get(0).getResource();
patientBVA2 = (Patient) responseBundle.getEntry().get(1).getResource();
}
@Test
public void testIsInstanceStoppable() throws IOException {
System.out.println("Start test :" + TestHelper.getTestMethodName());
Map<String, String> params = ImmutableMap.of("client", "espresso");
Entity entity =
Entity.entity(OBJECT_MAPPER.writeValueAsString(params), MediaType.APPLICATION_JSON_TYPE);
Response response = new JerseyUriRequestBuilder("clusters/{}/instances/{}/stoppable")
.format(STOPPABLE_CLUSTER, "instance1").post(this, entity);
String stoppableCheckResult = response.readEntity(String.class);
Assert.assertEquals(stoppableCheckResult,
"{\"stoppable\":false,\"failedChecks\":[\"HELIX:EMPTY_RESOURCE_ASSIGNMENT\",\"HELIX:INSTANCE_NOT_ENABLED\",\"HELIX:INSTANCE_NOT_STABLE\"]}");
System.out.println("End test :" + TestHelper.getTestMethodName());
}
/**
* Create a minimal Patient, then make sure we can retrieve it with varying
* format
*/
@Test(groups = { "server-pretty" })
public void testPrettyFormatting() throws Exception {
WebTarget target = getWebTarget();
// Build a new Patient and then call the 'create' API.
Patient patient = TestUtil.readLocalResource("Patient_DavidOrtiz.json");
Entity<Patient> entity = Entity.entity(patient, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Patient").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
// Get the patient's logical id value.
String patientId = getLocationLogicalId(response);
// Next, call the 'read' API to retrieve the new patient and verify it.
response =
target.queryParam("_pretty", "true").path("Patient/" + patientId)
.request(FHIRMediaType.APPLICATION_FHIR_JSON).header("_format", "application/fhir+json").get();
assertResponse(response, Response.Status.OK.getStatusCode());
String prettyOutput = response.readEntity(String.class);
response =
target.queryParam("_pretty", "false").path("Patient/" + patientId)
.request(FHIRMediaType.APPLICATION_FHIR_JSON).header("_format", "application/fhir+json").get();
String notPrettyOutput = response.readEntity(String.class);
assertNotEquals(prettyOutput, notPrettyOutput);
assertFalse(notPrettyOutput.contains("\n"));
assertTrue(prettyOutput.contains("\n"));
}
@Override
public Entity getEntity(InputStream value, String mediaType) {
return Entity.entity(value, getMediaType(mediaType));
}
@Test(groups = { "batch" }, dependsOnMethods = { "testBatchUpdatesVersionAware",
"testBatchUpdatesVersionAwareError1", "testBatchUpdatesVersionAwareError2" })
public void testBatchUpdatesVersionAwareError3() throws Exception {
String method = "testBatchUpdatesVersionAwareError3";
WebTarget target = getWebTarget();
// First, call the 'read' API to retrieve the previously-created patients.
assertNotNull(patientBVA2);
Response res1 = target.path("Patient/" + patientBVA2.getId())
.request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(res1, Response.Status.OK.getStatusCode());
Patient patientVA2 = res1.readEntity(Patient.class);
assertNotNull(patientVA2);
assertNotNull(patientBVA1);
Response res2 = target.path("Patient/" + patientBVA1.getId())
.request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(res2, Response.Status.OK.getStatusCode());
Patient patientVA1 = res2.readEntity(Patient.class);
assertNotNull(patientVA1);
// Make a small change to each patient.
patientVA2 = patientVA2.toBuilder().active(com.ibm.fhir.model.type.Boolean.TRUE).build();
patientVA1 = patientVA1.toBuilder().active(com.ibm.fhir.model.type.Boolean.FALSE).build();
Bundle bundle = buildBundle(BundleType.BATCH);
bundle = addRequestToBundle(null, bundle, HTTPVerb.PUT, "Patient/" + patientVA2.getId(), "W/\"2\"",
patientVA2);
bundle = addRequestToBundle(null, bundle, HTTPVerb.PUT, "Patient/" + patientVA1.getId(), "W/\"2\"",
patientVA1);
printBundle(method, "request", bundle);
Entity<Bundle> entity = Entity.entity(bundle, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.request().post(entity, Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
Bundle responseBundle = getEntityWithExtraWork(response,method);
assertResponseBundle(responseBundle, BundleType.BATCH_RESPONSE, 2);
assertBadResponse(responseBundle.getEntry().get(0), Status.PRECONDITION_FAILED.getStatusCode(),
"If-Match version '2' does not match current latest version of resource: 3");
assertBadResponse(responseBundle.getEntry().get(1), Status.PRECONDITION_FAILED.getStatusCode(),
"If-Match version '2' does not match current latest version of resource: 3");
}