Skip to content

Instantly share code, notes, and snippets.

@lucascs
Created July 13, 2013 17:11
Show Gist options
  • Save lucascs/5991378 to your computer and use it in GitHub Desktop.
Save lucascs/5991378 to your computer and use it in GitHub Desktop.
Lazy JSON Serialization
@Component
public class LazyJSONSerialization extends XStreamJSONSerialization {
private SerializerHolder holder;
public LazyJSONSerialization(SerializerHolder holder, HttpServletResponse response, TypeNameExtractor extractor, ProxyInitializer initializer, XStreamBuilder builder) {
super(response, extractor, initializer, builder);
this.holder = holder;
}
@Override
protected SerializerBuilder getSerializer() {
try {
return new XStreamSerializer(getXStream(), holder.createWriter(), extractor, initializer);
} catch (IOException e) {
throw new ResultException("Unable to serialize data", e);
}
}
}
@Intercepts(before=HibernateTransactionInterceptor.class)
public class LazySerializerInterceptor implements Interceptor {
public LazySerializerInterceptor(SerializerHolder holder, HttpServletResponse response) {
this.holder = holder;
this.response = response;
}
public boolean accepts(ResourceMethod method) { return true; }
public void intercept(InterceptorStack stack, ResourceMethod method, Object instance) {
stack.next(method, instance);
if (holder.getWriter() != null) {
response.getWriter().print(holder.getWriter());
}
}
}
@Component
public class SerializerHolder {
private StringWriter writer;
public Writer createWriter() {
this.writer = new StringWriter();
return this.writer;
}
public Writer getWriter() {
return this.writer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment