Imad
Imad

Reputation: 2741

DELETE and GET have faulty behavior in a Jax-RS Restful App

I am learning how to implement Rest API through a tutorial project.

I am facing a rather strange behavior from a routine I perform in order to test the standard CRUD methods...

Here's a general description of the code architecture:

Now, here's the routine which leaves me confused:

  1. Run app,
  2. Do a GET on /messages: Shows 2 entries,
  3. Do a POST with custom data: Data is added,
  4. Do a GET on /messages: Shows 3 entries,
  5. Do a DELETE on /messages/3: Deletes 3rd entry,
  6. Do a GET on /messages: Shows 2 entries,
  7. Do a DELETE on /messages/2: While debugging the app, the messageService instance in MessageRessource has a hashmap of size 1 after the DELETE method is processed,
  8. Do a GET on /messages: Shows 2 entries instead of 1.

My own thoughts on the problem:

For the code, please see the GitHub public project in the messenger App by AetosAkrivis

N.B : I know this isn't a real problem because I only need to remove the hardcoded Message entries in the constructor in order to be able to perform normally. But I am really curious about the reason of the malfunctioning of this routine.

Upvotes: 1

Views: 76

Answers (1)

pedrofb
pedrofb

Reputation: 39271

You have assumed that the JAX-RS container will only create one instance of the service MessageRessource, but it can decide to clean instances or create multiple. Each time it is done the initialization, your static messages will be updated with 2 additional entries. Results are indeterminate

@Path("/messages")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MessageRessource {

    private MessageService messageService;

    public MessageRessource() {
        messageService = new MessageService();
    }

public MessageService() {
    messages.put(1L, new Message(1L,"Hi","Imad"));
    messages.put(2L, new Message(2L,"Hello","Badr"));
}

P.S: Post your code instead of linking it

Upvotes: 1

Related Questions