public boolean delete(String token, String url, String resourcePath) { WebTarget target = client.target("https://" + url).path(resourcePath); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); setHeaders(invocationBuilder, token); Response response = invocationBuilder.delete(); return response.getStatus() == Response.Status.OK.getStatusCode(); }
/** * Invokes the given request * * @param <R> the return type * @param request the request to invoke * @return the response * @throws Exception the exception */ private <R> HttpResponse invoke(HttpRequest<R> request, boolean useNonStrictSSL) throws Exception { Client client = ClientFactory.create(useNonStrictSSL); WebTarget target = client.target(request.getEndpoint()).path(request.getPath()); if (Boolean.getBoolean(HttpLoggingFilter.class.getName())) target.register(new HttpLoggingFilter(Logger.getLogger("os"), 10000)); target = populateQueryParams(target, request); Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON); populateHeaders(invocation, request); Entity<?> entity = (request.getEntity() == null) ? null : Entity.entity(request.getEntity(), request.getContentType()); try { if (entity != null) { return HttpResponse.wrap(invocation.method(request.getMethod().name(), entity)); } if (HttpMethod.PUT == request.getMethod() || request.hasJson()) { return HttpResponse.wrap( invocation.method( request.getMethod().name(), Entity.entity(request.getJson(), ClientConstants.CONTENT_TYPE_JSON))); } return HttpResponse.wrap(invocation.method(request.getMethod().name())); } catch (ProcessingException pe) { throw new ConnectionException(pe.getMessage(), 0, pe); } catch (ClientErrorException e) { throw HttpResponse.mapException( e.getResponse().getStatusInfo().toString(), e.getResponse().getStatus(), e); } }
@Test public void call_server() throws Exception { String expectedSentence = "Hello Filibuster!"; Client httpClient = mock(Client.class); WebTarget webTarget = mock(WebTarget.class); Invocation.Builder builder = mock(Invocation.Builder.class); String json = "{\"sound\":\"SGVsbG8gRmlsaWJ1c3RlciE=\"}"; when(httpClient.target(anyString())).thenReturn(webTarget); when(webTarget.path(anyString())).thenReturn(webTarget); when(webTarget.queryParam(anyString(), anyString())).thenReturn(webTarget); when(webTarget.request(any(MediaType.class))).thenReturn(builder); when(builder.get(String.class)).thenReturn(json); String host = "localhost"; int port = 80; SpeechClient client = new SpeechClient(httpClient, new ObjectMapper(), host, port); SynthesizedSound actual = client.synthesise(expectedSentence); assertThat(actual.getSound(), is(expectedSentence.getBytes())); verify(httpClient).target("http://localhost:80"); verify(webTarget).path("synthesize"); String encoded = Base64.getEncoder().encodeToString(expectedSentence.getBytes("UTF-8")); verify(webTarget).queryParam("sentence", encoded); verify(webTarget).request(MediaType.APPLICATION_JSON_TYPE); verify(builder).get(String.class); }
@Before public void setUp() { RegionCache regionCache = new RegionCache(); regionCache.clear(); openStackRegion = new OpenStackRegionImpl(); Client client = mock(Client.class); WebTarget webResource = mock(WebTarget.class); builder = mock(Invocation.Builder.class); clientResponse = mock(Response.class); Response clientResponseAdmin = mock(Response.class); // when when(webResource.request(MediaType.APPLICATION_JSON)).thenReturn(builder); when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder); when(client.target(anyString())).thenReturn(webResource); openStackRegion.setClient(client); systemPropertiesProvider = mock(SystemPropertiesProvider.class); openStackRegion.setSystemPropertiesProvider(systemPropertiesProvider); String responseJSON = "{\"access\": {\"token\": {\"issued_at\": \"2014-01-13T14:00:10.103025\", \"expires\": \"2014-01-14T14:00:09Z\"," + "\"id\": \"ec3ecab46f0c4830ad2a5837fd0ad0d7\", \"tenant\": { \"description\": null, \"enabled\": true, \"id\": \"08bed031f6c54c9d9b35b42aa06b51c0\"," + "\"name\": \"admin\" } }, \"serviceCatalog\": []}}}"; when(builder.post(Entity.entity(anyString(), MediaType.APPLICATION_JSON))) .thenReturn(clientResponseAdmin); when(clientResponseAdmin.getStatus()).thenReturn(200); when(clientResponseAdmin.readEntity(String.class)).thenReturn(responseJSON); }
@Test public void testImplicitExplicitTemplate() throws IOException { final Invocation.Builder request = target("implicit-explicit").request(); Properties p = new Properties(); p.load(request.get(InputStream.class)); assertEquals( "/org/glassfish/jersey/tests/e2e/server/mvc/FlatViewProcessorTest.ImplicitExplicitTemplate.index.testp", p.getProperty("path")); assertEquals("ImplicitExplicitTemplate", p.getProperty("model")); p = new Properties(); p.load(request.post(Entity.entity("", MediaType.TEXT_PLAIN_TYPE), InputStream.class)); assertEquals( "/org/glassfish/jersey/tests/e2e/server/mvc/FlatViewProcessorTest.ImplicitExplicitTemplate.show.testp", p.getProperty("path")); assertEquals("post", p.getProperty("model")); p = new Properties(); p.load(target("implicit-explicit").path("sub").request().get(InputStream.class)); assertEquals( "/org/glassfish/jersey/tests/e2e/server/mvc/FlatViewProcessorTest.ImplicitExplicitTemplate.show.testp", p.getProperty("path")); assertEquals("get", p.getProperty("model")); }
public Post fetch(Session session, NextRequest next) { LOGGER.debug( ((next == null) ? "Initial request" : "next request: " + next) + "/n Session: " + session.toString()); WebTarget target = createInitialFetchTarget(); if (next != null) { target = fillNextParameters(next, target); } Invocation.Builder request = target.request(); request = appendCookies(session, request); Response response = request.post( Entity.entity( new NextToken.NextTokenBuilder().createNextToken(), MediaType.APPLICATION_JSON_TYPE)); response.bufferEntity(); try { String responseJson = response.readEntity(String.class); LOGGER.debug("Full response: " + responseJson); } catch (Exception ex) { ex.printStackTrace(); } Post post = response.readEntity(Post.class); response.close(); return post; }
// when BookResource.getBooks uses:: @RolesAllowed(value={"admin"}) // Then:: @Test(expected = javax.ws.rs.ForbiddenException.class) @Test public void testGetAll2() { final ClientConfig cc = getClientConfig(); final Client client = ClientBuilder.newClient(cc); final Invocation.Builder invocationBuilder = client.target(BASE_URI).request(); invocationBuilder.get(Books.class); }
@Test(expected = javax.ws.rs.NotAuthorizedException.class) public void testGetAll() { final ClientConfig cc = new ClientConfig(); final Client client = ClientBuilder.newClient(cc); final Invocation.Builder invocationBuilder = client.target(BASE_URI).request(); invocationBuilder.get(Books.class); }
/** * Share header settings for invocations. * * @param webTarget target web * @return */ private Response post(WebTarget webTarget) { Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON_TYPE); if (null != authorization) { invocationBuilder.header(HEADER_AUTHORIZATION, authorization); } return invocationBuilder.post(Entity.text("")); }
private CallReturn prepareCall( String jsonString, String path, MultivaluedMap<String, Object> headers, CALL_TYPE callType) throws IOException { Entity<String> itemToSend = Entity.json(jsonString); // LOG.debug("sending\n" + jsonString + "\n"); Invocation.Builder responseBuilder = getRestAudienceClient().getWebTarget().path(path).request(MediaType.APPLICATION_JSON); if (headers != null) { responseBuilder.headers(headers); } Response response = null; switch (callType) { case get: response = responseBuilder.get(); break; case post: { response = responseBuilder.post(itemToSend); } } return createCallReturnFromResponse(response); }
public <T> T putWor( String url, String resourcePath, Object object, Class<T> responseClass, Map<String, Object> queryParams, String worToken) { WebTarget target = client.target("https://" + url).path(resourcePath); if (queryParams != null) { for (Map.Entry<String, Object> entry : queryParams.entrySet()) { target = target.queryParam(entry.getKey(), entry.getValue()); } } Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); setHeaders(invocationBuilder, worToken); Response putResponse = invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE)); if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) { Logger.error( "PUT call to " + url + "/" + resourcePath + " returned status of " + putResponse.getStatus()); return null; } if (responseClass != null && putResponse.hasEntity() && putResponse.getStatus() == Response.Status.OK.getStatusCode()) return putResponse.readEntity(responseClass); return null; }
protected void setHeaders(Invocation.Builder invocationBuilder, String token) { invocationBuilder.header(Headers.WOR_API_KEY_TOKEN, token); String clientId = Utils.getConfigValue(ConfigurationKey.URI_PREFIX); if (!StringUtils.isEmpty(clientId)) { invocationBuilder.header(Headers.API_KEY_CLIENT_ID, clientId); } }
public Response sendRequest(String url, String requestType) { Client client = ClientBuilder.newClient(); System.out.println("Testing " + url); WebTarget target = client.target(url); Invocation.Builder invoBuild = target.request(); Response response = invoBuild.build(requestType).invoke(); return response; }
@Test public void testDispatchDynamic43() throws Exception { ResteasyClient client = new ResteasyClientBuilder().build43(); Invocation.Builder request = client.target(generateURL("/test/dispatch/dynamic")).request(); Response response = request.get(); assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); assertEquals("Wrong content of response", "forward", response.readEntity(String.class)); }
@Override public Suggestions getSuggestions( final RequestInfo requestInfo, final String selection, final String dependent, @Nullable final ResponseAction responseAction) { try { final URL url = getUrl(requestInfo, selection, dependent); Invocation.Builder requestBuilder = client .target(url.toURI()) .request() .accept(MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON); if (requestInfo.getAuthentication() != null) { requestBuilder = requestBuilder .property( HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, requestInfo.getAuthentication().getUsername()) .property( HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, requestInfo.getAuthentication().getPassword()); } if (responseAction == null) { // response does not require transformation return requestBuilder.get(Suggestions.class); } else { // we need to transform the custom XML or JSON response into Suggestions format final Response response = requestBuilder.get(); try (final InputStream is = response.readEntity(InputStream.class)) { final MediaType mediaType = response.getMediaType(); final Path transformation = responseAction.getTransformation(); if (mediaType != null && mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE) || mediaType.isCompatible(MediaType.TEXT_XML_TYPE)) { // custom XML response LOGGER.debug("Transforming XML response from: {} using: {}", url, transformation); return transformXmlResponse(is, transformation); } else if (mediaType != null && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)) { LOGGER.debug("Transforming JSON response from: {} using: {}", url, transformation); // custom JSON response return transformJsonResponse(is, transformation); } else { LOGGER.error( "Response from {} has unsupported Content-Type: {}", url, mediaType); // TODO(AR) maybe something more visible to the user return new Suggestions(); } } } } catch (final URISyntaxException | IOException | TransformationException e) { LOGGER.error(e.getMessage(), e); // TODO(AR) maybe something more visible to the user return new Suggestions(); } }
public PaymentNotification[] getNotifications(String userId) { WebTarget notificationTarget = appTarget.path("notification/user/" + userId); Invocation.Builder setupBuilder = notificationTarget.request(MediaType.APPLICATION_JSON); Response response = setupBuilder.get(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create(); String json = response.readEntity(String.class); return gson.fromJson(json, PaymentNotification[].class); }
public Response postSequenceFile( String url, String recordId, EntryType entryType, String sequence) { WebTarget target = client.target("https://" + url).path("/rest/file/sequence"); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); final FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.field("file", IOUtils.toInputStream(sequence), MediaType.TEXT_PLAIN_TYPE); multiPart.field("entryRecordId", recordId); multiPart.field("entryType", entryType.name()); return invocationBuilder.post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); }
@Test public void testImplicitTemplate() throws IOException { final Invocation.Builder request = target("implicit").request(); Properties p = new Properties(); p.load(request.get(InputStream.class)); assertEquals( "/org/glassfish/jersey/tests/e2e/server/mvc/FlatViewProcessorTest.ImplicitTemplate.index.testp", p.getProperty("path")); assertEquals("ImplicitTemplate", p.getProperty("model")); }
@Test public void testOrderBook() { Client client = ClientBuilder.newClient(); WebTarget target = client.target("https://api.bitfinex.com/v1"); target = target.path("/book/BTCUSD"); Invocation.Builder builder = target.request(); Response response = builder.get(); String quoteString = response.readEntity(String.class); Gson gson = new Gson(); OrderBook book = gson.fromJson(quoteString, OrderBook.class); System.out.println(book); }
@Test public void testTrades() { Client client = ClientBuilder.newClient(); WebTarget target = client.target("https://api.bitfinex.com/v1"); target = target.path("/trades/BTCUSD"); Invocation.Builder builder = target.request(); Response response = builder.get(); String quoteString = response.readEntity(String.class); Gson gson = new Gson(); List<Trade> trades = gson.fromJson(quoteString, List.class); System.out.println(trades); }
// WOR public <T> T getWor( String url, String path, Class<T> clazz, Map<String, Object> queryParams, String token) { WebTarget target = client.target("https://" + url).path(path); if (queryParams != null) { for (Map.Entry<String, Object> entry : queryParams.entrySet()) { target = target.queryParam(entry.getKey(), entry.getValue()); } } Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); setHeaders(invocationBuilder, token); return invocationBuilder.buildGet().invoke(clazz); }
/* * (non-Javadoc) * * @see org.slc.sli.api.client.impl.IRESTClient#deleteRequestWithHeaders(java.net.URL, * java.util.Map) */ @Override public Response deleteRequestWithHeaders(final URL url, final Map<String, Object> headers) throws MalformedURLException, URISyntaxException { if (sessionToken == null) { logger.log( Level.SEVERE, String.format("Token is null in call to RESTClient for url: %s", url.toString())); return null; } Invocation.Builder builder = client.target(url.toURI()).request(MediaType.APPLICATION_JSON); builder = getCommonRequestBuilder(sessionToken, builder, headers); Invocation i = builder.buildDelete(); return i.invoke(); }
@Test public void testInactiveControlRetriedOnceAndSucceeds() throws InterruptedException { final WebTarget QUALIFY_TARGET = Mockito.mock(WebTarget.class); final WebTarget FOLLOW_TARGET = Mockito.mock(WebTarget.class); final Invocation.Builder QUALIFY_BUILDER = Mockito.mock(Invocation.Builder.class); final AsyncInvoker QUALIFY_ASYNC = Mockito.mock(AsyncInvoker.class); final Invocation.Builder FOLLOW_BUILDER = Mockito.mock(Invocation.Builder.class); final AsyncInvoker FOLLOW_ASYNC = Mockito.mock(AsyncInvoker.class); Mockito.when(QUALIFY_TARGET.request()).thenReturn(QUALIFY_BUILDER); Mockito.when(QUALIFY_BUILDER.async()).thenReturn(QUALIFY_ASYNC); Mockito.when(FOLLOW_TARGET.request()).thenReturn(FOLLOW_BUILDER); Mockito.when(FOLLOW_BUILDER.async()).thenReturn(FOLLOW_ASYNC); final ChannelMonitor MONITOR = new RetryingControlChannelMonitor(config(), QUALIFY_TARGET, FOLLOW_TARGET); final Future CAPTURE_FUTURE = Mockito.mock(Future.class); final DataUnitCounter COUNTER = Mockito.mock(DataUnitCounter.class); Mockito.when(COUNTER.getDataUnitCount()).thenReturn(0); final ControlChannelId id = new ControlChannelId(10, 20, 30, 40); final Identifiable capture = new FollowRequest(10d, 20d, 0, 1337d, id); assert MONITOR.monitor(capture, CAPTURE_FUTURE, COUNTER); assert MONITOR.contains(id); Mockito.verify(CAPTURE_FUTURE, Mockito.never()).cancel(Mockito.anyBoolean()); Thread.sleep(1100); Mockito.verify(CAPTURE_FUTURE, Mockito.times(1)).cancel(Mockito.anyBoolean()); assert MONITOR.contains(id); ArgumentCaptor<InvocationCallback> QUALIFY_CALLBACK = ArgumentCaptor.forClass(InvocationCallback.class); Mockito.verify(QUALIFY_ASYNC).post(Mockito.any(Entity.class), QUALIFY_CALLBACK.capture()); ControlChannelQualities QUALITIES = Mockito.mock(ControlChannelQualities.class); Mockito.when(QUALITIES.getWacn()).thenReturn(id.getWacn()); Mockito.when(QUALITIES.getSystemId()).thenReturn(id.getSystemId()); Mockito.when(QUALITIES.getRfSubsystemId()).thenReturn(id.getRfSubsystemId()); Mockito.when(QUALITIES.getSiteId()).thenReturn(id.getSiteId()); QUALIFY_CALLBACK.getValue().completed(QUALITIES); assert !MONITOR.contains(id); Mockito.verify(FOLLOW_ASYNC, Mockito.times(1)) .post(Mockito.any(Entity.class), Mockito.any(InvocationCallback.class)); }
private Client getMockedClient() { Invocation.Builder builder = mock(Invocation.Builder.class); //noinspection unchecked when(builder.get(any(Class.class))).thenReturn(""); WebTarget webTarget = mock(WebTarget.class); when(webTarget.path(anyString())).thenReturn(webTarget); when(webTarget.queryParam(anyString(), anyString())).thenReturn(webTarget); when(webTarget.request(any(MediaType.class))).thenReturn(builder); Client httpClient = mock(Client.class); when(httpClient.target(anyString())).thenReturn(webTarget); return httpClient; }
/** * We can inject either proxy or a WebTarget for low level manipulations and assertions. * * @param webTarget configured resource ready for use, injected by Arquillian */ @Test public void createCustomerBareJAXRSResource( @ArquillianResteasyResource("rest/customer") JerseyWebTarget webTarget) { // Given final Invocation.Builder invocationBuilder = webTarget.request(); final Invocation invocation = invocationBuilder.buildPost(Entity.entity(new Customer(), MediaType.APPLICATION_JSON_TYPE)); // When final Response response = invocation.invoke(); // Then assertEquals(deploymentURL + "rest/customer", webTarget.getUri().toASCIIString()); assertEquals(MediaType.APPLICATION_JSON, response.getMediaType().toString()); assertEquals(200, response.getStatus()); }
private <C> C getAt(String uri, String sessionKey, MediaType mediaType, Class<C> c) { String thePath = uri; String queryParams = ""; WebTarget resource = resource(); if (thePath.contains("?")) { String[] pathParts = thePath.split("\\?"); thePath = pathParts[0]; queryParams = pathParts[1]; } Invocation.Builder requestBuilder = applyQueryParameters(queryParams, resource.path(thePath)).request(mediaType); if (StringUtil.isDefined(sessionKey)) { requestBuilder = requestBuilder.header(HTTP_SESSIONKEY, sessionKey); } return requestBuilder.get(c); }
private <R> void populateHeaders(Invocation.Builder invocation, HttpRequest<R> request) { if (!request.hasHeaders()) return; for (Map.Entry<String, Object> h : request.getHeaders().entrySet()) { invocation.header(h.getKey(), h.getValue()); } }
@SuppressWarnings("unchecked") private <E> E put(final E entity, String atURI, String withSessionKey) { String thePath = atURI; String queryParams = ""; WebTarget resource = resource(); if (thePath.contains("?")) { String[] pathParts = thePath.split("\\?"); thePath = pathParts[0]; queryParams = pathParts[1]; } Invocation.Builder resourcePutter = applyQueryParameters(queryParams, resource.path(thePath)) .request(MediaType.APPLICATION_JSON); if (isDefined(withSessionKey)) { resourcePutter = resourcePutter.header(HTTP_SESSIONKEY, withSessionKey); } Class<E> c = (Class<E>) entity.getClass(); return resourcePutter.put(Entity.entity(entity, MediaType.APPLICATION_JSON), c); }
@Override public <T> T post( String url, String resourcePath, Object object, Class<T> responseClass, Map<String, Object> queryParams) { WebTarget target = client.target("https://" + url).path(resourcePath); if (queryParams != null) { for (Map.Entry<String, Object> entry : queryParams.entrySet()) { target = target.queryParam(entry.getKey(), entry.getValue()); } } Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); Response postResponse = invocationBuilder.post(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE)); if (postResponse.hasEntity() && postResponse.getStatus() == Response.Status.OK.getStatusCode()) return postResponse.readEntity(responseClass); return null; }
public <T> T put(String url, String resourcePath, Object object, Class<T> responseClass) { WebTarget target = client.target("https://" + url).path(resourcePath); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); Response putResponse = invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE)); if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) { Logger.error( "PUT call to " + url + "/" + resourcePath + " returned status of " + putResponse.getStatus()); return null; } if (responseClass != null && putResponse.hasEntity() && putResponse.getStatus() == Response.Status.OK.getStatusCode()) return putResponse.readEntity(responseClass); return null; }