简体   繁体   中英

Check if JAXBElement parameter is null

I have the following method, that receives XML and creates a new book in the database:

@PUT
@Path("/{isbn}")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public SuccessfulRequestMessage createBook(JAXBElement<Book> bookParam,
        @PathParam("isbn") String isbn) {

    if(bookParam == null)
    {
        ErrorMessage errorMessage = new ErrorMessage(
                "400 Bad request",
                "To create a new book you must provide the corresponding XML code!");
        throw new MyWebServiceException(Response.Status.BAD_REQUEST,
                errorMessage);
    }
        ....................................................................
}

The problem is that when I don't send anything in the message body, the exception is not thrown. How could I check if the message body is empty?

Thanks!

Sorin

Try this:

public SuccessfulRequestMessage createBook(JAXBElement<Book> bookParam, 
                      @PathParam("isbn") String isbn) throws MyWebServiceException

It may be that the JAXBElement itself is not null but its payload is. Check bookParam.getValue() as well as just bookParam .

I found out about a little trick that can be done: instead of sending MediaType.APPLICATION_XML , I send application/x-www-form-urlencoded , represented by only one parameter, and this parameter will contain the XML code. Then I can check if the parameter is null or empty. Then, from the content of the parameter, I construct a JAXBElement. The code is the following:

@PUT
@Path("/{isbn}")
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_XML)
public SuccessfulRequestMessage createBook(@FormParam("code") String code,
        @PathParam("isbn") String isbn) throws MyWebServiceException {

    if(code == null || code.length() == 0)
    {
        ErrorMessage errorMessage = new ErrorMessage("400 Bad request",
                "Please provide the values for the book you want to create!");
        throw new MyWebServiceException(Response.Status.BAD_REQUEST,
                errorMessage);
    }

    //create the JAXBElement corresponding to the XML code from inside the string
    JAXBContext jc = null;
    Unmarshaller unmarshaller;
    JAXBElement<Book> jaxbElementBook = null;
    try {
        jc = JAXBContext.newInstance(Book.class);
        unmarshaller = jc.createUnmarshaller();
        StreamSource source = new StreamSource(new StringReader(code));
        jaxbElementBook = unmarshaller.unmarshal(source, Book.class);
    } catch (JAXBException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM