Skip to content

Instantly share code, notes, and snippets.

@dangnhdev
Last active January 30, 2016 14:49
Show Gist options
  • Save dangnhdev/c6b2853e4df089429063 to your computer and use it in GitHub Desktop.
Save dangnhdev/c6b2853e4df089429063 to your computer and use it in GitHub Desktop.
//A GET method in my stupid REST service for example.....
public Response sendMsg(String content, @QueryParam("msgType") String msgType) {
//Open class loader in try-with-resource
//Use null in constructor if you don't want to use parent class loader.
//In this case it's useful because I don't load any class from system classpath.
try (URLClassLoader clsLoader = URLClassLoader.newInstance(new URL[] {new URL("file:/lib/ACM_0.1.0.jar")}, null)){
Class<?> clazz = clsLoader.loadClass("com.hs.acm.client.message.in." + msgType);
Object msgObj = clazz.newInstance();
AcmClientReqMsg msg = (AcmClientReqMsg) msgObj;
msg.setAgentID("test agent ID " + clazz.getSimpleName());
msg.setTransID(new BigInteger(130, random).toString(32));
TextMessage jsonMsg = session.createTextMessage(gson.toJson(msg));
producer.send(dest, jsonMsg);
} catch (ClassNotFoundException ex) {
logger.error("Invalid message type", ex);
return Response.status(Response.Status.BAD_REQUEST).build();
} catch (InstantiationException | IllegalAccessException ex) {
logger.error("Cannot create message object: ", ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (IOException ex) {
logger.error("Cannot close class loader: ", ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(200).entity("Ok").build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment