Skip to content

Instantly share code, notes, and snippets.

@chongma
Created September 11, 2018 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chongma/608152be50bfe99a294bf420137f3b71 to your computer and use it in GitHub Desktop.
Save chongma/608152be50bfe99a294bf420137f3b71 to your computer and use it in GitHub Desktop.
example CXF webclient wrapper
package uk.me.kissy.external.utility;
import java.net.URI;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.StatusType;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;
import uk.me.kissy.entities.notification.NotificationStaff;
import uk.me.kissy.external.services.MessageService;
public class WebClient1 {
private static final Logger log = Logger.getLogger(WebClient1.class.getName());
@Resource(name = "development")
private boolean development;
// private static WebClient1 instance = null;
private WebClient webClient;
private MessageService messageService;
private static WebClient1 getInstance(MessageService messageService, String baseAddress, String username,
String password) {
WebClient1 webClient1 = new WebClient1();
webClient1.initialise(baseAddress, username, password);
webClient1.webClientSslSocket();
if (messageService != null) {
webClient1.messageService = messageService;
}
return webClient1;
}
// private static WebClient1 getInstance(MessageService messageService, String
// baseAddress) {
// if (instance == null) {
// instance = new WebClient1();
// instance.initialise(baseAddress);
// }
// return instance;
// }
public static WebClient1 create(MessageService messageService, String baseAddress, String tokenString) {
WebClient1 webClient1 = getInstance(messageService, baseAddress, null, null);
webClient1.header(tokenString);
// log.fine(tokenString);
return webClient1;
}
public static WebClient1 create(MessageService messageService, String baseAddress) {
WebClient1 webClient1 = getInstance(messageService, baseAddress, null, null);
return webClient1;
}
public static WebClient1 create(MessageService messageService, String baseAddress, String username,
String password) {
WebClient1 webClient1 = getInstance(messageService, baseAddress, username, password);
return webClient1;
}
// TODO this should not be necessary in java 9
// http://cxf.547215.n5.nabble.com/Custom-SSLSocketFactory-td5741482.html
// http://stackoverflow.com/questions/30817934/extended-server-name-sni-extension-not-sent-with-jdk1-8-0-but-send-with-jdk1-7
private void webClientSslSocket() {
HTTPConduit httpConduit = WebClient.getConfig(webClient).getHttpConduit();
if (httpConduit.getTlsClientParameters() != null) {
httpConduit.getTlsClientParameters().setSSLSocketFactory(new SSLSocketFactoryFacade());
} else {
TLSClientParameters tlsCP = new TLSClientParameters();
tlsCP.setSSLSocketFactory(new SSLSocketFactoryFacade());
httpConduit.setTlsClientParameters(tlsCP);
}
}
private void initialise(String baseAddress, String username, String password) {
if (username == null) {
webClient = WebClient.create(baseAddress);
} else {
webClient = WebClient.create(baseAddress, username, password, null);
}
}
public void header(String tokenString) {
webClient.header("Authorization", "bearer " + tokenString);
}
public Response get() {
Response response = webClient.get();
return checkResponse(response);
}
public Response get(String debugData) {
Response response = webClient.get();
return checkResponse(response, debugData);
}
public <T> T get(Class<T> entityType) {
Response response = webClient.get();
return checkResponse(response, entityType, null);
}
public <T> T get(Class<T> entityType, String debugData) {
Response response = webClient.get();
return checkResponse(response, entityType, debugData);
}
public <T> Collection<? extends T> getCollection(Class<T> memberClass) {
log.log(Level.FINE, "WebClient URI: " + webClient.getCurrentURI().toString());
return webClient.getCollection(memberClass);
}
public Response post(Object body) {
Response response = webClient.post(body);
return checkResponse(response);
}
public Response post(Object body, String debugData) {
Response response = webClient.post(body);
return checkResponse(response, debugData);
}
public <T> T post(Object body, Class<T> entityType) {
Response response = webClient.post(body);
return checkResponse(response, entityType, null);
}
public <T> T post(Object body, Class<T> entityType, String debugData) {
Response response = webClient.post(body);
return checkResponse(response, entityType, debugData);
}
private Response checkResponse(Response response) {
return checkResponse(response, null);
}
private Response checkResponse(Response response, String debugData) {
checkStatus(response, debugData);
return response;
}
private <T> T checkResponse(Response response, Class<T> entityType, String debugData) {
StatusType statusType = response.getStatusInfo();
if (checkStatus(response, debugData)) {
if (statusType.getStatusCode() == Status.NO_CONTENT.getStatusCode()) {
// no content was returned
} else {
try {
T t = response.readEntity(entityType);
return t;
} catch (Exception e) {
// e.printStackTrace();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("WebClient URI: " + getCurrentURI().toString());
if (debugData != null) {
stringBuffer.append("Debug data: " + debugData + System.lineSeparator());
}
stringBuffer.append("Stack trace: " + ExceptionUtils.getStackTrace(e));
sendNotification("REST good response code, bad data", stringBuffer.toString());
}
}
}
return null;
}
private boolean checkStatus(Response response, String debugData) {
StatusType statusType = response.getStatusInfo();
if (statusType.getStatusCode() != Status.OK.getStatusCode()
&& statusType.getStatusCode() != Status.CREATED.getStatusCode()
&& statusType.getStatusCode() != Status.ACCEPTED.getStatusCode()
&& statusType.getStatusCode() != Status.NO_CONTENT.getStatusCode()) {
log.log(Level.INFO, "Status: " + statusType.getStatusCode() + " - " + statusType.getReasonPhrase());
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("WebClient URI: " + getCurrentURI().toString());
stringBuffer.append("Response status: " + response.getStatus() + System.lineSeparator());
stringBuffer.append("Response text: " + response.readEntity(String.class) + System.lineSeparator());
if (debugData != null) {
stringBuffer.append("Debug data: " + debugData);
}
stringBuffer.append("Stack trace: " + ExceptionUtils.getStackTrace(new Throwable()));
// webClient.
sendNotification("REST bad response code", stringBuffer.toString());
return false;
}
return true;
}
private void sendNotification(String subject, String body) {
if (!development && messageService != null) {
// send error message
NotificationStaff notificationStaff = messageService.initialiseNotificationStaffSystem(subject, body);
messageService.notificationStaffSystem(notificationStaff);
} else {
log.log(Level.SEVERE, body);
}
}
public WebClient1 path(String path) {
webClient.path(path);
return this;
}
public WebClient1 query(String name, Object... values) {
webClient.query(name, values);
return this;
}
public WebClient1 accept(String... types) {
webClient.accept(types);
return this;
}
public WebClient1 type(String type) {
webClient.type(type);
return this;
}
public Response delete() {
Response response = webClient.delete();
return checkResponse(response);
}
public Response put(Object body) {
Response response = webClient.put(body);
return checkResponse(response);
}
public <T> Response postCollection(Object collection, Class<T> memberClass) {
Response response = webClient.postCollection(collection, memberClass);
return checkResponse(response);
}
public Response invoke(String httpMethod, Object body) {
Response response = webClient.invoke(httpMethod, body);
return checkResponse(response);
}
public URI getCurrentURI() {
return webClient.getCurrentURI();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment