Progamatically setting JSON View

350 views
Skip to first unread message

Vaibhav Dhawan

unread,
Mar 17, 2016, 9:10:11 AM3/17/16
to dropwizard-user
Hello,

Looking for a way to decide a json view on runtime based on certain conditions with dw 0.9.2. Example

if role is user, return userview.class
if role is admin, return adminview.class

I could see that MappingJacksonValue class provides a similar feature in spring boot and mvc. What would be the corresponding thing for dropwizard?
I have tried role based annotations on the entities/dto's but those doesnt seem to work with dropwizard(not sure how to set security filtering feature with dw).

I am happy with views implementation, just if i could programmatically decide the view to be returned in my resource.

frankgrimes97

unread,
Mar 17, 2016, 11:01:36 AM3/17/16
to dropwizard-user

bladecatcher

unread,
Mar 17, 2016, 11:12:31 AM3/17/16
to dropwizard-user
You should be able to retrieve the User Principal and though it , the Role that is assigned to the user. Will that work?

@RolesAllowed({"ADMIN","USER"})
@GET
public FreemarkerUserView getSecretPlan(@Context SecurityContext context) {
        User userPrincipal = (User) context.getUserPrincipal(); 
String role = userPrincipal.getRole();
if (role.equals("ADMIN")) {
return new AdminView();
} else if (role.equals("USER")) {
return new UserView();
}
throw new WebApplicationException();
}

Vaibhav Dhawan

unread,
Mar 18, 2016, 12:13:50 AM3/18/16
to dropwizard-user
Thanks frank. I will try this out.

bladecatcher, 

Yes, getting the role from principal is not an issue. However in my case, i have common entities that i am returning to the consumer and i am just using JsonViews to decide what should be returned to whom. Looks like in your case you care creating two different objects and returning them basis on role

Thanks

Tatu Saloranta

unread,
Mar 18, 2016, 12:18:05 AM3/18/16
to dropwiz...@googlegroups.com
Frank's suggestion makes sense, as ObjectReader/WriterModifier was specifically intended to allow dynamic configuration of JSON Views.
It is not as simple to use as it ideally would be, but integrating configurability plug-in as part of request/response handling lifecycle is bit challenging with JAX-RS. On plus side this can be used to configure many different aspects aside from Views.

-+ Tatu +-


--
You received this message because you are subscribed to the Google Groups "dropwizard-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to dropwizard-us...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages