Macejkou
Macejkou

Reputation: 686

Java EE 6 - Stateful REST as Stateful session bean

I am creating REST web service that need to be stateful. Consider following situation:

  1. Web service performs difficult and time consuming computations and returns very large result. So only number of results is returned by this service and whole result is saved on the server in stateful bean.
  2. When the result exists. Client can ask for a subset of existing results.

I am trying to do this via @Stateful session bean but it still acts like @Stateless. Now I am wondering wether it is even possible, because Client is not accepting any Cookie so server cannot identify it.

Is it possible to have Stateful bean accesed via REST?

Code sample:

@Path("/similarity/")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Stateful
@StatefulTimeout(600000) // 10 minutes
public class SimilarityResource {

    private List<SimilarityResult> savedSimilarityResults = new ArrayList<SimilarityResult>();

    @POST
    @Path("/atom-count/")
    public List<SimilarityResult> atomCountSimilarity(JAXBElement<SimilarityRequestXML> sr) {

        try {
            if (this.savedSimilarityResults.isEmpty()) {

                List<SimilarityResult> similarityResults = acs.findAllSimilar(); // Time consuming

                this.savedSimilarityResults = similarityResults; // Save results
                return similarityResults;
            } else {
                CompoundResponse cr = new CompoundResponse("Hureeey stateful bean works!.", 404);
                throw new WebApplicationException(cr.buildResponse());
            }

        } catch (CompoundSearchException e) {
            CompoundResponse cr = new CompoundResponse(500, e);
            throw new WebApplicationException(cr.buildResponse());
        }
    }

}

What I expect is, when I call this /atom-count/ method twice, it should response with 404.

Upvotes: 4

Views: 6316

Answers (1)

remigio
remigio

Reputation: 4211

You should annotate your resource class with @SessionScoped in order to tell JAX-RS to create request objects with session lifetime, otherwise the default is @RequestScoped.

Upvotes: 6

Related Questions