EJB example for stateless and stateful beans difference [duplicate] - java

This question already has answers here:
When to use Stateful session bean over Stateless session bean?
(2 answers)
Closed 8 years ago.
I'm new to EJB, and I'm trying to understand the diference between Stateless and Stateful bean, so I made a simple example to test them.
#Stateless
public class Service {
private int num;
public Service(){
}
public int getNum() {
return num;
}
public void setNum() {
this.num++;
}
}
#WebServlet("/Controller1")
public class Controller1 extends HttpServlet {
#EJB
private Service serv;
public Controller1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
serv.setNum();
response.getWriter().println(serv.getNum());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
And the Stateful equivalent:
#Stateful
public class ServiceStateful implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int num;
public ServiceStateful(){
}
public int getNum() {
return num;
}
public void setNum() {
this.num++;
}
}
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private ServiceStateful serv;
public Controller() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
serv.setNum();
response.getWriter().println(serv.getNum());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Both examples act exactly the same, which is surprising for me. Can someone please explain what is the deal here?

Your first example returns the previously set number by chance only : the get method could have been invoked on a different bean instance. It just happened to use the same instance in this particular case, but you can't count on it.
The second one is guaranteed to return you the previously set number, provided another request doesn't call the set method before the get method is called. A stateful bean should not be injected into a servlet.

You can use instance variables of a stateless session bean, but they're not guaranteed to be preserved across method calls. If both approaches behave the same, it simply means you're probably getting the same stateless session bean instance across method calls within the same session.

You are not supposed to have member fields (aka state) in a stateless session bean. For a stateful session bean it's ok. That's the difference.

A stateful bean maintain it initial state during the conversation with the client (on or many).
A Stateless bean state can be changed (it attributes) during the conversation with the client (doesn't affect other clients)
you can see the difference if you execute multiple times!!

Related

How to let the resource annotations to be inherited by subclasses

For example, I have a superclass like below
public abstract class SuperServlet extends HttpServlet {
#Resource(name = "varA")
protected static String varA;
}
And the subclass
public class SubServlet extends SuperServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("varA: " + varA);
}
}
I was planned to see the varA's value that I have set in the web.xml, but instead the value I got is null. So I think the resource annotation won't work in a scenario of inheritance like this.
Does anyone know how to make those annotation works on this?
found it. I cannot use it on a static variable because the injection doesn't apply to a field that belong to the class, need to be a individual object.

ContextNotActiveException while calling #Asynchronous method of #Stateless bean

