Jordi
Jordi

Reputation: 23237

bulk/batch friendly operation JAXRS

I'd like to build an JAXRS method, allows to specify a lumps of operations to perform on my resources.

For example, I have got a resource, Book. On this resource I deploy these methods: create, delete and update. If only, I set these method on Book resource, when my client needs to perform a lot of updates over a lot of book resources, he is going to have to send a lot of requests for each Book resource.

I'd like to deploy a JAXRS operation offers this functionality. For example: a batch method that receives which operation must to perform.

However, I've no idea how to do this. I'm using JAXRS-2.0.

Thanks for all.

Upvotes: 0

Views: 561

Answers (1)

Micah
Micah

Reputation: 50

This isn't a jaxrs-specific question by any means but more of a design question. The JAXRS implementation of this is relatively straight-forward.

From what you're describing, I would create a batch POST endpoint that has a specific data structure for the job. You accept a JSON blob (serialized form of this data structure) instructing the endpoint what to do. Once the endpoint receives the data, a thread is spawned off in the background to "do work" and an identifier of "the job" is returned (assuming this is a long-running task possibly). If you do return a "job id", you should also have an endpoint to "get status" which will return the current status and presumably some sort of output once the job has completed.

Example data structure you may want to accept as JSON:

{
    job_name: "Some job name",
    requests: [
        {
            tasks: ["UPDATE"],
            book_id: 122,
            data: {
                pages: 155, 
                last_published_date: "2015-09-01"
            }
        },
        {
            tasks: ["DELETE"],
            book_id: 957
        }
    ]
}

Your actual endpoint in JAXRS may look something like this:

  @POST
  @Path(value = "batch")
  @Produces(MediaType.APPLICATION_JSON)
  public String batchRequest(String batchRequest) {
      BatchRequest requestObj = null;

      if (!StringUtils.isBlank(batchRequest))
      {
          Gson gson = new Gson();
          requestObj = gson.fromJson(batchRequest, BatchRequest.class);

          // This is the class that would possibly spawn off a thread
          // and return some sort of details about the job
          JobDetails jobDetails = JobRunner.run(requestObj);

          return gson.toJson(jobDetails);
      }

      return "error";
}

Hopefully this makes sense and helps out. Please feel free to reply with additional questions and I'll try to help as much as I can!

Upvotes: 1

Related Questions