javax.ws.rs.client.Entity Java Examples
The following examples show how to use
javax.ws.rs.client.Entity.
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: POST_Related_IT.java From agrest with Apache License 2.0 | 7 votes |
@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(); }
Example #2
Source File: K8sNetworkWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * 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); }
Example #3
Source File: DefaultDockerClient.java From docker-client with Apache License 2.0 | 6 votes |
@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; } } }
Example #4
Source File: ProjectPropertyResourceTest.java From dependency-track with Apache License 2.0 | 6 votes |
@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); }
Example #5
Source File: HttpUtil.java From onos with Apache License 2.0 | 6 votes |
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; }
Example #6
Source File: AuthRestTest.java From mobi with GNU Affero General Public License v3.0 | 6 votes |
@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()); }
Example #7
Source File: RestP2pClientTest.java From tessera with Apache License 2.0 | 6 votes |
@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(); }
Example #8
Source File: K8sNodeWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * 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); }
Example #9
Source File: CompactDiscsDatabaseClient.java From maven-framework-project with MIT License | 6 votes |
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(); } }
Example #10
Source File: DemoServletsAdapterTest.java From keycloak with Apache License 2.0 | 6 votes |
@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(); }
Example #11
Source File: TckTests.java From microprofile-lra with Apache License 2.0 | 6 votes |
/** * 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); }
Example #12
Source File: MetersResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * 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)); }
Example #13
Source File: TestPipelineStoreResource.java From datacollector with Apache License 2.0 | 6 votes |
@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) ); }
Example #14
Source File: ObjectEndpointTest.java From act-platform with ISC License | 6 votes |
@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)); }
Example #15
Source File: ObjectEndpointTest.java From act-platform with ISC License | 6 votes |
@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)); }
Example #16
Source File: BundleTest.java From FHIR with Apache License 2.0 | 6 votes |
@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"); }
Example #17
Source File: DocumentResourceTest.java From foxtrot with Apache License 2.0 | 6 votes |
@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); }
Example #18
Source File: OpenstackSubnetWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * 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); }
Example #19
Source File: SortingTest.java From FHIR with Apache License 2.0 | 6 votes |
@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); }
Example #20
Source File: PUT_Related_IT.java From agrest with Apache License 2.0 | 6 votes |
@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(); }
Example #21
Source File: WorkBundleCompletedActionTest.java From emissary with Apache License 2.0 | 6 votes |
@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")); }
Example #22
Source File: CreateOrderNaiveTest.java From coffee-testing with Apache License 2.0 | 6 votes |
@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); }
Example #23
Source File: App.java From Java-EE-8-Design-Patterns-and-Best-Practices with MIT License | 6 votes |
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(); } }
Example #24
Source File: JerseyDockerHttpClient.java From docker-java with Apache License 2.0 | 5 votes |
private Entity<InputStream> toEntity(Request request) { InputStream body = request.body(); if (body != null) { return Entity.entity(body, MediaType.APPLICATION_JSON_TYPE); } switch (request.method()) { case "POST": return Entity.json(null); default: return null; } }
Example #25
Source File: BundleTest.java From FHIR with Apache License 2.0 | 5 votes |
@Test(groups = { "batch" }) public void testBatchCreatesForDelete() throws Exception { String method = "testBatchCreatesForDelete"; 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. patientBD1 = (Patient) responseBundle.getEntry().get(0).getResource(); patientBD2 = (Patient) responseBundle.getEntry().get(1).getResource(); }
Example #26
Source File: RefreshTokenServlet.java From tutorials with MIT License | 5 votes |
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientId = config.getValue("client.clientId", String.class); String clientSecret = config.getValue("client.clientSecret", String.class); JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); Client client = ClientBuilder.newClient(); WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); Form form = new Form(); form.param("grant_type", "refresh_token"); form.param("refresh_token", actualTokenResponse.getString("refresh_token")); String scope = request.getParameter("scope"); if (scope != null && !scope.isEmpty()) { form.param("scope", scope); } Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class); JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class); if (jaxrsResponse.getStatus() == 200) { request.getSession().setAttribute("tokenResponse", tokenResponse); } else { request.setAttribute("error", tokenResponse.getString("error_description", "error!")); } dispatch("/", request, response); }
Example #27
Source File: AccessTokenTest.java From keycloak with Apache License 2.0 | 5 votes |
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)); }
Example #28
Source File: InfluxDbClient.java From tessera with Apache License 2.0 | 5 votes |
public Response postMetrics() { MetricsEnquirer metricsEnquirer = new MetricsEnquirer(mbs); List<MBeanMetric> metrics = metricsEnquirer.getMBeanMetrics(appType); InfluxDbProtocolFormatter formatter = new InfluxDbProtocolFormatter(); String formattedMetrics = formatter.format(metrics, tesseraAppUri, appType); ClientBuilder clientBuilder = ClientBuilder.newBuilder(); if (influxConfig.isSsl()) { final SSLContextFactory sslContextFactory = ClientSSLContextFactory.create(); final SSLContext sslContext = sslContextFactory.from(influxConfig.getServerUri().toString(), influxConfig.getSslConfig()); clientBuilder.sslContext(sslContext); } Client client = clientBuilder.build(); WebTarget influxTarget = client.target(influxConfig.getServerUri()).path("write").queryParam("db", influxConfig.getDbName()); return influxTarget .request(MediaType.TEXT_PLAIN) .accept(MediaType.TEXT_PLAIN) .post(Entity.text(formattedMetrics)); }
Example #29
Source File: MergeRequestRestTest.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
@Test public void updateCommentWithInvalidCommentSizeTest() { doThrow(new IllegalArgumentException()).when(requestManager).updateComment(any(Resource.class), any(Comment.class)); Response response = target().path("merge-requests/" + encode(request1.getResource().stringValue()) + "/comments/" + encode(comment1.getResource().stringValue())) .request() .put(Entity.text(largeComment)); ArgumentCaptor<Comment> commentArgumentCaptor = ArgumentCaptor.forClass(Comment.class); verify(requestManager).updateComment(eq(comment1.getResource()), commentArgumentCaptor.capture()); Comment comment = commentArgumentCaptor.getValue(); assertNotEquals(comment.getProperty(vf.createIRI(_Thing.description_IRI)), Optional.empty()); assertEquals(comment.getProperty(vf.createIRI(_Thing.description_IRI)).get().stringValue(), largeComment); assertEquals(response.getStatus(), 400); }
Example #30
Source File: HeartbeatActionTest.java From emissary with Apache License 2.0 | 5 votes |
@Theory public void badParams(String badValue) { // setup formParams.put(HeartbeatAdapter.FROM_PLACE_NAME, Arrays.asList(badValue)); formParams.put(HeartbeatAdapter.TO_PLACE_NAME, Arrays.asList(badValue)); // test final Response response = target(HEARTBEAT_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, StringStartsWith.startsWith("Heartbeat failed")); }