Injecting custom objects into the Request Bean - jersey

In my JAX-RS, Jersey application, I need to include a custom check before any API is invoked before the all the request to be processed. The best approach is to use a JAX-RS filter. To do this custom check, I need to do a database hit, check a few things etc. The results from the database hit, would be useful to code path so I would like to pass them on. Rather than have the rest of code path have to make another B hit. I see I can inject lots of thins using the #Context annotation. Is there anyway I can extend this to get JAX-RS / Jersey to inject some custom objects?
Thanks

Related

Spring: `RequestScope` vs `RequestContextHolder`

I am writing a Spring Boot service and wanted to include some form of RequestContext available to the controllers that might store things like the authenticated user and a request id. However, I see multiple approaches:
Use an #RequestScope bean
Use ServletRequest.setAttribute
Use Spring RequestContextHolder
What are the tradeoffs between these approaches?
Broadly speaking, RequestScope is the Spring magic way. It internally uses a RequestContextHolder which in turn depends on ServletRequest.setAttribute.
Said differently, the Spring way, is IMHO RequestScope. RequestContextHolder makes sense if you prefer limit the magic of Spring annotations.
Finaly, ServletRequest.setAttribute is still lower level, and should mainly be used if you want the code to be compatible with a non Spring application.
Moreover, for the first two ways, Spring uses a thread scoped object to store a reference to the request context, which allows the programmer to access the beans even in methods that do not explicitely receive the Request object.

Single instance of an object per transaction

I have a use case, that theoretically seems to me as it would be a solved problem. But i'm not able to find a sure fired implementation.
I've created a RESTful API, using Apache CXF, Spring and Hibernate
This application encompasses a standard Service-Proxy-DAO layered structure
I need to instantiate a custom logger object at my service (or pre-service) layer and initialize a bunch of parameters which will remain constant, for the most part through every call that goes through my application layers and back.
How can i, for every individual service call, initialize this logger object once, and use it across all my layers without having to instantiate it everytime. Either i inject the initialized object in every class i need or something on those lines.
I don't want to use static blocks, or pass the object in method signatures.
Is there anything that i can use as a part of the Spring, CXF or other java framework that allows me to implement this use-case.
EDIT: I would define a transaction as a single call to a web service endpoint, from invocation to response.
ThreadLocal would be an ideal candidate to solve your problem.
UPDATE:
Creating a thread local that is available in all the places where this "shared" reference is required will give all these contexts access to this resource without having to pass the reference around.
see http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/ - looks like a good explanation of how to use thread local and also deals with your problem space.

ClassBridge called by MassIndexer and access to spring service

