Saturday, May 20, 2017

RestEasy Client Wrapper

A wrapper interface and implementation could be used to hide the RestEasy implementation details. It also provide a flexibility to switch to other providers. For example, there are chances that some applications are tied to older Java versions or Spring framework versions. You may have to use RestEasy 2 and RestEasy 3 for different applications.



       @Override
       public P get(final URI uri, final String id, final Map<String, String> parameterMap, final Map<String, String> headerMap) {
             final String finalUri = RestClientUtil.buildQueryPath(uri, id);

             final P result;
             try {
                    final ClientRequest request = RestClientUtil.createClientRequest(finalUri.toString(), this.proxyHost,
                                 this.proxyPort, this.trustAllCerts);
                    logger.debug("proxy is used. host:" + this.proxyHost + " port:" + this.proxyPort);
                    request.accept(MediaType.APPLICATION_JSON_TYPE);
                    populateParameters(request, parameterMap);
                    populateHeaders(request, headerMap);

                    final ClientResponse<P> response = request.get(pClass);
                    if (response.getStatus() > 300) {
                           throw new RuntimeException("Get failed : HTTP error code received: " + response.getStatus());
                    }
                    result = response.getEntity();
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }
             return result;      }

       @Override
       public P postInMultiPartForm(final URI uri, final String parameterName, final Q content, final Map<String, String> headerMap) {
             if (uri == null) {
                    throw new IllegalArgumentException("uri is null.");
             }
             if (parameterName == null) {
                    throw new IllegalArgumentException("parameterName is null.");
             }
             if (content == null) {
                    throw new IllegalArgumentException("content is null.");
             }

             final P result;
             try {
                    final ClientRequest request = RestClientUtil.createClientRequest(uri.toString(), this.proxyHost,
                                 this.proxyPort, this.trustAllCerts);
                    request.accept(MediaType.APPLICATION_JSON_TYPE);
                    final MultipartFormDataOutput multipartFormData = new MultipartFormDataOutput();
                    multipartFormData.addFormData(parameterName, content, MediaType.APPLICATION_JSON_TYPE);
                    request.body(MediaType.MULTIPART_FORM_DATA_TYPE, multipartFormData);

                    this.populateHeaders(request, headerMap);
                    final ClientResponse<P> response = request.post(pClass);

                    if (response.getStatus() > 301) {
                           throw new RuntimeException("Post failed : HTTP error code received: " + response.getStatus());
                    }
                    result = response.getEntity();
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }

             return result;
       }

       @Override
       public P post(final URI uri, final Q content, final Map<String, String> headerMap) {
             if (uri == null) {
                    throw new IllegalArgumentException("uri is null.");
             }
             if (content == null) {
                    throw new IllegalArgumentException("content is null.");
             }

             final P result;
             try {
                    final ClientRequest request = RestClientUtil.createClientRequest(uri.toString(), this.proxyHost,
                                 this.proxyPort, this.trustAllCerts);
                    request.accept(MediaType.APPLICATION_JSON_TYPE);
                    request.body(MediaType.APPLICATION_JSON_TYPE, content);
                    this.populateHeaders(request, headerMap);
                    final ClientResponse<P> response = request.post(this.pClass);

                    if (response.getStatus() > 300) {
                           throw new RuntimeException("Post failed : HTTP error code received: " + response.getStatus());
                    }
                    result = response.getEntity();
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }
             return result;
       }

       @Override
       public P put(final URI uri, final String id, Q content, final Map<String, String> headerMap) {
             if (uri == null) {
                    throw new IllegalArgumentException("uri is null.");
             }
             if (id == null) {
                    throw new IllegalArgumentException("id is null.");
             }
             if (content == null) {
                    throw new IllegalArgumentException("content is null.");
             }
             final String finalUri = RestClientUtil.buildQueryPath(uri, id);

             final P result;
             try {
                    final ClientRequest request = RestClientUtil.createClientRequest(finalUri.toString(), this.proxyHost,
                                 this.proxyPort, this.trustAllCerts);
                    request.accept(MediaType.APPLICATION_JSON_TYPE);
                    request.body(MediaType.APPLICATION_JSON_TYPE, content);
                    this.populateHeaders(request, headerMap);
                   
                    final ClientResponse<P> response = request.put(this.pClass);

                    if (response.getStatus() > 300) {
                           throw new RuntimeException("Post failed : HTTP error code received: " + response.getStatus());
                    }
                    result = response.getEntity();
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }
             return result;
       }

       @Override
       public P delete(final URI uri, final String id, final Map<String, String> headerMap) {
             final String finalUri = RestClientUtil.buildQueryPath(uri, id);

             final P result;
             try {
                    final ClientRequest request = new ClientRequest(finalUri.toString());
                    request.accept(MediaType.APPLICATION_JSON_TYPE);
                    this.populateHeaders(request, headerMap);

                    final ClientResponse<P> response = request.delete(pClass);
                    if (response.getStatus() > 300) {
                           throw new RuntimeException("Get failed : HTTP error code received: " + response.getStatus());
                    }
                    result = response.getEntity();
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }
             return result;
       }


