@Test public void testNewOwner() { final Response r1 = target("/owners/new").request().get(); assertEquals(200, r1.getStatus()); assertEquals("newowner", ((View) r1.getEntity()).getTemplateName()); final Form form = new Form() .param("name", "Barack Obama") .param("address", "1600 Penn Ave") .param("city", "Washington DC") .param("telephone", "800-555-5555"); final Response r2 = target("/owners/new").request().post(Entity.form(form)); assertNotNull(r2); assertEquals(303, r2.getStatus()); assertNotNull(r2.getHeaderString("Location")); final Response r3 = target(r2.getHeaderString("Location")).request().get(); assertNotNull(r3); assertEquals(200, r3.getStatus()); final View view = (View) r3.getEntity(); final Owner owner = (Owner) view.getModel().get("owner"); assertEquals("Barack Obama", owner.getName()); }
/** * Calls a state alteration method for one station. * @param station the station to undelete/delete from the REST service. * @param path the URL path of the state alteration endpoint. * @see <a href="http://www.radio-browser.info/webservice#station_delete"> * The API endpoint</a> */ private void triggerStationState(final Station station, final String path) { Objects.requireNonNull(station, "station must be non-null"); MultivaluedMap<String, String> requestParams = new MultivaluedHashMap<>(); Entity entity = Entity.form(requestParams); Response response = null; try { response = builder(webTarget .path(path) .path(station.getId())) .post(entity); logResponseStatus(response); UrlResponse urlResponse = response.readEntity( UrlResponse.class); if (!urlResponse.isOk()) { throw new RadioBrowserException(urlResponse.getMessage()); } } finally { close(response); } }
private static void registerUser(String url, MediaType mediaType) { System.out.println("Registering user via " + url); User user = new User(1L, "larrypage"); Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Response response = target.request().post(Entity.entity(user, mediaType)); try { if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); } System.out.println("Successfully got result: " + response.readEntity(String.class)); } finally { response.close(); client.close(); } }
/** * Persists order in database. * @param blob Sessionblob * @param addressName adress * @param address1 adress * @param address2 adress * @param creditCardCompany creditcard * @param creditCardExpiryDate creditcard * @param creditCardNumber creditcard * @param totalPriceInCents totalPrice * @throws NotFoundException If 404 was returned. * @throws LoadBalancerTimeoutException On receiving the 408 status code * and on repeated load balancer socket timeouts. * @return empty SessionBlob */ public static SessionBlob placeOrder(SessionBlob blob, String addressName, String address1, String address2, String creditCardCompany, String creditCardExpiryDate, long totalPriceInCents, String creditCardNumber) throws NotFoundException, LoadBalancerTimeoutException { Response r = ServiceLoadBalancer.loadBalanceRESTOperation(Service.STORE, "useractions", Product.class, client -> client.getService().path(client.getApplicationURI()) .path(client.getEndpointURI()).path("placeorder") .queryParam("addressName", addressName) .queryParam("address1", address1) .queryParam("address2", address2) .queryParam("creditCardCompany", creditCardCompany) .queryParam("creditCardNumber", creditCardNumber) .queryParam("creditCardExpiryDate", creditCardExpiryDate) .queryParam("totalPriceInCents", totalPriceInCents) .request(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(Entity.entity(blob, MediaType.APPLICATION_JSON), Response.class)); throwCommonExceptions(r); return readEntityOrNull(r, SessionBlob.class); }
/** * Execute a PUT method on an object * * @param object the object to put * @return the response */ @PublicAtsApi public RestResponse putObject( Object object ) { // execute PUT Invocation.Builder invocationBuilder = constructInvocationBuilder("PUT object to"); RestResponse response; if (object != null) { if (StringUtils.isNullOrEmpty(requestMediaType)) { throw new RestException("Content type is not set! Content type is mandatory for PUT."); } response = new RestResponse(invocationBuilder.method("PUT", Entity.entity(getActualBodyObject(object), RestMediaType.toMediaType(requestMediaType, requestMediaCharset)), Response.class)); } else { response = new RestResponse(invocationBuilder.method("PUT", Response.class)); } logRESTResponse(response); initInternalVariables(); // return response return response; }
@Test public void testAddRolesWithValidRequestObject() { AppCreateDTO request = new AppCreateDTO(); Set<String> roles = new HashSet<>(); roles.add(roleName); request.setColor("Green"); request.setRoles(roles); Role role = new Role(roleName); Mockito.when(rolesDAO.save(role)).thenReturn(role); Response response = resources.client().target(rolesUrl).request().post(Entity.json(request)); ResponseValidator.validate(response, 201); }
private Result executeAction(Action action, Object lraInfo, String lraUri) { log.infof("executing action - %s", action); Client client = ClientBuilder.newClient(); URI build = UriBuilder .fromUri(servicesLocator.getServiceUri(action.getService())) .path(API_PREFIX) .path(action.getType().getPath()) .build(); log.info("action request url - " + build); WebTarget target = client.target(build); Response response = target.request().header(LRAClient.LRA_HTTP_HEADER, lraUri).post(Entity.json(lraInfo)); log.info("Result of action - " + response.readEntity(String.class)); Result result = response.getStatus() == Response.Status.OK.getStatusCode() ? Result.COMPLETED : Result.NEED_COMPENSATION; response.close(); return result; }
public void resize(String clusterId, Integer minWorkers, Integer maxWorkers) throws HttpException { ClusterInfoDTO cluster = new ClusterInfoDTO(); cluster.ClusterId = clusterId; AutoScaleDTO autoScaleDTOSettings = new AutoScaleDTO(); autoScaleDTOSettings.MinWorkers = minWorkers; autoScaleDTOSettings.MaxWorkers = maxWorkers; cluster.AutoScale = autoScaleDTOSettings; Response response = _target.path("resize") .register(Session.Authentication) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(cluster)); // check response status code checkResponse(response, "InteractiveCluster " + clusterId + " is not in a RUNNING state"); }
@Test public void testExecute_WithUpdateInspectionPort_ExpectErrorCode() { // Assume. Response response = null; try { InspectionPortElement inspectionPort = createInspectionPortEntity(); Entity<InspectionPortElement> entity = Entity.entity(inspectionPort, MediaType.APPLICATION_JSON); String badParam = "IdNotMatching"; // Act. response = target("controller/1.2.3.0/inspectionPorts/" + badParam) .request() .header(this.AUTHORIZATION_HEADER, this.AUTHORIZATION_CREDS) .put(entity); response.close(); // Assert. assertThat(response.getStatus()).isEqualTo(500); } finally { if (response != null) { response.close(); } } }
/** * Tests adding of new virtual device using POST via JSON stream. */ @Test public void testPostVirtualDevice() { NetworkId networkId = networkId3; DeviceId deviceId = devId2; expect(mockVnetAdminService.createVirtualDevice(networkId, deviceId)).andReturn(vdev2); expectLastCall(); replay(mockVnetAdminService); WebTarget wt = target(); InputStream jsonStream = VirtualNetworkWebResourceTest.class .getResourceAsStream("post-virtual-device.json"); String reqLocation = "vnets/" + networkId.toString() + "/devices"; Response response = wt.path(reqLocation).request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(jsonStream)); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); String location = response.getLocation().getPath(); assertThat(location, Matchers.startsWith("/" + reqLocation + "/" + vdev2.id().toString())); verify(mockVnetAdminService); }
@Test public void makePost_checkProcessingExceptionIsThrown() throws IOException, SAXException, ParserConfigurationException, URISyntaxException, SOAPRequestError { ProcessingException exception = mock(ProcessingException.class); when(webResourceBuilder.post(any(Entity.class))).thenThrow(exception); Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); URI matchingServiceUri = new URI("http://heyyeyaaeyaaaeyaeyaa.com/abc1"); try { soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri); fail("Exception should have been thrown"); } catch(ProcessingException e) { assertThat(e).isEqualTo(exception); } }
@Test @Ignore // TODO DX-3144 public void testTestApis() { doc("Creating test dataset"); NamespaceService ns = newNamespaceService(); expectSuccess(getBuilder(getAPIv2().path("/test/create")).buildPost(Entity.json(""))); assertEquals(4, ns.getSpaces().size()); assertEquals(1, ns.getHomeSpaces().size()); doc("Clearing all data"); expectSuccess(getBuilder(getAPIv2().path("/test/clear")).buildPost(Entity.json(""))); assertEquals(0, ns.getSpaces().size()); assertEquals(0, ns.getHomeSpaces().size()); expectSuccess(getBuilder(getAPIv2().path("/test/create")).buildPost(Entity.json(""))); assertEquals(4, ns.getSpaces().size()); assertEquals(1, ns.getHomeSpaces().size()); expectSuccess(getBuilder(getAPIv2().path("/test/clear")).buildPost(Entity.json(""))); assertEquals(0, ns.getSpaces().size()); assertEquals(0, ns.getHomeSpaces().size()); }
private boolean portDown(String switchName, String portNo) throws Throwable { System.out.println("\n==> Set Port Down"); long current = System.currentTimeMillis(); Client client = ClientBuilder.newClient(new ClientConfig()); Response result = client .target(trafficEndpoint) .path("/port/down") .queryParam("switch", switchName) .queryParam("port", portNo) .request() .post(Entity.json("")); System.out.println(String.format("===> Response = %s", result.toString())); System.out.println(String.format("===> Set Port Down Time: %,.3f", getTimeDuration(current))); return result.getStatus() == 200; }
/** * Tests adding of a null virtual link using POST via JSON stream. */ @Test public void testPostVirtualLinkNullJsonStream() { NetworkId networkId = networkId3; replay(mockVnetAdminService); WebTarget wt = target(); try { String reqLocation = "vnets/" + networkId.toString() + "/links"; wt.path(reqLocation) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(null), String.class); fail("POST of null virtual link did not throw an exception"); } catch (BadRequestException ex) { assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request")); } verify(mockVnetAdminService); }
@Test public void testNoUserTestFilter() throws Exception { Assume.assumeFalse(BaseTestServer.isMultinode()); // we should be able to login using the default user doc("make sure we can login as the default user"); login(); doc("use the clear test API"); expectSuccess(getBuilder(getAPIv2().path("/test/clear")).buildPost(Entity.json(""))); doc("make sure server returns proper response"); // clearing everything should not affect the server response if NoUserTestFilter is being used { final UserLogin userLogin = new UserLogin(DEFAULT_USERNAME, DEFAULT_PASSWORD); GenericErrorMessage errorMessage = expectStatus(Response.Status.FORBIDDEN, getAPIv2().path("/login").request(JSON).buildPost(Entity.json(userLogin)), GenericErrorMessage.class); assertErrorMessage(errorMessage, GenericErrorMessage.NO_USER_MSG, ""); } }
@Test public void testAddBookWithNecessaryFields() throws Exception { Book book = new Book(); book.setTitle("How to Win Friends & Influence People"); book.setAuthor("Dale Carnegie"); book.setIsbn("067142517X"); book.setPages(299); Entity<Book> bookEntity = Entity.entity(book, MediaType.APPLICATION_JSON); Response response = target("books") .request(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, authHeaderValue) .post(bookEntity); assertEquals(201, response.getStatus()); assertNotNull(response.getHeaderString("Location")); Book bookResponse = response.readEntity(Book.class); assertEquals("How to Win Friends & Influence People", bookResponse.getTitle()); assertEquals("Dale Carnegie", bookResponse.getAuthor()); assertEquals("067142517X", bookResponse.getIsbn()); assertEquals(299, bookResponse.getPages().intValue()); assertEquals(204, cleanUp(bookResponse.getId()).getStatus()); }
@Test public void postNewTodoItemThatFailsValidation() throws AuthenticationException, UnsupportedEncodingException { final String blankTodoItem = fixture("fixtures/todoItem_blank.json"); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.createItem(eq(oacc), any(TodoItem.class))) .thenThrow(new IllegalArgumentException("Either title or completed (or both) is required")); final Response response = resources.getJerseyTest() .target("/todos") .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .post(Entity.entity(blankTodoItem, MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(422); // 422 Unprocessable Entity verifyZeroInteractions(oacc); }
@Test public void testAddPermissionsWithValidRequestObject() { AppCreateDTO request = new AppCreateDTO(); Set<String> permissions = new HashSet<>(); permissions.add(permissionName); request.setPermissions(permissions); request.setColor("Green"); Permission permission = new Permission(permissionName); Mockito.when(permissionDAO.save(permission)).thenReturn(permission); Response response = resources.client().target(permissionsUrl).request().post(Entity.json(request)); ResponseValidator.validate(response, 201); }
protected final Response getFormPostResponse(String data, String endpoint, Class<? extends OutputStream> compressingClass, String encoding) throws IOException { byte[] bytes; if (compressingClass == null) { bytes = data.getBytes(StandardCharsets.UTF_8); } else { bytes = compress(data, compressingClass); } MediaType type = encoding == null ? MediaType.TEXT_PLAIN_TYPE : new MediaType("application", encoding); InputStream in = new ByteArrayInputStream(bytes); StreamDataBodyPart filePart = new StreamDataBodyPart("data", in, "data", type); try (MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE)) { multiPart.getBodyParts().add(filePart); return target(endpoint).request().post( Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); } }
@Test public void shouldReturnErrorResponseWhenLocalMatchingServiceRespondsWithError() throws Exception { localMatchingService.reset(); localMatchingService.register(MATCHING_REQUEST_PATH, 500, "application/json", "foo"); AttributeQuery attributeQuery = AttributeQueryBuilder.anAttributeQuery() .withId(REQUEST_ID) .withIssuer(anIssuer().withIssuerId(HUB_ENTITY_ID).build()) .withSubject(aSubjectWithAssertions(asList( anAuthnStatementAssertion(), aDefaultMatchingDatasetAssertion()), REQUEST_ID, HUB_ENTITY_ID)) .build(); Document attributeQueryDocument = getAttributeQueryToElementTransformer(signatureAlgorithmForHub, digestAlgorithmForHub, HUB_ENTITY_ID).apply(attributeQuery).getOwnerDocument(); javax.ws.rs.core.Response response = client.target(MATCHING_SERVICE_URI).request() .post(Entity.entity(attributeQueryDocument, TEXT_XML_TYPE)); assertThat(response.getStatus()).isEqualTo(500); }
@Test public void patchTodoItemWithoutAuthorization() throws AuthenticationException, UnsupportedEncodingException { final long todoItemId = 1; final String todoItem = fixture("fixtures/todoItem_new.json"); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.updateItem(eq(oacc), any(Long.class), any(TodoItem.class))) .thenThrow(new NotAuthorizedException("not authorized")); final Response response = resources.getJerseyTest() .target("/todos/" + todoItemId) .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // to support PATCH .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .build("PATCH", Entity.entity(todoItem, MediaType.APPLICATION_JSON)) .invoke(); assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode()); // 403 Forbidden }
@Override public boolean put(DeviceId device, String request, InputStream payload, String mediaType) { WebTarget wt = getWebTarget(device, request); Response response = null; if (payload != null) { try { response = wt.request(mediaType) .put(Entity.entity(IOUtils.toString(payload, StandardCharsets.UTF_8), mediaType)); } catch (IOException e) { log.error("Cannot do PUT {} request on device {} because can't read payload", request, device); } } else { response = wt.request(mediaType).put(Entity.entity(null, mediaType)); } return checkReply(response); }
@Test public void testUpdateSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy2"); sourceConfig.setType(SourceType.NAS); NASConfig nasConfig = new NASConfig(); nasConfig.setPath("/"); sourceConfig.setConfig(nasConfig.toByteString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig, nasConfig); Source updatedSource = new Source(createdSourceConfig); updatedSource.setDescription("Desc"); Source source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildPut(Entity.entity(updatedSource, JSON)), Source.class); assertEquals(source.getDescription(), "Desc"); assertEquals(source.getTag(), "1"); newNamespaceService().deleteSource(new SourcePath(source.getName()).toNamespaceKey(), 1); }
@Test public void testExecute_WithPostPort_ExpectErrorCode() { // Assume. Response response = null; try { PortEntity port = createPortEntity(); Entity<PortEntity> portEntity = Entity.entity(port, MediaType.APPLICATION_JSON); String badParam = "IdNotMatching"; // Act. response = target("controller/1.2.3.0/portElements/" + badParam) .request() .header(this.AUTHORIZATION_HEADER, this.AUTHORIZATION_CREDS) .post(portEntity); response.close(); // Assert. assertThat(response.getStatus()).isEqualTo(500); } finally { if (response != null) { response.close(); } } }
@Test public void testModifyUserWithInvalidUserID() { //test user modify with invalid id UserDTO userDTO = createUser(); Permission permission = new Permission(userDTO.getPermission().getName()); permission.setId(1); Role roleObj = new Role(role); roleObj.setId(1); Optional<Permission> permissionFromDB = Optional.of(permission); Mockito.when(permissionDAO.find(1)).thenReturn(permissionFromDB); Optional<Role> roleFromDB = Optional.of(roleObj); Mockito.when(rolesDAO.find(1)).thenReturn(roleFromDB); Optional<User> userFromDB = Optional.absent(); Mockito.when(userDAO.find(userID)).thenReturn(userFromDB); Response response = resources.client().target(modifyUrl).request().post(Entity.json(userDTO)); ResponseValidator.validate(response, 204); }
/** * Tests creating an intent with POST. */ @Test public void testPost() { ApplicationId testId = new DefaultApplicationId(2, "myApp"); expect(mockCoreService.getAppId("myApp")) .andReturn(testId); replay(mockCoreService); mockIntentService.submit(anyObject()); expectLastCall(); replay(mockIntentService); InputStream jsonStream = IntentsResourceTest.class .getResourceAsStream("post-intent.json"); WebTarget wt = target(); Response response = wt.path("intents") .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(jsonStream)); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); String location = response.getLocation().getPath(); assertThat(location, Matchers.startsWith("/intents/myApp/")); }
@Test public void testRandomIncrease() throws Exception { final Response response = target() .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .get(); final Number rnd = response.readEntity(Number.class); final Response incResponse = target() .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(rnd, MediaType.APPLICATION_JSON_TYPE)); final Number increased = incResponse.readEntity(Number.class); assertEquals(rnd.getNumber() + 1, increased.getNumber()); }
/** * Tests adding a set of devices in region with POST. */ @Test public void testAddDevicesPost() { mockRegionAdminService.addDevices(anyObject(), anyObject()); expectLastCall(); replay(mockRegionAdminService); WebTarget wt = target(); InputStream jsonStream = RegionsResourceTest.class .getResourceAsStream("region-deviceIds.json"); Response response = wt.path("regions/" + region1.id().toString() + "/devices") .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(jsonStream)); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); verify(mockRegionAdminService); }
@Test @DisplayName("Simple request with address missing optional fields") public void runCase() throws Exception { Response response = client.target(configuration.getLocalMatchingServiceMatchUrl()) .request(APPLICATION_JSON) .post(Entity.json(fileUtils.readFromResources("simple-case-excluding-optional-address-fields.json"))); validateMatchNoMatch(response); }
private Response postJson(){ Response response = client.target(url) .request() .header("Authorization", getAuthHeader()) .post(Entity.json(body.get())); return response; }
protected void post(Object obj, ApiObjectRef ref) { URI uri = getApiUrl().clone() .path("{resourceRef}") .build(ref.getRef()); getClient() .target(uri) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(obj, MediaType.APPLICATION_JSON_TYPE)); }
@Test public void gsonJacksonRoundtrip() { List<String> result = client.target(SERVER_URI) .path("/") .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(Collections.singletonList(13)), new GenericType<List<String>>() {}); check(result).isOf("a", "b", "c", "[13]"); }
@Test public void defaultErrorHandling() { try { client.target(SERVER_URI) .path("/") .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(""), new GenericType<List<String>>() {}); check(false); } catch (WebApplicationException ex) { check(ex.getResponse().getStatus()).is(400); } }
@Test public void testCreateTenantFails() throws Exception { // Given: the server has been configured with the LdapUserGroupProvider, which is non-configurable, // and: the client wants to create a tenant Tenant tenant = new Tenant(); tenant.setIdentity("new_tenant"); // When: the POST /tenants/users endpoint is accessed final Response createUserResponse = client .target(createURL("tenants/users")) .request() .header("Authorization", "Bearer " + adminAuthToken) .post(Entity.entity(tenant, MediaType.APPLICATION_JSON_TYPE), Response.class); // Then: an error is returned assertEquals(409, createUserResponse.getStatus()); // When: the POST /tenants/users endpoint is accessed final Response createUserGroupResponse = client .target(createURL("tenants/user-groups")) .request() .header("Authorization", "Bearer " + adminAuthToken) .post(Entity.entity(tenant, MediaType.APPLICATION_JSON_TYPE), Response.class); // Then: an error is returned because the UserGroupProvider is non-configurable assertEquals(409, createUserGroupResponse.getStatus()); }
@Test public void TestGetChatMemberCount() { webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatMemberCount()); Entity<Update> entity = Entity.json(getUpdate()); BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetChatMemberCount.class); assertEquals("{\"chat_id\":\"12345\",\"method\":\"getChatMembersCount\"}", map(result)); }
/** * createTask - create a task within the current model * @param task * - the task to be created */ public void createTask(Task task) { logger.info("createTask entry: {}", task.getLabel()); String url = getModelSysURL() + "/meta:hasTask"; logger.info("createTask URL: {}", url); Invocation.Builder invocationBuilder = getInvocationBuilder(url); JsonObject taskObject = new JsonObject(); JsonArray taskTypeList = new JsonArray(); taskTypeList.add("sys:Task"); taskObject.put("@type", taskTypeList); JsonObject labelObject = new JsonObject(); labelObject.put("@value", task.getLabel().getValue()); labelObject.put("@language", task.getLabel().getLanguageCode()); taskObject.put("rdfs:label", labelObject); String taskPayload = taskObject.toString(); Date startDate = new Date(); logger.info("createTask making call : {} {}", taskPayload, startDate.getTime()); Response response = invocationBuilder.post(Entity.entity(taskPayload, "application/ld+json")); logger.info("createTask call complete: {}", startDate.getTime()); /* * Possible response codes are: - 201 in case of success - 409 in case * of constraint violation (if e. g. concept scheme already exists) */ logger.info("createTask status: {}", response.getStatus()); if (logger.isDebugEnabled()) { logger.debug("createTask response: {}", response.readEntity(String.class)); } }
private Response processRequest(String url, String method, String payload, String authHeader) { Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Builder builder = target.request(); builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); if (authHeader != null) { builder.header(HttpHeaders.AUTHORIZATION, authHeader); } return (payload != null) ? builder.build(method, Entity.json(payload)).invoke() : builder.build(method).invoke(); }
public RpcClientResult post(String path, String content) { if (null == serverUri) { throw new RuntimeException("service url is null"); } WebTarget target = client.target(serverUri).path(path); return target.request().buildPost(Entity.entity(content, MediaType.APPLICATION_JSON)).invoke(RpcClientResult.class); }
@Test public void testInvalidJsonRequestReturns400() throws Exception { List<String> requests = ListUtils.list( "{\"value", "{\"value : \"something\"}", "{\"value\" : \"something" ); for (String request : requests) { Response response = target("/v1/fact").request().post(Entity.json(request)); assertEquals(400, response.getStatus()); assertMessages(getMessages(response), "Invalid JSON request received.", "invalid.json.request"); } }