I wonder whether it is possible to use any spring services from within hibernate search ClassBridge.
Abstract:
My entity does not have all information i'd like to put into indexed document. I can not get it by #IndexedEmbeded too. This data comes from external data source, and I have service to provide this. This is only needed when reindexing. When indexing single object save service provide this information in transient entity field.
For reindex I use MassIndexer.
My application is working in Spring MVC environment. I use annotation driven configuration. So to access my service I need only use #Autowired annotation and service is ready to be used.
Solution?
When using Hibernate Search life is not so easy (or I have no idea how it could be).
To get additional information I decided to use ClassBridge. I also implement simple MassIndexer procedure called from within my spring service.
In my ClassBridge spring does not autowire service. When I try do quick workaround and use static field in ClassBridge and pass service reference from MassIndexer caller the other problem occurred. Service reports exception "no session" (sessionFactory.getCurrentSession() throws exception)... I have no idea where to go further.
What is recommended way to access Spring service from within ClassBridge code?
How can I get active hibernate Session (or SessionFactory) from within ClassBridge?
Thanx for you time & hope your help.
The recommended way is through compile time weaving and #Configurable
A comment on this page (http://guylabs.ch/2014/02/22/autowiring-pring-beans-in-hibernate-jpa-entity-listeners/) provides a much simpler way of handling this that might be useful. You can have Spring autowire an object for you, more explicitly by calling:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
Doc: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/context/support/SpringBeanAutowiringSupport.html

Per-Request DependencyResolver in Web API

In MVC, a ModelValidatorProvider is instantiated and called to validate a model on each request. This means that in a DI environment, it can take dependencies on objects scoped within a single request, such as a Unit of Work or Database context. In Web API, this appears to have been significantly changed. Instead of being instantiated per-request, the ModelValidatorProvider appears to be long-lived and instantiated within the application startup. The WebAPI then caches the results from the ModelValidatorProvider per-type, meaning that the ModelValidator cannot take any dependencies from DI.
I am trying to implement my ModelValidator to use a factory using a Service Locator (please, no automatic 'anti-pattern' comments!). This would allow me to construct an internal validator object within each request, which would be able to take dependencies from the container. However, I cannot get hold of a Dependency Resolver or container scoped to the current request from within this ModelValidator which is essentially scoped as a Singleton. I've tried to use GlobalConfiguration.Configuration.DependencyResolver, but this only returns globally-scoped services (from the root scope, also mentioned here)
I'm working in Autofac, so an autofac-specific solution would be suitable (e.g. MVC has AutofacDependencyResolver.Current, which internally uses DependencyResolver.GetService). There is no equivalent available in the WebAPI integration, presumably because of the reason mentioned above where the global DependencyResolver only returns globally-scoped services.
The reason I'm trying to do this (as well as for my own use) is to implement the Web API integration for FluentValidation, which currently does not exist. There have been two attempts so far, but neither of these handle the Dependency Injection issue and instead result in a single static ModelValidator.
Things I've tried so far:
Using GlobalConfiguration.Configuration.DependencyResolver (returns objects from the root scope)
Taking a dependency on Func<IComponentContext> (always returns the root context)
In an answer which has since been removed, it was suggested to remove IModelValidatorProvider service from the Web API config. This had to be done using reflection since the interface and the implementing classes are all defined as internal, but it did make the validators work better (because the ModelValidator was constructed per request). However, there is a significant performance hit to doing it this way due to the use of reflection to check for validators on the model and every property it has, so I don't want to take this option.
Filip W's answer suggests using HttpRequestMessage to get the Dependency Scope, but I've not found anything such as HttpRequestMessage.Current which would provide access to this object from within a long-lived object - if that could be achieved I believe everything would fall into place.
To get current dependency scope, you have to use (surprise, surprise :) GetDependencyScope() of the current HttpRequestMessage (more about which you can read up on MSDN) instead of GlobalConfiguration.
I blogged about Web API per-request dependency scope a while ago - that should be helpful.

A heavily customized Spring Web application and the dispatcher servlet

We have a web application that uses spring, struts and camel right now and there is a lot of customization we have done to allow us to know when beans are added to the context.
So, we have gotten to a point where we would like to remove struts from the application, because we are only using it to handle actions and we figure we could either use spring or camel to do the same thing. So I was able to get it to work with camel/velocity, but we didn't like how we really couldn't use the request object directly in the jsp (afaik, you have to put everything in the header of the Exchange and in the jsp you would do ${header.someReqVariableName}).
So we wanted to go the spring route, but since we load the context.xml directly, we have a provider that extends ContextSingletonBeanFactoryLocator and we pass the xml file name as a param, we haven't been able to figure out how to get the DispatcherServlet to work without giving it another configuration xml.
Is there a way to either:
Have camel use jsp for processing a jsp (and have all the usage of jsp tags)?
or
Have spring to see that a context has already been loaded and use that instead of having another new one?
or
Something better I have thought up?
You can use camel-jetty to expose HTTP endpoints, but I wouldn't use it for any complex web app development (JPS, etc). I'd use use Spring MVC (or similar) and use Camel for any complex routing/messaging requirements...
Here is another way, you can use the producer template to send the request to the camel context if you can get the reference of the camel context from the spring.

Resources