Pass Default Application Context to Remote EJB Anonymously - java

I have a complicated scenario, for which i have no idea how to go about:
I have my ejbs running in a remote server.
And my web application running in a different server.
I have an ApplicationContext, that will differ based on domain, language, country etc.
I would like this application context to be passed to the remote EJB anonymously, in such a way that developers dont have to invoke all of their backend requests with the ApplicationContext as a parameter.
This is the scenarion, lets says i have a remote Stateless EJB:
#Stateless
public class MyStateless implements MyStatelessRemote{
//The application context that needs to be supplied form the front-end
#Inject //probably define a producer method to always supply a new one.
private ApplicationContext applicationContext;
public void doCheckSomething(final MySomethingData data){}
}
And on the frontend:
#SessionScoped
#Named
public class MyController implements Serializable{
#EJB
private MyStatelessRemote statelessRemote
//The current application/session context to be passed to the Stateless ejb on every invocation.
#Inject
private ApplicationContext executionContext;
public void doSomeOrderOrSomethingSimilar(){
//At this point, the current application context needs to be supplied to the remote EJB
//Which it may use to check on order validity based on configurations such as country
//language etc.
statelessRemote.doCheckSomething(mySomething);
}
}
With more than 20 EJBS and each having an average of 8 to 10 methods, and considering the likelihood that almost every ejb may need to know the executioncontext of the caller,
is it possible to parse the current execution context, through configuration or otherwise to the ejb during invocation of any method?
I am using Wildfly8 with remote ejb3.1, CDI1.1, JSF2.2
The application context may change when, for example the user changes his/her language
EDIT:
I am looking for something similar to Web Service inbound and outbound interceptors.

What you're describing is not possible using CDI/EJB, without passing in parameters to your remote EJB.

After few months working on jboss/wildfly server, i finally found a away to achieve this functionality:
Client-Side Code: (Based on jboss ejbclient)
package com.mycompany.view.service.wildfly.invocationcontext;
import com.mycompany.ejb.internal.MyCompanyAccount;
import com.mycompany.view.service.account.LoggedInAccount;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import org.jboss.ejb.client.AttachmentKey;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.ejb.client.EJBClientInterceptor;
import org.jboss.ejb.client.EJBClientInvocationContext;
import static com.mycompany.management.wildfly.invocationcontext.MyCompanyInvocationContextKey.MYCOMPANY_ACCOUNT_NUMBER;
/**
* Registers itself as a jboss client interceptor.
* #author marembo
*/
#Singleton
#Startup
public class MyCompanyInvocationContextInterceptor implements EJBClientInterceptor {
private static final Logger LOG = Logger.getLogger(MyCompanyInvocationContextInterceptor.class.getName());
private static final AttachmentKey<Long> MYCOMPANY_ACCOUNT_NUMBER_KEY = new AttachmentKey<>();
#Inject
#LoggedInAccount
private Instance<MyCompanyAccount> loggedInAccount;
#PostConstruct
void registerSelf() {
EJBClientContext.requireCurrent().registerInterceptor(0, this);
}
#Override
public void handleInvocation(final EJBClientInvocationContext ejbcic) throws Exception {
LOG.log(Level.INFO, "Intercepting invocation on: {0}", ejbcic.getInvokedMethod());
final EJBClientContext clientContext = ejbcic.getClientContext();
if (!loggedInAccount.isUnsatisfied()) {
final MyCompanyAccount mycompanyAccount = loggedInAccount.get();
if (mycompanyAccount != null) {
final Long accountNumber = mycompanyAccount.getAccountNumber();
clientContext.putAttachment(MYCOMPANY_ACCOUNT_NUMBER_KEY, accountNumber);
}
}
ejbcic.getContextData().put(MYCOMPANY_ACCOUNT_NUMBER, "348347878483");
ejbcic.sendRequest();
}
#Override
public Object handleInvocationResult(final EJBClientInvocationContext ejbcic) throws Exception {
return ejbcic.getResult();
}
}
On the server side, i register a global interceptor:
package com.mycompany.management.wildfly.extension;
import com.mycompany.management.facade.account.MyCompanyAccountFacade;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.EJBContext;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
/**
* Default interceptor does not require #Interceptor
* #author marembo
*/
public class MyCompanyInvocationContextReceiver {
private static final Logger LOG = Logger.getLogger(MyCompanyInvocationContextReceiver.class.getName());
#Resource
private EJBContext ejbContext;
#EJB
private MyCompanyInvocationContext mycompanyInvocationContext;
#EJB
private MyCompanyAccountFacade mycompanyAccountFacade;
#AroundInvoke
public Object setMyCompanyAccount(final InvocationContext invocationContext) throws Exception {
final Map<String, Object> contextData = ejbContext.getContextData();
LOG.log(Level.INFO, "EJBContext data: {0}", contextData);
LOG.log(Level.INFO, "InvocationContext data: {0}", invocationContext.getContextData());
return invocationContext.proceed();
}
}
and the ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns = "http://java.sun.com/xml/ns/javaee"
version = "3.1"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">
<interceptors>
<interceptor>
<interceptor-class>com.mycompany.management.wildfly.extension.MyCompanyInvocationContextReceiver</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>com.mycompany.management.wildfly.extension.MyCompanyInvocationContextReceiver</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar>
As indicated on the server side interceptor, you can get the client-sent-data either from the InvocationContext or from the EJBContext.

