Search in sources :

Example 16 with ResteasyClientBuilder

use of org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder in project scheduling by ow2-proactive.

the class SchedulerStateRest method submitPlannings.

@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_KEY, 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();
        }
    }
}
Also used : ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) PAActiveObject(org.objectweb.proactive.api.PAActiveObject) FileObject(org.apache.commons.vfs2.FileObject) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory)

Example 17 with ResteasyClientBuilder

use of org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder in project scheduling by ow2-proactive.

the class DataSpaceClient method list.

@Override
public ListFile list(IRemoteSource source) throws NotConnectedException, PermissionException {
    StringBuffer uriTmpl = (new StringBuffer()).append(restDataspaceUrl).append(source.getDataspace().value());
    ResteasyClient client = new ResteasyClientBuilder().providerFactory(providerFactory).httpEngine(httpEngine).build();
    ResteasyWebTarget target = client.target(uriTmpl.toString()).path(source.getPath()).queryParam("comp", "list");
    List<String> includes = source.getIncludes();
    if (includes != null && !includes.isEmpty()) {
        target = target.queryParam("includes", includes.toArray(new Object[includes.size()]));
    }
    List<String> excludes = source.getExcludes();
    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).get();
        if (response.getStatus() != HttpURLConnection.HTTP_OK) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new NotConnectedException("User not authenticated or session timeout.");
            } else {
                throw new RuntimeException(String.format("Cannot list the specified location: %s", source.getPath()));
            }
        }
        return response.readEntity(ListFile.class);
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
Also used : ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) NotConnectedException(org.ow2.proactive.scheduler.common.exception.NotConnectedException) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 18 with ResteasyClientBuilder

use of org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder in project scheduling by ow2-proactive.

the class DataSpaceClient method upload.

@Override
public boolean upload(final ILocalSource source, final IRemoteDestination destination) throws NotConnectedException, PermissionException {
    if (log.isDebugEnabled()) {
        log.debug("Uploading from " + source + " to " + destination);
    }
    StringBuffer uriTmpl = (new StringBuffer()).append(restDataspaceUrl).append(destination.getDataspace().value());
    ResteasyClient client = new ResteasyClientBuilder().providerFactory(providerFactory).httpEngine(httpEngine).build();
    ResteasyWebTarget target = client.target(uriTmpl.toString()).path(destination.getPath());
    Response response = null;
    try {
        response = target.request().header("sessionid", sessionId).put(Entity.entity(new StreamingOutput() {

            @Override
            public void write(OutputStream outputStream) throws IOException, WebApplicationException {
                source.writeTo(outputStream);
            }
        }, new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (Locale) null, source.getEncoding())));
        if (response.getStatus() != HttpURLConnection.HTTP_CREATED) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new NotConnectedException("User not authenticated or session timeout.");
            } else {
                throw new RuntimeException("File upload failed. Status code:" + response.getStatus());
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Upload from " + source + " to " + destination + " performed with success");
        }
        return true;
    } catch (IOException ioe) {
        throw Throwables.propagate(ioe);
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
Also used : Locale(java.util.Locale) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) WebApplicationException(javax.ws.rs.WebApplicationException) NotConnectedException(org.ow2.proactive.scheduler.common.exception.NotConnectedException) OutputStream(java.io.OutputStream) IOException(java.io.IOException) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 19 with ResteasyClientBuilder

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

the class WebTargetBuilder method createClient.

public static ResteasyClient createClient(ExecutorService executorService, int connectionPoolSize, long overrideSocketTimeout, UnaryOperator<ResteasyClientBuilder> builderConfigurator) {
    // Create all of this config code in order to deal with expires cookies in responses
    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setConnectionRequestTimeout(Long.valueOf(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS).intValue()).setConnectTimeout(Long.valueOf(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS).intValue()).setSocketTimeout(Long.valueOf(overrideSocketTimeout).intValue()).build();
    HttpClient apacheClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine(apacheClient);
    ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder().httpEngine(engine).connectionPoolSize(connectionPoolSize).connectionCheckoutTimeout(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS).readTimeout(overrideSocketTimeout, TimeUnit.MILLISECONDS).connectTimeout(CONNECTION_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS).register(new JacksonConfig());
    if (executorService != null) {
        clientBuilder.executorService(executorService);
    }
    if (builderConfigurator != null) {
        clientBuilder = builderConfigurator.apply(clientBuilder);
    }
    return clientBuilder.build();
}
Also used : JacksonConfig(org.openremote.container.json.JacksonConfig) RequestConfig(org.apache.http.client.config.RequestConfig) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) HttpClient(org.apache.http.client.HttpClient) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine)

Example 20 with ResteasyClientBuilder

use of org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder 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)

Aggregations

ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)40 ResteasyClient (org.jboss.resteasy.client.jaxrs.ResteasyClient)22 ResteasyWebTarget (org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)18 Response (javax.ws.rs.core.Response)11 Test (org.junit.Test)9 ApacheHttpClient4Engine (org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine)8 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)7 ServicesInterface (com.baeldung.client.ServicesInterface)6 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)6 ResteasyProviderFactory (org.jboss.resteasy.spi.ResteasyProviderFactory)6 NotConnectedException (org.ow2.proactive.scheduler.common.exception.NotConnectedException)6 RequestConfig (org.apache.http.client.config.RequestConfig)5 ApacheHttpClient43Engine (org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine)5 IOException (java.io.IOException)4 Client (javax.ws.rs.client.Client)4 HttpClient (org.apache.http.client.HttpClient)4 ProcessingException (javax.ws.rs.ProcessingException)3 ClientHttpEngine (org.jboss.resteasy.client.jaxrs.ClientHttpEngine)3 Movie (com.baeldung.model.Movie)2 JacksonJaxbJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider)2