Parse streaming XML over a socket

Is it possible to parse XML incrementally over a socket connection? I would like to parse and respond dyanamically to streaming XML and I am looking for some direction. Everything that I have read so far with respect to parsing XML from files. Thanks in advance

You will want to look into a SAX parser, they are specifically intended for parsing xml over an input stream. They call callbacks to handle each element that arrives from the socket.
However, there are a lot of posts about the sax parsers hanging, and I just posted last week trying to find the cause/solution. I've seen a number of solutions posted, but none have worked in my case. No replies to my post yet.
Steve

Similar Messages

  • Streaming sound over a socket

    Does anyone know how to capture sound on a microphone and streamed over a socket connection to a remote machine. When the remote machine receives this it plays it directly to speakers.
    I don't want to capture a bit of sound and send a sound file I would like to be able to stream it like an internet phone.
    Does anyone know what would be the best way to go about doing this?

    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=&qt=%2Bvoice+%2Bover&x=13&y=2
    http://www.google.com/search?hl=en&lr=&ie=UTF-8&oe=UTF-8&q=%2Bvoice+%2Bover++%2Binternet

  • Streaming video over TCP (sockets)

    We are trying to stream only video files between a client and a server, but we don't know how. We are using sockets TCP to connect both systems and we would like to know if exists any class in Java that could be helpful for us, or if any of you has created a source code that could help us and give us ideas about how to continue.
    Thanks in advance

    If you want exact representations of the video files, that is, bit for bit equality from end to end, tcp is fine. But you say streaming, so you will want to have a look at the UDP. This transfer doesn't care if some bits are lost along the way.
    If you want tcp, you should use RMI to transfer your files.

  • XML parsing on messages over socket

    Hi,
    My java client gets the XML messages from server over a socket and I want to parse the message using the function parse(InputStream in) (for DOM parser) or parse(InputStream in, DefaultHandler h) (for SAX). But both these parsers are hanging and are waiting for end-of-file character which I guess is not possibl to send over a socket without closing the socket.
    Is there any way of making the parser not hang for input.
    Thanks
    Jeevan

    Have you tried to add the end of file character manually?
    // Some code left out here...
    char eof = (char)0x1A;
    // myXMLDocument is the document you want to send
    myXMLDocument += eof;
    //out is a PrintWriter object based on your OutputStream
    out.println(myXMLDocument);This worked for me!
    Regards,
    Erik.

  • Parsing XML from a socket that does not close

    Hi -
    I've seen similar questions to this already posted, but either they did not really apply to my situation or they were not answered.
    I have to read messages from a server and process them individually, but the protocol does not indicate the message length or give any sort of terminating character. You only know you have a complete message because it will be a well formed XML fragment. To complicate matters more, there could be extra binary data preceding each XML message. I must stress that I did not write this server, and I have no influence over the protocol at all, so while I certainly agree that this is not such a good protocol, changing it is not an option.
    I'm hoping that there is a reasonable way to deal with this with an existing parser. Ironically, I don't really need to parse the XML at all, I just need to know when the current message is over but the only indication I get is that it will be the end of an XML fragment.
    I do have the ability to strip off the non-XML binary data, so if there is some way that I can give the stream to a SAX (or other) parser when I know XML is coming and have it inform me when tags begin and end, or ideally inform me when it is done a complete XML fragment, that would be perfect. I'm aware of how to do this using SAX normally, but it seems that it will not function correctly when there is no EOF or other indication that the document has ended.
    The best algorithm I have come up with (and it's pretty cheesy) is:
    1. Start with a string buffer.
    2. Append data from the socket to the buffer one byte at a time.
    3. Keep checking if there is a '<' character that is not followed by '?' or '!'. (ie - don't concern myself with the special XML elements that don't close with '/>' or </tagName>. I keep them in the buffer to pass on when I'm done though.)
    4. When I get my first tag with <tagName> I make note of what this tag is and increment a counter. If the tag is self closing, then I'm done.
    5. Anytime I see this tag I increment the counter.
    6. Anytime I see </tagName> I decrement the counter. If the counter = 0, I am done.
    7. I pass on the entire message, preceding binary data, special XML tags and the fragment to the module that actually processes it.
    This has a few problems. I'll have to go out of my way to support multiple character encodings, I'll have to be careful to catch all the special XML tags, and its quite CPU intensive to be interested in every single character that comes down the pipe (but I suppose this is not avoidable). Also, I just don't like to re-invent the wheel because I'm likely to make an error that a well established parser would not make.
    Does anyone have any suggestions for this, or know of a parser that will deal with fragments using streams that don't close?
    Thanks!

    The parser expects to read to the end of the stream. If you closed the stream right after you wrote to it, I bet it would work. You wouldn't want to close the stream though would you? Try sending the string using a DataOuputStream and calling DataOutputStream.writeUTF(String) on the client side. Then, on the server side call String str = in.readUTF() (where 'in' is a DataInputStream). Then wrap the string in a StringReader and give the StringReader to the parser as it's input source.

  • Send XML over Sockets

    I am beginning and I need to send XML formatted data from Swing Client to Server for parsing/processing/and response.
    There are no web server available to use. I think its best to use socket connection, but how do I send xml data over socket, and how do I receive it from server and parse it?
    I have read and cannot find a similar example.

    Xerces has DOMSerializer which can be used to serialize a Document object to a string. Once it's a string it's trivial to transmit over a socket connection. On the other side, to parse it, you'll have to create a StringReader for the received string and then an InputSource from the StringReader. You'll then be able to pass the InputSource to the DocumentBuilder.parse( ) method to generate a Document on the receiving side.
    Hope that helps,
    - Jesse

  • XML query over a socket

    I can't seem to find any thing anywhere about doing this. I was want to be able to send a query:
    <?xml version="1.0"?>
    <query />
    to a remote server (which will return a bunch of results). I've created an in/out socket... but that's about it.

    Simple POST xml java client, takes URL and a number of terms as argument, constructs query document, sends it to server and echos response to standard output:import java.io.*;
    import java.net.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    public class PostXml {
      public static void main (String[] args) {
        try {
          final Document queryDocument = XmlUtils.createDocument("", "query");
          final Element root = queryDocument.getDocumentElement();
          for (int index = 1; index < args.length; index++) {
            XmlUtils.addTextElement(root, "", "term", args[index]);
          XmlUtils.echoXml(XmlUtils.parse(postXml(args[0], queryDocument)), System.out);
        } catch (Exception ex) {
          ex.printStackTrace(System.out);
      public static InputStream postXml (String targetURL, Document document ) throws IOException {
        final URLConnection connection = new URL(targetURL).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("content-type", "application/xml");
        XmlUtils.echoXml(document, connection.getOutputStream());
        return connection.getInputStream();
    }Servlet parses xml input and returns xml document based on the content:import java.io.IOException;
    import java.io.Writer;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    public class QueryServlet extends HttpServlet {
      public void doPost (final HttpServletRequest request,
                          final HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("application/xml");
        try {
          final Document queryDocument = XmlUtils.parse(request.getInputStream());
          final Element queryElement = queryDocument.getDocumentElement();
          final NodeList terms = queryElement.getElementsByTagName("term");
          final Document responseDocument = XmlUtils.createDocument("", "response");
          final Element responseElement = responseDocument.getDocumentElement();
          for (int index = 0; index < terms.getLength(); index++) {
            XmlUtils.addTextElement(responseElement, "", "recieved", XmlUtils.textValue(terms.item(index)));
          XmlUtils.echoXml(responseDocument, response.getOutputStream());
        } catch (XmlException xe) {
          XmlUtils.echoXml(XmlUtils.errorDocument(xe), response.getOutputStream());
      public void doGet (final HttpServletRequest request,
                         final HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        final Writer out = response.getWriter();
        out.write("use POST");
    }Utilities to hide much DOM cruft and checked exception proliferation:import java.io.InputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.xml.sax.SAXException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMImplementation;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    * Some of this removes oddities in DOM; most is wrapping exceptions so
    * that the different toolkits throw the same exception for like operations.
    public class XmlUtils {
      static final DocumentBuilderFactory documentBuilderFactory;
      static final DOMImplementation domImplementation;
      static {
        DocumentBuilderFactory factory = null;
        DOMImplementation domI = null;
        try {
          factory = DocumentBuilderFactory.newInstance();
          domI = factory.newDocumentBuilder().getDOMImplementation();
        } catch (ParserConfigurationException pce) {
          // log it
        documentBuilderFactory = factory;
        domImplementation = domI;
      private static Transformer nullTransform;
      public static void echoXml (final Document document, final OutputStream out) throws IOException {
        try {
          if (nullTransform == null) {
            final TransformerFactory factory = TransformerFactory.newInstance();
            nullTransform = factory.newTransformer();
          nullTransform.transform(new DOMSource(document), new StreamResult(out));
        } catch (TransformerException te) {
          final IOException ioe = new IOException("failed to write document to stream");
          ioe.initCause(te);
          throw ioe;
      public static Document errorDocument (final Throwable error) {
        try {
          final Document errorDocument = createDocument();
          errorDocument.appendChild(errorElement(errorDocument, error));
          return errorDocument;
        } catch (XmlException xe) {
          // as this is called to provide a document representing an error
          // during error handling, throwing anything could cause a loop
          return null;
      static Element errorElement (final Document document, final Throwable error) {
        final Element errorElement = document.createElementNS("", "error");
        addTextElement(errorElement, "", "class", error.getClass().getName());
        final StackTraceElement[] stack = error.getStackTrace();
        for (int index = 0; index < stack.length; index++) {
          addTextElement(errorElement, "", "stack", stack[index].toString());
        if (error.getCause() != null) {
          final Element causedBy = document.createElementNS("", "caused-by");
          causedBy.appendChild(errorElement(document, error.getCause()));
          errorElement.appendChild(causedBy);
        return errorElement;
      public static Element addTextElement (final Element parent, final String url, final String qname, final String content) {
        final Document document = parent.getOwnerDocument();
        final Element child = document.createElementNS(url, qname);
        child.appendChild(document.createTextNode(content));
        parent.appendChild(child);
        return parent;
      public static String textValue (final Node node) {
        switch (node.getNodeType()) {
          case Node.CDATA_SECTION_NODE:
          case Node.TEXT_NODE : return node.getNodeValue();
          default: return concat(node.getChildNodes(), new StringBuffer()).toString();
      public static StringBuffer concat (final NodeList nodelist, final StringBuffer buffer) {
        for (int index = 0, length = nodelist.getLength(); index < length; index++) {
          final Node node = nodelist.item(index);
          switch (node.getNodeType()) {
            case Node.CDATA_SECTION_NODE:
            case Node.TEXT_NODE : {
              buffer.append(node.getNodeValue());
              break;
            case Node.ELEMENT_NODE: {
              concat(node.getChildNodes(), buffer);
              break;
        return buffer;
      public static Document parse (InputStream stream) throws XmlException, IOException {
        try {
          return documentBuilderFactory.newDocumentBuilder().parse(stream);
        } catch (SAXException saxe) {
          throw new XmlException(saxe);
        } catch (ParserConfigurationException pce) {
          throw new XmlException(pce);
      public static Document createDocument (String url, String qname) {
        return domImplementation.createDocument(url, qname, null);
      public static Document createDocument () throws XmlException {
        try {
          return documentBuilderFactory.newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException pce) {
          throw new XmlException(pce);
    }

  • How to parse a XML stream sent to servlet with PUT method

    Hi,
    I have to interface my servlet app with other apps communicating with XML.
    This way, My servlet will receive a XML stream in the http request, parse it and send back a XML message.
    What I've done is :
    An html page to send a XML File with a put method :
    <form enctype="multipart/form-data" method="PUT" action="http://localhost:8080/MyApp/servlet/TestUploadServlet">
         <input type="file" size="20" name="FileToUpload" value="Select File">
         <input type="submit" name="UploadFile" value="Upload">
         <input type="reset" value="Reset">
    </form>
    A servlet TestUploadServlet with :
    SAXParser parser = new SAXParser( );
    Trace.traceLine( "SAXParser" );
    parser.setContentHandler (this);
    try {
    parser.parse( new InputSource( requete.getInputStream() ) );
    catch (SAXException e) {
    Trace.traceLine( e.getMessage() );
    catch (IOException e) {
    Trace.traceLine( e.getMessage() );
    and the methods startElement, stopElement and other to work with the elements detected by the parser (already used by other programs parsing local xml files).
    And it doesn't work.
    is the html code is a good way to send a file in the http Put method ?
    is the parser.parse( new InputSource( requete.getInputStream() ) ); a good method to read the stream ?
    please help.

    I think the problemn comes from the method used to send the <XML> stream.
    Using an html form doesn't seem to be a good method.
    I tried several methods or examples found and none of them seems to work.
    here is another example in the servlet side :
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream output = res.getOutputStream();
    output.println("ContentType: " + req.getContentType() + "<BR>");
    int content_length = req.getContentLength();
    output.println("ContentLength: " + content_length + "<BR>");
    if(content_length > 0) {
    output.println("Content: ");
    ServletInputStream input = req.getInputStream();
    byte [] buffer = new byte[1024];
    int nb;
    while((nb=input.read(buffer))!= -1) {
    output.write(buffer,0,nb);
    Can somebody tell me how to write a java code sending a http request with the content of a file in the content of the request ?

  • Write updated Object with ObjectOutput Stream over a socket

    Hello,
    i would like to use an ObjectOutput Stream ot write over a socket between 2 process. But each time the object is modified on a given process i would like to resend it to the other in order to get the object updated.
    My porblem is that the object is never retrieved in its modified state on the second process.
    here is the class that i'm using to send and receive objects.
    On the server it is instanciated with serverMode=true and false on the client
    public class GameClient extends Thread
         private String m_servername="";
         private int m_serverport=0;
         private ObjectOutputStream m_oos = null;
         private ObjectInputStream m_ois = null;
         private Socket m_socket = null;
         private ServerSocket m_serverSocket = null;
         private Vector<INetworkController> m_listeners = new Vector<INetworkController>();
         private static final Trace trace = new Trace("SimpleClient");
         private boolean m_serverMode=false;
         public GameClient(String serverName,int port,boolean serverMode) throws IOException, UnknownHostException
              try
                   m_serverMode = serverMode;
                   m_servername=serverName.trim();
                   m_serverport=port;
                   if (m_serverMode)
                        m_serverSocket = new ServerSocket( m_serverport);
                   else
                        m_socket = new Socket(m_servername, m_serverport);
                        m_oos = new ObjectOutputStream(m_socket.getOutputStream());
                        m_ois = new ObjectInputStream(m_socket.getInputStream());
                   start();
              catch (BindException e)
                   e.printStackTrace();
                   String message = "Impossible de lancer le serveur. Un autre process �coute d�j� sur ce port";
                   System.exit(0);
         public void run()
              try
                   if (m_serverMode)
                        Socket client = m_serverSocket.accept();
                        m_oos = new ObjectOutputStream(client.getOutputStream());
                        m_ois = new ObjectInputStream(client.getInputStream());
              catch(Exception e)
                   e.printStackTrace();
              trace.startMethod("run()");
              trace.println("Listening Client Thred started");
              while(true)
                   try
                        Event serverMessage = (Event) m_ois.readObject();
                        trace.println("Waiting for message");
                        dispatchEvent(serverMessage);
                        trace.println("Message Reveived");
                   catch(Exception e)
                        String message = "La connexion r�seau a �t� perdue";
                        e.printStackTrace();
                        trace.endMethod();
                        try
                             if(m_socket!=null)
                                  m_socket.close();
                             if (m_serverSocket!=null)
                                  m_serverSocket.close();
                             m_oos.close();
                             m_ois.close();
                        catch (Exception e2)
                             e2.printStackTrace();
                        return;
         private int m_counter=0;
         public void sendNetworkMessage(Event msg)throws IOException, UnknownHostException
              if (m_oos != null)
                   m_oos.writeObject(msg);     
                   m_oos.flush();
                   //m_oos.reset();
              time = System.currentTimeMillis()-time;
              trace.endMethod();
         }Each time an object can be read, the read object is dispatch with the method dsiaptchEvent() which is not described here...
    I do not inderstand what's wrong in here
    Edited by: Voldor on Oct 16, 2007 4:10 PM

    Thanks but if i uncomment m_oos.reset() each time i write something on the socket (on the client or on the server) it is more and more longer to retrieve the writeen object on the other side of the socket (more than 40 sec after 12 messages exchanged, 6 coming from the server and 6 form the client)
    and after all i got the following
    java.lang.ArrayIndexOutOfBoundsException
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(Unknown Source)
         at java.net.SocketInputStream.read(Unknown Source)
         at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
         at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
         at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at dt.communication.GameClient.run(GameClient.java:78)Do you have any idea ? Any recommandation about when to call reset ?
    Edited by: Voldor on Oct 16, 2007 4:44 PM

  • Connection refused Exception parsing an xml on a network drive

    I am getting a "java.net.ConnectException: Connection refused: connect" exception when I try to parse an xml file over a network drive with a url like "\\Host\shared\file.xml". The problem only happens if I use a full qualified url to the file, if I map the drive to the local server then it works fine. This means that "\\Host\shared\file.xml" fails while "G:\file.xml" works but the two point to the same file. The other thing is that it fails for JDK 1.4.0 but works file for JDK1.3.1. Same program, same classpath, same server: it works with JDK1.3.1 but throws the exception for JDK1.4.0. Following is the full exception trace:
    java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:295)
    at java.net.PlainSocketImpl.connectToAddress PlainSocketImpl.java:161)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:148)
    at java.net.Socket.connect(Socket.java:425)
    at java.net.Socket.connect(Socket.java:375)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:139)
    at sun.net.NetworkClient.openServer(NetworkClient.java:118)
    at sun.net.ftp.FtpClient.openServer(FtpClient.java:387)
    at sun.net.ftp.FtpClient.<init>(FtpClient.java:651)
    at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.ja
    va:175)
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnec
    tion.java:257)
    at java.net.URL.openStream(URL.java:955)
    at org.apache.xerces.readers.DefaultReaderFactory.createReader(DefaultRe
    aderFactory.java:149)
    at org.apache.xerces.readers.DefaultEntityHandler.startReadingFromDocume
    nt(DefaultEntityHandler.java:491)
    at org.apache.xerces.framework.XMLParser.parseSomeSetup(XMLParser.java:3
    12)
    at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1080)
    at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1122)

    From the stack trace posted it appears that URL.openStream decided to use FTP to access the file. Of course that won't work. But the key is that a URL is expected, at least that's what I infer from this line:
    at java.net.URL.openStream(URL.java:955)
    And \\Host\shared\file.xml isn't a URL. Looks like 1.4 has fixed something which broke that shortcut. Change it to a real URL, something like
    file:////Host/shared/file.xml
    Four / is probably correct, although you may have to try it with three.

  • Basic Question: plain XML over HTTP

    I would be getting messages in plain XML over HTTP. What should I use to receive those messages. Server is not SOAP based, so client cannot be SOAP based. Should I use JAX-RPC, but when I looked at the documentation, it is giving info regarding SOAP and plain xml over http. Can anyone help me?
    Thanks

    From my understanding, you would be getting a plain xml string by connecting to a server over http.
    You can is DOM or SAX apis to parse this xml input stream.
    For eg: if you are using DOM apis, then you can pass the input stream of the HttpURLConnection as follow...
         DocumentBuilderFactory buildFactory = DocumentBuilderFactory.newInstance();
         buildFactory.setIgnoringElementContentWhitespace(false);
         buildFactory.setValidating(false);
         DocumentBuilder docBuilder = buildFactory.newDocumentBuilder();
         URL url=new URL("http://someserver.com/abc.jsp");
         HttpURLConnection conn= (HttpURLConnection)url.openConnection();
         InputStream in= conn.getInputStream();
         Document doc = docBuilder.parse(in);
         ..Hope this helps...

  • Parseing an XML Document as a String

    Hi all,
    i am trying to parse an XML document to a parser. I get the file as a request parameter, which is filled in to at String variable.
    But for some reason i get an SAXException, does anyone se the problem?
    Thank you for your help...
    Below is the code
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.text.*;
    import java.net.*;
    import java.net.URL;
    import java.sql.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import javax.xml.parsers.*;
    import javax.xml.transform.stream.StreamSource;
    public class StartServlet extends HttpServlet
    private boolean debug = true;
    private final static String CONTENT = "content";
    private final static String COOKIES = "cookies";
    String resp = new String();
    private static String NODE_TYPES[] = new String[] {
         "ELEMENT",
         "ATTRIBUTE",
         "TEXT",
         "CDATA_SECTION",
         "ENTITY_REFERENCE",
         "ENTITY",
         "PROCESSING_INSTRUCTION",
         "COMMENT",
         "DOCUMENT",
         "DOCUMENT_TYPE",
         "DOCUMENT_FRAGMENT",
         "NOTATION" };
    public static void println(String s, int indent) {
         for(int i = 0 ; i < indent; i++) {
                   System.out.println(" ");
         System.out.println(s);
    public static void println(String s) {
         System.out.println(s);
    public static void print(Node node){
         printImpl(node, 0);
    public static void printImpl(Node node, int indent){
         if(node == null) {
              return;
         String nodeType = NODE_TYPES[node.getNodeType()];
         String nodeName = node.getNodeName();
         String nodeValue = node.getNodeValue();
         if(nodeValue != null) {
              nodeValue = nodeValue.trim();
         if(nodeType.equals("TEXT") && nodeValue.equals("")) {
              ; //Ignore emty node
         else {
              println(nodeType + " - " + nodeName + " - " + nodeValue, indent);
         NamedNodeMap attributes = node.getAttributes();
         if (attributes != null) {
              for(int i = 0; i < attributes.getLength(); i++) {
                   printImpl(attributes.item(i), indent + 1);
         NodeList children = node.getChildNodes();
         if(children != null) {
              for(int i = 0; i < children.getLength(); i++){
                   printImpl(children.item(i), indent + 1);
    public static DocumentBuilder newBuilder(boolean validation)
                        throws ParserConfigurationException {
         DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
         domFactory.setValidating(validation);
         domFactory.setNamespaceAware(true);
         DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
         //domBuilder.setErrorHandler(new PrintErrorHandler());
         return domBuilder;
    public static Document newDocument()
                        throws ParserConfigurationException{
         DocumentBuilder domBuilder = newBuilder(false);
         Document document = domBuilder.newDocument();
         return document;
    public static Document parse( String xml, boolean validation)
                        throws ParserConfigurationException, IOException, SAXException {
              DocumentBuilder domBuilder = newBuilder(validation);
              Document document = domBuilder.parse(xml);
              return document;
    public void init() {
    public void service( javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) {
              String[] cookies = null;
              try{
                   Hashtable document = getDocument("http://.../first.xml", cookies);
                   resp = (String) document.get(CONTENT);
                   debug(resp);
                   print(parse(resp, false));
              catch (SAXParseException e){
                   System.out.println("Saxfejl");
                   //System.exit(1);
              catch (Exception e){
                   e.printStackTrace();
                   System.exit(1);
    public void debug(String msg) {
         if(debug) {
              System.out.println(msg);
    public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
         try
              // Insert user code from here.
         catch(Throwable theException)
              // uncomment the following line when unexpected exceptions
              // are occuring to aid in debugging the problem.
              //theException.printStackTrace();
    public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
         performTask(request, response);
    public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
         performTask(request, response);
    private Hashtable getDocument(String urlCode, String[] oldCookies) {
         Hashtable document = new Hashtable();
         HttpURLConnection http = null;
         try {
              URL httpURL = new URL(urlCode);
              // If HTTP Protocol, then open connection using the Request method indicated
              URLConnection conn = httpURL.openConnection();
              http = (HttpURLConnection) conn;
              //http.setRequestMethod("GET");
              http.setDoInput(true);
              http.setDoOutput(true);
              http.setUseCaches(false);
              http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
              if (oldCookies != null) {
                   for (int j = 0; j < oldCookies.length; j++) {
                        String cookie = oldCookies[j];
                        http.setRequestProperty("Cookie", cookie);
              http.connect();
              http.getContent();
              StringBuffer tsb = new StringBuffer("");
              if (http.getResponseCode() == 200) {
                   InputStream cis = http.getInputStream();
                   byte[] a = new byte[1024];
                   int n = cis.read(a);
                   while (n >= 0) {
                        tsb.append(new String(a, 0, n));
                        n = cis.read(a);
                   cis.close();
                   document.put(CONTENT, tsb.toString());
              String[] cookies = null;
              if (cookies == null) {
                   int headerFieldIndex = 0;
                   String headerFieldValue = http.getHeaderField(headerFieldIndex);
                   Vector cookieValues = new Vector();
                   while (headerFieldValue != null) {
                        String headerFieldName = http.getHeaderFieldKey(headerFieldIndex);
                        if ((headerFieldName != null) && headerFieldName.toLowerCase().equals("set-cookie")) {
                             int index = headerFieldValue.indexOf(";");
                             if (index > -1) {
                                  headerFieldValue = headerFieldValue.substring(0, index);
                             cookieValues.addElement(headerFieldValue);
                        headerFieldValue = http.getHeaderField(++headerFieldIndex);
                   cookies = new String[cookieValues.size()];
                   cookieValues.copyInto(cookies);
              document.put(COOKIES, cookies);
         catch (Exception e) {
              debug("url problem" + e);
         finally {
              if (http != null) {
                   http.disconnect();
         return document;
    }

    Hi,
    Use this code it will helpful to you.
    resultXMLDocument=(XmlDocument)documentDoc;
    StringWriter sw = new StringWriter();
    resultXMLDocument.write((Writer) sw);
    xmlString=sw.toString();
    thnaks,
    suneel

  • B2B-51566 Description: Parse stream error with RosettaNet 1.1

    Hi
    Need help with the following error message
    B2B-51566 Parse stream error
    We have a trading partner set up to use RosettaNet 1.1 protocol and we are getting 51566 error. We are NOT experiencing this error with a trading partner who is in RosettaNet 2.0
    we are currently patched up to 11.1.1.5
    One thing I notice is when i go to the message and open the packed message i get this "Cannot display Packed Message in binary format."
    Here is the payload
    XMessage-ID: <[email protected]d.e2open.com>
    MIME-Version: 1.0
    Content-Type: multipart/related;
         boundary="----=_Part_176_29725195.1331307008851";
         type="Application/x-RosettaNet"
    Content-Description: This is the RosettaNet Business Message
    Content-ID: "-15059242:135f6ea5e3c:-62b9"
    ------=_Part_176_29725195.1331307008851
    Content-Type: Application/xml; rnsubtype=preamble-header; name=Preamble
    Content-Transfer-Encoding: binary
    Content-Disposition: attachment; filename=Preamble
    Content-ID: <[email protected]>
    Content-Description: This is the Preamble Header part of the Business Message
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE Preamble SYSTEM "PreamblePartMessageGuideline.dtd">
    <Preamble>
    <DateTimeStamp>20120309T153008.852Z</DateTimeStamp>
    <GlobalAdministeringAuthorityCode>RosettaNet</GlobalAdministeringAuthorityCode>
    <GlobalUsageCode>Production</GlobalUsageCode>
    <VersionIdentifier>1.1</VersionIdentifier>
    </Preamble>
    ------=_Part_176_29725195.1331307008851
    Content-Type: Application/xml; rnsubtype=service-header; name=ServiceHeader
    Content-Transfer-Encoding: binary
    Content-Disposition: attachment; filename=ServiceHeader
    Content-ID: <[email protected]>
    Content-Description: This is the Service Header part of the Business Message
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ServiceHeader SYSTEM "ServiceHeaderPartMessageGuideline.dtd">
    <ServiceHeader>
    <ProcessControl>
    <ProcessIdentity>
    <description>
    <FreeFormText>NotNull</FreeFormText>
    </description>
    <GlobalProcessCode>Request Purchase Order</GlobalProcessCode>
    <GlobalProcessIndicatorCode>3A4</GlobalProcessIndicatorCode>
    <initiatingPartner>
    <GlobalBusinessIdentifier>007710825</GlobalBusinessIdentifier>
    </initiatingPartner>
    <InstanceIdentifier>PIPC0A85CB8135F814CB4200000EAFE56F0</InstanceIdentifier>
    <VersionIdentifier>V02.00</VersionIdentifier>
    </ProcessIdentity>
    <ServiceRoute>
    <fromService>
    <BusinessServiceDescription>
    <GlobalBusinessServiceCode>Seller Service</GlobalBusinessServiceCode>
    </BusinessServiceDescription>
    </fromService>
    <toService>
    <BusinessServiceDescription>
    <GlobalBusinessServiceCode>Buyer Service</GlobalBusinessServiceCode>
    </BusinessServiceDescription>
    </toService>
    </ServiceRoute>
    <TransactionControl>
    <AttemptCount>1</AttemptCount>
    <PartnerRoleRoute>
    <fromRole>
    <PartnerRoleDescription>
    <GlobalPartnerRoleClassificationCode>Seller</GlobalPartnerRoleClassificationCode>
    </PartnerRoleDescription>
    </fromRole>
    <toRole>
    <PartnerRoleDescription>
    <GlobalPartnerRoleClassificationCode>Buyer</GlobalPartnerRoleClassificationCode>
    </PartnerRoleDescription>
    </toRole>
    </PartnerRoleRoute>
    <TransactionIdentity>
    <GlobalTransactionCode>Request Purchase Order</GlobalTransactionCode>
    <InstanceIdentifier>TIC0A85CB8135F814CB4200000EAFE5700</InstanceIdentifier>
    </TransactionIdentity>
    <SignalControl>
    <inResponseTo>
    <ActionIdentity>
    <GlobalBusinessActionCode>Purchase Order Request Action</GlobalBusinessActionCode>
    <InstanceIdentifier>C0A85CB8135F814C33C00000EAFE5670</InstanceIdentifier>
    </ActionIdentity>
    </inResponseTo>
    <InstanceIdentifier>20120309T153008.882Z</InstanceIdentifier>
    <PartnerRoute>
    <fromPartner>
    <PartnerDescription>
    <BusinessDescription>
    <GlobalBusinessIdentifier>364132837</GlobalBusinessIdentifier>
    </BusinessDescription>
    <GlobalPartnerClassificationCode>null</GlobalPartnerClassificationCode>
    </PartnerDescription>
    </fromPartner>
    <toPartner>
    <PartnerDescription>
    <BusinessDescription>
    <GlobalBusinessIdentifier>007710825</GlobalBusinessIdentifier>
    </BusinessDescription>
    <GlobalPartnerClassificationCode>null</GlobalPartnerClassificationCode>
    </PartnerDescription>
    </toPartner>
    </PartnerRoute>
    <SignalIdentity>
    <GlobalBusinessSignalCode>Receipt Acknowledge</GlobalBusinessSignalCode>
    <VersionIdentifier>1.1</VersionIdentifier>
    </SignalIdentity>
    </SignalControl>
    </TransactionControl>
    </ProcessControl>
    </ServiceHeader>
    ------=_Part_176_29725195.1331307008851
    Content-Type: Application/xml; rnsubtype=service-content;
         name=ReceiptAcknowledgement
    Content-Transfer-Encoding: binary
    Content-Disposition: attachment; filename=ReceiptAcknowledgement
    Content-ID: <[email protected]>
    Content-Description: This is the Service Content part of the Business Message
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ReceiptAcknowledgement SYSTEM "ReceiptAcknowledgementMessageGuideline.dtd">
    <ReceiptAcknowledgement>
    <fromRole>
    <PartnerRoleDescription>
    <ContactInformation>
    <contactName>
    <FreeFormText>E2open Support</FreeFormText>
    </contactName>
    <EmailAddress>[email protected]</EmailAddress>
    <telephoneNumber>
    <CommunicationsNumber>650-381-6000</CommunicationsNumber>
    </telephoneNumber>
    </ContactInformation>
    <GlobalPartnerRoleClassificationCode>Seller</GlobalPartnerRoleClassificationCode>
    <PartnerDescription>
    <BusinessDescription>
    <GlobalBusinessIdentifier>364132837</GlobalBusinessIdentifier>
    <GlobalSupplyChainCode>Information Technology</GlobalSupplyChainCode>
    </BusinessDescription>
    <GlobalPartnerClassificationCode>null</GlobalPartnerClassificationCode>
    </PartnerDescription>
    </PartnerRoleDescription>
    </fromRole>
    <receivedDocumentDateTime>
    <DateTimeStamp>20120309T153008.907Z</DateTimeStamp>
    </receivedDocumentDateTime>
    <receivedDocumentIdentifier>
    <ProprietaryDocumentIdentifier>337719</ProprietaryDocumentIdentifier>
    </receivedDocumentIdentifier>
    <thisMessageDateTime>
    <DateTimeStamp>20120309T153008.904Z</DateTimeStamp>
    </thisMessageDateTime>
    <thisMessageIdentifier>
    <ProprietaryMessageIdentifier>20120309T153008.905Z</ProprietaryMessageIdentifier>
    </thisMessageIdentifier>
    <toRole>
    <PartnerRoleDescription>
    <GlobalPartnerRoleClassificationCode>Buyer</GlobalPartnerRoleClassificationCode>
    <PartnerDescription>
    <BusinessDescription>
    <GlobalBusinessIdentifier>007710825</GlobalBusinessIdentifier>
    <GlobalSupplyChainCode>Information Technology</GlobalSupplyChainCode>
    </BusinessDescription>
    <GlobalPartnerClassificationCode>null</GlobalPartnerClassificationCode>
    </PartnerDescription>
    </PartnerRoleDescription>
    </toRole>
    </ReceiptAcknowledgement>
    ------=_Part_176_29725195.1331307008851--

    I do have SR but hoping i can get quicker answer hereYou may always escalate the SR if you are not getting response timely. Anyways, give the reference of this thread in the SR and ask service engineer to file a bug.
    I will email you the wire messageI saw the wire message you mailed across. There are some junk characters in the starting of the payload and that's why parsing is failing. Most probably it is a BOM (Byte Order Mark). Ask your TP to send messages in UTF-8 encoding without BOM or any other junk character in the starting of the message. You may open the wire message payload you mailed across in notepad or textpad and you will able to see those junk characters in the starting of the payload.
    Regards,
    Anuj

  • Parsing an XML doc with unavailable entity (DTD)

    Hi all,
    I am trying to parse an XML file (web.xml) that has the following DOCTYPE in the head of the document:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app id="WebApp">When the parser starts, it will look for the DTD on the Sun site, however my work firewall blocks access to this so I get an exception when parsing.
    To resolve this, I have tried to force the parser to look for a local copy of the DTD instead of the Sun site but to no avail. I still get the same error but don't know why it wont look at the local DTD.
    Here is my code:
    * InterceptingXml.java
    * Created on 04 April 2006, 15:58
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package org.xmldemos;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.xml.sax.EntityResolver;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    * @author CS781RJ
    public class InterceptingXml
        /** Creates a new instance of InterceptingXml */
        public InterceptingXml() { }
        public void parse(String filename)
            try
                // Create an XML parser
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                // Install the entity resolver
                builder.setEntityResolver(new MyResolver());
                // Parse the XML file
                Document doc = builder.parse(new File(filename));
            catch (SAXException e) { e.printStackTrace(); }
            catch (ParserConfigurationException e) { e.printStackTrace(); }
            catch (IOException e) { e.printStackTrace(); }
            catch (Exception e) { e.printStackTrace(); }
        public class MyResolver implements EntityResolver
            // This method is called whenever an external entity is accessed
            // for the first time.
            public InputSource resolveEntity(String publicId, String systemId)
                try
                    System.out.println("publicId: " + publicId + " systemId: " + systemId);
                    // Wrap the systemId in a URI object to make it convenient
                    // to extract the components of the systemId
                    URI uri = new URI(systemId);
                    System.out.println("URI scheme: " + uri.getScheme());
                    System.out.println("URI scheme specific: " + uri.getSchemeSpecificPart());
                    // Check if external source is a file
                    if ("http".equals(uri.getScheme()))
                        String filename = uri.getSchemeSpecificPart();
                        filename = "file:/C:/web-app_2_3.dtd";
                        InputSource isrc = new InputSource(new FileReader(filename));
                        return isrc;
                catch (URISyntaxException e) { }
                catch (IOException e) { }
                // Returning null causes the caller to try accessing the systemid
                return null;
        public static void main(String[] args)
            InterceptingXml ixml = new InterceptingXml();
            ixml.parse("c:\\web.xml");
    }And here is the exception:
    init:
    deps-jar:
    compile-single:
    run-single:
    publicId: -//Sun Microsystems, Inc.//DTD Web Application 2.3//EN systemId: http://java.sun.com/dtd/web-app_2_3.dtd
    URI scheme: http
    URI scheme specific: //java.sun.com/dtd/web-app_2_3.dtd
    java.net.UnknownHostException: java.sun.com
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
            at java.net.Socket.connect(Socket.java:507)
            at java.net.Socket.connect(Socket.java:457)
            at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
            at sun.net.www.http.HttpClient.openServer(HttpClient.java:365)
            at sun.net.www.http.HttpClient.openServer(HttpClient.java:477)
            at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
            at sun.net.www.http.HttpClient.New(HttpClient.java:287)
            at sun.net.www.http.HttpClient.New(HttpClient.java:299)
            at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:792)
            at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:744)
            at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:669)
            at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:913)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:973)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:905)
            at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:872)
            at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:282)
            at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(XMLDocumentScannerImpl.java:1021)
            at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
            at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)
            at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
            at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
            at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:250)
            at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:292)
            at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:172)
            at org.xmldemos.InterceptingXml.parse(InterceptingXml.java:45)
            at org.xmldemos.InterceptingXml.main(InterceptingXml.java:88)
    BUILD SUCCESSFUL (total time: 18 seconds)I have noticed that return isrc; does not get executed even though the debugger steps to the line above it.
    Thanks in advance.
    Riz

    What's the point of all that code in your EntityResolver? Would the code work just as well if the DTD didn't even exist? Then do this:public InputSource resolveEntity(String publicId, String systemId)
                return new InputSource(new StringReader(""));
            }However if you really do need to redirect to a local copy of the DTD then consider this:catch (IOException e) { }can be a real barrier to understanding in the case that an IOException is thrown. At least print a stacktrace. And: the FileReader class wants a file name in its constructor, not a URI. And in this code:String filename = uri.getSchemeSpecificPart();
    filename = "file:/C:/web-app_2_3.dtd";you could write this instead:String filename = "file:/C:/web-app_2_3.dtd";which would be both shorter and easier to understand.

  • Problem in parsing a xml string using dom parser

    i want to parse a Xml String using a Dom parser......the parse function in dom parser takes only input stream as argument.......so i made the code as
    InputStream inputstream = new StringBufferInputStream(XmlData) ;
    InputSource inputSource = new InputSource(inputstream );
    but saxexception is coming and also warning called
    "java.io.StringBufferInputStream in java.io has been deprecated"
    please help me.........

    i want to parse a Xml String using a Dom
    parser......the parse function in dom parser takes
    only input stream as argument.......This is not true of the DOM parser in Java 1.4. So you might want to get rid of your old parser and replace it by something more current. Or perhaps you are using 1.4 and you just didn't read all of the API docs.

Maybe you are looking for

  • I can't open a new tab by clicking on a tab - I think some dodgy software has stopped it

    I was trying out a pdf converter - Babylon. It did 2 things to Firefox: 1. It created this as my home page (I can fix this) http://search.babylon.com/home?AF=10588 2. I can no longer click and launch a new tab- in Tools Options Tabs I have all 5 boxe

  • No Display, just blank screen in itunes store ver. 10.7

    Hi All, so when i log into itunes Store i get a blank screen in the middle.  the side bar shows, but the middle is blank and the little tool bar with home, music, appstore etc also not there. i am using windows 7 and upgraded to latest itunes 10.7 it

  • Mouse events during Thread.sleep

    hi. I have an applet . I have a alghoritm simulator. Everytime I find a solution I call the method Thread.sleep . I want to pause the application and I create a JToggleButton Pause . When I press the Pause during sleep mouse event are managed at the

  • Portege R500 - Bluescreen after installing WXP SP3

    *laptop toshiba Portege R500* *model-no ppr50e00j00fs4* Installed SP3 via update-site, got message SP3 sucessfull installed please restart ... now bluescreen an no possibility to restart! Not even in save mode! If I try to start with the installation

  • Reconciliation does not provision??

    According to what I have read from a doc: Reconciliation only updates Identity Manager users and the account index; it does not fetch or provision other resource accounts for performance reasons. I don't quite get it. If I have an authoritative resou