Related

WebSocket endpoint and CDI injection: No active contexts for scope RequestScoped

I want to inject a #RequestScoped CDI bean in my Java EE 7 WebSocket endpoint.
However I am getting error WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped.
What am I doing wrong and why it is not possible?
#Named
#RequestScoped
public class Storage {
}
Which I #Inject in the endpoint like this:
#ServerEndpoint("/serverpush")
public class ContratoEndpoint {
#Inject
private Storage storage;
}
And I am getting the following stack trace:
org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped
at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:689)
at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.getIfExists(ContextualInstanceStrategy.java:90)
at org.jboss.weld.bean.ContextualInstanceStrategy$CachingContextualInstanceStrategy.getIfExists(ContextualInstanceStrategy.java:165)
at org.jboss.weld.bean.ContextualInstance.getIfExists(ContextualInstance.java:63)
at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:83)
at org.jboss.weld.bean.proxy.ProxyMethodHandler.getInstance(ProxyMethodHandler.java:125)
As #John mentioned, RequestContext is not active in WebSocket methods. Instead of using Deltaspike (which is a good option), you can also write your own Interceptor to activate/deactivate weld RequestContext.
As you are using Wildfly, you can use weld as a provided dependency :
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>2.2.12.Final</version>
<scope>provided</scope>
</dependency>
Then you can define an InterceptorBinding #RequestContextOperation :
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
#InterceptorBinding
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.METHOD, ElementType.TYPE })
public #interface RequestContextOperation
{
}
And the corresponding RequestContextInterceptor where we activate/deactivate the RequestContext:
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.jboss.weld.context.RequestContext;
import org.jboss.weld.context.unbound.Unbound;
#Interceptor
#RequestContextOperation
public class RequestContextInterceptor {
/** The RequestContext */
#Inject
#Unbound
private RequestContext m_requestContext;
/**
*
* #param p_invocationContext
* #return
* #throws Exception
*/
#AroundInvoke
public Object activateRequestContext(final InvocationContext p_invocationContext) throws Exception {
try {
m_requestContext.activate();
return p_invocationContext.proceed();
} finally {
m_requestContext.invalidate();
m_requestContext.deactivate();
}
}
}
You can then use the #RequestContextOperation annotation on your class or on a specific method :
#ServerEndpoint("/serverpush")
public class ContratoEndpoint {
#Inject
private Storage storage;
#OnMessage
#RequestContextOperation
public String handleMessage(String message){
// Here the #RequestScoped bean is valid thanks to the #RequestContextOperation InterceptorBinding
storage.yourMethod();
....
}
}
WebSockets do not initialize a request scope context for their method invocations. You can use deltaspike context control to manually start a request context for the method invocation.
Although Request Scope is not active in WebSockets (including Atmosphere) you can manually activate it using the approach proposed in a previous answer.
However, since CDI 2.0, you can use the #ActivateRequestContext annotation (from javax.enterprise.context.control.ActivateRequestContext) interceptor to do just that.
Either annotate the class or the method where you want to have Request Scope and this will activate it at the beginning of method execution and deactivate it when it finishes,

How can I unit-test a Jersey web application deployed on Tomcat?

