Java Code Examples for org.jboss.resteasy.client.jaxrs.ResteasyClient#target()

The following examples show how to use org.jboss.resteasy.client.jaxrs.ResteasyClient#target() . 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: RestClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@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 3
Source File: SignedServiceTest.java    From maven-framework-project with MIT License 6 votes vote down vote up
@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 4
Source File: CompactDiscsDatabaseClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
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 5
Source File: ClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
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 6
Source File: RMRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
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 7
Source File: FidoU2fClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
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 8
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
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 9
Source File: OauthClientTest.java    From maven-framework-project with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		String truststorePath = "C:/Users/Andres/jboss/2do_jboss/jboss-as-7.1.1.Final/standalone/configuration/client-truststore.ts";
		String truststorePassword = "changeit";
		truststorePath = EnvUtil.replace(truststorePath);

		KeyStore truststore = loadKeyStore(truststorePath, truststorePassword);

		ResteasyClient client = new ResteasyClientBuilder()
				.disableTrustManager().trustStore(truststore).build();

		Form form = new Form().param("grant_type", "client_credentials");
		ResteasyWebTarget target = client
				.target("https://localhost:8443/oauth-server/j_oauth_token_grant");
		target.register(new BasicAuthentication("andres", "andres"));

		AccessTokenResponse tokenResponse = target.request().post(
				Entity.form(form), AccessTokenResponse.class);
		Response response = client
				.target("https://localhost:8443/discstore/discs")
				.request()
				.header(HttpHeaders.AUTHORIZATION,
						"Bearer " + tokenResponse.getToken()).get();
		try {
			String xml = response.readEntity(String.class);
			System.out.println(xml);
		} finally {
			client.close();
		}

	}
 
Example 10
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public void pullFile(String sessionId, String space, String path, String outputPath) throws Exception {
    String uriTmpl = (new StringBuilder(restEndpointURL)).append(addSlashIfMissing(restEndpointURL))
                                                         .append("scheduler/dataspace/")
                                                         .append(space)
                                                         .append(URLEncoder.encode(path, "UTF-8"))
                                                         .toString();

    ResteasyClient client = buildResteasyClient(providerFactory);

    ResteasyWebTarget target = client.target(uriTmpl);
    Response 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 retrieve the file. Status code: %s", response.getStatus()),
                           response);
        }
    }
    try {
        File file = new File(outputPath);
        if (response.hasEntity()) {
            copyInputStreamToFile(response.readEntity(InputStream.class), file);
        } else {
            // creates an empty file
            file.createNewFile();
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (response != null) {
            response.close();
        }
        if (!client.isClosed()) {
            client.close();
        }
    }
}
 
Example 11
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean pushFile(String sessionId, String space, String path, String fileName, InputStream fileContent)
        throws Exception {
    String uriTmpl = (new StringBuilder(restEndpointURL)).append(addSlashIfMissing(restEndpointURL))
                                                         .append("scheduler/dataspace/")
                                                         .append(space)
                                                         .append(URLEncoder.encode(path, "UTF-8"))
                                                         .toString();

    ResteasyClient client = buildResteasyClient(providerFactory);

    ResteasyWebTarget target = client.target(uriTmpl);

    MultipartFormDataOutput formData = new MultipartFormDataOutput();
    formData.addFormData("fileName", fileName, MediaType.TEXT_PLAIN_TYPE);
    formData.addFormData("fileContent", fileContent, MediaType.APPLICATION_OCTET_STREAM_TYPE);

    GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(formData) {
    };

    Response response = target.request()
                              .header("sessionid", sessionId)
                              .post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));

    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("File upload failed. Status code: %d", response.getStatus()), response);
        }
    }
    return response.readEntity(Boolean.class);
}
 
Example 12
Source File: SchedulerStateRest.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String submitPlannings(String sessionId, PathSegment pathSegment, Map<String, String> jobContentXmlString)
        throws JobCreationRestException, NotConnectedRestException, IOException {

    checkAccess(sessionId, "plannings");

    Map<String, String> jobVariables = workflowVariablesTransformer.getWorkflowVariablesFromPathSegment(pathSegment);

    if (jobContentXmlString == null || jobContentXmlString.size() != 1) {
        throw new JobCreationRestException("Cannot find job body: code " + HttpURLConnection.HTTP_BAD_REQUEST);
    }

    Map<String, Object> requestBody = new HashMap<>(2);
    requestBody.put("variables", jobVariables);
    requestBody.put("xmlContentString", jobContentXmlString.entrySet().iterator().next().getValue());

    Response response = null;
    try {
        ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
        SchedulerRestClient.registerGzipEncoding(providerFactory);
        ResteasyClient client = new ResteasyClientBuilder().providerFactory(providerFactory).build();
        ResteasyWebTarget target = client.target(PortalConfiguration.JOBPLANNER_URL.getValueAsString());
        response = target.request()
                         .header("sessionid", sessionId)
                         .post(Entity.entity(requestBody, "application/json"));

        if (HttpURLConnection.HTTP_OK != response.getStatus()) {
            throw new IOException(String.format("Cannot access resource %s: code %d",
                                                PortalConfiguration.JOBPLANNER_URL.getValueAsString(),
                                                response.getStatus()));
        }
        return response.readEntity(String.class);
    } finally {
        if (response != null) {
            response.close();
        }
    }

}
 
