Java Code Examples for org.jboss.resteasy.client.jaxrs.ResteasyWebTarget#proxy()

The following examples show how to use org.jboss.resteasy.client.jaxrs.ResteasyWebTarget#proxy() . 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: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@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 2
Source File: UmaClientFactory.java    From oxAuth with MIT License 6 votes vote down vote up
public UmaTokenService createTokenService(UmaMetadata metadata, ClientHttpEngine engine) {
    ResteasyWebTarget target = newClient(engine).target(new ResteasyUriBuilder().uri(metadata.getTokenEndpoint()));
    return target.proxy(UmaTokenService.class);
}
 
Example 3
Source File: UmaClientFactory.java    From oxAuth with MIT License 6 votes vote down vote up
public UmaPermissionService createPermissionService(UmaMetadata metadata, ClientHttpEngine engine) {
    ResteasyWebTarget target = newClient(engine).target(new ResteasyUriBuilder().uri(metadata.getPermissionEndpoint()));
    return target.proxy(UmaPermissionService.class);
}
 
Example 4
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@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 5
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 6
Source File: FidoU2fClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public RegistrationRequestService createRegistrationRequestService(U2fConfiguration metadataConfiguration) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(metadataConfiguration.getRegistrationEndpoint()));
    RegistrationRequestService proxy = target.proxy(RegistrationRequestService.class);

    return proxy;
}
 
Example 7
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
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 8
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 9
Source File: AbstractScimClient.java    From SCIM-Client with Apache License 2.0 5 votes vote down vote up
AbstractScimClient(String domain, Class<T> serviceClass) {
    /*
     Configures a proxy to interact with the service using the new JAX-RS 2.0 Client API, see section
     "Resteasy Proxy Framework" of RESTEasy JAX-RS user guide
     */
    if (System.getProperty("httpclient.multithreaded") == null) {
        client = new ResteasyClientBuilder().build();
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //Change defaults if supplied
        getIntegerProperty("httpclient.multithreaded.maxtotal").ifPresent(cm::setMaxTotal);
        getIntegerProperty("httpclient.multithreaded.maxperroute").ifPresent(cm::setDefaultMaxPerRoute);
        getIntegerProperty("httpclient.multithreaded.validateafterinactivity").ifPresent(cm::setValidateAfterInactivity);

        logger.debug("Using multithreaded support with maxTotalConnections={} and maxPerRoutConnections={}", cm.getMaxTotal(), cm.getDefaultMaxPerRoute());
        logger.warn("Ensure your oxTrust 'rptConnectionPoolUseConnectionPooling' property is set to true");

        CloseableHttpClient httpClient = HttpClients.custom()
	.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
        		.setConnectionManager(cm).build();
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);

        client = new ResteasyClientBuilder().httpEngine(engine).build();
    }
    ResteasyWebTarget target = client.target(domain);

    scimService = target.proxy(serviceClass);
    target.register(ListResponseProvider.class);
    target.register(AuthorizationInjectionFilter.class);
    target.register(ScimResourceProvider.class);

    ClientMap.update(client, null);
}
 
Example 10
Source File: GaClientTest.java    From phisix with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	Client client = new ResteasyClientBuilder()
			.httpEngine(new URLConnectionEngine())
			.register(StocksProvider.class)
			.build();
	ResteasyWebTarget target = (ResteasyWebTarget) client.target("http://www.google-analytics.com");
	gaClient = target.proxy(GaClient.class);
}
 
Example 11
Source File: PseClientTest.java    From phisix with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	Client client = new ResteasyClientBuilder()
			.httpEngine(new URLConnectionEngine())
			.register(StocksProvider.class)
			.build();
	ResteasyWebTarget target = (ResteasyWebTarget) client.target("https://www.pse.com.ph/stockMarket");
	pseClient = target.proxy(PseClient.class);
}
 
Example 12
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 13
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public TokenManager(Config config, Client client) {
    this.config = config;
    ResteasyWebTarget target = (ResteasyWebTarget) client.target(config.getServerUrl());
    if (!config.isPublicClient()) {
        target.register(new BasicAuthFilter(config.getClientId(), config.getClientSecret()));
    }
    this.tokenService = target.proxy(TokenService.class);
    this.accessTokenGrantType = config.getGrantType();

    if (CLIENT_CREDENTIALS.equals(accessTokenGrantType) && config.isPublicClient()) {
        throw new IllegalArgumentException("Can't use " + GRANT_TYPE + "=" + CLIENT_CREDENTIALS + " with public client");
    }
}
 
Example 14
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 15
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 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 dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
    }

    // TODO more configs to add
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager 20是当前池化clientconnectionmanager的默认最大值
    connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

    connectionMonitor.addConnectionManager(connectionManager);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT))
            .setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT))
            .build();

    SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(true)
            .setTcpNoDelay(true)
            .build();

    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                @Override
                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;
                }
            })
            .setDefaultRequestConfig(requestConfig)
            .setDefaultSocketConfig(socketConfig)
            .build();

    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: UmaClientFactory.java    From oxAuth with MIT License 4 votes vote down vote up
public UmaResourceService createResourceService(UmaMetadata metadata, ClientHttpEngine engine) {
    ResteasyWebTarget target = newClient(engine).target(new ResteasyUriBuilder().uri(metadata.getResourceRegistrationEndpoint()));
    return target.proxy(UmaResourceService.class);
}
 
Example 19
Source File: AbstractStoresTest.java    From alfresco-simple-content-stores with Apache License 2.0 3 votes vote down vote up
/**
 * Obtains an authentication ticket from an Alfresco system via the Public ReST API.
 *
 * @param client
 *            the client to use for making the ReST API call
 * @param baseUrl
 *            the base URL of the Alfresco instance
 * @param user
 *            the user for which to obtain the ticket
 * @param password
 *            the password of the user
 * @return the issued authentication ticket
 */
protected static String obtainTicket(final ResteasyClient client, final String baseUrl, final String user, final String password)
{
    final ResteasyWebTarget targetServer = client.target(UriBuilder.fromPath(baseUrl));
    final AuthenticationV1 authentication = targetServer.proxy(AuthenticationV1.class);

    final TicketRequest rq = new TicketRequest();
    rq.setUserId(user);
    rq.setPassword(password);
    final TicketEntity ticket = authentication.createTicket(rq);
    return ticket.getId();
}
 
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);
}