I am trying to execute a Struts2 Action from inside a Quartz job — generalizing, from any context which is not the processing of an HTTP request.
I started here http://struts.apache.org/2.0.6/docs/how-can-we-schedule-quartz-jobs.html but the document seems to be pretty obsolete.
I believe (but I may be wrong) I’ve boiled it down to the need to obtain a Container object:
import java.util.HashMap;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.DefaultActionProxyFactory;
...
HashMap ctx = new HashMap();
DefaultActionProxyFactory factory= new DefaultActionProxyFactory();
factory.setContainer(HOW DO I GET THE CONTAINER??);
ActionProxy proxy = factory.createActionProxy("", "scheduled/myjob", ctx);
One solution would be to issue an http request (via TCP) against localhost. I would prefer to avoid that.
I somewhat fear what providing this answer may encourage some people to do, but as a proof of concept and to actually provide a solution to anyone who may, for whatever reason (maybe they are inheriting some whacked out application for which this is needed?), need to execute Struts2 actions outside of a normal request context.
But, here is a raw (it is provided as a starting point, not an optimal implementation), but working, solution:
First, add these three classes to a package called com.stackoverflow.struts2.quartz:
A simple job that just asks for a proxy for the given job context and executes it:
Some constants for passing around the action details:
A custom ActionProxyFactory that can be accessed statically from the ActionJob:
Then, in your struts.xml, add:
Then you can schedule action executions with some simple code:
And that’s it. This code will cause the action to be executed every second indefinitely, and the interceptors will all fire and the dependencies will be injected. Of course, any logic or interceptors that depend on Servlet object like an HttpServletRequest are not going to operate properly, but then it wouldn’t make sense to schedule those actions outside of the servlet context, anyway.