views:

234

answers:

2

Consider a simply servlet:

// MyServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
    UtilClass.doSomething(getServletContext().getRealPath(SOME_FILE));
}

And the utility class does something with the file:

// UtilClass.java
public String doSomething(String filePath)
{
    File f = new File(filePath);
    String s = readWhateverFrom(f);
    return s;
}

I am now porting the doSomething() function to a web service running under Tomcat and Axis2. How would I port it so that I can still access the context and get access to a file under the servlet?

A: 

Sounds like a job for a Servlet Filter and a ThreadLocal. Axis is running within a Servlet Context, too. So all you have to do is to implement a custom javax.servlet.Filter, stuffing in the ServletRequest into a ThreadLocal where you can access it from within your utility class. You can get the ServletContext from the FilterConfig.

mhaller
I assume that SOME_FILE is part of the web-service internals, not part of the business parameters.
mhaller
that solution would work, but it is already implemented by the web service stack.
Bozho
The problem with using either ServletContext or WebServiceContext directly is that you will have a dependency on them within your utility class - which you sure don't want to have. Stuffing in such information in your own ThreadLocal and let filters/listeners do that is more clean from a dep-mgmt point of view. But you're right, if it's already there, use it and don't reinvent the wheel :-)
mhaller
+2  A: 

You should get ahold of your (jax-ws) MessageContext. This would depend on your configuration, but perhaps using

@Resource
private WebServiceContext wsCtx;

and in your method:

MessageContext messageContext = wsCtx.getMessageContext()

ServletContext ctx = (ServletContext) 
           messageContext.getProperty(MessageContext.SERVLET_CONTEXT);

Edit: Seems like Axis2 (as well as Axis) support the following:

HttpServlet servlet = (HttpServlet) 
    MessageContext.getCurrentContext().getProperty(HTTPConstants.MC_HTTP_SERVLET);
ServletContext ctx = servlet.getServletContext();

With the following imports:

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
Bozho
sounds like a good idea - but I'm getting a null `wsCtx`. Any idea why?
Yuval A
tried changing name to `wsContext` and removing the `private` - no dice...
Yuval A
Hm. I updated my post
Bozho