Or a simplified type less version (only String as result, no mapping to POJO)


       @Override
       public String get(URI uri, String id, Map<String, String> parameterMap, final Map<String, String> headerMap) {
             final String finalUri = RestClientUtil.buildQueryPath(uri, id);
             logger.info("finalUri:" + finalUri);
             final String result;
             try {
                    final ClientRequest request = RestClientUtil.createClientRequest(finalUri.toString(), this.proxyHost,
                                 this.proxyPort, this.trustAllCerts);
                    request.accept(MediaType.APPLICATION_JSON_TYPE);

                    populateParameters(request, parameterMap);
                    populateHeaders(request, headerMap);

                    final ClientResponse<String> response = request.get(String.class);
                    if (response.getStatus() > 300) {
                           throw new RuntimeException("Get failed : HTTP error code received: " + response.getStatus());
                    }

                    result = response.getEntity();
                    logger.info("result:" + result);
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }
             return result;
       }

       @Override
       public String post(final URI uri, final String jsonAsString) {
             return this.post(uri, jsonAsString, null);
       }

       @Override
       public String postInMultiPartForm(final URI uri, final String parameterName, final String contentAsJsonString) {
             return this.postInMultiPartForm(uri, parameterName, contentAsJsonString, null);
       }

       @Override
       public String post(URI uri, String jsonAsString, Map<String, String> headerMap) {
             if (uri == null) {
                    throw new IllegalArgumentException("uri is null.");
             }
             if (jsonAsString == null) {
                    throw new IllegalArgumentException("jsonAsString is null.");
             }

             final String result;
             try {
                    final ClientRequest request = RestClientUtil.createClientRequest(uri.toString(), this.proxyHost,
                                 this.proxyPort, this.trustAllCerts);
                    request.accept(MediaType.APPLICATION_JSON_TYPE);
                    request.body(MediaType.APPLICATION_JSON_TYPE, jsonAsString);
                    this.populateHeaders(request, headerMap);
                    System.out.println("*****************headers: " + request.getHeaders());
                    final ClientResponse<String> response = request.post(String.class);

                    if (response.getStatus() > 300) {
                           throw new RuntimeException("Post failed : HTTP error code received: " + response.getStatus());
                    }
                    result = response.getEntity();
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }

             return result;
       }

       @Override
       public String postInMultiPartForm(URI uri, String parameterName, String contentAsJsonString,
                    Map<String, String> headerMap) {
             if (uri == null) {
                    throw new IllegalArgumentException("uri is null.");
             }
             if (parameterName == null) {
                    throw new IllegalArgumentException("parameterName is null.");
             }
             if (contentAsJsonString == null) {
                    throw new IllegalArgumentException("contentAsJsonString is null.");
             }

             final String result;
             try {
                    final ClientRequest request = RestClientUtil.createClientRequest(uri.toString(), this.proxyHost,
                                 this.proxyPort, this.trustAllCerts);
                    request.accept(MediaType.APPLICATION_JSON_TYPE);
                    final MultipartFormDataOutput multipartFormData = new MultipartFormDataOutput();
                    multipartFormData.addFormData(parameterName, contentAsJsonString, MediaType.APPLICATION_JSON_TYPE);
                    request.body(MediaType.MULTIPART_FORM_DATA_TYPE, multipartFormData);
                    this.populateHeaders(request, headerMap);
                    final ClientResponse<String> response = request.post(String.class);

                    if (response.getStatus() > 301) {
                           throw new RuntimeException("Post failed : HTTP error code received: " + response.getStatus());
                    }
                    result = response.getEntity();
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }

             return result;
       }

RestClient 2.x Customization of Proxy and Connection Timeout

If there is a need to configure proxy setting, or connection timeout setting for RestEasy client, here is the code sample.


public class RestClientUtil {
private static final Logger logger = LoggerFactory.getLogger(RestClientUtil.class);

public static String buildQueryPath(@NotNull final URI uri, final String id) {
logger.debug("uri: " + uri + ", id:" + id);
final StringBuilder finalUri = new StringBuilder(uri.toString());
if (id != null && !id.isEmpty()) {
finalUri.append("/").append(id).toString();
}

logger.debug("finalUri: " + finalUri.toString());
return finalUri.toString();
}

public static ClientRequest createClientRequest(@NotNull final String finalUri, final String proxyHost, final int proxyPort,
final boolean trustAllCerts) {
final ClientRequest request;

if (proxyHost != null) {
final DefaultHttpClient httpClient;
if (trustAllCerts == true) {
try {
httpClient = createAllTrustingClient();
} catch (GeneralSecurityException e) {
throw new IllegalStateException("failed in createAllTrustingClient", e);
}
} else {
httpClient = new DefaultHttpClient();
}

HttpParams params = setConnectionParams(httpClient);

final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
final ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
request = new ClientRequest(finalUri, executor);
} else {
final DefaultHttpClient httpClient;
if (trustAllCerts == true) {
try {
httpClient = createAllTrustingClient();
} catch (GeneralSecurityException e) {
throw new IllegalStateException("failed in createAllTrustingClient", e);
}
final ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
request = new ClientRequest(finalUri, executor);
} else {
request = new ClientRequest(finalUri);
}
}
return request;
}

protected static HttpParams setConnectionParams(final DefaultHttpClient httpClient) {
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
return params;
}

public static DefaultHttpClient createAllTrustingClient() throws GeneralSecurityException {
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

final TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};

final SSLSocketFactory factory = new SSLSocketFactory(trustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme("https", 443, factory));

final ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
mgr.setMaxTotal(1000);
mgr.setDefaultMaxPerRoute(1000);

final DefaultHttpClient client = new DefaultHttpClient(mgr, new DefaultHttpClient().getParams());
return client;
}
}