Skip to content

Instantly share code, notes, and snippets.

@pavolloffay
Created December 10, 2015 11:58
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 pavolloffay/79c454068650d80c055c to your computer and use it in GitHub Desktop.
Save pavolloffay/79c454068650d80c055c to your computer and use it in GitHub Desktop.
Bus context classloader
public static <T extends BasicMessage> BasicMessageWithExtraData<T> fromJSON(InputStream in, Class<T> clazz) {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(AbstractMessage.class.getClassLoader());
final T obj;
final byte[] remainder;
try (JsonParser parser = new JsonFactory().configure(Feature.AUTO_CLOSE_SOURCE, false).createParser(in)) {
Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod(clazz);
final ObjectMapper mapper = (ObjectMapper) buildObjectMapperForDeserializationMethod.invoke(null);
if (FailOnUnknownProperties.class.isAssignableFrom(clazz)) {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
}
obj = mapper.readValue(parser, clazz);
final ByteArrayOutputStream remainderStream = new ByteArrayOutputStream();
final int released = parser.releaseBuffered(remainderStream);
remainder = (released > 0) ? remainderStream.toByteArray() : new byte[0];
} catch (Exception e) {
throw new IllegalArgumentException("Stream cannot be converted to JSON object of type [" + clazz + "]",
e);
}
return new BasicMessageWithExtraData<T>(obj, new BinaryData(remainder, in));
} finally {
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment