org.jboss.resteasy.client.jaxrs.ResteasyClient Java Examples
The following examples show how to use
org.jboss.resteasy.client.jaxrs.ResteasyClient.
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: 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 #2
Source File: LoginPageTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void acceptLanguageHeader() { ProfileAssume.assumeCommunity(); CloseableHttpClient httpClient = (CloseableHttpClient) new HttpClientBuilder().build(); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); loginPage.open(); Response response = client.target(driver.getCurrentUrl()).request().acceptLanguage("de").get(); Assert.assertTrue(response.readEntity(String.class).contains("Anmeldung bei test")); response = client.target(driver.getCurrentUrl()).request().acceptLanguage("en").get(); Assert.assertTrue(response.readEntity(String.class).contains("Log in to test")); client.close(); }
Example #3
Source File: ProxyFactory.java From robozonky with Apache License 2.0 | 6 votes |
public static ResteasyClient newResteasyClient() { LOGGER.debug("Creating RESTEasy client."); final Settings settings = Settings.INSTANCE; final long socketTimeout = settings.getSocketTimeout() .toMillis(); LOGGER.debug("Set socket timeout to {} ms.", socketTimeout); final long connectionTimeout = settings.getConnectionTimeout() .toMillis(); LOGGER.debug("Set connection timeout to {} ms.", connectionTimeout); final ResteasyClientBuilder builder = ((ResteasyClientBuilder) ClientBuilder.newBuilder()) .useAsyncHttpEngine() .readTimeout(socketTimeout, TimeUnit.MILLISECONDS) .connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); /* * setup HTTP proxy when required (see * http://docs.jboss.org/resteasy/docs/4.0.0.Final/userguide/html/RESTEasy_Client_Framework.html#http_proxy) */ settings.getHttpsProxyHostname() .ifPresent(host -> { final int port = settings.getHttpsProxyPort(); builder.property("org.jboss.resteasy.jaxrs.client.proxy.host", host) .property("org.jboss.resteasy.jaxrs.client.proxy.port", port); LOGGER.debug("Set HTTP proxy to {}:{}.", host, port); }); return builder.build(); }
Example #4
Source File: RestEasyClientLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void testDeleteMovie() { final ResteasyClient client = new ResteasyClientBuilder().build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); moviesResponse = proxy.deleteMovie(batmanMovie.getImdbId()); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println(moviesResponse.readEntity(String.class)); throw new RuntimeException("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); System.out.println("Response Code: " + moviesResponse.getStatus()); }
Example #5
Source File: RestEasyClientLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void testUpdateMovie() { final ResteasyClient client = new ResteasyClientBuilder().build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); batmanMovie.setTitle("Batman Begins"); moviesResponse = proxy.updateMovie(batmanMovie); if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) { System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); System.out.println("Response Code: " + moviesResponse.getStatus()); }
Example #6
Source File: RestClientTransport.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override protected Object buildProxy(ClientTransportConfig transportConfig) throws SofaRpcException { SofaResteasyClientBuilder builder = new SofaResteasyClientBuilder(); ResteasyClient client = builder .registerProvider().logProviders() .establishConnectionTimeout(transportConfig.getConnectTimeout(), TimeUnit.MILLISECONDS) .socketTimeout(transportConfig.getInvokeTimeout(), TimeUnit.MILLISECONDS) .connectionPoolSize(Math.max(transportConfig.getConnectionNum(), MIN_CONNECTION_POOL_SIZE)) .build(); ProviderInfo provider = transportConfig.getProviderInfo(); String url = "http://" + provider.getHost() + ":" + provider.getPort() + StringUtils.CONTEXT_SEP + StringUtils.trimToEmpty(provider.getPath()); ResteasyWebTarget target = client.target(url); return target.proxy(ClassUtils.forName(transportConfig.getConsumerConfig().getInterfaceId())); }
Example #7
Source File: PaginatedApiTest.java From robozonky with Apache License 2.0 | 6 votes |
@Test void checkPagination() { final PaginatedApi<S, T> p = spy(new PaginatedApi<>(null, null, null, mock(ResteasyClient.class))); doReturn(null).when(p) .execute(any(), any(), any()); final Function<T, List<S>> f = o -> Collections.emptyList(); final Select sel = mock(Select.class); final int total = 1000; final RoboZonkyFilter filter = mock(RoboZonkyFilter.class); when(filter.getLastResponseHeader(eq("X-Total"))) .thenReturn(Optional.of("" + total)); final PaginatedResult<S> result = p.execute(f, sel, 1, 10, filter); assertThat(result.getTotalResultCount()).isEqualTo(total); verify(filter, never()).setRequestHeader(eq("X-Order"), any()); verify(filter).setRequestHeader(eq("X-Size"), eq("10")); verify(filter).setRequestHeader(eq("X-Page"), eq("1")); verify(p).execute(eq(f), eq(sel), eq(filter)); }
Example #8
Source File: PaginatedApiTest.java From robozonky with Apache License 2.0 | 6 votes |
@Test void checkSorting() { String sortString = UUID.randomUUID() .toString(); final PaginatedApi<S, T> p = spy(new PaginatedApi<>(null, null, null, mock(ResteasyClient.class))); p.setSortString(sortString); doReturn(null).when(p) .execute(any(), any(), any()); final Function<T, List<S>> f = o -> Collections.emptyList(); final Select sel = mock(Select.class); final int total = 1000; final RoboZonkyFilter filter = mock(RoboZonkyFilter.class); when(filter.getLastResponseHeader(eq("X-Total"))) .thenReturn(Optional.of("" + total)); final PaginatedResult<S> result = p.execute(f, sel, 1, 10, filter); assertThat(result.getTotalResultCount()).isEqualTo(total); verify(filter, times(1)).setRequestHeader(eq("X-Order"), eq(sortString)); verify(p).execute(eq(f), eq(sel), eq(filter)); }
Example #9
Source File: RestEasyClientLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void testAddMovieMultiConnection() { final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient); final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); final Response batmanResponse = proxy.addMovie(batmanMovie); final Response transformerResponse = proxy.addMovie(transformerMovie); if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); } if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus()); } batmanResponse.close(); transformerResponse.close(); cm.close(); }
Example #10
Source File: AbstractStoresTest.java From alfresco-simple-content-stores with Apache License 2.0 | 6 votes |
/** * Configures and constructs a Resteasy client to use for calling the Alfresco Public ReST API in the dockerised deployment. * * @return the configured client */ protected static ResteasyClient setupResteasyClient() { final SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new RestAPIBeanDeserializerModifier()); final ResteasyJackson2Provider resteasyJacksonProvider = new ResteasyJackson2Provider(); final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_EMPTY); mapper.registerModule(module); resteasyJacksonProvider.setMapper(mapper); final LocalResteasyProviderFactory resteasyProviderFactory = new LocalResteasyProviderFactory(new ResteasyProviderFactoryImpl()); resteasyProviderFactory.register(resteasyJacksonProvider); // will cause a warning regarding Jackson provider which is already registered RegisterBuiltin.register(resteasyProviderFactory); resteasyProviderFactory.register(new MultiValuedParamConverterProvider()); final ResteasyClient client = new ResteasyClientBuilderImpl().providerFactory(resteasyProviderFactory).build(); return client; }
Example #11
Source File: RestEasyClientLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void testAddMovie() { final ResteasyClient client = new ResteasyClientBuilder().build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); moviesResponse = proxy.addMovie(transformerMovie); if (moviesResponse.getStatus() != Response.Status.CREATED.getStatusCode()) { System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus()); } moviesResponse.close(); System.out.println("Response Code: " + moviesResponse.getStatus()); }
Example #12
Source File: SignedServiceTest.java From maven-framework-project with MIT License | 6 votes |
@Test public void testVerification() { // Keys repository DosetaKeyRepository repository = new DosetaKeyRepository(); repository.setKeyStorePath("demo.jks"); repository.setKeyStorePassword("changeit"); repository.start(); // Building the client ResteasyClient client = new ResteasyClientBuilder().build(); Verifier verifier = new Verifier(); Verification verification = verifier.addNew(); verification.setRepository(repository); WebTarget target = client .target("http://localhost:8080/signatures-1.0/signed"); Invocation.Builder request = target.request(); request.property(Verifier.class.getName(), verifier); // Invocation to Restful web service Response response = request.post(Entity.text("Rene")); // Status 200 OK Assert.assertEquals(200, response.getStatus()); System.out.println(response.readEntity(String.class)); response.close(); client.close(); }
Example #13
Source File: ZipkinJAXRSTest.java From thorntail with Apache License 2.0 | 6 votes |
@Test public void testSpanLogging() throws Exception { ResteasyClient client = (ResteasyClient) ResteasyClientBuilder.newClient(); client.register(ClientRequestInterceptor.class); client.register(ClientResponseInterceptor.class); Response response = client.target("http://localhost:8080").request(MediaType.TEXT_PLAIN).get(); Assert.assertEquals(200, response.getStatus()); // check log file for span reporting & the specified service name // the default zipkin fraction logs to system out List<String> logContent = Files.readAllLines(Paths.get(LOG_FILE)); boolean spanPresent = logContent.stream().anyMatch(line -> line.contains(SPAN_COLLECTOR)); Assert.assertTrue("Span logging missing from log file", spanPresent); boolean serviceNamePresent = logContent.stream().anyMatch(line -> line.contains(SERVICE_NAME)); Assert.assertTrue("Service name " + SERVICE_NAME + " missing from log file", serviceNamePresent); }
Example #14
Source File: CompactDiscsDatabaseClient.java From maven-framework-project with MIT License | 6 votes |
public static List<String> getCompactDiscs(HttpServletRequest request) { ServletOAuthClient oAuthClient = (ServletOAuthClient) request .getServletContext().getAttribute( ServletOAuthClient.class.getName()); KeyStore truststore = oAuthClient.getTruststore(); ResteasyClient rsClient = new ResteasyClientBuilder() .disableTrustManager().trustStore(truststore).build(); String urlDiscs = "https://localhost:8443/discstore/discs"; try { String bearerToken = "Bearer " + oAuthClient.getBearerToken(request); Response response = rsClient.target(urlDiscs).request() .header(HttpHeaders.AUTHORIZATION, bearerToken).get(); return response.readEntity(new GenericType<List<String>>() { }); } catch (BadRequestException bre) { bre.printStackTrace(); } catch (InternalServerErrorException isee) { isee.printStackTrace(); } finally { rsClient.close(); } return null; }
Example #15
Source File: RestEasyClientLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void testListAllMovies() { final ResteasyClient client = new ResteasyClientBuilder().build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); moviesResponse = proxy.addMovie(batmanMovie); moviesResponse.close(); final List<Movie> movies = proxy.listMovies(); System.out.println(movies); }
Example #16
Source File: RestEasyClientLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void testMovieByImdbId() { final String transformerImdbId = "tt0418279"; final ResteasyClient client = new ResteasyClientBuilder().build(); final ResteasyWebTarget target = client.target(FULL_PATH); final ServicesInterface proxy = target.proxy(ServicesInterface.class); final Response moviesResponse = proxy.addMovie(transformerMovie); moviesResponse.close(); final Movie movies = proxy.movieByImdbId(transformerImdbId); System.out.println(movies); }
Example #17
Source File: ImpersonationTest.java From keycloak with Apache License 2.0 | 5 votes |
protected Cookie testSuccessfulImpersonation(String admin, String adminRealm) { ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder(); resteasyClientBuilder.connectionPoolSize(10); resteasyClientBuilder.httpEngine(AdminClientUtil.getCustomClientHttpEngine(resteasyClientBuilder, 10)); ResteasyClient resteasyClient = resteasyClientBuilder.build(); // Login adminClient try (Keycloak client = login(admin, adminRealm, resteasyClient)) { // Impersonate return impersonate(client, admin, adminRealm); } }
Example #18
Source File: KeycloakTestingClient.java From keycloak with Apache License 2.0 | 5 votes |
KeycloakTestingClient(String serverUrl, ResteasyClient resteasyClient) { if (resteasyClient != null) { client = resteasyClient; } else { ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder(); resteasyClientBuilder.connectionPoolSize(10); if (serverUrl.startsWith("https")) { // Disable PKIX path validation errors when running tests using SSL resteasyClientBuilder.disableTrustManager().hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY); } resteasyClientBuilder.httpEngine(AdminClientUtil.getCustomClientHttpEngine(resteasyClientBuilder, 10)); client = resteasyClientBuilder.build(); } target = client.target(serverUrl); }
Example #19
Source File: ImpersonationTest.java From keycloak with Apache License 2.0 | 5 votes |
Keycloak createAdminClient(String realm, String clientId, String username, String password, ResteasyClient resteasyClient) { if (password == null) { password = username.equals("admin") ? "admin" : "password"; } return KeycloakBuilder.builder().serverUrl(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth") .realm(realm) .username(username) .password(password) .clientId(clientId) .resteasyClient(resteasyClient) .build(); }
Example #20
Source File: FidoU2fClientFactory.java From oxAuth with MIT License | 5 votes |
public U2fConfigurationService createMetaDataConfigurationService(String u2fMetaDataUri) { ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); ResteasyWebTarget target = client.target(UriBuilder.fromPath(u2fMetaDataUri)); U2fConfigurationService proxy = target.proxy(U2fConfigurationService.class); return proxy; }
Example #21
Source File: ImpersonationTest.java From keycloak with Apache License 2.0 | 5 votes |
private Keycloak login(String username, String realm, ResteasyClient resteasyClient) { String clientId = establishClientId(realm); Keycloak client = createAdminClient(realm, clientId, username, null, resteasyClient); client.tokenManager().grantToken(); // only poll for LOGIN event if realm is not master // - since for master testing event listener is not installed if (!AuthRealm.MASTER.equals(realm)) { EventRepresentation e = events.poll(); Assert.assertEquals("Event type", EventType.LOGIN.toString(), e.getType()); Assert.assertEquals("Client ID", clientId, e.getClientId()); Assert.assertEquals("Username", username, e.getDetails().get("username")); } return client; }
Example #22
Source File: ClientFactory.java From oxAuth with MIT License | 5 votes |
public IntrospectionService createIntrospectionService(String p_url, ClientHttpEngine engine) { ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); ResteasyWebTarget target = client.target(UriBuilder.fromPath(p_url)); IntrospectionService proxy = target.proxy(IntrospectionService.class); return proxy; }
Example #23
Source File: BuildEndpointTest.java From pnc with Apache License 2.0 | 5 votes |
@Test public void shouldGetSCMArchiveLink() throws ClientException, ReflectiveOperationException { BuildClient client = new BuildClient(RestClientConfiguration.asAnonymous()); // Disable redirects so we can test the actual response Field f = ClientBase.class.getDeclaredField("client"); f.setAccessible(true); ResteasyClient reClient = (ResteasyClient) f.get(client); ApacheHttpClient43EngineWithRetry engine = (ApacheHttpClient43EngineWithRetry) reClient.httpEngine(); engine.setFollowRedirects(false); Response internalScmArchiveLink = client.getInternalScmArchiveLink(buildId); assertThat(internalScmArchiveLink.getStatusInfo()).isEqualTo(Status.TEMPORARY_REDIRECT); assertThat(internalScmArchiveLink.getHeaderString("Location")).isNotEmpty(); }
Example #24
Source File: RestFactory.java From KubernetesAPIJavaClient with Apache License 2.0 | 5 votes |
public KubernetesAPI createAPI(URI uri, String userName, String password) { // Configure HttpClient to authenticate preemptively // by prepopulating the authentication data cache. // http://docs.jboss.org/resteasy/docs/3.0.9.Final/userguide/html/RESTEasy_Client_Framework.html#transport_layer // http://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/authentication.html#d5e1032 HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(userName, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // 4. Create client executor and proxy ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, localcontext); ResteasyClient client = new ResteasyClientBuilder().connectionPoolSize(connectionPoolSize).httpEngine(engine) .build(); client.register(JacksonJaxbJsonProvider.class).register(JacksonConfig.class); ProxyBuilder<KubernetesAPI> proxyBuilder = client.target(uri).proxyBuilder(KubernetesAPI.class); if (classLoader != null) { proxyBuilder = proxyBuilder.classloader(classLoader); } return proxyBuilder.build(); }
Example #25
Source File: RMRestClient.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
private static RMRestInterface createRestProxy(ResteasyProviderFactory provider, String restEndpointURL, ClientHttpEngine httpEngine) { ResteasyClient client = buildResteasyClient(provider); ResteasyWebTarget target = client.target(restEndpointURL); RMRestInterface rmRestInterface = target.proxy(RMRestInterface.class); return createExceptionProxy(rmRestInterface); }
Example #26
Source File: SchedulerRestClient.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
private static SchedulerRestInterface createRestProxy(ResteasyProviderFactory provider, String restEndpointURL, ClientHttpEngine httpEngine) { ResteasyClient client = buildResteasyClient(provider); ResteasyWebTarget target = client.target(restEndpointURL); SchedulerRestInterface schedulerRestClient = target.proxy(SchedulerRestInterface.class); return createExceptionProxy(schedulerRestClient); }
Example #27
Source File: SchedulerRestClient.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public Map<String, Object> metadata(String sessionId, String dataspacePath, String pathname) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)) .append("data/") .append(dataspacePath) .append(escapeUrlPathSegment(pathname)); ResteasyClient client = buildResteasyClient(providerFactory); ResteasyWebTarget target = client.target(uriTmpl.toString()); Response response = null; try { response = target.request().header("sessionid", sessionId).head(); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Cannot get metadata from %s in %s.", pathname, dataspacePath), response); } } MultivaluedMap<String, Object> headers = response.getHeaders(); Map<String, Object> metaMap = Maps.newHashMap(); if (headers.containsKey(HttpHeaders.LAST_MODIFIED)) { metaMap.put(HttpHeaders.LAST_MODIFIED, headers.getFirst(HttpHeaders.LAST_MODIFIED)); } return metaMap; } finally { if (response != null) { response.close(); } } }
Example #28
Source File: SchedulerRestClient.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public ListFile list(String sessionId, String dataspacePath, String pathname) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)) .append("data/") .append(dataspacePath) .append('/'); ResteasyClient client = buildResteasyClient(providerFactory); ResteasyWebTarget target = client.target(uriTmpl.toString()).path(pathname).queryParam("comp", "list"); Response response = null; try { response = target.request().header("sessionid", sessionId).get(); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Cannot list the specified location: %s", pathname), response); } } return response.readEntity(ListFile.class); } finally { if (response != null) { response.close(); } } }
Example #29
Source File: SchedulerRestClient.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public boolean delete(String sessionId, String dataspacePath, String path, List<String> includes, List<String> excludes) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)) .append("data/") .append(dataspacePath) .append('/'); ResteasyClient client = buildResteasyClient(providerFactory); ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path); if (includes != null && !includes.isEmpty()) { target = target.queryParam("includes", includes.toArray(new Object[includes.size()])); } if (excludes != null && !excludes.isEmpty()) { target = target.queryParam("excludes", excludes.toArray(new Object[excludes.size()])); } Response response = null; try { response = target.request().header("sessionid", sessionId).delete(); if (response.getStatus() != HttpURLConnection.HTTP_NO_CONTENT) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Cannot delete file(s). Status code: %s", response.getStatus()), response); } } return true; } finally { if (response != null) { response.close(); } } }
Example #30
Source File: SchedulerRestClient.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public boolean upload(String sessionId, StreamingOutput output, String encoding, String dataspace, String path) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)) .append("data/") .append(dataspace); ResteasyClient client = buildResteasyClient(providerFactory); ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path); Response response = null; try { response = target.request() .header("sessionid", sessionId) .put(Entity.entity(output, new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (Locale) null, encoding))); if (response.getStatus() != HttpURLConnection.HTTP_CREATED) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("File upload failed. Status code: %d" + response.getStatus()), response); } } return true; } finally { if (response != null) { response.close(); } } }