I'm building a Jersey web application deployed on Tomcat. I'm having a hard time understanding how to unit test the app.
Testing the core business logic (the non-Jersey-resource classes) is possible by simply instantiating the classes in my tests and calling methods on them (this has nothing to do with Jersey or Tomcat).
But what is the right way to unit test the Jersey resource classes (i.e., the classes that map to URLs)?
Do I need to have Tomcat running for this? Or should I mock the request and response objects, instantiate the resource classes in my tests, and feed the mocks to my classes?
I have read about testing in Jersey's site, but they're using Grizzly and not Tomcat in their examples, which is different.
Please explain how this should be done. Example code would be welcome.
If you just want to unit test, there's no need to start any server. If you have an services (business layer) or any other injections like UriInfo and things of that nature, you can just mock the. A pretty popular mocking framework is Mockito. Below is a complete example
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Beside Jersey dependencies, you will need Mockito.
*
* <dependency>
* <groupId>org.mockito</groupId>
* <artifactId>mockito-core</artifactId>
* <version>1.10.19</version>
* </dependency>
*
* #author Paul Samsotha
*/
public class SomethingResourceUnitTest {
public static interface SomeService {
String getSomethingById(int id);
}
#Path("something")
public static class SomethingResource {
private final SomeService service;
#Inject
public SomethingResource(SomeService service) {
this.service = service;
}
#GET
#Path("{id}")
public Response getSomethingById(#PathParam("id") int id) {
String result = service.getSomethingById(id);
return Response.ok(result).build();
}
}
private SomethingResource resource;
private SomeService service;
#Before
public void setUp() {
service = Mockito.mock(SomeService.class);
resource = new SomethingResource(service);
}
#Test
public void testGetSomethingById() {
Mockito.when(service.getSomethingById(Mockito.anyInt())).thenReturn("Something");
Response response = resource.getSomethingById(1);
assertThat(response.getStatus(), is(200));
assertThat(response.getEntity(), instanceOf(String.class));
assertThat((String)response.getEntity(), is("Something"));
}
}
See Also:
How to get instance of javax.ws.rs.core.UriInfo
If you want to run an integration test, personally I don't see much difference whether or not you are running a Grizzly container vs. running a Tomcat container, as long as you are not using anything specific to Tomcat in your application.
Using the Jersey Test Framework is a good option for integration testing, but they do not have a Tomcat provider. There is only Grizzly, In-Memory and Jetty. If you are not using any Servlet APIs like HttpServletRequest or ServletContext, etc, the In-Memory provider may be a viable solution. It will give you quicker test time.
See Also:
junit 4 test case to test rest web service for some examples, aside from the ones given in the documentation.
If you must use Tomcat, you can run your own embedded Tomcat. I have not found much documentation, but there is an example in DZone. I don't really use the embedded Tomcat, but going of the example in the previous link, you can have something like the following (which has been tested to work)
import java.io.File;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Aside from the Jersey dependencies, you will need the following
* Tomcat dependencies.
*
* <dependency>
* <groupId>org.apache.tomcat.embed</groupId>
* <artifactId>tomcat-embed-core</artifactId>
* <version>8.5.0</version>
* <scope>test</scope>
* </dependency>
* <dependency>
* <groupId>org.apache.tomcat.embed</groupId>
* <artifactId>tomcat-embed-logging-juli</artifactId>
* <version>8.5.0</version>
* <scope>test</scope>
* </dependency>
*
* See also https://dzone.com/articles/embedded-tomcat-minimal
*
* #author Paul Samsotha
*/
public class SomethingResourceTomcatIntegrationTest {
public static interface SomeService {
String getSomethingById(int id);
}
public static class SomeServiceImpl implements SomeService {
#Override
public String getSomethingById(int id) {
return "Something";
}
}
#Path("something")
public static class SomethingResource {
private final SomeService service;
#Inject
public SomethingResource(SomeService service) {
this.service = service;
}
#GET
#Path("{id}")
public Response getSomethingById(#PathParam("id") int id) {
String result = service.getSomethingById(id);
return Response.ok(result).build();
}
}
private Tomcat tomcat;
#Before
public void setUp() throws Exception {
tomcat = new Tomcat();
tomcat.setPort(8080);
final Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath());
final ResourceConfig config = new ResourceConfig(SomethingResource.class)
.register(new AbstractBinder() {
#Override
protected void configure() {
bind(SomeServiceImpl.class).to(SomeService.class);
}
});
Tomcat.addServlet(ctx, "jersey-test", new ServletContainer(config));
ctx.addServletMapping("/*", "jersey-test");
tomcat.start();
}
#After
public void tearDown() throws Exception {
tomcat.stop();
}
#Test
public void testGetSomethingById() {
final String baseUri = "http://localhost:8080";
final Response response = ClientBuilder.newClient()
.target(baseUri).path("something").path("1")
.request().get();
assertThat(response.getStatus(), is(200));
assertThat(response.readEntity(String.class), is("Something"));
}
}

Instantiate EJB Via Factory

