Search in sources :

Example 31 with ResteasyClient

use of org.jboss.resteasy.client.jaxrs.ResteasyClient in project openremote by openremote.

the class WebsocketAgentProtocol method doSubscription.

protected void doSubscription(Map<String, List<String>> headers, WebsocketSubscription subscription) {
    if (subscription instanceof WebsocketHTTPSubscription) {
        WebsocketHTTPSubscription httpSubscription = (WebsocketHTTPSubscription) subscription;
        if (TextUtil.isNullOrEmpty(httpSubscription.uri)) {
            LOG.warning("Websocket subscription missing or empty URI so skipping: " + subscription);
            return;
        }
        URI uri;
        try {
            uri = new URI(httpSubscription.uri);
        } catch (URISyntaxException e) {
            LOG.warning("Websocket subscription invalid URI so skipping: " + subscription);
            return;
        }
        if (httpSubscription.method == null) {
            httpSubscription.method = WebsocketHTTPSubscription.Method.valueOf(DEFAULT_HTTP_METHOD);
        }
        if (TextUtil.isNullOrEmpty(httpSubscription.contentType)) {
            httpSubscription.contentType = DEFAULT_CONTENT_TYPE;
        }
        if (httpSubscription.headers != null) {
            headers = headers != null ? new HashMap<>(headers) : new HashMap<>();
            Map<String, List<String>> finalHeaders = headers;
            httpSubscription.headers.forEach((header, values) -> {
                if (values == null || values.isEmpty()) {
                    finalHeaders.remove(header);
                } else {
                    List<String> vals = new ArrayList<>(finalHeaders.compute(header, (h, l) -> l != null ? l : Collections.emptyList()));
                    vals.addAll(values);
                    finalHeaders.put(header, vals);
                }
            });
        }
        WebTargetBuilder webTargetBuilder = new WebTargetBuilder(resteasyClient, uri);
        if (headers != null) {
            webTargetBuilder.setInjectHeaders(headers);
        }
        LOG.fine("Creating web target client for subscription '" + uri + "'");
        ResteasyWebTarget target = webTargetBuilder.build();
        Invocation invocation;
        if (httpSubscription.body == null) {
            invocation = target.request().build(httpSubscription.method.toString());
        } else {
            invocation = target.request().build(httpSubscription.method.toString(), Entity.entity(httpSubscription.body, httpSubscription.contentType));
        }
        Response response = invocation.invoke();
        response.close();
        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
            LOG.warning("WebsocketHttpSubscription returned an un-successful response code: " + response.getStatus());
        }
    } else {
        client.sendMessage(ValueUtil.convert(subscription.body, String.class));
    }
}
Also used : java.util(java.util) DEFAULT_CONTENT_TYPE(org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_CONTENT_TYPE) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) URISyntaxException(java.net.URISyntaxException) AttributeRef(org.openremote.model.attribute.AttributeRef) ValueUtil(org.openremote.model.util.ValueUtil) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) Supplier(java.util.function.Supplier) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) Attribute(org.openremote.model.attribute.Attribute) AbstractNettyIOClientProtocol(org.openremote.agent.protocol.io.AbstractNettyIOClientProtocol) AttributeEvent(org.openremote.model.attribute.AttributeEvent) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TextUtil(org.openremote.model.util.TextUtil) URI(java.net.URI) HttpHeaders(org.apache.http.HttpHeaders) OAuthGrant(org.openremote.model.auth.OAuthGrant) ValueType(org.openremote.model.value.ValueType) DEFAULT_HTTP_METHOD(org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_HTTP_METHOD) Pair(org.openremote.model.util.Pair) Invocation(javax.ws.rs.client.Invocation) Logger(java.util.logging.Logger) Entity(javax.ws.rs.client.Entity) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) BasicAuthHelper(org.jboss.resteasy.util.BasicAuthHelper) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Response(javax.ws.rs.core.Response) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ChannelHandler(io.netty.channel.ChannelHandler) WebTargetBuilder.createClient(org.openremote.container.web.WebTargetBuilder.createClient) UsernamePassword(org.openremote.model.auth.UsernamePassword) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) AttributeExecuteStatus(org.openremote.model.attribute.AttributeExecuteStatus) Invocation(javax.ws.rs.client.Invocation) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Response(javax.ws.rs.core.Response) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 32 with ResteasyClient

