Search in sources :

Example 21 with ResteasyClient

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

the class RestProtocol method doRefer.

@Override
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    // TODO more configs to add
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager
    connectionManager.setMaxTotal(url.getParameter(CONNECTIONS_KEY, HTTPCLIENTCONNECTIONMANAGER_MAXTOTAL));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(CONNECTIONS_KEY, HTTPCLIENTCONNECTIONMANAGER_MAXPERROUTE));
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
        connectionMonitor.start();
    }
    connectionMonitor.addConnectionManager(connectionManager);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(url.getParameter(CONNECT_TIMEOUT_KEY, DEFAULT_CONNECT_TIMEOUT)).setSocketTimeout(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)).build();
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).setKeepAliveStrategy((response, 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_KEY)) {
                return Long.parseLong(value) * 1000;
            }
        }
        return HTTPCLIENT_KEEPALIVEDURATION;
    }).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 : COMMA_SPLIT_PATTERN.split(url.getParameter(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 : TIMEOUT_KEY(org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY) DEFAULT_CONNECT_TIMEOUT(org.apache.dubbo.remoting.Constants.DEFAULT_CONNECT_TIMEOUT) AbstractProxyProtocol(org.apache.dubbo.rpc.protocol.AbstractProxyProtocol) INTERFACE_KEY(org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) SERVER_KEY(org.apache.dubbo.remoting.Constants.SERVER_KEY) SocketConfig(org.apache.http.config.SocketConfig) RequestConfig(org.apache.http.client.config.RequestConfig) COMMA_SPLIT_PATTERN(org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN) BootstrapListener(org.apache.dubbo.remoting.http.servlet.BootstrapListener) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) ProtocolServer(org.apache.dubbo.rpc.ProtocolServer) StringUtils(org.apache.dubbo.common.utils.StringUtils) URL(org.apache.dubbo.common.URL) Map(java.util.Map) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) GetRestful(org.jboss.resteasy.util.GetRestful) LinkedList(java.util.LinkedList) HttpBinder(org.apache.dubbo.remoting.http.HttpBinder) HTTP(org.apache.http.protocol.HTTP) HeaderElementIterator(org.apache.http.HeaderElementIterator) DEFAULT_TIMEOUT(org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) EXTENSION_KEY(org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY) ApplicationModel(org.apache.dubbo.rpc.model.ApplicationModel) CONNECTIONS_KEY(org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY) RpcException(org.apache.dubbo.rpc.RpcException) HeaderElement(org.apache.http.HeaderElement) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CONNECT_TIMEOUT_KEY(org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ServletManager(org.apache.dubbo.remoting.http.servlet.ServletManager) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ServletContext(javax.servlet.ServletContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Collections(java.util.Collections) 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) HeaderElement(org.apache.http.HeaderElement) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) 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(org.apache.dubbo.rpc.RpcException) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 22 with ResteasyClient

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

the class RecaptchaUtil method verifyGoogleRecaptcha.

public boolean verifyGoogleRecaptcha(String gRecaptchaResponse, String secretKey) {
    boolean result = false;
    try {
        String uriTemplate = "https://www.google.com/recaptcha/api/siteverify";
        ResteasyClient resteasyClient;
        if (ProxyUtil.isProxyRequied()) {
            URLConnectionEngine engine = new URLConnectionEngine();
            resteasyClient = ((ResteasyClientBuilder) ResteasyClientBuilder.newBuilder()).httpEngine(engine).build();
        } else {
            resteasyClient = (ResteasyClient) ResteasyClientBuilder.newClient();
        }
        WebTarget webTarget = resteasyClient.target(uriTemplate);
        Builder clientRequest = webTarget.request();
        clientRequest.accept("application/json");
        Form requestForm = new Form();
        requestForm.param("secret", secretKey);
        requestForm.param("response", gRecaptchaResponse);
        Response response = clientRequest.buildPost(Entity.form(requestForm)).invoke();
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> map = mapper.readValue(new ByteArrayInputStream(response.readEntity(String.class).getBytes()), new TypeReference<Map<String, String>>() {
            });
            return Boolean.parseBoolean(map.get("success"));
        } finally {
            response.close();
            if (resteasyClient.httpEngine() != null) {
                resteasyClient.httpEngine().close();
            }
        }
    } catch (Exception e) {
        log.warn("Exception happened while verifying recaptcha, check your internet connection", e);
        return result;
    }
}
Also used : ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Form(javax.ws.rs.core.Form) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) Builder(javax.ws.rs.client.Invocation.Builder) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) WebTarget(javax.ws.rs.client.WebTarget) Map(java.util.Map) URLConnectionEngine(org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 23 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, Map<String, String> genericInfos) throws NotConnectedRestException {
    String uriTmpl = restEndpointURL + addSlashIfMissing(restEndpointURL) + "scheduler/submit";
    ResteasyClient client = buildResteasyClient(providerFactory);
    ResteasyWebTarget target = client.target(uriTmpl);
    // Generic infos
    if (genericInfos != null) {
        for (String key : genericInfos.keySet()) {
            target = target.queryParamNoTemplate(key, genericInfos.get(key));
        }
    }
    // Multipart form
    MultipartFormDataOutput formData = new MultipartFormDataOutput();
    // Add job to multipart
    formData.addFormData(FILE_KEY, job, mediaType);
    // Add variables to multipart
    if (variables != null && variables.size() > 0) {
        formData.addFormData(VARIABLES_KEY, variables, MediaType.APPLICATION_JSON_TYPE);
    }
    // Multipart form entity
    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 : ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) 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 24 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 = buildResteasyClient(providerFactory);
    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 : Locale(java.util.Locale) 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 25 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 = 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);
}
Also used : ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) 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)

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