So I have a service I am hooking by instantiating it through a factory that creates a proxy so it can process some annotations I have on the service. So my question is this...is there a way with JavaEE to have my dependency injection instantiate the instances of said service through the factory instead of however EJB's are normally instantiated by the server.
And otherwise...is there another way I could direct the Servlet or EJB container to process annotations for me? Like a bolt in of sorts that could have the code for handling the reflective analysis of the annotated class/method/fields?
I am sorry if this question is hard to understand, I'm having a hard time figuring out how to ask it. Here is an example of a factory one might use to instantiate a service (through a proxy).
package com.trinary.test.service;
import java.lang.reflect.Proxy;
import com.trinary.security.owasp.proxy.OWASPMethodValidatorProxy;
public class TestServiceFactory {
Class<?>[] interfaces = {TestService.class};
public TestService createESignService() throws IllegalArgumentException, InstantiationException, IllegalAccessException {
return (TestService)Proxy.newProxyInstance(
this.getClass().getClassLoader(),
interfaces,
new OWASPMethodValidatorProxy<TestService>(TestServiceImpl.class));
}
}
I would love it if in a servlet I might do something like this:
package com.trinary.test.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.trinary.test.service.TestService;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = -1778574173539761350L;
#EJB protected TestService testService;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("PATH: " + req.getPathInfo());
// ...
resp.setContentType("text/html");
resp.getWriter().append("<html><h1>TESTY TEST!</h1></html>");
}
}
In the above you can see how I might be injecting test service into my servlet. But I would like the EJB container to instantiate new instances of TestService using the factory instead of however the container usually does it. Is there a way to do this?
There's no way to directly intercept #EJB at the injection point, but you could intercept the method call on the actual bean using an EJB interceptor. If you can switch to CDI #Inject in the client, then you could use a CDI interceptor. At that point, you could use a CDI producer method to have more control over the object injected into the servlet.
I just discovered how to solve my issue. First as a commenter pointed out, I went with CDI instead of EJB (I need to understand what the difference between the two is and if most Application servers support it).
Secondly I used the #Produces annotation on the method in my factory like so:
import java.lang.reflect.Proxy;
import javax.ejb.Stateless;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
import com.trinary.security.owasp.proxy.OWASPMethodValidatorProxy;
#Local
public class TestServiceFactory {
Class<?>[] interfaces = {TestService.class};
#Produces
#Default
public TestService createESignService() throws IllegalArgumentException, InstantiationException, IllegalAccessException {
return (TestService)Proxy.newProxyInstance(
this.getClass().getClassLoader(),
interfaces,
new OWASPMethodValidatorProxy<TestService>(TestServiceImpl.class));
}
}
And then in my servlet I can now do this:
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.trinary.test.service.TestService;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = -1778574173539761350L;
#Inject TestService testService;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("PATH: " + req.getPathInfo());
testService.method(...);
// ...
resp.setContentType("text/html");
resp.getWriter().append("<html><h1>TESTY TEST!</h1></html>");
}
}
However if you were to try to use this with the service TestService marked up as a managed bean, you would get an exception because it would be ambiguous which way you want to instantiate it unless you want to use a #Qualifer annotation. I elected not to. I just want everywhere this gets injected to use the factory to instantiate.

Jersey - How to use #Context annotation outside of a servlet?