use of org.jboss.resteasy.client.jaxrs.ResteasyClient in project openremote by openremote.

the class WebsocketIOClient method doConnect.

@Override
protected Future<Boolean> doConnect() {
    if (oAuthGrant != null) {
        LOG.fine("Retrieving OAuth access token: " + getClientUri());
        ResteasyClient client = createClient(executorService, 1, CONNECTION_TIMEOUT_MILLISECONDS, null);
        try {
            OAuthFilter oAuthFilter = new OAuthFilter(client, oAuthGrant);
            authHeaderValue = oAuthFilter.getAuthHeader();
            if (TextUtil.isNullOrEmpty(authHeaderValue)) {
                throw new RuntimeException("Returned access token is null");
            }
            LOG.fine("Retrieved access token via OAuth: " + getClientUri());
        } catch (SocketException | ProcessingException e) {
            LOG.log(Level.SEVERE, "Failed to retrieve OAuth access token for '" + getClientUri() + "': Connection error");
            return CompletableFuture.completedFuture(false);
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Failed to retrieve OAuth access token: " + getClientUri());
            return CompletableFuture.completedFuture(false);
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }
    return super.doConnect();
}
Also used : SocketException(java.net.SocketException) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) OAuthFilter(org.openremote.container.web.OAuthFilter) SocketException(java.net.SocketException) ProcessingException(javax.ws.rs.ProcessingException) ProcessingException(javax.ws.rs.ProcessingException)

Example 33 with ResteasyClient

use of org.jboss.resteasy.client.jaxrs.ResteasyClient in project java by wavefrontHQ.

the class APIContainer method createService.

/**
 * Create RESTeasy proxies for remote calls via HTTP.
 */
private <T> T createService(String serverEndpointUrl, Class<T> apiClass) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(clientHttpEngine).providerFactory(resteasyProviderFactory).build();
    ResteasyWebTarget target = client.target(serverEndpointUrl);
    return target.proxy(apiClass);
}
Also used : ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 34 with ResteasyClient

use of org.jboss.resteasy.client.jaxrs.ResteasyClient in project dubbo by alibaba.

the class RestProtocol method doRefer.

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
    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.TIMEOUT_KEY, Constants.DEFAULT_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() {

        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);
    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);
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) SocketConfig(org.apache.http.config.SocketConfig) ConnectionKeepAliveStrategy(org.apache.http.conn.ConnectionKeepAliveStrategy) HeaderElement(org.apache.http.HeaderElement) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) HeaderElementIterator(org.apache.http.HeaderElementIterator) RpcException(com.alibaba.dubbo.rpc.RpcException) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 35 with ResteasyClient

use of org.jboss.resteasy.client.jaxrs.ResteasyClient in project java by wavefrontHQ.

the class AbstractAgent method createAgentService.

/**
 * Create RESTeasy proxies for remote calls via HTTP.
 */
