Add annotation to programmatically added child resource via resource builder - jax-rs

I am programmatically adding child resources via the resource builder and need the resulting resource method to have the PermitAll annotation present.
Is this possible using some jersey API?

So, with my request filter checking for PermitAll annotation on the resource method, I relaized I can annotate the Inflector.apply() method directly to make the request filter work without modifying it.
resourceBuilder.handledBy(new Inflector<ContainerRequestContext, String>() {
#Override
**#PermitAll**
public String apply(ContainerRequestContext data) {
// ...
}
}

Related

How to implement Custom Deserializer

I have written a custom serializer and attached it to my RestClient. I am trying to also implement a custom deserializer as well. I noticed in my code that the serializer gets called when i added it to my client like so :RestClient Client = new RestClient(options).UseSerializer<CustomJsonSerializer>();
However, I am not sure what code to add to point to my custom deserializer and where to add it.
I am trying to call a method that essentially hijack's the response content, changes the string, and then sends the modified string back as the new response content to then be deserialized.
Where would i add the code to call my custom deserializer? What would the code snippet look like? And is it possible to even alter the response.content before the deserialization happens? And if so, how do i implement that?
The UseSerializer<T> expects T to be IRestSerializer, which has properties for ISerializer and IDeserializer. The Deserializer property needs to return your custom deserializer.
public interface IRestSerializer {
ISerializer Serializer { get; }
IDeserializer Deserializer { get; }
...

MIcronaut-Jaxrs #RequestScope create only one object even with multiple requests

I am trying to inject a io.micronaut.runtime.http.scope.RequestScope object into my jaxrs resource. Here I am priting object to see if it creates different objects for each request. But the object created Only once, even when I sent multiple requests.
Is this a known issue ? Any other way to work around this if that's the case.
#RequestScope
public class RequestScopeObjectX {
public RequestScopeObjectX() {
System.out.println("-------------------------"+this);
}
}
And in. my jaxrs resource class I am doing injecting it
#Inject
RequestScopeObjectX objectX;

Injecting IOptions<> into ApiKeyAuthorizeAttribute

I am using options pattern that stores different configurations, including API keys for different environments. So far I have been using it fine and injecting my values into classes as needed.
However, I faced a little challenge while trying to setup authorization in the controller and run validation against my ApiKey that is unique per environment, because I was not able to inject IOptions into ApiKeyAuthorizeAttribute class to perform validation.
Here is how my controller looks like now:
[ApiKeyAuthorize]
public class NotificationSettingsController : Controller
{
//some endpoints here
}
ApiKeyAuthorize Class:
public class ApiKeyAuthorizeAttribute : Attribute, IAuthorizationFilter
{
//////This...
private readonly IOptions<MyConfig> _config;
public ApiKeyAuthorizeAttribute(IOptions<MyConfig> config)
{
_config = config;
}
/////////...is what I am trying to accomplish
public void OnAuthorization(AuthorizationFilterContext context)
{
var request = context.HttpContext.Request;
var foundApiKeys = request.Headers.TryGetValue("ReplaceWithOptionsApiKeyName", out var requestApiKeys);
if (!foundApiKeys || requestApiKeys[0] != "ReplaceWithOptionsApiKeyValue")
{
context.Result = new UnauthorizedResult();
}
}
}
My problem is that injecting here isn't possible, but I need to get a value from IOptions<> to run ApiKey validation.
Attributes are constructed in-place, so it's not possible to inject dependencies into them. However, ASP.NET Core provides a workaround. Instead of applying the attribute directly, you can use the ServiceFilter attribute instead and pass it the type of the filter you want to apply:
[ServiceFilter(typeof(ApiAuthorizeAttribute))]
This will dynamically apply the filter to the controller/action while instantiating it with any dependencies it requires at the same time. However, it does limit you in the other direction. For example, if you need to do something like:
[ApiAuthorizeAttribute(Roles = "Admin")]
It would not be possible to achieve this with the ServiceFilter attribute, because you cannot pass property values, like Roles here, along with the type.

Spring data REST content negotiation

I have an annotated RepositoryRestResource for domain objects whose fields also contain binary data (images.) The Spring Rest machinery will create nice RESTful links for these fields, but I would also like to introduce a handler that returns the bare binary when browsers send an "image/*" accept header.
I could overlay a controller on the same paths, but it's brittle and I'd rather write a strategy class for this.
Possible? Any idea where to plug it in the Spring plumbing?
TIA,
Edoardo
Using the #RepositoryRestController annotation "properly", you should be able to restrict the controller override to the "image/*" only.
Say you have a simple domain object model (getters/setters and a some annotations omitted...)
public class Item {
#Id
private String id;
private String name;
}
Let's override the controller for image/* only
#RepositoryRestController
#ResponseBody
public class ItemRepositoryRestController {
#Autowired
private ItemRepository repository;
#RequestMapping(value = "/items/{id}", method = RequestMethod.GET,
produces = "image/*")
public Item getItem(#PathVariable(value = "id") String id)
{
Item item = repository.findOne(id);
/* do some magic with your item */
return item;
}
Obviously, no image/* data is returned here - you'll actually get a 400 error - but you do only get to this controller if asking if accepting image/*, while going through the automagic Spring Rest Controller when not asking for image/* if and only if you use #RequestMapping at the method level.
I haven't been to the point where I return raw binary data, you may have to use the HttpServletResponse directly as shown here. Or perhaps you already have an answer for this since in your comment you mention having added another resource path already (in which case I'm interested in how you return the raw data).

Jackson - how to find active JsonView at runtime

I have UI object that wraps JPA entity and in constructor of that UI object I do lazy loading of some properties. In that same constructor I need to know what JsonView is currently active so I dont lazy load some fields that are not needed if say its the List view.
Is there way to find out from constructor what is current active JsonView at runtime. Or is there any other way to achieve what I described above.
My current plan
create custom serializer that during serialization will call setJsonView(Class jsonView) of the object that it serializes. All my objects that serialized will have to support that method. Inside that metid I can do lazy loading based on now known json view. Something like this:
public class JsonViewSerializer extends JsonSerializer<BaseSerializableEntity> {
#Override
public void serialize(BaseSerializableEntity value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
value.setJsonView(provider.getSerializationView());
// need to pass serialization to base class...
}
}
Currently active view is accessible via context object (SerializerProvider or DeserializationContext), using method getActiveView().