I am trying to set up a Jersey ClientResponseFilter. It is working fine, but I want to deserialize my request parameters into a String so I can write helpful messages into a log file containing the actual data.
I was thinking about using MessageBodyWorkers for this. As this link below says:
"In case you need to directly work with JAX-RS entity providers, for example to serialize an entity in your resource method, filter or in a composite entity provider, you would need to perform quite a lot of steps."
Source: 7.4. Jersey MessageBodyWorkers API
This is exactly what I want to prevent.
So I was thinking about injecting the messagebodyworkers into my filter like this:
package somepackage.client.response;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.message.MessageBodyWorkers;
import org.slf4j.Logger;
#Provider
public class ResponseFilter implements ClientResponseFilter {
// TODO: these workers are not injected
#Context
private MessageBodyWorkers workers;
private final Logger logger;
public ResponseFilter(Logger logger) {
this.logger = logger;
}
#Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext)
throws IOException {
if (responseValid(responseContext)) {
return;
}
logger.error("Error", "Some param");
}
private boolean responseValid(ClientResponseContext responseContext) {
if (responseContext.getStatus() == HttpServletResponse.SC_OK) {
return true;
}
return false;
}
}
But the reference is always null and remains null. Note that this filter is running in a standalone application, no servlet container is available.
Why isn't the annotation working in this case? How can I make it work? Or if making this approach to work is impossible, how can I work around this?
Any suggestions?
OK. Here is the workaround solution for the problem above: we should use #Inject and the HK2 Dependency Injection Kernel
HK2 Dependency Injection Kernel Link
First we need to make some changes to the filter:
package somepackage.client.response;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import org.glassfish.jersey.message.MessageBodyWorkers;
import org.slf4j.Logger;
public class ResponseFilter implements ClientResponseFilter {
#Inject
private MessageBodyWorkers workers;
private Logger logger;
#Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext)
throws IOException {
if (responseValid(responseContext)) {
return;
}
logger.error("Error", "Some param");
}
private boolean responseValid(ClientResponseContext responseContext) {
if (responseContext.getStatus() == HttpServletResponse.SC_OK) {
return true;
}
return false;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
}
As you can see the constructor changed, the class uses the default constructor, and the annotation changed to #Inject. Be aware that there are two #Inject annotations with the same name. Make sure you use: javax.inject.Inject.
Then we need to implement org.glassfish.hk2.utilities.binding.AbstractBinder:
package somepackage.client;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.message.MessageBodyWorkers;
import org.glassfish.jersey.message.internal.MessageBodyFactory;
public class Binder extends AbstractBinder {
#Override
protected void configure() {
bind(MessageBodyFactory.class).to(MessageBodyWorkers.class);
}
}
And finally we should register the filter and our binder in the client:
...
client.register(ResponseFilter.class);
client.register(new SitemapBinder());
...
Then the worker is going to be injected fine.

Injecting HttpRequest At Class Level [duplicate]

I've got a session scoped CDI bean, and I need to somehow access the HttpServletRequest object in this bean's #PostConstruct method. Is it possible? I've tried to Inject such an object, but it results in:
WELD-001408 Unsatisfied dependencies for type [HttpServletRequest] with qualifiers [#Default] at injection point [[field] #Inject ...]
As I understood while googling, the Seam framework has such a functionality, but I have a standard Java EE application on a GlassFish server.
Is it even possible to somehow pass the request to a CDI bean's #PostConstruct method?
As per your comment, you want access to the user principal. You can just inject it like this: #Inject Principal principal; or #Resource Principal principal;, see Java EE 6 Tutorial.
Update
I'll answer your direct question. In Java EE 7 (CDI 1.1) injection of HttpServletRequest is supported out of the box. In Java EE 6 (CDI 1.0) however, this is not supported out of the box. To get it working, include the class below into your web-app:
import javax.enterprise.inject.Produces;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
#WebListener
public class CDIServletRequestProducingListener implements ServletRequestListener {
private static ThreadLocal<ServletRequest> SERVLET_REQUESTS = new ThreadLocal<>();
#Override
public void requestInitialized(ServletRequestEvent sre) {
SERVLET_REQUESTS.set(sre.getServletRequest());
}
#Override
public void requestDestroyed(ServletRequestEvent sre) {
SERVLET_REQUESTS.remove();
}
#Produces
private ServletRequest obtain() {
return SERVLET_REQUESTS.get();
}
}
Note: Tested only on GlassFish 3.1.2.2
When using the code from rdcrng be aware of the following:
* The producer-method obtain is dependent-scoped, thus is only called once for application scoped beans (and will resolve to problems for every other request except the first)
* You can solve this with #RequestScoped
* When RequestScoped annotated, you will only get a proxy, and thus you cannot cas it to HttpServletRequest. So you maybe want a producer for HttpServletRequest.
Also note: As per CDI specification link passage 3.6, java ee beans are NOT consideres managed beans. Thus you will end up with two instances of CDIServletRequestProducingListener - one managed by the Java EE container, one managed by the CDI-container. It only works because SERVLET_REQUESTS is static.
Following the modified code for your convenience.
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
#WebListener
public class CDIServletRequestProducingListener implements ServletRequestListener {
private static ThreadLocal<ServletRequest> SERVLET_REQUESTS = new ThreadLocal<ServletRequest>();
#Override
public void requestInitialized(ServletRequestEvent sre) {
SERVLET_REQUESTS.set(sre.getServletRequest());
}
#Override
public void requestDestroyed(ServletRequestEvent sre) {
SERVLET_REQUESTS.remove();
}
#RequestScoped
#Produces
private HttpServletRequest obtainHttp() {
ServletRequest servletRequest = SERVLET_REQUESTS.get();
if (servletRequest instanceof HttpServletRequest) {
return (HttpServletRequest) servletRequest;
} else {
throw new RuntimeException("There is no HttpServletRequest avaible for injection");
}
}
}

Categories

Resources