Close

JAX-RS - Providers Examples

JAX-RS JAVA EE 

    @GET
@Path("{path}")
public String create(@PathParam("path") String path,
@Context Providers providers) {
ContextResolver<MyContext> cr = providers
.getContextResolver(MyContext.class, MediaType.WILDCARD_TYPE);
MyContext<String> c = cr.getContext(String.class);
String r = c.get(path);
return "response: " + r;
}
Original Post




@Provider
@Produces("text/csv")
public class CsvWriter<T> implements MessageBodyWriter<List<T>> {
@Context
Providers providers;

@Override
public void writeTo(List<T> ts, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException {
String response = "";
for (T t : ts) {
try {
Class<?> c = t.getClass();
//using Java Bean API to access property values
BeanInfo beanInfo = Introspector.getBeanInfo(c);
String temp = "";
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
if (pd.getName().equals("class")) {//skip getClass()
continue;
}
Object o = pd.getReadMethod().invoke(t);
temp += "," + o;
}
if (temp.length() > 0) {
temp = temp.substring(1);
response += temp + "\n";
}
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
//using Providers instance
MessageBodyWriter<String> plainTextWriter = providers.getMessageBodyWriter(String.class,
genericType, annotations, MediaType.TEXT_PLAIN_TYPE);
plainTextWriter.writeTo(response, String.class, genericType, annotations, mediaType,
httpHeaders, entityStream);
}

@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}

@Override
public long getSize(List<T> ts, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
}
Original Post




See Also