#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Posts
    5
    Rep Power
    0

    JAXB unmarshall. closed stream error?


    Im getting serious unmarshall errors. If i convert the HTTP to a inputstream i get a closed stream error. Anyone know possibly that happens?. Thats why i converted it to a string and used a BufferedInputStream.

    [GOOGLE]
    Code:
    HttpUriRequest getRequest = new HttpGet(getURL);
    
    		// *************************************************************
    		// **************Adding user-token to HTTP header***************
    		// *************************************************************
    		if (userToken != null) {
    			getRequest.setHeader("mb-user-token", userToken);
    		}
    		// *************************************************************
    
    		page = "";
    		System.out.println("The requested URL is: " + getURL + "\n");
    		try {
    			// Create two responses which will stream separately to text and Xml
    			// document
    			HttpResponse response1 = xmlclient.execute(getRequest);
    			// HttpResponse response2 = textclient.execute(getRequest);
    
    			// Determine the status code of the HTTP request and act accordingly
    			int statusCode = response1.getStatusLine().getStatusCode();
    			System.out.println("The status code is:" + statusCode);
    
    			// If the statuscode = 200, then the request was returned
    			// successfully
    			if (statusCode == 200) {
    
    				HttpEntity entity = response1.getEntity();
    
    				
    				
    				
    				
    				
    				DocumentBuilderFactory factory = DocumentBuilderFactory
    						.newInstance();
    				JAXBContext context = JAXBContext.newInstance("comx");
    				stream = entity.getContent();
    				
    				
    				try {
    					/*InputStreamReader in = new InputStreamReader(is);
    					BufferedReader br = new BufferedReader(in);
    					String read = br.readLine();
    					
    					
    					
    					
    					
    
    					while(read != null) {
    					    
    					    
    					    xmlString += br.readLine();
    					}
    				*/
    					
    			
    					//stream = new ByteArrayInputStream(xmlString.getBytes());
    					
    					Unmarshaller unmarshaller = context.createUnmarshaller();
    					
    					machineResponse= (MachineResponse) unmarshaller.unmarshal(stream);
    					
    					
    					
    					DocumentBuilder builder = factory.newDocumentBuilder();
    					doc = builder.parse(entity.getContent());
    					returnXML = XMLtool.getStringFromDocument(doc);
    					
    				} catch (SAXException e) {
    					e.printStackTrace();
    				} catch (ParserConfigurationException e) {
    					e.printStackTrace();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    
    			}[/GOOGLE]
    trying to convert the xml response into the classes i created in JAXB. My jaxb classes are in the package name "comx".
  2. #2
  3. Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    May 2004
    Location
    Superior, CO, USA
    Posts
    2,418
    Rep Power
    1713
    You've only given bits and pieces of what issue you're having. I'd assume that HttpResponse is from HttpClient? I do it a bit differently than you - I don't assume a text stream up front but convert to it on the fly:

    java Code:
    HttpGet httpGet = new HttpGet( url );
    HttpResponse response = httpClient.execute( getHttpHost(), httpGet );
    HttpEntity responseEntity = response.getEntity();
     
    if( responseEntity != null ) {
        InputStream inputStream = responseEntity.getContent();
        try {
            StringBuilder builder = new StringBuilder();
             byte[]  readBuffer = new byte[8192];
             int bytesRead = 0;
             while( (bytesRead = inputStream.read(readBuffer)) != -1 ) {
                String nextString = new String( readBuffer, 0, bytesRead );
                builder.append( nextString );
             }
             httpClient.getConnectionManager().shutdown();
             return builder.toString();
         }
         catch (IOException ioe) {
             throw ioe;
         }
         catch (RuntimeException re) {
            httpGet.abort();
            throw re;
         }
         finally {
             inputStream.close();
        }
    }


    Edit: Forgot the rest...

    And then:

    java Code:
    String theData = <result from above method>;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class);
        Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
     
        MyClass myClass = (MyClass)unMarshaller.unmarshal( new StreamSource( new StringReader( theData ) ) );            
    }
    catch (JAXBException e) {
    ...
    }
    Last edited by stdunbar; May 8th, 2012 at 11:04 AM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Posts
    5
    Rep Power
    0
    Originally Posted by stdunbar
    You've only given bits and pieces of what issue you're having. I'd assume that HttpResponse is from HttpClient? I do it a bit differently than you - I don't assume a text stream up front but convert to it on the fly:

    java Code:
    HttpGet httpGet = new HttpGet( url );
    HttpResponse response = httpClient.execute( getHttpHost(), httpGet );
    HttpEntity responseEntity = response.getEntity();
     
    if( responseEntity != null ) {
        InputStream inputStream = responseEntity.getContent();
        try {
            StringBuilder builder = new StringBuilder();
             byte[]  readBuffer = new byte[8192];
             int bytesRead = 0;
             while( (bytesRead = inputStream.read(readBuffer)) != -1 ) {
                String nextString = new String( readBuffer, 0, bytesRead );
                builder.append( nextString );
             }
             httpClient.getConnectionManager().shutdown();
             return builder.toString();
         }
         catch (IOException ioe) {
             throw ioe;
         }
         catch (RuntimeException re) {
            httpGet.abort();
            throw re;
         }
         finally {
             inputStream.close();
        }
    }


    Edit: Forgot the rest...

    And then:

    java Code:
    String theData = <result from above method>;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class);
        Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
     
        MyClass myClass = (MyClass)unMarshaller.unmarshal( new StreamSource( new StringReader( theData ) ) );            
    }
    catch (JAXBException e) {
    ...
    }
    Even from your code i got this error

    Code:
    java.io.IOException: Attempted read from closed stream.
    	at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:126)
    	at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:121)
    When creating the jaxbcontext
    Code:
    JAXBContext.newInstance(what goes in here);
    what do you creat e a new instance of is it the location of the object factory?
  6. #4
  7. Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    May 2004
    Location
    Superior, CO, USA
    Posts
    2,418
    Rep Power
    1713
    Originally Posted by Gruaig
    When creating the jaxbcontext
    Code:
    JAXBContext.newInstance(what goes in here);
    what do you creat e a new instance of is it the location of the object factory?
    I am unmarshalling a single class so you'll see I put MyClass.class - the class reference. The code for that uses a file generated from an XSD though I'm not validating against a schema (I should be though...)

    It has something like:

    java Code:
    //
    // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- 
    // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
    // Any modifications to this file will be lost upon recompilation of the source schema. 
    // Generated on: 2012.05.09 at 08:05:02 AM MDT 
    //
     
    package myPackage;
     
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
     
     
    /**
     * <p>Java class for myClass element declaration.
     * 
     * <p>The following schema fragment specifies the expected content contained within this class.
     * 
     * <pre>
     * &lt;element name="myClass">
     *   &lt;complexType>
     *     &lt;complexContent>
     *       &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *         &lt;sequence>
     *           &lt;element name="theId" type="{http://www.w3.org/2001/XMLSchema}int"/>
     *           &lt;element name="someText" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *         &lt;/sequence>
     *       &lt;/restriction>
     *     &lt;/complexContent>
     *   &lt;/complexType>
     * &lt;/element>
     * </pre>
     * 
     * 
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "theId",
        "someText"
    })
    @XmlRootElement(name = "myClass", namespace = "http://www.somedomain.tld/schema/myClass")
    public class MyClass {
     
        @XmlElement(namespace = "http://www.somedomain.tld/schema/myClass")
        protected int theId;
        @XmlElement(namespace = "http://www.somedomain.tld/schema/myClass", required = true)
        protected String someText;
     
        // getters and setters
    }
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Posts
    5
    Rep Power
    0
    So i generated JAXB classes from my xsd there stored in comx.
    I cant figure this out ive tried everything I'll post my full code here.
    Code:
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.StringReader;
    
    import comx.*;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Unmarshaller;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.stream.StreamSource;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    import comx.MachineResponse;
    
    public class APIrequest {
    
    	private BufferedReader in = null;
    	private DefaultHttpClient xmlclient = new DefaultHttpClient();
    	// private DefaultHttpClient textclient = new DefaultHttpClient();
    	private String getURL;
    	private String page;
    	private Document doc;
    	private String userToken = null, userID = null, accountID = null;
    	private String returnXML;
    	private NodeList accountList;
    	private MachineResponse machineResponse=null;
    	private InputStream is;
    
    	private String xmlString;
    	private InputStream stream;
    	
    	
    	
    	
    
    	// Constructs a request used for logging in
    	public APIrequest(String getURL) {
    
    		this.getURL = getURL;
    	}
    
    	// Constructs a request for every other API call which includes the
    	// user-token returned from the login request
    	public APIrequest(String getURL, String userToken) {
    
    		this.getURL = getURL;
    		this.userToken = userToken;
    
    	}
    
    	// Method which retrieves the xml feed from a HTTP request
    	public String getXML() {
    		// Create a new HTTP request with the provided URL
    		HttpUriRequest getRequest = new HttpGet(getURL);
    
    		// *************************************************************
    		// **************Adding user-token to HTTP header***************
    		// *************************************************************
    		if (userToken != null) {
    			getRequest.setHeader("mb-user-token", userToken);
    		}
    		// *************************************************************
    
    		page = "";
    		System.out.println("The requested URL is: " + getURL + "\n");
    		try {
    			// Create two responses which will stream separately to text and Xml
    			// document
    			HttpResponse response1 = xmlclient.execute(getRequest);
    			// HttpResponse response2 = textclient.execute(getRequest);
    
    			// Determine the status code of the HTTP request and act accordingly
    			int statusCode = response1.getStatusLine().getStatusCode();
    			System.out.println("The status code is:" + statusCode);
    
    			// If the statuscode = 200, then the request was returned
    			// successfully
    			if (statusCode == 200) {
    
    				HttpEntity entity = response1.getEntity();
    
    				
    				
    				
    				
    				ObjectFactory of = new ObjectFactory();
    				
    				DocumentBuilderFactory factory = DocumentBuilderFactory
    						.newInstance();
    				JAXBContext context = JAXBContext.newInstance(of.getClass());
    				stream = entity.getContent();
    				
    				
    					if(response1.getEntity() !=null){
    						
    						InputStream inputstream = entity.getContent();
    					
    						try {
    					        StringBuilder Str_builder = new StringBuilder();
    					         byte[]  readBuffer = new byte[8192];
    					         int bytesRead = 0;
    					         while( (bytesRead = inputstream.read(readBuffer)) != -1 ) {
    					            String nextString = new String( readBuffer, 0, bytesRead );
    					            Str_builder.append( nextString );
    					         }
    					         
    					         String XMLOBJECTS = Str_builder.toString();
    						
    					         JAXBContext jaxbContext = JAXBContext.newInstance(comx.MachineResponse.class);
    					         Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
    					      
    					         machineResponse = (MachineResponse) unMarshaller.unmarshal( new StreamSource( new StringReader( XMLOBJECTS ) ) ); 
    						
    				
    					
    					
    					DocumentBuilder builder = factory.newDocumentBuilder();
    					doc = builder.parse(entity.getContent());
    					returnXML = XMLtool.getStringFromDocument(doc);
    					
    				} catch (SAXException e) {
    					e.printStackTrace();
    				} catch (ParserConfigurationException e) {
    					e.printStackTrace();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    
    			}
    
    			// Print out error messages according to the status code returned
    			else if (statusCode == 400) {
    				page = "Bad Request \n The request could not be understood by the server due to malformed syntax";
    			}
    
    			else if (statusCode == 403) {
    				page = "The request was a legal request, but the server is refusing to repsond to it.";
    
    				HttpEntity entity1 = response1.getEntity();
    
    				DocumentBuilderFactory factory1 = DocumentBuilderFactory
    						.newInstance();
    	
    
    				
    				try {
    					
    					
    					DocumentBuilder builder = factory1.newDocumentBuilder();
    					doc = builder.parse(entity1.getContent());
    					returnXML = XMLtool.getStringFromDocument(doc);
    				
    
    				} catch (SAXException e) {
    					e.printStackTrace();
    				} catch (ParserConfigurationException e) {
    					e.printStackTrace();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    
    			}
    
    			else if (statusCode == 404) {
    				page = "Not Found \n The server has not found anything matching the Request-URI";
    			}
    
    			else if (statusCode == 408) {
    				page = "Request Timeout \n The client did not produce a request within the time that the server was prepared to wait.";
    			}
    
    			else if (statusCode == 500) {
    				page = "Internal Server Error \n The server encountered an unexpected condition which prevented it from fulfilling the request. ";
    			} else if (statusCode == 503) {
    				page = "Service Unavailable \n The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.";
    			} else {
    				page = "There was an unkown error";
    			}
    			System.out.println(page + "\n");
    			}
    			
    	
    			
    
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return returnXML;
    	}
    	
    
    	public Document getDocument() {
    		return doc;
    	}
    	public MachineResponse getResponse(){
    		return machineResponse;
    		
    		
    	}
    
    	// Method which gets the 'status' of the returned xml
    	public String getStatus() {
    
    		// Get the document containing the xml
    		Document doc = this.getDocument();
    
    		// Get the root element (usually 'machine-response')
    		Element e = doc.getDocumentElement();
    
    		// Get the child nodes of the root element
    		NodeList nl = e.getChildNodes();
    
    		// Traverse the child nodes in order to find the 'status' node
    		String nodeName = "";
    		String value = "";
    		int i;
    		int L = nl.getLength();
    		for (i = 0; i < L; i++) {
    			nodeName = nl.item(i).getNodeName();
    			if (nodeName.equals("status")) {
    				// When the status node is found, get the value found therein.
    				value = nl.item(i).getTextContent();
    				i = L;
    			} else {
    				value = "No status node present!";
    			}
    		}
    
    		return value;
    	}
    
    	// Method which gets the user-token associated with a user login
    	public String getUserToken() {
    
    		// Get the document containing the xml
    		Document doc = this.getDocument();
    
    		// Get the root element (usually 'machine-response')
    		Element e = doc.getDocumentElement();
    
    		// Get the child nodes of the root element
    		NodeList nl = e.getChildNodes();
    
    		// Traverse the child nodes in order to find the 'response' node
    		String nodeName = "";
    		String value = "";
    		int i;
    		int L = nl.getLength();
    		int nodeIndex = 0;
    		for (i = 0; i < L; i++) {
    			nodeName = nl.item(i).getNodeName();
    			if (nodeName.equals("response")) {
    				// When the response node is found, get the value found therein.
    				value = nl.item(i).getTextContent();
    				nodeIndex = i;
    				i = L;
    			} else {
    				value = "No response node present!";
    			}
    		}
    
    		// Once the response node has been located, find the login-token node
    		// and get the value therein
    		nl = nl.item(nodeIndex).getChildNodes();
    		L = nl.getLength();
    		for (i = 0; i < L; i++) {
    			nodeName = nl.item(i).getNodeName();
    			if (nodeName.equals("login-token")) {
    				// When the login-token node is found, get the value found
    				// therein.
    				value = nl.item(i).getTextContent();
    				i = L;
    			} else {
    				value = "No login-token node present!";
    			}
    		}
    		userToken = value;
    		return value;
    	}
    
    	public String getUserID() {
    		if (!userToken.equals("No login-token node present!")
    				&& (userToken.length() > 1)) {
    			// Extract userID from user token
    			int underscorePos = userToken.indexOf('_');
    			userID = userToken.substring(0, underscorePos);
    
    		}
    		return userID;
    	}
    
    	public String getAccountID() {
    		// get accountID from returned document
    		if (!userToken.equals("No login-token node present!")) {
    			// Extract accountID from xml
    			// Get the document containing the xml
    			Document doc = this.getDocument();
    
    			// Get the root element (usually 'machine-response')
    			Element e = doc.getDocumentElement();
    
    			// Get the child nodes of the root element
    			accountList = e.getElementsByTagName("account");
    			accountID = accountList.item(0).getAttributes().getNamedItem("id")
    					.getTextContent();
    
    		}
    		return accountID;
    	}
    }
    Thanks

IMN logo majestic logo threadwatch logo seochat tools logo