2

I'm trying to make a RESTful Web Service which implements all four CRUD operations. I got stuck in "Create" because somehow I'm not able to obtain the posted data. Here is the method I wrote. Just as a info, I'm using Jersey RI of JAX-RS + JAXB XML to serialize objects.

Here it is:

@POST
@Consumes("application/xml")
public Response createStudent(InputStream is) {
 Student st = this.readStudent(is);
 st.setUserId(idCounter.incrementAndGet());
 studentDB.put(st.getUserId(), st);
 System.out.println("Created student " + st.getUserId());
 return Response.created(URI.create("/student/"+ st.getUserId())).build();

}

And the readStudent method is below:

 protected Student readStudent(InputStream is){

 JAXBContext ctx;

 Student st = null;
 try { 
  String xml = is.toString();
     System.out.println(xml);
  ctx = JAXBContext.newInstance(Student.class);
   st = (Student) ctx.createUnmarshaller().unmarshal(new StringReader(xml));
   return st;
 } catch (JAXBException e){
  e.printStackTrace();
 } 
 finally { return st; }

}

Can someone give me some light about this? I exhausted every idea to make this works and nothing worked!

Thanks in advance.

3 Answers 3

2

I think your problem is the line in which you use the toString() method to get the string of the InputStream:

String xml = is.toString();

You should read the data in the input stream and append it to a new string. The toString() is a string representation of the stream, but not the contents of it. You have to use the read methods of the InputStream and append the bytes to a new String using a StringBuilder or a StringWriter.

Sign up to request clarification or add additional context in comments.

Comments

0

After sweating hard looking for a answer, I've managed to fix it! It was just a missing dependency to resteasy-jaxb-provider.jar . Without this .jar the servlet wasn't able to do the automatic conversion from POJO to XML and vice-versa

Comments

0

I don't understand why you don't have createStudent(Student student) instead. The whole idea of jsr311 is for the parameters to also be parsed and given to the function.

EDIT For a second I thought I was confusing things. But I found an example here http://blogs.oracle.com/enterprisetechtips/entry/configuring_json_for_restful_web

@PUT
       @Consumes("application/json")
       public synchronized void setStatus(StatusInfoBean status) {
          ...
       }

So you don't even need to parse xml or json. This work is already done for you

1 Comment

Hm, tried that and received this message while trying to curl the URI: Could not find message body reader for type: class com.esconn.domain.Student of content type: application/xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.