protected WavefrontAPI createAgentService() {
    ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
    factory.registerProvider(JsonNodeWriter.class);
    if (!factory.getClasses().contains(ResteasyJackson2Provider.class)) {
        factory.registerProvider(ResteasyJackson2Provider.class);
    }
    if (httpUserAgent == null) {
        httpUserAgent = "Wavefront-Proxy/" + props.getString("build.version");
    }
    ClientHttpEngine httpEngine;
    if (javaNetConnection) {
        httpEngine = new JavaNetConnectionEngine() {

            @Override
            protected HttpURLConnection createConnection(ClientInvocation request) throws IOException {
                HttpURLConnection connection = (HttpURLConnection) request.getUri().toURL().openConnection();
                connection.setRequestProperty("User-Agent", httpUserAgent);
                connection.setRequestMethod(request.getMethod());
                // 5s
                connection.setConnectTimeout(httpConnectTimeout);
                // 60s
                connection.setReadTimeout(httpRequestTimeout);
                if (connection instanceof HttpsURLConnection) {
                    HttpsURLConnection secureConnection = (HttpsURLConnection) connection;
                    secureConnection.setSSLSocketFactory(new SSLSocketFactoryImpl(HttpsURLConnection.getDefaultSSLSocketFactory(), httpRequestTimeout));
                }
                return connection;
            }
        };
    } else {
        HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().setUserAgent(httpUserAgent).setMaxConnTotal(httpMaxConnTotal).setMaxConnPerRoute(httpMaxConnPerRoute).setConnectionTimeToLive(1, TimeUnit.MINUTES).setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(httpRequestTimeout).build()).setSSLSocketFactory(new SSLConnectionSocketFactoryImpl(SSLConnectionSocketFactory.getSystemSocketFactory(), httpRequestTimeout)).setRetryHandler(new DefaultHttpRequestRetryHandler(httpAutoRetries, true)).setDefaultRequestConfig(RequestConfig.custom().setContentCompressionEnabled(true).setRedirectsEnabled(true).setConnectTimeout(httpConnectTimeout).setConnectionRequestTimeout(httpConnectTimeout).setSocketTimeout(httpRequestTimeout).build()).build();
        final ApacheHttpClient4Engine apacheHttpClient4Engine = new ApacheHttpClient4Engine(httpClient, true);
        // avoid using disk at all
        apacheHttpClient4Engine.setFileUploadInMemoryThresholdLimit(100);
        apacheHttpClient4Engine.setFileUploadMemoryUnit(ApacheHttpClient4Engine.MemoryUnit.MB);
        httpEngine = apacheHttpClient4Engine;
    }
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(factory).register(GZIPDecodingInterceptor.class).register(gzipCompression ? GZIPEncodingInterceptor.class : DisableGZIPEncodingInterceptor.class).register(AcceptEncodingGZIPFilter.class).build();
    ResteasyWebTarget target = client.target(server);
    return target.proxy(WavefrontAPI.class);
}
Also used : ResteasyJackson2Provider(org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) GZIPDecodingInterceptor(org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) ClientInvocation(org.jboss.resteasy.client.jaxrs.internal.ClientInvocation) IOException(java.io.IOException) AcceptEncodingGZIPFilter(org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter) ClientHttpEngine(org.jboss.resteasy.client.jaxrs.ClientHttpEngine) HttpURLConnection(java.net.HttpURLConnection) GZIPEncodingInterceptor(org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor) HttpClient(org.apache.http.client.HttpClient) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

ResteasyClient (org.jboss.resteasy.client.jaxrs.ResteasyClient)66 ResteasyWebTarget (org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)42 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)28 Response (javax.ws.rs.core.Response)17 Test (org.junit.Test)14 NotConnectedRestException (org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException)10 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)8 ApacheHttpClient4Engine (org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine)7 ServicesInterface (com.baeldung.client.ServicesInterface)6 NotConnectedException (org.ow2.proactive.scheduler.common.exception.NotConnectedException)6 ProcessingException (javax.ws.rs.ProcessingException)5 IOException (java.io.IOException)4 Map (java.util.Map)4 WebTarget (javax.ws.rs.client.WebTarget)4 RequestConfig (org.apache.http.client.config.RequestConfig)4 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)4 ClientHttpEngine (org.jboss.resteasy.client.jaxrs.ClientHttpEngine)4 Locale (java.util.Locale)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 ApacheHttpClient4Resource (org.jboss.additional.testsuite.jdkall.present.jaxrs.client.resource.ApacheHttpClient4Resource)3