gtludwig
gtludwig

Reputation: 5601

How to unmarshall a InputStream using JAXB?

I'm getting a ClassCastException when trying to unmarshall an object in a XML notation.

My desktop client calls for a RESTful service that returns the properly formatted and validated list.

The method that spits out the exception is:

public class DecodeXML {

    JAXBContext jaxbContext;
    Unmarshaller jaxbUnmarshaller;

    public Agent convertXmlToAgent(InputStreamReader inputStreamReader) {
    //      XStream xstream = new XStream();
    //      xstream.processAnnotations(Agent.class);
    //      xstream.processAnnotations(FtpConnection.class);
    //      xstream.processAnnotations(SmtpConnection.class);
    //      xstream.processAnnotations(SqlConnection.class);
    //
    //      return (Agent) xstream.fromXML(inputStreamReader);


        try {
            jaxbContext = JAXBContext.newInstance(Agent.class);
            jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            jaxbUnmarshaller.unmarshal(inputStreamReader);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return (Agent) jaxbUnmarshaller;
    }
}

The commented out section is the former implementation I'm moving from.

The Agent pojo is

@XmlRootElement (name = "agent")
@XmlAccessorType(XmlAccessType.NONE)
public class Agent extends BasePojo {

    private static final long serialVersionUID = 1L;

    @XmlElement(name = "description")
    private String description;

    @XmlElement(name = "agentId")
    private String agentId;

    @XmlElement(name = "ftpConnection")
    private FtpConnection ftpConnection;

    @XmlElement(name = "smtpConnection")
    private SmtpConnection smtpConnection;

    @XmlElement(name = "sqlConnection")
    private SqlConnection sqlConnection;

    @XmlElement(name = "pollIntervall")
    private Integer pollInterval;

    @XmlElement(name = "lastExecutionDate")
    private Date lastExecutionDate;
    // getters and setters

What am I not seeing here?

Upvotes: 2

Views: 9483

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

Well, your code does

return (Agent) jaxbUnmarshaller;

The unmarshaller is not an Agent. It's the object that allows parsing the XML and generating an Agent.

You want

 return (Agent) jaxbUnmarshaller.unmarshal(inputStreamReader);

I notice that you didn't post the stack trace of the exception. That's probably a sign that you didn't consider it important. But that's your biggest mistake. If you read it carefully, you'd notice that it precisely indicates which line of your code is the cause of the exception.

Upvotes: 4

Related Questions