I am getting a HttpservletRequest from client, i am trying to parse the request (Using JAXB, DOM). For that i am using the following code
String str_request = IOUtils.toString(request.getInputStream());
System.out.println("String is " + str_request);
requestStream = new ByteArrayInputStream(str_request.getBytes());
My problem is, when i pass the requestStream to my parser methods, one method is working fine, but another fails. I guess there is problem with inputStream, but i could not solve this. Can any one suggest a solution for this problem.
Dom Parser Method:
public String parseMethodName(InputStream request) throws SAXException,
IOException,
ParserConfigurationException {
System.out.println("in parseMethodName");
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
System.out.println("bfor parse");
Document doc = dBuilder.parse(request);
System.out.println("After parse");
methodName =
doc.getElementsByTagName("methodName").item(0).getTextContent();
}
JAXB parser Method:
System.out.println("in parse ******");
JAXBContext context = JAXBContext.newInstance(MethodCall.class);
System.out.println("bfor unmarshall ****");
Unmarshaller um = context.createUnmarshaller();
System.out.println("After unmarshall ****");
mc = (MethodCall) um.unmarshal(is);
I am getting the following Exception:
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException: Premature end of file.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:481)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:199)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:168)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:184)
You shouldn’t be converting the input stream to a String and then back to a byte array. That’s just asking to lose data, especially as you use the platform default encoding when converting a string to a byte array.
See if whichever
IOUtilsclass you’re using contains a method to just completely read anInputStreamto abyte[], and use that as the basis for yourByteArrayInputStream.Note that if you want to read the data multiple times, you’ll either need to reset the stream, or create a new stream around the same byte array.