Example 13
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@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 14
Source File: RemoteUserFederationProvider.java    From keycloak-user-migration-provider with Apache License 2.0 5 votes vote down vote up
private static FederatedUserService buildClient(String uri) {

        ResteasyClient client = new ResteasyClientBuilder().disableTrustManager().build();
        ResteasyWebTarget target =  client.target(uri);

        return target
                .proxyBuilder(FederatedUserService.class)
                .classloader(FederatedUserService.class.getClassLoader())
                .build();
    }
 
Example 15
Source File: RestEasyTestClient.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) {

		ResteasyClient client = new ResteasyClientBuilder().build();
		
		//GET example
		ResteasyWebTarget getDummy = client.target("http://localhost:8080/RestEasy-Example/employee/99/getDummy");
		
		Response getDummyResponse = getDummy.request().get();
		
		String value = getDummyResponse.readEntity(String.class);
        System.out.println(value);
        getDummyResponse.close();  
        
        //POST example
		ResteasyWebTarget add = client.target("http://localhost:8080/RestEasy-Example/employee/add");
		Employee emp = new Employee();
		emp.setId(50);emp.setName("Rick");emp.setSalary(1000);
		Response addResponse = add.request().post(Entity.entity(emp, MediaType.APPLICATION_XML));
		System.out.println(addResponse.readEntity(GenericResponse.class));
		System.out.println("HTTP Response Code:"+addResponse.getStatus());
		addResponse.close();
		
		addResponse = add.request().post(Entity.entity(emp, MediaType.APPLICATION_XML));
		System.out.println(addResponse.readEntity(GenericResponse.class));
		System.out.println("HTTP Response Code:"+addResponse.getStatus());
		addResponse.close();
		
		//DELETE example
		ResteasyWebTarget delete = client.target("http://localhost:8080/RestEasy-Example/employee/50/delete");
		Response deleteResponse = delete.request().delete();
		System.out.println(deleteResponse.readEntity(GenericResponse.class));
		System.out.println("HTTP Response Code:"+deleteResponse.getStatus());
		deleteResponse.close();
		
		deleteResponse = delete.request().delete();
		System.out.println(deleteResponse.readEntity(GenericResponse.class));
		System.out.println("HTTP Response Code:"+deleteResponse.getStatus());
		deleteResponse.close();
	}
 
Example 16
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example 17
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example 18
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example 19
Source File: ExportClientImpl.java    From support-rulesengine with Apache License 2.0 4 votes vote down vote up
private ExportClient getClient() {
  ResteasyClient client = new ResteasyClientBuilder().build();
  ResteasyWebTarget target = client.target(url);
  return target.proxy(ExportClient.class);
}
 
Example 20
Source File: AbstractStoresTest.java    From alfresco-simple-content-stores with Apache License 2.0 3 votes vote down vote up
/**
 * Initialised a simple Java facade for calls to a particular Alfresco Public ReST API interface.
 *
 * @param client
 *            the client to use for making ReST API calls
 * @param baseUrl
 *            the base URL of the Alfresco instance
 * @param api
 *            the API interface to facade
 * @param ticket
 *            the authentication ticket to use for calls to the API
 * @return the Java facade of the API
 */
protected static <T> T createAPI(final ResteasyClient client, final String baseUrl, final Class<T> api, final String ticket)
{
    final ResteasyWebTarget targetServer = client.target(UriBuilder.fromPath(baseUrl));

    final ClientRequestFilter rqAuthFilter = (requestContext) -> {
        final String base64Token = Base64.encodeBase64String(ticket.getBytes(StandardCharsets.UTF_8));
        requestContext.getHeaders().add("Authorization", "Basic " + base64Token);
    };
    targetServer.register(rqAuthFilter);

    return targetServer.proxy(api);
}