I am injecting a #Stateless bean in a Asynchronous Servlet and calling #Asynchronous method from the Serrvlet. In the server logs of the jboss i am not able to see any of the Exception but whhile starting the Java Mission Control ,Flight Recorder i can see ContextNotActiveExcetion whenever Servlet makes a call to the #Asyncrhonous method.
Servlet ::
#WebServlet(urlPatterns = { "/asyncservice" }, asyncSupported = true)
public class AsyncServiceServlet extends HttpServlet {
#Inject
private Service service;
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
final AsyncContext asyncContext = request.startAsync(request, response);
asyncContext.start(new Runnable() {
#Override
public void run() {
try {
service.service(asyncContext);
} catch (ContextNotActiveException | IOException e) {
e.printStackTrace();
}
});
}
Service class ::
#Stateless
public class Service {
#Asynchronous
public void service(final AsyncContext asyncContext) throws IOException {
HttpServletResponse res = (HttpServletResponse) asyncContext.getResponse();
res.setStatus(200);
asyncContext.complete();
}
}
the stack trace i can see in the flight Recorder ::
java.lang.Throwable.<init>() 4
java.lang.Exception.<init>() 4
java.lang.RuntimeException.<init>() 4
javax.enterprise.context.ContextException.<init>() 4
javax.enterprise.context.ContextNotActiveException.<init>() 4
org.jboss.weld.context.ContextNotActiveException.<init>(Enum,Object[]) 4
org.jboss.weld.manager.BeanManagerImpl.getContext(Class) 4
org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(InterceptorContext) 4
org.jboss.invocation.InterceptorContext.proceed() 4
org.jboss.invocation.InitialInterceptor.processInvocation(InterceptorContext) 4
org.jboss.invocation.InterceptorContext.proceed() 4
org.jboss.invocation.ChainedInterceptor.processInvocation(InterceptorContext) 4
org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(InterceptorContext) 4
org.jboss.invocation.InterceptorContext.proceed() 4
org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(InterceptorContext) 4
org.jboss.invocation.InterceptorContext.proceed() 4
org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(InterceptorContext,TransactionManager,EJBComponent) 4
org.jboss.as.ejb3.tx.CMTTxInterceptor.required(InterceptorContext,EJBComponent,int) 4
org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(InterceptorContext)
I have been going through many posts but still the issue remain the same, please help me out .
javadoc for AsyncContext.start:
Registers the given AsyncListener with the most recent asynchronous
cycle that was started by a call to one of the
ServletRequest.startAsync() methods. The given AsyncListener will
receive an AsyncEvent when the asynchronous cycle completes
successfully, times out, or results in an error.
Implying that by the time this call to
service.service(asyncContext);
Is made, the httpservletrequest "context" may not be available and the request may even have been committed, resulting to CDI not being able to determine any '#RequestScoped' beans used by your service.
Note that AsyncContext.start registers an onEvent to be invoked when the async call is completed, or on error, not when it starts.
You would probably want to add listeners to be invoked before calling AsyncContext.start
The exception has no effect on functionality; it's handled under the hood.
The ContextNotActiveExcetion applies to #RequestScoped beans. You start double async processing with AsyncContext.start and the #Asynchronous EJB call.
The exception you see within flight recorder is to test, whether the default RequestScoped context is active and to proceed, if so. If the RequestScoped context is not active, a new EjbRequestContext is activated and associated with the thread.
You can cause a visible ContextNotActiveExcetion when you create a #SessionScoped bean and inject/access that one within your Service
MySessionScoped.java
#SessionScoped
public class MySessionScoped implements Serializable {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Service.java
#Stateless
public class Service {
#Inject
private MySessionScoped mySessionScoped;
#Asynchronous
public void service(final AsyncContext asyncContext) throws IOException {
System.out.println(mySessionScoped.getValue());
HttpServletResponse res = (HttpServletResponse) asyncContext.getResponse();
res.setStatus(200);
asyncContext.complete();
}
}

How to call Generic Portlet methods from servlet?

I have created a portlet and able all my business logic is performing in a servlet. I need to get the liferay login user details in the servlet. SO I have created a class which will extend the GenericPortlet. Now My question is how can I call that class I need to execute the GenericPorlet unimplemented method. My code is as follows,
public class ActionProcess extends GenericPortlet {
public void init() throws PortletException{
super.init();
}
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
User user = (User) request.getAttribute(WebKeys.USER);
ThemeDisplay td =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
User urs = td.getUser();
System.out.println("doView "+ urs);
System.out.println("doView "+ user);
}
}
Now I need to call the doView() and return the values to servlet. How can I do that my servlet code is.
#WebServlet("/demoClass")
public class demoClass extends HttpServlet {
private static final long serialVersionUID = 1L;
public demoClass() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response); //
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Here I am performing the business logic....
//How do I call the ActionProcess class here, I need to get the User name which is return by diView() method
}
}
Any suggestions?
You can't, and my answer is very similar to my answer to your very similar question.
It's the framework's (portal's) business to call the lifecycle methods of a portlet. Not yours.
You need to rethink your problem and come up with a different architecture. Or give us your problem to suggest a different solution than the one that you're currently pursuing.
Differing from that answer, I'm assuming that in this case you're within the very same same web application (portlet and servlet are deployed in the same webapp). However, just like in that other question, a portlet's request is routed through the portal while the servlet's request is not. You'll not have the data available.

GWT RPCServlet - Junit + getThreadLocalRequest

In my RPCServlet I am using the method AbstractRemoteServiceServlet.getThreadLocalRequest() to get the HttpSession. Now I want to unit-test it. I am using Mockito and thought I just could mock everything, but the method is final and protected.
Is there any other way to Unit-test AbstractRemoteServiceServlet.getThreadLocalRequest().getSession()
At the end you are trying to get a Session. In our case we solve this situation doing this:
Using GUICE for getting our instances (making them available in the GIVEN part of the test)
public class TestServerModule extends com.google.inject.AbstractModule {
#Override
protected void configure() {
.....
bind(HttpServletRequest.class).to(MockRequest.class).in(Singleton.class);
bind(HttpServletResponse.class).to(MockResponse.class).in(Singleton.class);
....
}
....
#Provides
#Singleton
RequestUtil getRequestUtil(final HttpServletRequest req, final HttpServletResponse resp) {
return new RequestUtilsImpl() {
public HttpServletRequest getThreadRequest() {
return req;
}
public HttpServletResponse getThreadResponse() {
return resp;
}
};
}
RequestUitl object contains everything related with Session and more server stuff (that is not important for your problem :D). The important part here is you can have access to the getThreadRequest(), so you have access to getSession() method.
What is the problem? You can not have a real HttpServletRequest object in your instances, so you need to mock them. For doing it, we specified the bind rules at the top.
At the end your test should be something like:
#RunWith(...)
#GuiceModules({TestServerModule.class, ....})
public class YourTest extends junit.framework.TestCase {
#Inject RequestUtil requestUtil;
....
#Test public void
test_session_after_doing_something() {
//GIVEN
HttpSession mockedSession = requestUtil.getThreadRequest().getSession();
....
}
....
}

Static or nonstatic action in mvc?

i want to ask you about mvc. How it works. So, this is simple example(I don't use any frameworks)
in Controller(Servlet):
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String page = null;
AbstractCommand action;
action = ActionFactory.getAction(request);// get command from factory
page = action.execute(request, response);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
for action we create a common interface(Strategy pattern):
public interface AbstractAction {
public String execute(HttpServletRequest request, HttpServletResponse response);
}
Simple Action(Example):
public class HelloAction implements AbstractAction {
#Override
public String execute(HttpServletRequest request,
HttpServletResponse response) {
//....(some actions to modify request)
String page = "/main.jsp";
return page;
}
}
And now, our factory:
public class ActionFactory {
private enum Actions{
HELLO;
}
public static AbstractAction getAction(HttpServletRequest request){
String action = request.getParameter("action");//take parameter from jsp
Actions actionEnum = Actions.valueOf(action.toUpperCase());
switch (actionEnum) {
case HELLO:
return new HelloAction();
}
}
}
We came to the place where I am in confused. Servlet is initialized only once, and only one for all requests. Just forwards requests to the actions where we modify request or response. But, we create NEW instance of the class for every request. Here can occur memory overflow!? Or not?
Can we make these actions static(static method, one for all request)? If two requests come at the same time what will happen to them?
What do you think about this, please share your experience.
P.S. sorry for bad english.
How about Singleton pattern to get the instance of the Action class ?
Just add some abstact getInstance() method in AbstractAction.
Make every implementation provide its own instance.
In every implementation class, use Singleton pattern so that only one instance exists.
Make sure no action class stores any data related to a specific request.
As i understood the jsp, the whole thing is stateless, if u access the servlet by http request, the servlet will be created in a new instance.
After leaving the servlet by .forward(), it will be released by garbage collection.
2,3,...,n requests = 2,3,...,n servlets.
by forwarding to a jsp, the only way to access the servlet from jsp is a new http request = new servlet. ( will move to the doPost method)

Categories