Created
December 10, 2015 11:58
-
-
Save pavolloffay/79c454068650d80c055c to your computer and use it in GitHub Desktop.
Bus context classloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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