下面列出了怎么用javax.ws.rs.client.Entity的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testTraverseByObjectSearch() throws Exception {
when(getTiService().traverseGraph(any(), isA(TraverseByObjectSearchRequest.class)))
.then(i -> StreamingResultSet.<String>builder().setValues(ListUtils.list("something")).build());
TraverseByObjectSearchRequest request = new TraverseByObjectSearchRequest()
.setQuery("g.values('value')");
Response response = target("/v1/object/traverse").request().post(Entity.json(request));
JsonNode payload = getPayload(response);
assertEquals(200, response.getStatus());
assertTrue(payload.isArray());
assertEquals(1, payload.size());
assertEquals("something", payload.get(0).asText());
verify(getTiService(), times(1)).traverseGraph(notNull(), isA(TraverseByObjectSearchRequest.class));
}
/**
* Tests the results of the REST API PUT method without modifying the nodes.
*/
@Test
public void testUpdateNodesWithoutModifyOperation() {
expect(mockK8sNodeAdminService.node(anyString())).andReturn(null).once();
replay(mockK8sNodeAdminService);
final WebTarget wt = target();
InputStream jsonStream = K8sNodeWebResourceTest.class
.getResourceAsStream("k8s-node-minion-config.json");
Response response = wt.path(NODE_PATH).request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(jsonStream));
final int status = response.getStatus();
assertThat(status, is(304));
verify(mockK8sNodeAdminService);
}
@Test
public void testBadUser() {
Client client = ClientBuilder.newClient();
URI uri = OIDCLoginProtocolService.tokenUrl(authServerPage.createUriBuilder()).build("demo");
WebTarget target = client.target(uri);
String header = BasicAuthHelper.createHeader("customer-portal", "password");
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
.param("username", "[email protected]")
.param("password", "password");
Response response = target.request()
.header(HttpHeaders.AUTHORIZATION, header)
.post(Entity.form(form));
assertEquals(401, response.getStatus());
response.close();
client.close();
}
/**
* TCK test to verify that methods annotated with {@link AfterLRA}
* are notified correctly when an LRA terminates
*/
@Test
public void testAfterLRAListener() {
URI lra = lraClient.startLRA(null, lraClientId(), lraTimeout(), ChronoUnit.MILLIS);
WebTarget resourcePath = tckSuiteTarget.path(AFTER_LRA_LISTENER_PATH).path(AFTER_LRA_LISTENER_WORK);
Response response = resourcePath
.request().header(LRA_HTTP_CONTEXT_HEADER, lra).put(Entity.text(""));
checkStatusAndCloseResponse(Response.Status.OK, response, resourcePath);
lraClient.closeLRA(lra);
lraTestService.waitForCallbacks(lra);
// verify that the LRA is now in one of the terminal states
assertTrue("testAfterLRAListener: LRA did not finish",
lraClient.isLRAFinished(lra, lraMetricService, AfterLRAListener.class.getName()));
// verify that the resource was notified of the final state of the LRA
assertTrue("testAfterLRAListener: end synchronization was not invoked on resource " + resourcePath.getUri(),
lraMetricService.getMetric(LRAMetricType.Closed, lra, AfterLRAListener.class.getName()) >= 1);
}
private Response getResponse(String request, InputStream payload, MediaType mediaType) {
WebTarget wt = getWebTarget(request);
Response response = null;
if (payload != null) {
try {
response = wt.request(mediaType)
.post(Entity.entity(IOUtils.toString(payload, StandardCharsets.UTF_8), mediaType));
} catch (IOException e) {
log.error("Cannot do POST {} request on GNPY because can't read payload", request);
}
} else {
response = wt.request(mediaType).post(Entity.entity(null, mediaType));
}
return response;
}
/**
* Tests creating a meter with POST, but wrong deviceID.
*/
@Test
public void testPostWithWrongDevice() {
mockMeterService.submit(anyObject());
expectLastCall().andReturn(meter5).anyTimes();
replay(mockMeterService);
replay(mockDeviceService);
WebTarget wt = target();
InputStream jsonStream = MetersResourceTest.class
.getResourceAsStream("post-meter.json");
Response response = wt.path("meters/of:0000000000000002")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_BAD_REQUEST));
}
@Test
public void testImportPipelineWithPipelineCredentials() throws Exception {
Response response = target("/v1/pipeline/xyz/export").queryParam("rev", "1").request().get();
PipelineEnvelopeJson pipelineEnvelope = response.readEntity(PipelineEnvelopeJson.class);
ArgumentCaptor<Boolean> encryptCredentialsArgumentCaptor = ArgumentCaptor.forClass(Boolean.class);
response = target("/v1/pipeline/newFromImport/import").queryParam("rev", "1")
.queryParam("encryptCredentials", true)
.request()
.post(Entity.json(pipelineEnvelope));
pipelineEnvelope = response.readEntity(PipelineEnvelopeJson.class);
Assert.assertNotNull(pipelineEnvelope);
Assert.assertNotNull(pipelineEnvelope.getPipelineConfig());
Assert.assertNotNull(pipelineEnvelope.getPipelineRules());
Assert.assertNull(pipelineEnvelope.getLibraryDefinitions());
Mockito.verify(pipelineStore).save(
Mockito.anyString(),
Mockito.anyString(),
Mockito.anyString(),
Mockito.anyString(),
Mockito.any(),
Mockito.eq(true)
);
}
@Test
public void testRelate_ToMany_New() {
e2().insertColumns("id_", "name").values(24, "xxx").exec();
Response r = target("/e2/24/e3s")
.request()
.post(Entity.json("{\"name\":\"zzz\"}"));
onSuccess(r)
.replaceId("RID")
.bodyEquals(1, "{\"id\":RID,\"name\":\"zzz\",\"phoneNumber\":null}");
e3().matcher().assertOneMatch();
e3().matcher().eq("e2_id", 24).eq("name", "zzz").assertOneMatch();
}
@Test
void createVerifyOrder() {
Order order = new Order("Espresso", "Colombia");
JsonObject requestBody = createJson(order);
Response response = ordersTarget.request().post(Entity.json(requestBody));
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL)
throw new AssertionError("Status was not successful: " + response.getStatus());
URI orderUri = response.getLocation();
Order loadedOrder = client.target(orderUri)
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Order.class);
Assertions.assertThat(loadedOrder).isEqualToComparingOnlyGivenFields(order, "type", "origin");
List<URI> orders = ordersTarget.request(MediaType.APPLICATION_JSON_TYPE)
.get(JsonArray.class).getValuesAs(JsonObject.class).stream()
.map(o -> o.getString("_self"))
.map(URI::create)
.collect(Collectors.toList());
assertThat(orders).contains(orderUri);
}
@Test
public void missingWorkSpaceKey() {
// setup
formParams.replace(SPACE_NAME, Arrays.asList(WORKSPACE_NAME + "ThisWillMiss"));
// test
final Response response = target(WORK_BUNDLE_COMPLETED_ACTION).request().post(Entity.form(formParams));
// verify
final int status = response.getStatus();
assertThat(status, equalTo(500));
final String result = response.readEntity(String.class);
assertThat(
result,
equalTo("There was a problem while processing the WorkBundle: Not found: http://workBundleCompletedActionTest:7001/WorkSpaceThisWillMiss"));
}
/**
* Tests the results of the REST API PUT method with modifying the network.
*/
@Test
public void testUpdateNetworkWithModifyOperation() {
mockAdminService.updateNetwork(anyObject());
replay(mockAdminService);
String location = PATH + "/network-1";
final WebTarget wt = target();
InputStream jsonStream = K8sNetworkWebResourceTest.class
.getResourceAsStream("k8s-network.json");
Response response = wt.path(location)
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(jsonStream));
final int status = response.getStatus();
assertThat(status, is(200));
verify(mockAdminService);
}
@Test
public void testSearchObjectFactsByTypeValue() throws Exception {
String type = "ip";
String value = "27.13.4.125";
when(getTiService().searchObjectFacts(any(), isA(SearchObjectFactsRequest.class))).then(i -> {
SearchObjectFactsRequest request = i.getArgument(1);
assertEquals(type, request.getObjectType());
assertEquals(value, request.getObjectValue());
return StreamingResultSet.<Fact>builder().setValues(createFacts()).build();
});
Response response = target(String.format("/v1/object/%s/%s/facts", type, value)).request().post(Entity.json(new SearchObjectFactsRequest()));
JsonNode payload = getPayload(response);
assertEquals(200, response.getStatus());
assertTrue(payload.isArray());
assertEquals(3, payload.size());
verify(getTiService(), times(1)).searchObjectFacts(notNull(), isA(SearchObjectFactsRequest.class));
}
@Test(groups = { "batch" })
public void testResourceURLMismatch() throws Exception {
String method = "testResourceURLMismatch";
WebTarget target = getWebTarget();
Patient patient = TestUtil.readLocalResource("Patient_DavidOrtiz.json");
Bundle bundle = buildBundle(BundleType.BATCH);
bundle = addRequestToBundle(null, bundle, HTTPVerb.POST, "Observation", null, patient);
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);
printBundle(method, "response", responseBundle);
assertResponseBundle(responseBundle, BundleType.BATCH_RESPONSE, 1);
assertBadResponse(responseBundle.getEntry().get(0), Status.BAD_REQUEST.getStatusCode(),
"does not match type specified in request URI");
}
@Test
public void testSaveDocument() throws Exception {
String id = UUID.randomUUID()
.toString();
Document document = new Document(id, System.currentTimeMillis(), getMapper().getNodeFactory()
.objectNode()
.put("hello", "world"));
Entity<Document> documentEntity = Entity.json(document);
resources.client()
.target("/v1/document/" + TestUtils.TEST_TABLE_NAME)
.request()
.post(documentEntity);
getElasticsearchConnection().refresh(ElasticsearchUtils.getIndices(TestUtils.TEST_TABLE_NAME));
Document response = getQueryStore().get(TestUtils.TEST_TABLE_NAME, id);
compare(document, response);
}
/**
* Tests the results of the REST API POST with duplicated subnet ID.
*/
@Test
public void testCreateSubnetWithDuplicatedId() {
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
mockOpenstackNetworkAdminService.createSubnet(anyObject());
expectLastCall().andThrow(new IllegalArgumentException());
replay(mockOpenstackNetworkAdminService);
final WebTarget wt = target();
InputStream jsonStream = OpenstackSubnetWebResourceTest.class
.getResourceAsStream("openstack-subnet.json");
Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
final int status = response.getStatus();
assertThat(status, is(400));
verify(mockOpenstackNetworkAdminService);
}
@Test(groups = { "server-search" }, dependsOnMethods = { "testCreatePatient1" })
public void testCreateObservation1() throws Exception {
WebTarget target = getWebTarget();
Observation observation = TestUtil.buildPatientObservation(patientId, "Observation1.json");
Entity<Observation> entity = Entity.entity(observation, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response = target.path("Observation").request().post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
// Get the patient's logical id value.
String observationId = getLocationLogicalId(response);
// Next, call the 'read' API to retrieve the new patient and verify it.
response = target.path("Observation/"
+ observationId).request(FHIRMediaType.APPLICATION_FHIR_JSON).get();
assertResponse(response, Response.Status.OK.getStatusCode());
Observation responseObservation = response.readEntity(Observation.class);
// use it for search
observationId = responseObservation.getId();
TestUtil.assertResourceEquals(observation, responseObservation);
}
@Test
public void testRelate_ValidRel_ToOne_New_PropagatedId() {
e8().insertColumns("id")
.values(7)
.values(8).exec();
Response r1 = target("/e8/8/e9").request().put(Entity.json("{}"));
onSuccess(r1).bodyEquals(1, "{\"id\":8}");
e9().matcher().assertOneMatch();
e9().matcher().eq("e8_id", 8).assertOneMatch();
// PUT is idempotent... doing another update should not change the picture
Response r2 = target("/e8/8/e9").request().put(Entity.json("{}"));
onSuccess(r2).bodyEquals(1, "{\"id\":8}");
e9().matcher().assertOneMatch();
e9().matcher().eq("e8_id", 8).assertOneMatch();
}
public static void main( String[] args ) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(URL);
try {
CompletionStage<String> csf = target.request()
.rx()
.post(Entity.entity(new FileInputStream(new File(FILE_PATH)),"application/pdf"),String.class);
csf.whenCompleteAsync((path, err)->{
if( Objects.isNull( err ) )
System.out.println("File saved on: " + path);
else
err.printStackTrace();
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@Test
public void sendPartyInfoReturns400() {
Invocation.Builder m = restClient.getWebTarget().getMockInvocationBuilder();
byte[] responseData = "Result".getBytes();
Response response = mock(Response.class);
when(response.readEntity(byte[].class)).thenReturn(responseData);
when(response.getStatus()).thenReturn(400);
doAnswer(
(invocation) -> {
return Response.status(400).build();
})
.when(m)
.post(any(Entity.class));
String targetUrl = "http://somedomain.com";
byte[] data = "Some Data".getBytes();
boolean outcome = client.sendPartyInfo(targetUrl, data);
assertThat(outcome).isFalse();
}
@Test
public void createPropertyInvalidTest() {
Project project = qm.createProject("Acme Example", null, "1.0", null, null, null, true, false);
ProjectProperty property = new ProjectProperty();
property.setProject(project);
property.setGroupName("mygroup");
property.setPropertyName("prop1");
property.setPropertyValue("value1");
property.setPropertyType(IConfigProperty.PropertyType.STRING);
property.setDescription("Test Property 1");
Response response = target(V1_PROJECT + "/" + UUID.randomUUID() + "/property").request()
.header(X_API_KEY, apiKey)
.put(Entity.entity(property, MediaType.APPLICATION_JSON));
Assert.assertEquals(404, response.getStatus(), 0);
Assert.assertNull(response.getHeaderString(TOTAL_COUNT_HEADER));
String body = getPlainTextBody(response);
Assert.assertEquals("The project could not be found.", body);
}
@Override
public String initSwarm(final SwarmInit swarmInit) throws DockerException, InterruptedException {
assertApiVersionIsAbove("1.24");
try {
final WebTarget resource = resource().path("swarm").path("init");
return request(POST, String.class, resource, resource.request(APPLICATION_JSON_TYPE),
Entity.json(swarmInit));
} catch (DockerRequestException e) {
switch (e.status()) {
case 400:
throw new DockerException("bad parameter", e);
case 500:
throw new DockerException("server error", e);
case 503:
throw new DockerException("node is already part of a swarm", e);
default:
throw e;
}
}
}
@Test
public void loginAuthValidNoPrincipalsTest() throws Exception {
// Setup:
String authorization = USERNAME + ":" + PASSWORD;
when(RestSecurityUtils.authenticateUser(eq("mobi"), any(Subject.class), eq(USERNAME), eq(PASSWORD), eq(mobiConfiguration))).thenReturn(true);
Response response = target().path("session").request()
.header("Authorization", "Basic " + Base64.encode(authorization.getBytes())).post(Entity.json(""));
assertEquals(response.getStatus(), 401);
verifyStatic();
RestSecurityUtils.authenticateUser(eq("mobi"), any(Subject.class), eq(USERNAME), eq(PASSWORD), eq(mobiConfiguration));
verify(tokenManager, never()).generateAuthToken(anyString());
verify(engineManager, times(0)).getUserRoles(anyString());
Map<String, NewCookie> cookies = response.getCookies();
assertEquals(0, cookies.size());
}
public static List<String> getCompactDiscs() {
ResteasyClient rsClient = new ResteasyClientBuilder().disableTrustManager().build();
Form form = new Form().param("grant_type", "client_credentials");
ResteasyWebTarget resourceTarget = rsClient.target(urlAuth);
resourceTarget.register(new BasicAuthentication("andres", "andres"));
AccessTokenResponse accessToken = resourceTarget.request().post(Entity.form(form),
AccessTokenResponse.class);
try {
String bearerToken = "Bearer " + accessToken.getToken();
Response response = rsClient.target(urlDiscs).request()
.header(HttpHeaders.AUTHORIZATION, bearerToken).get();
return response.readEntity(new GenericType<List<String>>() {
});
} finally {
rsClient.close();
}
}
protected Response executeGrantRequest(WebTarget grantTarget, String username, String password) {
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
.param("username", username)
.param("password", password)
.param(OAuth2Constants.SCOPE, OAuth2Constants.SCOPE_OPENID);
return grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, header)
.post(Entity.form(form));
}
private static <T> T post(String inputString, WebTarget clientResource, Class<T> clazz) throws BlockCypherException {
if (logger.isDebugEnabled()) {
logger.debug(MessageFormat.format("Posting to {0}: {1}", clientResource.getUri(), inputString));
}
Response response = clientResource.request(MediaType.APPLICATION_JSON).post(Entity.entity(inputString, MediaType.APPLICATION_JSON));
if (response.getStatus() != 201) {
throw getBlockCypherException(clientResource, response);
} else {
T returnedObject = GsonFactory.getGson().fromJson(response.readEntity(String.class), clazz);
return returnedObject;
}
}
@Test
public void TestSendLocation() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendLocation());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, SendLocation.class);
assertEquals("{\"chat_id\":\"12345\",\"latitude\":12.5,\"longitude\":21.5,\"reply_to_message_id\":53,\"method\":\"sendlocation\"}", map(result));
}
@Test(groups = { "server-search" })
public void testCreateObservationWithRange() throws Exception {
WebTarget target = getWebTarget();
Observation observation =
TestUtil.buildPatientObservation(patientId, "Observation5.json");
Entity<Observation> entity =
Entity.entity(observation, FHIRMediaType.APPLICATION_FHIR_JSON);
Response response =
target.path("Observation").request()
.header("X-FHIR-TENANT-ID", tenantName)
.header("X-FHIR-DSID", dataStoreId)
.post(entity, Response.class);
assertResponse(response, Response.Status.CREATED.getStatusCode());
// Get the observation's logical id value.
observationId = getLocationLogicalId(response);
// Next, call the 'read' API to retrieve the new observation and verify it.
response = target.path("Observation/"
+ observationId).request(FHIRMediaType.APPLICATION_FHIR_JSON)
.header("X-FHIR-TENANT-ID", tenantName)
.header("X-FHIR-DSID", dataStoreId)
.get();
assertResponse(response, Response.Status.OK.getStatusCode());
Observation responseObservation =
response.readEntity(Observation.class);
// use it for search
observationId = responseObservation.getId();
TestUtil.assertResourceEquals(observation, responseObservation);
}
@Test
public void updateTeamInvalidTest() {
Team team = new Team();
team.setName("My Team");
team.setUuid(UUID.randomUUID());
Response response = target(V1_TEAM).request()
.header(X_API_KEY, apiKey)
.post(Entity.entity(team, MediaType.APPLICATION_JSON));
Assert.assertEquals(404, response.getStatus(), 0);
Assert.assertNull(response.getHeaderString(TOTAL_COUNT_HEADER));
String body = getPlainTextBody(response);
Assert.assertEquals("The team could not be found.", body);
}
@Test
public void createOidcUserTest() {
final OidcUser user = new OidcUser();
user.setUsername("blackbeard");
Response response = target(V1_USER + "/oidc").request()
.header("Authorization", "Bearer " + jwt)
.put(Entity.entity(user, MediaType.APPLICATION_JSON));
Assert.assertEquals(201, response.getStatus(), 0);
Assert.assertNull(response.getHeaderString(TOTAL_COUNT_HEADER));
JsonObject json = parseJsonObject(response);
Assert.assertNotNull(json);
Assert.assertEquals("blackbeard", json.getString("username"));
}
private synchronized Response invokeRestEndpoint(URI lra, String basePath, String path, int coerceResponse) {
WebTarget resourcePath = target.path(basePath).path(path).queryParam(STATUS_CODE_QUERY_NAME, coerceResponse);
Invocation.Builder builder = resourcePath.request();
if (lra != null) {
builder.header(LRA.LRA_HTTP_CONTEXT_HEADER, lra);
}
return builder.put(Entity.text(""));
}