Search in sources :

Example 6 with ResteasyClient

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

the class SchedulerRestClient method pushFile.

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 = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory).build();
    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);
}
Also used : Response(javax.ws.rs.core.Response) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) GenericEntity(javax.ws.rs.core.GenericEntity) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) NotConnectedRestException(org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException) MultipartFormDataOutput(org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput)

Example 7 with ResteasyClient

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

the class SchedulerRestClient method upload.

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 = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory).build();
    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();
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) Variant(javax.ws.rs.core.Variant) Locale(java.util.Locale) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) NotConnectedRestException(org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException)

Example 8 with ResteasyClient

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

the class SchedulerRestClient method submit.

private JobIdData submit(String sessionId, InputStream job, MediaType mediaType, Map<String, String> variables) throws Exception {
    String uriTmpl = restEndpointURL + addSlashIfMissing(restEndpointURL) + "scheduler/submit";
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory).build();
    ResteasyWebTarget target = client.target(uriTmpl);
    if (variables != null) {
        for (String key : variables.keySet()) {
            target = target.matrixParam(key, variables.get(key));
        }
    }
    MultipartFormDataOutput formData = new MultipartFormDataOutput();
    formData.addFormData("file", job, mediaType);
    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("Job submission failed status code: %d", response.getStatus()), response);
        }
    }
    return response.readEntity(JobIdData.class);
}
Also used : Response(javax.ws.rs.core.Response) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) GenericEntity(javax.ws.rs.core.GenericEntity) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) NotConnectedRestException(org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException) MultipartFormDataOutput(org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput)

Example 9 with ResteasyClient

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

the class JaxRsClient method runRequest.

/**
 * The purpose of this method is to run the external REST request.
 *
 * @param url       The url of the RESTful service
 * @param mediaType The mediatype of the RESTful service
 */
private String runRequest(String url, MediaType mediaType) {
    String result = null;
    System.out.println("===============================================");
    System.out.println("URL: " + url);
    System.out.println("MediaType: " + mediaType.toString());
    // Using the RESTEasy libraries, initiate a client request
    ResteasyClient client = new ResteasyClientBuilder().build();
    // Set url as target
    ResteasyWebTarget target = client.target(url);
    // Be sure to set the mediatype of the request
    target.request(mediaType);
    // Request has been made, now let's get the response
    Response response = target.request().get();
    result = response.readEntity(String.class);
    response.close();
    // HTTP 200 indicates the request is OK
    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed request with HTTP status: " + response.getStatus());
    }
    // We have a good response, let's now read it
    System.out.println("\n*** Response from Server ***\n");
    System.out.println(result);
    System.out.println("\n===============================================");
    return result;
}
Also used : Response(javax.ws.rs.core.Response) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 10 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)

Aggregations

ResteasyClient (org.jboss.resteasy.client.jaxrs.ResteasyClient)20 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)19 ResteasyWebTarget (org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)19 Response (javax.ws.rs.core.Response)11 NotConnectedRestException (org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException)9 NotConnectedException (org.ow2.proactive.scheduler.common.exception.NotConnectedException)6 IOException (java.io.IOException)4 InputStream (java.io.InputStream)3 Locale (java.util.Locale)3 File (java.io.File)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 GenericEntity (javax.ws.rs.core.GenericEntity)2 Variant (javax.ws.rs.core.Variant)2 FileUtils.copyInputStreamToFile (org.apache.commons.io.FileUtils.copyInputStreamToFile)2 MultipartFormDataOutput (org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput)2 ListFile (org.ow2.proactive_grid_cloud_portal.dataspace.dto.ListFile)2 RpcException (com.alibaba.dubbo.rpc.RpcException)1 FileNotFoundException (java.io.FileNotFoundException)1 OutputStream (java.io.OutputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1