private <T> RestResponse<T> getRequest(final String path, final Class<T> type) { try (Response response = client.target(serverAddress) .path(path) .request(MediaType.APPLICATION_JSON_TYPE) .get()) { return response.getStatus() == Response.Status.OK.getStatusCode() ? RestResponse.successful(response.readEntity(type)) : createErrorResponse(path, response); } catch (final Exception e) { throw new KsqlRestClientException("Error issuing GET to KSQL server. path:" + path, e); } }
public String start() { final Response response = addProperties(client.target(requestTokenUri).request()) .post(null); if (response.getStatus() != 200) { throw new RuntimeException(LocalizationMessages.ERROR_REQUEST_REQUEST_TOKEN(response.getStatus())); } final MultivaluedMap<String, String> formParams = response.readEntity(Form.class).asMap(); parameters.token(formParams.getFirst(OAuth1Parameters.TOKEN)); secrets.tokenSecret(formParams.getFirst(OAuth1Parameters.TOKEN_SECRET)); return UriBuilder.fromUri(authorizationUri).queryParam(OAuth1Parameters.TOKEN, parameters.getToken()) .build().toString(); }
@Override public void sendMessageSync(String destAddress, String message, boolean command) throws MessageException { Response response = getRequestBuilder().post(Entity.entity(preparePayload(destAddress, message), mediaType)); if (response.getStatus() / 100 != 2) { throw new MessageException(response.readEntity(String.class)); } }
@Test public void testAssignPost() { String prediction = target("/assign").request().post(Entity.text("-1.5,0.5\n-1,0")) .readEntity(String.class); Assert.assertEquals("4\n4\n", prediction); }
@Test public void runAppAndBasicTest() throws InterruptedException, ExecutionException{ Response response = rest.get("http://localhost:8080/simple-app/status/ping"); assertThat(response.getStatus(),is(400)); assertThat(response.readEntity(String.class), containsString("{\"errorCode\":\"EMPTY_REQUEST\",\"message\":\"Error id:")); } }
private Optional<SignedJwt> getAndCacheAppTokenFromServer() { MultivaluedMap<String, String> formData = new MultivaluedHashMap<>(); formData.putSingle("grant_type", "client_credentials"); formData.putSingle("scope", "urn:opc:idm:__myscopes__"); Response tokenResponse = tokenEndpoint .request() .accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.form(formData)); if (tokenResponse.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { JsonObject response = tokenResponse.readEntity(JsonObject.class); String accessToken = response.getString(ACCESS_TOKEN_KEY); LOGGER.finest(() -> "Access token: " + accessToken); SignedJwt signedJwt = SignedJwt.parseToken(accessToken); this.appToken = signedJwt; this.appJwt = signedJwt.getJwt(); return Optional.of(signedJwt); } else { LOGGER.severe("Failed to obtain access token for application to read groups" + " from IDCS. Response code: " + tokenResponse.getStatus() + ", entity: " + tokenResponse.readEntity(String.class)); return Optional.empty(); } }
private ApioResult _invokeBuilder( String httpMethod, Invocation.Builder builder, Entity<String> entity) throws ApioException { Response response = _handleResponse(httpMethod, builder, entity); String messageEntity = response.readEntity(String.class); int statusCode = response.getStatus(); Response.StatusType statusType = response.getStatusInfo(); if (statusType.getFamily() == Response.Status.Family.SUCCESSFUL) { return new ApioResult(statusCode, messageEntity); } if (_log.isDebugEnabled()) { _log.debug( "{} request failed: {}. \n{}", httpMethod, statusCode, messageEntity); } throw new ApioException( statusCode, "Request failed: \n" + messageEntity); }
@Test public void getTables() throws Exception { String tablesPath = "/tables"; Response response = _webTarget.path(tablesPath).request().get(Response.class); String responseBody = response.readEntity(String.class); TablesList tablesList = JsonUtils.stringToObject(responseBody, TablesList.class); Assert.assertNotNull(tablesList); List<String> tables = tablesList.getTables(); Assert.assertNotNull(tables); Assert.assertEquals(tables.size(), 1); Assert.assertEquals(tables.get(0), TABLE_NAME); String secondTable = "secondTable"; addTable(secondTable); response = _webTarget.path(tablesPath).request().get(Response.class); responseBody = response.readEntity(String.class); tablesList = JsonUtils.stringToObject(responseBody, TablesList.class); Assert.assertNotNull(tablesList); tables = tablesList.getTables(); Assert.assertNotNull(tables); Assert.assertEquals(tables.size(), 2); Assert.assertTrue(tables.contains(TABLE_NAME)); Assert.assertTrue(tables.contains(secondTable)); }
formValues.putSingle("code", code); Response response = oidcConfig.tokenEndpoint().request() .accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.form(formValues)); JsonObject jsonResponse = response.readEntity(JsonObject.class); String tokenValue = jsonResponse.getString("access_token"); String entity = response.readEntity(String.class); LOGGER.log(Level.FINE, "Invalid token or failed request when connecting to OIDC Token Endpoint. Response: " + entity); res.status(Http.Status.UNAUTHORIZED_401);
/** {@inheritDoc} */ public Property<?> readProperty(String name) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Property name cannot be null nor empty"); } Response cRes = ClientHttpUtils.invokeGetMethod(getStore().path(name), authorization); if (Status.NOT_FOUND.getStatusCode() == cRes.getStatus()) { throw new PropertyNotFoundException(name); } String resEntity = (String) cRes.readEntity(String.class); return PropertyJsonParser.parseProperty(resEntity); }
final String url = "http://stackoverflow.com/questions/27160440/" + "jersey-client-api-vs-jersey-test-framework"; Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Response response = target.request().accept(MediaType..get(); String html = response.readEntity(String.class); System.out.println(html); response.close();
public void test() { WebTarget target = client.target(BASE_URI); Response response = target.path("hello").request().get(); String hello = response.readEntity(String.class); assertEquals("Hello World!", hello); response.close();
@Override protected AuthResponse execute(AuthCmd command) { WebTarget webResource = getBaseResource().path("/auth"); LOGGER.trace("POST: {}", webResource); Response response = webResource.request().accept(MediaType.APPLICATION_JSON) .post(entity(command.getAuthConfig(), MediaType.APPLICATION_JSON)); if (response.getStatus() == 401) { throw new UnauthorizedException("Unauthorized"); } return response.readEntity(AuthResponse.class); }
@Test public void testPredictPost() { String prediction = target("/predict").request().post(Entity.text("A,-5,\nB,0,")) .readEntity(String.class); double expectedValue1 = (1.0 + 2.0 * 100.0) / 3.0; double expectedValue2 = (10.0 + 2 * 1000.0) / 3; Assert.assertEquals(expectedValue1 + "\n" + expectedValue2 + "\n", prediction); }
@Test public void runAppAndBasicTest(){ Response response = rest.get("http://localhost:8080/simple-app/status/ping"); assertThat(response.getStatus(),is(400)); assertThat(response.readEntity(String.class), containsString("{\"errorCode\":\"INTERNAL_SERVER_ERROR\",\"message\":")); } }
@Override public TokenResult refreshAccessToken(final String refreshToken) { refreshTokenProperties.put(OAuth2Parameters.REFRESH_TOKEN, refreshToken); final Form form = new Form(); for (final Map.Entry<String, String> entry : refreshTokenProperties.entrySet()) { form.param(entry.getKey(), entry.getValue()); } final Response response = client.target(refreshTokenUri) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() != 200) { throw new ProcessingException(LocalizationMessages.ERROR_FLOW_REQUEST_REFRESH_TOKEN(response.getStatus())); } this.tokenResult = response.readEntity(TokenResult.class); return tokenResult; }
.request() .header("Authorization", "Bearer " + appToken) .post(Entity.json(requestBuilder.build())); JsonObject jsonObject = groupResponse.readEntity(JsonObject.class); JsonArray groups = jsonObject.getJsonArray("groups"); + subject + "\". Response code: " + groupResponse.getStatus() + ", entity: " + groupResponse.readEntity(String.class)); return Optional.empty();
private static <T> RestResponse<T> createErrorResponse( final String path, final Response response) { final KsqlErrorMessage errorMessage = response.readEntity(KsqlErrorMessage.class); if (errorMessage != null) { return RestResponse.erroneous(errorMessage); } if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { return RestResponse.erroneous(404, "Path not found. Path='" + path + "'. " + "Check your ksql http url to make sure you are connecting to a ksql server."); } if (response.getStatus() == Status.UNAUTHORIZED.getStatusCode()) { return RestResponse.erroneous(UNAUTHORIZED_ERROR_MESSAGE); } if (response.getStatus() == Status.FORBIDDEN.getStatusCode()) { return RestResponse.erroneous(FORBIDDEN_ERROR_MESSAGE); } return RestResponse.erroneous( Errors.toErrorCode(response.getStatus()), "The server returned an unexpected error."); }
private ResponseValue toResponseValue(Response response) { Status status = Status.fromStatusCode(response.getStatus()); this.logger.debug("Response status is {}.", status.getStatusCode()); Family family = response.getStatusInfo().getFamily(); String data = response.readEntity(String.class); switch (family) { case SUCCESSFUL:
@Path("/date") public class DateResource { @POST @Consumes(MediaType.APPLICATION_JSON) public Response postPerson(Person person) { return Response.ok(DateTimeFormatter.ISO_DATE.format( person.getBirthDate())).build(); } } @Test public void testResteasy() throws Exception { WebTarget target = client.target( TestPortProvider.generateURL(BASE_URI)).path("date"); String person = "{\"birthDate\":\"2015-01-04\"}"; Response response = target.request().post(Entity.json(person)); System.out.println(response.readEntity(String.class)); response.close(); }