0

Every night a XML document comes in a folder in the WS server. I want the web service to read this XML file at a certain time (let's say at 05:00) and place it in a object stored in memory, every day.

How can I achieve this? Which object should I use? I intend to use a JAX-WS. Could it be possible using JAX-RS too?

Tks.

denstorti
  • 127
  • 2
  • 12
  • 2
    If "storing a n XML file in a memory object" is all you need you might as well read the file into a byte array. If there's more to it, you should say so, e.g., Is the web service a single program? Does it need details from the XML document? Do you have an XML Schema for it? Etc. ... – laune Jan 23 '15 at 14:14
  • It's just store in memory, until the next read (to update the data). I'll create some tests. tks – denstorti Jan 23 '15 at 14:26

1 Answers1

0

You can store it as an attribute in the ServletContext of the application. It will be accessible to any JAX-WS services or JAX-RS resources in the web module. As an added bonus, if your JAX-WS service and JAX-RS resources are in the same module (war), they will share the same instance of the object/document you place there.

For the JAX-RS resource:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.servlet.ServletContext;

@Path("myresource")
public class MyResource {

    @Context ServletContext context;

    @GET
    @Produces("text/plain")
    public String getMyResource() {
        return context.getAttribute("cachedDocument");
    }
}

For the JAX-WS service:

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

@WebService
public class MyService {
@Resource
private WebServiceContext context;

    @WebMethod
    public String getDocument() {
        ServletContext servletContext =
    (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
        return servletContext.getAttribute("cachedDocument");
    }
}

See also: ServletContext javadocs.

Scott Heaberlin
  • 3,364
  • 1
  • 23
  • 22
  • Thank you for your answer. I think I was searching for something more like this http://stackoverflow.com/questions/11096310/singleton-object-in-java-web-service, a singleton object loaded once and shared among all my web service threads. About your answer, is this context already instantiated or I need to init it manually? Tks. – denstorti Jan 27 '15 at 15:03
  • 1
    Context is provided for you by the application server (container) runtime. To go the singleton route is to roll your own solution to a problem the spec authors solved years ago. Just my two cents. – Scott Heaberlin Jan 27 '15 at 15:09