Resolving "IOException: Underlying input stream returned zero bytes" errors

Hi guys,
I'm currently working on a simple application that reads GPS receiver data from a serial port using the RXTX library. However, everytime I try to read the resulting InputStream (which I convert to a BufferedReader) using readLine(), after 2 or 3 lines of reading normally, I always get the following exception:
GPSNotifier::run(): I/O error encountered while reading from COM4
java.io.IOException: Underlying input stream returned zero bytes
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:268)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at discomm.gps.GPSNotifier.run(GPSNotifier.java:260)
at java.lang.Thread.run(Thread.java:619)
I'm not sure how to fix this problem, since it occurs everytime I run the application. The code for opening the stream is as follows:
// Open up the port: no problems here ...
CommPortIdentifier comm = CommPortIdentifier.getPortIdentifier(port_name);
CommPort port = comm.open(APP_NAME, OPEN_TIMEOUT);
SerialPort serial_port = (SerialPort) port;
serial_port.setSerialPortParams(PORT_BAUDRATE, PORT_DATABITS, PORT_STOPBITS, PORT_PARITY);
BufferedReader in = BufferedReader(new InputStreamReader(serial_port.getInputStream()));
String line = null;
// Problem is here ...
while ((line = in.readLine()) != null) {
}The IOException always occurs when readLine() is called. Any ideas on how to fix this problem?
Thanks in advance,
Simon Liu

I don't use readLine() but read()
A bit of code:
          BufferedReader inStream = new BufferedReader(new InputStreamReader(inputStream));
          byte ch = 0;
          char myChar;
          int charVal;          
          try{               
               while((ch = (byte)inStream.read()) != -1){
                    if((ch == 13) || (ch == 10)){ //In ASCII code: 13 = Carriage return, 10 = line feed. When the GPS receiver sends those characters, the while loop must be broken to avoid an IOException                         
                         break;
                    }else{
                         myChar = (char)ch;
                    charVal = myChar;
                    //System.out.print("byte=" + ch +" myChar=" + myChar + " charVal=" + charVal + "\n");
                    System.out.print(myChar);
               }

Similar Messages

  • XPath query string returns zero node error

    I have created car loan bpel application. One is Citi Loan and another is Star Loan.
    I have created just like similar to sample loan demo.
    I have entered the SSN, email, carModel, carYear, loanAmount and creditRating value and submitted. It will initiated the following tasks successfully.
    StarLoan Instance
    CitiLoan Instance
    TaskManager Instance
    CreditRating Instance
    Root appln. instance
    I have created one user approval page for Approve/Reject (jsp). Through this page, I have approved the CitiLoan offer. I have faced the following errors.
    <output>
    <part name="payload" >
    <loanOffer>7.4</loanOffer>
    </part>
    </output>
    <loanOffer>7.4</loanOffer>
    <selectionFailure>
    <part name="summary" >
    <summary>XPath query string returns zero node. According to BPEL4WS spec 1.1 section 14.3, The assign activity <to> part query should not return zero node. Please check the BPEL source at line number "90" and verify the <to> part xpath query. </summary>
    </part>
    </selectionFailure>
    Please help me.
    Thanks in advance.
    Regards,
    Sara

    Let us know if you have customized SOA composite for user creation approval?
    -Vamsi.

  • Problem reading input stream of urlconnection within portal

    Hi,
    This may be a generic server issue rather than portal but since it's my portal app that's displaying the problem I'll post it here.
    Part of my Portal attempts to POST to a remote server to retrieve some search results.
    In environments A & B (both standalone instances) this works fine.
    In environment C this works on the managed instances in the cluster but not the admin instance.
    In environment D (again standalone) it fails, but if I add a managed instance it works from the managed instance.
    The problem I'm seeing is that I get a stuck thread and the thread dump shows it is blocked attempting to read the resulting input from a urlconnection. (Using a buffered input stream).
    I've copied the code to a standalone class that runs fine from the same server(s). I've pasted this code below, the contents of the test() method were copied directly from my webapp (urls changed here for clarity).
    Does anyone know of any securitymanager issues that may cause this?
    Or anything else for that matter?
    Code sample:
    package src.samples;
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    public class POSTTest {
         public static boolean test()
         URL url = null;
         try {
         url = new URL
    ("http://hostx:80/myapp/search.html");
         catch (MalformedURLException e)
         e.printStackTrace();
         return false;
         URLConnection urlConn;
         DataOutputStream printout;
         BufferedReader input;
         urlConn = null;
         try {
         urlConn = url.openConnection();
         catch (IOException e)
         e.printStackTrace();
         return false;
         // Let the run-time system (RTS) know that we want input.
         urlConn.setDoInput (true);
         // Let the RTS know that we want to do output.
         urlConn.setDoOutput (true);
         // No caching, we want the real thing.
         urlConn.setUseCaches (false);
         // Specify the content type.
         urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
         // Send POST output (this is a POST because we write then read as per the JDK Javadoc)
         printout = null;
         String body = "";
         try {
         System.out.println("url=" + url.toString());
         printout = new DataOutputStream (urlConn.getOutputStream ());
         String content = "param1=A&param2=B&param3=C&param4=D&param5=E";
         System.out.println("urlParams= " + content);
         printout.writeBytes (content);
         System.out.println("written parameters");
         printout.flush ();
         System.out.println("flushed parameters");
         printout.close ();
         System.out.println("closed parameter stream");
         // <b>Get response data - this is where it blocks indefinitely</b>
         input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
         System.out.println("got input");
         String str;
         while (null != ((str = input.readLine()))) {
         body = body + str + "\n";
         System.out.println("read input:");
         System.out.println(body);
         input.close ();
         System.out.println("closed input stream");
         catch (IOException e) {
         System.out.println("IOException caught: read failed");
         e.printStackTrace();
         return false;
         return true;
         * @param args
         public static void main(String[] args) {
              System.out.println("Test result= " + test());

    In your recuperar() method, read the FTP input stream into a byte array. (You can do that by copying it to a ByteArrayOutputStream and then getting the byte array from that object.) Then, return a ByteArrayInputStream based on those bytes. After you call completePendingCommand(), of course.
    That's one way.
    PC&#178;

  • Wsus Sync Failed. WebException: The underlying connection was closed: An unexpected error occurred on a send. --- System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.

    Hi I have installed wsus 3 sp2 on a win 2008 R2 Sp1
    before the installation , I have updated the windows
    I can open easily browse internet , but when I try to configure synchronization .but it fails.
    No firewall , no proxy ............. I am behind a nat.
    Wsus version is 3.2.7600.256.
    I have searched and searched .....
    Can any body help me
    WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.
    at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
       at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
       at Microsoft.UpdateServices.ServerSync.ServerSyncCompressionProxy.GetWebResponse(WebRequest webRequest)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
       at Microsoft.UpdateServices.ServerSyncWebServices.ServerSync.ServerSyncProxy.GetAuthConfig()
       at Microsoft.UpdateServices.ServerSync.ServerSyncLib.InternetGetServerAuthConfig(ServerSyncProxy proxy, WebServiceCommunicationHelper webServiceHelper)
       at Microsoft.UpdateServices.ServerSync.ServerSyncLib.Authenticate(AuthorizationManager authorizationManager, Boolean checkExpiration, ServerSyncProxy proxy, Cookie cookie, WebServiceCommunicationHelper webServiceHelper)
       at Microsoft.UpdateServices.ServerSync.CatalogSyncAgentCore.SyncConfigUpdatesFromUSS()
       at Microsoft.UpdateServices.Serve

    Hi
    yes . it is alloweded.
    Nat rule permits any ip traffic . No problem with https...
    also my windows is fully updated.
    here is my netstat -an , maybe usefull.
     TCP    0.0.0.0:135            0.0.0.0:0              LISTENING
     TCP    0.0.0.0:445            0.0.0.0:0              LISTENING
     TCP    0.0.0.0:8530           0.0.0.0:0              LISTENING
     TCP    0.0.0.0:8531           0.0.0.0:0              LISTENING
     TCP    0.0.0.0:47001          0.0.0.0:0              LISTENING
     TCP    0.0.0.0:49152          0.0.0.0:0              LISTENING
     TCP    0.0.0.0:49153          0.0.0.0:0              LISTENING
     TCP    0.0.0.0:49154          0.0.0.0:0              LISTENING
     TCP    0.0.0.0:49155          0.0.0.0:0              LISTENING
     TCP    0.0.0.0:49156          0.0.0.0:0              LISTENING
     TCP    --------------------:139       0.0.0.0:0              LISTENING
     TCP    --------------------:8530      172.16.2.201:53317     ESTABLISHED
     TCP    --------------------:49362     23.65.244.185:443      ESTABLISHED
     TCP    --------------------:49363     23.65.244.185:443      ESTABLISHED
     TCP    --------------------:49367     23.65.244.185:443      ESTABLISHED
     TCP    --------------------:49377     23.65.244.185:443      ESTABLISHED
     TCP    --------------------:49414     131.253.34.141:443     ESTABLISHED
     TCP    --------------------:49416     216.239.32.20:80       ESTABLISHED
     TCP    --------------------:49417     216.239.32.20:80       ESTABLISHED
     TCP    --------------------:49418     173.194.70.113:80      ESTABLISHED
     TCP    --------------------:49419     173.194.70.113:80      ESTABLISHED
     TCP    --------------------:49420     65.52.103.78:80        ESTABLISHED
     TCP    --------------------:49421     65.52.103.78:80        ESTABLISHED
     TCP    --------------------:49424     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49425     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49426     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49427     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49428     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49429     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49430     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49431     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49432     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49433     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49434     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49435     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49436     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49437     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49438     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49439     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49440     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49441     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49442     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49443     88.221.93.54:80        ESTABLISHED
     TCP    --------------------:49444     88.221.93.54:80        ESTABLISHED
     TCP    --------------------:49445     88.221.93.63:80        ESTABLISHED
     TCP    --------------------:49446     88.221.93.63:80        ESTABLISHED
     TCP    --------------------:49447     88.221.93.63:80        ESTABLISHED
     TCP    --------------------:49448     88.221.93.63:80        ESTABLISHED
     TCP    --------------------:49449     88.221.93.63:80        ESTABLISHED
     TCP    --------------------:49450     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49451     88.221.93.31:80        ESTABLISHED
     TCP    --------------------:49453     88.221.93.30:80        ESTABLISHED
     TCP    --------------------:49456     65.55.58.184:80        ESTABLISHED
     TCP    --------------------:49457     65.55.58.184:80        ESTABLISHED
     TCP    --------------------:49460     131.253.34.142:80      ESTABLISHED
     TCP    --------------------:49461     131.253.34.142:80      ESTABLISHED
     TCP    --------------------:49462     65.52.103.78:80        ESTABLISHED
     TCP    --------------------:49463     65.52.103.78:80        ESTABLISHED
     TCP    --------------------:49464     63.251.85.33:80        ESTABLISHED
     TCP    --------------------:49466     131.253.40.50:80       ESTABLISHED
     TCP    --------------------:49467     131.253.40.50:80       ESTABLISHED

  • IOException: Connection reset by peer: JVM_recv in socket input stream read

    hi
    I encountered a problem : a program throw out an exception:java.io.IOException: Io exception:
    Connection reset by peer: JVM_recv in socket input stream read.
    I tried my best to resolve it ,but unfortunately,i didn't know what caused the exception.
    the following is my application environment:
    I have two PC(Win2000os),one is a server which installed oracle9.2.0.2 and jdeveloper9.0.3,the another is a
    client which only intalled jdeveloper9.0.3.Two days ago,i performed a web application on my client with
    jdeveloper,and it includes some JSP and a javabean files.JSP Page finished uploading client xml file to a
    folder on server and the javabean finished loading the xml file into a xmltype column.I can make sure the
    connection is established and the javabean is OK,beacause my some jsp page can successfully use
    <jsp:usebean> tag and use the javabean's some other public interfaces,except the interface that finishs
    loading the xml file into a xmltype(clob) column.
    Then i do many tests!I changed the javabean to a java class incluse a main method beacause it is easy to
    debug.Finally i found the following code caused the exception:
    public CLOB writetoClob( CLOB clob, InputStream is )throws SQLException, IOException {
    InputStreamReader reader = new InputStreamReader( is );
    Writer writer = clob.getCharacterOutputStream( );
    char[] buffer = new char[clob.getChunkSize(  )];
    int charsRead;
    for ( charsRead = reader.read( buffer ); charsRead > -1;charsRead = reader.read( buffer ) ) {
    writer.write( buffer, 0, charsRead );
    writer.close();
    return clob;
    when it runs to writer.close(),the exception is caused!
    Then i copy the java class to the server,it runs ok!
    That is to say ,the same code,the different result!
    But when i run my web application on server with jdeveloper Embedded OC4J Server and a jsp page loaded javabean
    and run to mentioned code ,the same exception occured!
    I checked the application log in event viewer,the descriptions was:
    The data buffer created for the "AppleTalk" service in the "C:\WINNT\system32\atkctrs.dll" library is not
    aligned on an 8-byte boundary. This may cause problems for applications that are trying to read the
    performance data buffer. Contact the manufacturer of this library or service to have this problem corrected or
    to get a newer version of this library.
    I search some some resolution about this exception with web and someone sayed :
    This basically means that a network error occurred while the client was receiving data from the server. But
    what is really happening is that the server actually accepts the connection, processes the request, and sends a
    reply to the client. However, when the server closes the socket, the client believes that the connection has
    been terminated abnormally because the socket implementation sends a TCP reset segment telling the client to
    throw away the data and report an error.
    Sometimes, this problem is caused by not properly closing the input/output streams and the socket connection.
    Make sure you close the input/output streams and socket connection properly. If everything is closed properly,
    however, and the problem persists, you can work around it by adding Thread.sleep(1000) before closing the
    streams and the socket. This technique, however, is not reliable and may not work on all systems.
    In general,the following information is conclution:
    Web application runs error both on client and on server.
    If it was changed to a client java class,it only run ok on server!
    i have done anything that i can do now,i feel depressed very much!
    how can i resolve the problem!
    Any a little help will be appreciated!
    regards!
    Thanks
    Jiawei ZHAO

    How can i solve the problem.
    Thanks in advance!
    Jiawei Zhao

  • How do I return an input stream from a text file

    Suppose there's a class with methods..
    one of the methods is something like..
    public int value() and has a return statement at the end obviously for returning an int value..
    Another method reads a text file and creates an input stream..
    Scanner data  = new Scanner(new File(input.next()));
    I want to return the data when I do a call to this method, but I'm not sure what the method heading would look like..

    flounder wrote:
    Are we supposed to magically know what those errors are? Do you think that copying and pasting the exact error messages and indicating the lines they occur on would be useful to us?Sorry about that..
    I've replicated the same code below; and put the number of the line where the error is.
    +cannot find symbol variable read     [line 21]+
    +cannot find symbol variable read     [line 23]+
    +cannot find symbol variable read     [line 29]+
    +cannot find symbol variable read     [line 31]+
    +cannot find symbol variable inputStream     [line 44]+
    +calculate() in textInput cannot be applied to (java.util.Scanner)     [line 57]+
    the reason I have the _______ for the createInputStream() method is because I'm not really sure what the heading type should be to return the input stream.
    import java.io.*;
    import java.util.*;
    public class textInput
              public void requestFileName()
                   Scanner input = new Scanner(System.in);
                   System.out.print("Enter file name: ");
              public _______ createInputStream() throws FileNotFoundException
                   Scanner input = new Scanner(System.in);
                   Scanner read = new Scanner(new File(input.next()));
                   return read;
              public void calculate() throws IOException
    21           double max;
                   double min;
    23            int count = 0;
                   double total = 0;
                   if (read.hasNextDouble())
                        double temp = read.nextDouble();
    29                 max = temp;
                        min = temp;
    31                 count++
                        total += temp;
                        while (read.hasNextDouble())
                             double current = read.nextDouble();
                             count++;
                             min = Math.min(current, min);
                             max = Math.max(current, max);
                             total += current;
                   System.out.println("Max of: " + max);
                   System.out.println("Min of: " + min);
    44            System.out.println("Average of " + total/count);
              public void close() throws IOException
                   inputStream.close();
              public static void main(String[] args)
                   textInput run = new textInput();
                   try
    57                 run.requestFileName();
                        run.createInputStream();
                        run.calculate();
                        run.close();
                   catch(FileNotFoundException e)
                        System.out.println("File not found.");
                        System.exit(0);
                   catch(IOException e)
                        System.out.prinln("File not found.");
                        System.exit(0);
    }

  • Output/Input Streams Cannot Resolve Symbol..

    It is missing something, how do I declare the below 2 variables?
         //Get streams to send and receive data
         private void getSockStreams() throws IOException {
              //Set up output streams for objects
              output = new ObjectOutputStream(connection.getOutputStream());
              output.flush(); //Flush output buffer to send header information.
              //Set up input stream for objects.
              input = new ObjectInputStream(connection.getInputStream());
              displayMessage("Got I/O Streams");
         }Error:
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\appinterface.java:74: cannot resolve symbol
    symbol  : variable output
    location: class appinterface
                    output = new ObjectOutputStream(connection.getOutputStream());
                    ^
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\appinterface.java:75: cannot resolve symbol
    symbol  : variable output
    location: class appinterface
                    output.flush(); //Flush output buffer to send header information.
                    ^
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\appinterface.java:78: cannot resolve symbol
    symbol  : variable input
    location: class appinterface
                    input = new ObjectInputStream(connection.getInputStream());
                    ^
    3 errors
    Process completed.

    Same way you declare any variables in Java:ObjectOutputSream output;
    output = ....
    OR
    ObjectOutputStream output = ...

  • Set the max bytes per packet for an input stream

    Hi,
    I got this problem:
    I want to store some images into a DB. Now if the images are huge, the DB told me, that the packet size is too large
    maybe like that : 'Packet for query is too large (1668641 > 1048576)'
    I use an ByteArrayInputStream for the transmission to the DB.
    So if I am not able to set the max. packet size of the DB is it possible to cut the input stream into pieces to send them to the DB ?
    regards,
    Olek

    None of this makes any sense.
    The MySQL driver will be using TCP to talk to the database server. TCP is a stream oriented protocol. You can't control the size of the packets (other than the maximum by frigging with OS settings - don't do that). Neither can the server detect the sizes of incoming packets. It just sees a stream of bytes and has no idea where the write() boundries are or how the TCP protocol split that into IP packets - it's just a stream of bytes arriving in the same order they were sent.
    And... the max TCP segment size is nowhere near 32Mb, so that doesn't make any sense eeither.
    So, I conclude (especially in light of the answer about the config settings) that "packet" is a badly abused term by MySQL that allows it to limit the size of individual requests in order to provide some kind of protection against badly written clients and/or malicious attacks. If you need to send more data than this, just up the limit - especially if this is an intranet application where the client is under your control and attacks are unlikely.

  • Storing input stream in a buffer

    Hi, what is the best way to read an input stream and save it into a buffer?
    Thanks,
    Andrea

    Not sure if any of the following are an improvement or not. But here are just a few thoughts. Why handle all the byte array allocation yourself? IMO, it would be easier to simply use a ByteArrayOutputStream at that point. The listeners can call toByteArray() and be passed an offset and length of what was read.
    Now that I think about it, you could probably make it a bit more generic even than that. For example, here is a class I end up using all the time:
    public final class Pipe
        /** Buffer size to read in and output. */
        private static final int DEFAULT_BUFFER_SIZE = 2048;
         * Private constructor.  Use public static facade methods instead.
        private Pipe()
            super();
         * Pipes the specified binary data to the specified output stream.
         * @param   target                      Binary data to output
         * @param   out                         Stream to write
         * @throws  IOException
        public static final void pipe(final byte[] target, final OutputStream out)
            throws IOException
            assert (target != null) : "Missing byte array";
            assert (out != null) : "Missing output stream";
            pipe(new ByteArrayInputStream(target), out, true);
         * Reads from the specified input stream and returns all data as an in-memory.
         * binary array.  Note:  Since streams may be of any arbitrary size, this
         * method requires that you wrap your original stream in a {@link FiniteInputStream}.
         * Please ensure that this method is only used to read in data under, say, 2mB.
         * @param   in                          Stream to read
         * @return  byte[]                      Binary data read
         * @throws  IOException
        public static final byte[] pipe(final FiniteInputStream in)
            throws IOException
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            pipe(in, byteOut, true);
            return byteOut.toByteArray();
         * Reads from the specified input stream and outputs immediately to the specified.
         * output stream.  <br>
         * <br>
         * If you have any confusion about which <code>Pipe</code> method to use, choose
         * this one.  It has the lowest memory overhead and is the most efficient.  Always
         * choose this method when streaming large amounts of data or content.
         * @param   in                          Input stream to read
         * @param   out                         Output stream to write
         * @param   close                       Close both stream if true
         * @return  long                        Byte count piped
         * @throws  IOException
        public static final long pipe(final InputStream in, final OutputStream out, final boolean close)
            throws IOException
            assert (in != null) : "Missing input stream";
            assert (out != null) : "Missing output stream";
            long bytesPiped = 0L;
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            try
                int bytesRead = in.read(buffer);
                while (bytesRead >= 0)
                    if (bytesRead > 0)
                        out.write(buffer, 0, bytesRead);
                        bytesPiped = bytesPiped + bytesRead;
                    bytesRead = in.read(buffer);
                out.flush();
                return bytesPiped;
            finally
                if (close)
                    IoHelper.close(in);
                    IoHelper.close(out);
    }You simply could add the listener feature (which I do think is useful and elegant). Note the FiniteInputStream and FiniteOutputStream are just sub-classes of FilterInputStream and FilterOutputStream that allow you to limit how many bytes are piped, if desired.
    - Saish

  • Read input stream

    My function tried to parse a inputstream(xml format) but I keep getting exception: Exception org.xml.sax.SAXParseException: The root element is required in a well-formed document. I checked my XML format, it looks correct. Is there a way I can print out the input stream but still be able to parse it later with the sam input stream? Thanks.
    public static final Document getDOMTree(InputStream input) throws Exception
    try
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = factory.newDocumentBuilder();
         Document doc = builder.parse(input);
    return doc;
    } catch(DOMException de) {
    System.out.println("parse error " +de);
         throw new Exception(de.toString());
    } catch(Exception e)
    System.out.println("Exception " +e);
         throw new Exception(e.toString());
    }

    Here's a class that I use for viewing outputstreams in a similar way - you can either adjust it to work as an input stream, or do a quick web search on TeeInputStream - I suspect you'll find some code.
    Cheers,
    - K
    * Copyright (c) 2001 Matthew Feldt. All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided the copyright notice above is
    * retained.
    * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR
    * IMPLIED WARRANTIES.
    * TeeOutputStream.java
    * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan
    * Exercise 3-7:
    * Write a subclass of OutputStream named TeeOutputStream that acts like a T
    * joint in a pipe; the stream sends its output to two different output streams,
    * specified when the TeeOutputStream is created. Write a simple test program
    * that uses two TeeOutputStream objects to send text read from System.in to
    * System.out and to two different test files.
    * @author Matthew Feldt <[email protected]>
    * @version 1.0, 02/12/2001 08:23
    import java.io.*;
    public class TeeOutputStream extends OutputStream {
        OutputStream ostream1, ostream2;
        /** sole TeeOutputStream constructor */
        public TeeOutputStream(OutputStream o1, OutputStream o2) throws IOException {
            ostream1 = o1;
            ostream2 = o2;
        public void close() throws IOException {
            ostream1.close();
            ostream2.close();
        public void flush() throws IOException {
            ostream1.flush();
            ostream2.flush();
        public void write(int b) throws IOException {
            byte[] buf = new byte[1];
            buf[0] = (byte)b;
            write(buf, 0, 1);
        public void write(byte[] b, int off, int len) throws IOException {
            ostream1.write(b, off, len);
            ostream2.write(b, off, len);
        /** test class */
        static class Test {
            public static void main (String args[]) {
                final String f1 = "tee1.out", f2 = "tee2.out";
                int ch;
                try {
                    // create a TeeOutputStream with System.out and a file
                    // as output streams
                    TeeOutputStream t1 = new TeeOutputStream(
                        System.out, new FileOutputStream(f1));
                    // create a TeeOutputStream with t1 and a second file as
                    // output streams
                    TeeOutputStream tee = new TeeOutputStream(
                        t1,    new FileOutputStream(f2));
                    // read characters from System.in and write to the tee
                    while ((ch = System.in.read()) != -1) {
                        tee.write(ch);
                    tee.close(); // close the tee
                } catch(FileNotFoundException e) {
                    System.err.println(e.getMessage());
                } catch(IOException e) {
                    System.err.println(e.getMessage());
    }

  • Problem reading image from input Stream

    I'm having a problem reading an image through an input stream. It gives me the error
    Premature end of JPEG file
    sun.awt.image.ImageFormatException: JPEG datastream contains no imageand my code looks like
    public Image getImage(String name, String command){
              if(command.equals(pCode)){
                   Image image=null;
                   System.out.println(name);
                   InputStream is = getClass().getResourceAsStream(name);
                   BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] byBuf =new byte[10000];
                     try {
                        int byteRead = bis.read(byBuf,0,10000);
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                     image = Toolkit.getDefaultToolkit().createImage(byBuf);
                   return image;
              return null;
         }And the string name looks when printed is: usr/images/PRLogo.jpg

    If the image is bigger than 10K, this code will break.
    You can pass an InputStream to javax.imageio.ImageIO.read. That's probably an easier option than trying to do the buffering yourself.

  • Is this the best way to measure the speed of an input stream?

    Hi guys,
    I have written the following method to read the source of a web page. I have added the functionality to calculate the speed.
    public StringBuffer read(String url)
            int lc = 0;
            long lastSpeed = System.currentTimeMillis();
            //string buffer for reading in the characters
            StringBuffer buffer = new StringBuffer();
            try
                //try to set URL
                URL URL = new URL(url);
                //create input streams
                InputStream content = (InputStream) URL.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(content));
                //in line
                String line;
                //while still reading in
                while ((line = in.readLine()) != null)
                    lc++;
                    if ((lc % _Sample_Rate) == 0)
                        this.setSpeed(System.currentTimeMillis() - lastSpeed);
                        lastSpeed = System.currentTimeMillis();
                    //add character to string buffer
                    buffer.append(line);
            //catch errors
            catch (MalformedURLException e)
                System.out.println("Invalid URL - " + e);
            catch (IOException e)
                System.out.println("Invalid URL - " + e);
            //return source
            return buffer;
        }Is it faster to read bytes rather than characters?
    This method is a very important part of my project and must be as quick as possible.
    Any ideas on how I can make it quicker? Is my approach to calculating the speed the best way to it?
    Any help/suggestions would be great.
    thanks
    alex

    sigh
    reading bytes might be slightly faster than reading chars, since you don't have to do the conversion and you don't have to make String objects. Certainly, you don't want to use readLine. If you're using a reader, use read(buf, length, offset)
    My suggestion:
    Get your inputstream, put a bufferedInputStream over it, and use tje loadAll method from my IOUtils class.
    IOUtils is given freely, but please do not change its package or submit this as your own work.
    ====
    package tjacobs;
    import java.awt.Component;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JOptionPane;
    public class IOUtils {
         public static final int DEFAULT_BUFFER_SIZE = (int) Math.pow(2, 20); //1 MByte
         public static final int DEFAULT_WAIT_TIME = 30 * 1000; // 30 Seconds
         public static final int NO_TIMEOUT = -1;
         public static final boolean ALWAYS_BACKUP = false;
         public static String loadTextFile(File f) throws IOException {
              BufferedReader br = new BufferedReader(new FileReader(f));
              char data[] = new char[(int)f.length()];
              int got = 0;
              do {
                   got += br.read(data, got, data.length - got);
              while (got < data.length);
              return new String(data);
         public static class TIMEOUT implements Runnable {
              private long mWaitTime;
              private boolean mRunning = true;
              private Thread mMyThread;
              public TIMEOUT() {
                   this(DEFAULT_WAIT_TIME);
              public TIMEOUT(int timeToWait) {
                   mWaitTime = timeToWait;
              public void stop() {
                   mRunning = false;
                   mMyThread.interrupt();
              public void run () {
                   mMyThread = Thread.currentThread();
                   while (true) {
                        try {
                             Thread.sleep(mWaitTime);
                        catch (InterruptedException ex) {
                             if (!mRunning) {
                                  return;
         public static InfoFetcher loadData(InputStream in) {
              byte buf[] = new byte[DEFAULT_BUFFER_SIZE]; // 1 MByte
              return loadData(in, buf);
         public static InfoFetcher loadData(InputStream in, byte buf[]) {
              return loadData(in, buf, DEFAULT_WAIT_TIME);
         public static InfoFetcher loadData(InputStream in, byte buf[], int waitTime) {
              return new InfoFetcher(in, buf, waitTime);
         public static String loadAllString(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              fetcher.run();
              return new String(fetcher.buf, 0, fetcher.got);
         public static byte[] loadAll(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              fetcher.run();
              byte bytes[] = new byte[fetcher.got];
              for (int i = 0; i < fetcher.got; i++) {
                   bytes[i] = fetcher.buf;
              return bytes;
         public static class PartialReadException extends RuntimeException {
              public PartialReadException(int got, int total) {
                   super("Got " + got + " of " + total + " bytes");
         public static class InfoFetcher implements Runnable {
              public byte[] buf;
              public InputStream in;
              public int waitTime;
              private ArrayList mListeners;
              public int got = 0;
              protected boolean mClearBufferFlag = false;
              public InfoFetcher(InputStream in, byte[] buf, int waitTime) {
                   this.buf = buf;
                   this.in = in;
                   this.waitTime = waitTime;
              public void addInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        mListeners = new ArrayList(2);
                   if (!mListeners.contains(fll)) {
                        mListeners.add(fll);
              public void removeInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        return;
                   mListeners.remove(fll);
              public byte[] readCompletely() {
                   run();
                   return buf;
              public int got() {
                   return got;
              public void run() {
                   if (waitTime > 0) {
                        TIMEOUT to = new TIMEOUT(waitTime);
                        Thread t = new Thread(to);
                        t.start();
                   int b;
                   try {
                        while ((b = in.read()) != -1) {
                             if (got + 1 > buf.length) {
                                  buf = expandBuf(buf);
                             buf[got++] = (byte) b;
                             int available = in.available();
                             if (got + available > buf.length) {
                                  buf = expandBuf(buf);
                             got += in.read(buf, got, available);
                             signalListeners(false);
                             if (mClearBufferFlag) {
                                  mClearBufferFlag = false;
                                  got = 0;
                   } catch (IOException iox) {
                        throw new PartialReadException(got, buf.length);
                   } finally {
                        buf = trimBuf(buf, got);
                        signalListeners(true);
              private void setClearBufferFlag(boolean status) {
                   mClearBufferFlag = status;
              public void clearBuffer() {
                   setClearBufferFlag(true);
              private void signalListeners(boolean over) {
                   if (mListeners != null) {
                        Iterator i = mListeners.iterator();
                        InputStreamEvent ev = new InputStreamEvent(got, buf);
                        //System.out.println("got: " + got + " buf = " + new String(buf, 0, 20));
                        while (i.hasNext()) {
                             InputStreamListener fll = (InputStreamListener) i.next();
                             if (over) {
                                  fll.gotAll(ev);
                             } else {
                                  fll.gotMore(ev);
         public static interface InputStreamListener {
              public void gotMore(InputStreamEvent ev);
              public void gotAll(InputStreamEvent ev);
         public static class InputStreamEvent {
              public int totalBytesRetrieved;
              public byte buffer[];
              public InputStreamEvent (int bytes, byte buf[]) {
                   totalBytesRetrieved = bytes;
                   buffer = buf;
              public int getBytesRetrieved() {
                   return totalBytesRetrieved;
              public byte[] getBytes() {
                   return buffer;
         public static void copyBufs(byte src[], byte target[]) {
              int length = Math.min(src.length, target.length);
              for (int i = 0; i < length; i++) {
                   target[i] = src[i];
         public static byte[] expandBuf(byte array[]) {
              int length = array.length;
              byte newbuf[] = new byte[length *2];
              copyBufs(array, newbuf);
              return newbuf;
         public static byte[] trimBuf(byte[] array, int size) {
              byte[] newbuf = new byte[size];
              for (int i = 0; i < size; i++) {
                   newbuf[i] = array[i];
              return newbuf;

  • IMac went crazy, no fixed but many files become zero bytes in size

    I don't even know where to start. I guess first I'll list some background information:
    My wife and I share a iMac which she uses it as her workstation for illustration and I use it as Plex Media Server and Transmission etc. So she would normally use it by day, but my account would be always logged in in the background and I use SSH and Remote Desktop to control my account.
    And since the ultimate symptom are I don't how many zero byte files, here are some configuration information.
    1) iMac 27" late 2012 with 128 GB Apple SSD and 3TB HDD
    2) A custom fusion drive with 1 logical volume consist of 3 physical volumes.
    3) The configuration is odd because I wanted to use both fusion drive and BOOTCAMP. So there is a BOOTCAMP volume as well.
    This happened in the past couple of days. At first my wife was complaining about loosing wifi connection and keyboard connectivity problems. For wifi I typically instructed her to turn wifi on and off or try to reboot the computer. For the keyboard problem, it turned out to be a software problem not Bluetooth because disabling a third part IME seemed to resolve the problem.
    Then at one night, she accidentally unplug the iMac while it's on (it's always on, and my wife never reboot or shut it down unless I intervene). No she freaked out as she couldn't remember if she saved her illustration work. Luckily she did. And at this point of time, after booting it up, the PSD file was intact and the latest version. Okay, we moved on. I didn't worry about too much about the power failure because this happened before. And normally Disk Utility in Recovery HD would fix the problem.
    Then on the day after, it started loosing sound. So I tried to fix it. Now when I tried to login, it said "Cannot find "login" keychains". Choose "Restore to Default", doesn't work and Finder was keeping crashing and relaunching. Hopping a restart would fixed but it didn't. Then I tried all regular maintaining techniques include fix disk, fix permission, clear all sorts of caches with OnyX. Because there was a power failure, the disk did need some repairing and according to Disk Utility, it appeared OK now, but the problem was still there.
    Then I created a new user, works seemingly fine. Deleted my old account and created it agin with the same UID, same problem. Almost all the applications failed to launch except "Notes" and "Maps". It seemed to be a user problem but using the same user ID but new Home folder, the problem came back. This baffled me. I never came across something like this.
    Then I hoped upgrade system to 10.10.3 would help (it was 10.10.2). And it did. Now finder can open. Keychains still missing and could be reset to default. But at least I could open Keychains Access now. And from there I created a new login keychain. And my wife's account didn't have this keychain issue, I assumed the situation was under control.
    Now, the wired thing happened. My wife fired up Photoshop, it's reporting problems loading preferences. Moved preferences file else where, it said unexpected EOF. Looked it up and ended LAYOUT.psp or something became zero bytes. I deleted it and let photoshop create default one. Now photoshop works. But the PSD my wife panicked about earlier became zero byte.
    Verified the disk again, appears to be OK, again, appears to be OK.
    The only thing worth mentioning was the amount of something called "Metadata Volume" and "double redundancy". It says "The Logical Volume Family has a 4482 MB Metadata Volume double redundancy". I'm not sure whether or not this is usual.
    Now I'm trying to recovery all the PSD files on the disk with a Data Recovery App. But while I'm waiting I found some other files now its zero bytes. This really worries me. And I'm still not sure what cause the problem or even what the problem was or is. I suspect it has something to do with fusion drive as when I do rsync -W --inplace, the speed is normally 20~30 which is a bit low to me.
    If you read this far, I really appreciate it. I'm sorry it's so long and unclear. It's because its like nothing I encountered before and the problem is hidden with many little issues on the surface.
    But I will try to summarise my question:
    1) What could possibly be the root cause of those problems
    2) What happened to those files.
    3) Is there anyway to recovery them other than standing all the sectors of the disk
    4) Would it be better off with fusion drive.

    I don't even know where to start. I guess first I'll list some background information:
    My wife and I share a iMac which she uses it as her workstation for illustration and I use it as Plex Media Server and Transmission etc. So she would normally use it by day, but my account would be always logged in in the background and I use SSH and Remote Desktop to control my account.
    And since the ultimate symptom are I don't how many zero byte files, here are some configuration information.
    1) iMac 27" late 2012 with 128 GB Apple SSD and 3TB HDD
    2) A custom fusion drive with 1 logical volume consist of 3 physical volumes.
    3) The configuration is odd because I wanted to use both fusion drive and BOOTCAMP. So there is a BOOTCAMP volume as well.
    This happened in the past couple of days. At first my wife was complaining about loosing wifi connection and keyboard connectivity problems. For wifi I typically instructed her to turn wifi on and off or try to reboot the computer. For the keyboard problem, it turned out to be a software problem not Bluetooth because disabling a third part IME seemed to resolve the problem.
    Then at one night, she accidentally unplug the iMac while it's on (it's always on, and my wife never reboot or shut it down unless I intervene). No she freaked out as she couldn't remember if she saved her illustration work. Luckily she did. And at this point of time, after booting it up, the PSD file was intact and the latest version. Okay, we moved on. I didn't worry about too much about the power failure because this happened before. And normally Disk Utility in Recovery HD would fix the problem.
    Then on the day after, it started loosing sound. So I tried to fix it. Now when I tried to login, it said "Cannot find "login" keychains". Choose "Restore to Default", doesn't work and Finder was keeping crashing and relaunching. Hopping a restart would fixed but it didn't. Then I tried all regular maintaining techniques include fix disk, fix permission, clear all sorts of caches with OnyX. Because there was a power failure, the disk did need some repairing and according to Disk Utility, it appeared OK now, but the problem was still there.
    Then I created a new user, works seemingly fine. Deleted my old account and created it agin with the same UID, same problem. Almost all the applications failed to launch except "Notes" and "Maps". It seemed to be a user problem but using the same user ID but new Home folder, the problem came back. This baffled me. I never came across something like this.
    Then I hoped upgrade system to 10.10.3 would help (it was 10.10.2). And it did. Now finder can open. Keychains still missing and could be reset to default. But at least I could open Keychains Access now. And from there I created a new login keychain. And my wife's account didn't have this keychain issue, I assumed the situation was under control.
    Now, the wired thing happened. My wife fired up Photoshop, it's reporting problems loading preferences. Moved preferences file else where, it said unexpected EOF. Looked it up and ended LAYOUT.psp or something became zero bytes. I deleted it and let photoshop create default one. Now photoshop works. But the PSD my wife panicked about earlier became zero byte.
    Verified the disk again, appears to be OK, again, appears to be OK.
    The only thing worth mentioning was the amount of something called "Metadata Volume" and "double redundancy". It says "The Logical Volume Family has a 4482 MB Metadata Volume double redundancy". I'm not sure whether or not this is usual.
    Now I'm trying to recovery all the PSD files on the disk with a Data Recovery App. But while I'm waiting I found some other files now its zero bytes. This really worries me. And I'm still not sure what cause the problem or even what the problem was or is. I suspect it has something to do with fusion drive as when I do rsync -W --inplace, the speed is normally 20~30 which is a bit low to me.
    If you read this far, I really appreciate it. I'm sorry it's so long and unclear. It's because its like nothing I encountered before and the problem is hidden with many little issues on the surface.
    But I will try to summarise my question:
    1) What could possibly be the root cause of those problems
    2) What happened to those files.
    3) Is there anyway to recovery them other than standing all the sectors of the disk
    4) Would it be better off with fusion drive.

  • JVM_recv in socket input stream error

    I've opened a socket and I'm able to access the OutputStream. However, when I try to wrap a ObjectInputStream around the socket's InputStream, I get this error:
    SocketException: Connection reset by peer: JVM_recv in socket input stream read.
    What should I be looking for?
    Larry

    Here's the code which appears to be relevant, with some commentary on what happens when it is run. Large portions of (hopefully) irrelevant code have been snipped.
    Client:
    COMMENT: Start a server using RMI. This appears to
    COMMENT: succeed, since a message printed by this
    COMMENT: server does appear.
    try {
    DistLrnRemoteData dlrd =
    (DistLrnRemoteData)Naming.lookup(
    "//"+personHost+
    "/DistanceLearningData");
    dlrd.activatePersonServer(); // Get server going
    catch (Exception e) {
    System.err.println(e);
    COMMENT: This line is NOT printed, so apparently
    COMMENT: there is no Exception.
    System.err.println("Unable to initialize remote Person server");
    e.printStackTrace(System.err);
    Person result = new Person();
    int count = 10;
    boolean opened = false;
    Socket gpsocket = null;
    while (!opened) {
    try {
    COMMENT: The client attempts to open the socket
    COMMENT: here. The server never seems to accept it,
    COMMENT: but this call appears to succeed. There is
    COMMENT: no Exception. The server is running code
    COMMENT: from the class RemoteDataServer, so the
    COMMENT: port should be the same. The testing was
    COMMENT: done with a single host acting as both
    COMMENT: client and server, so there isn't any firewall
    COMMENT: or network outage problem.
    gpsocket = new Socket(personHost,
    RemoteDataServer.personReadPort);
    opened = true;
    catch (IOException ioe) {
    count--;
    if (count <= 0) {
    COMMENT: This line is NOT printed, so apparently there
    COMMENT: is no IOException when the Socket is
    COMMENT: created. Nor does an UnknownHostException
    COMMENT: or SecurityException stop the program.
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    result = null;
    return result;
    try {
    Thread.sleep(1000);
    catch (InterruptedException ie) {
    System.err.println(ie);
    ie.printStackTrace(System.err);
    // Read the serialized object
    try {
    COMMENT: No problem with the next line, which attempts
    COMMENT: to access the OutputStream of the socket.
    MyStringWriter msw = new MyStringWriter(
    gpsocket.getOutputStream());
    COMMENT: The next line causes the message.
    ObjectInputStream ois =
    new ObjectInputStream(gpsocket.getInputStream());
    msw.write(personRealName);
    // Now read the resulting Person.
    try {
    result = (Person)(ois.readObject());
    catch (ClassNotFoundException cnfe) {
    System.err.println(cnfe);
    cnfe.printStackTrace(System.err);
    System.exit(4);
    catch (IOException ioe) {
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    result = null;
    Server:
    public void activateFocusServer() throws java.rmi.RemoteException {
    String [] cmd = new String[2];
    cmd[0] = new String("java");
    cmd[1] = new String("RemoteDataServer");
    try {
    COMMENT: FORTE's Output window shows a message
    COMMENT: from this process
    Process dbserver =
    Runtime.getRuntime().exec(cmd); // Server will self-destruct
    // after a timeout period
    catch (IOException ioe) {
    COMMENT: This message is never printed
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    RemoteDataServer:
    public RemoteDataServer() {
    try {
    ...many different servers started here...
    ServerSocket PersonReadSocket = new ServerSocket(personReadPort);
    PersonReadListener prl = new PersonReadListener(PersonReadSocket);
    prl.start();
    catch (IOException ioe) {
    COMMENT: This message is never printed.
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    COMMENT: PersonReadListener is an inner class:
    class PersonReadListener extends java.lang.Thread {
    private Thread BaseThread;
    private ServerSocket theSocket;
    /** Creates an object to listen for PersonRead requests
    * @param ss The server socket to listen with
    public PersonReadListener(ServerSocket ss) {
    theSocket = ss;
    /** Initializes the thread to listen for PersonRead requests
    public void start() {
    BaseThread = new Thread(this);
    BaseThread.start();
    /** The code for the server to listen for PersonRead requests
    public void run() {
    while(true) {
    try {
    COMMENT: This code doesn't have access to System.err
    COMMENT: so a file is created to print debugging output
    PrintWriter debug = new PrintWriter(new FileWriter("person.debug"));
    COMMENT: The next line IS printed, so the server gets
    COMMENT: this far.
    debug.println("Waiting for connection for person's name");
    debug.close();
    PersonReadClientConnection someone =
    new PersonReadClientConnection(theSocket.accept());
    COMMENT: If the previous "debug.close" line is
    COMMENT: commented out and the next two lines are
    COMMENT: uncommented, the next line is NOT
    COMMENT: printed, so apparently the accept nevers
    COMMENT: happens! Why does the accept fail, but
    COMMENT: the client's socket creation succeed?
    // debug.println("Accepted a connection");
    // debug.close();
    someone.start();
    catch (IOException ioe) {
    COMMENT: These lines are NOT printed
    System.err.println(ioe);
    ioe.printStackTrace(System.err);

  • Parsing XML from Socket input stream

    I create a sax parser to which I send the InputStream from the socket
    But my HandlerBase never gets the events. I get startDocument
    but that is it, I never get any other event.
    The code I have works just like expected when I make the InputStream
    come from a file. The only differeence I see is that when I file is used the
    InputStream is fully consumed while with the socket the InputStream
    is kept open (I MUST KEEP THE SOCKET OPEN ALL THE TIME). If the parser
    does not generate the events unless the InputStream is fully consumed,
    isn't that against the whole idea of SAX (sax event driven) .
    Has anyone been succesfull parsing XML from the InputStream of a socket?
    if yes how?
    I am using JAXP 1.0.1 but I can upgrade to JAXP 1.1.0
    which uses SAX 2.0
    Does anybody know if my needs can be met by JAXP 1.1.0?
    Thanks

    I did the same with client/server model.
    I have client program with SAX parser. Please try if you can make the server side. I was be able to write the program with help from this forum. Please search to see if you can get the forum from which I got help for this program.
    // JAXP packages
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    // JAVA packages
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class XMLSocketClient {
    final private static int buffSize = 1024*10;
    final private static int PORTNUM = 8888;
         final private static int threadSleepValue = 1000;
    private static void usage() {
    System.err.println("Usage: XMLSocketClient [-v] serverAddr");
    System.err.println(" -v = validation");
    System.exit(1);
    public static void main(String[] args) {
    String address = null;
    boolean validation = false;
    Socket socket = null;
    InputStreamReader isr_socket = null;
    BufferedReader br_socket = null;
    CharArrayReader car = null;
    BufferedReader br_car = null;
    char[] charBuff = new char[buffSize];
    int in_buff = 0;
    * Parse arguments of command options
    for (int i = 0; i < args.length; i++) {
    if (args.equals("-v")) {
    validation = true;
    } else {
    address = args[i];
    // Must be last arg
    if (i != args.length - 1) {
    usage();
    // Initialize the socket and streams
    try {
    socket = new Socket(address, PORTNUM);
    isr_socket = new InputStreamReader(socket.getInputStream());
    br_socket = new BufferedReader(isr_socket, buffSize);
    catch (IOException e) {
    System.err.println("Exception: couldn't create stream socket "
    + e.getMessage());
    System.exit(1);
    * Check whether the buffer has input.
    try {
    while (br_socket.ready() != true) {
                   try {
                        Thread.currentThread().sleep(threadSleepValue);     
                   catch (InterruptedException ie) {
              System.err.println("Interrupted error for sleep: "+ ie.getMessage());
                   System.exit(1);
    catch (IOException e) {
    System.err.println("I/O error for in.read(): "+ e.getMessage());
    System.exit(1);
    try {
    in_buff = br_socket.read(charBuff, 0, buffSize);
    System.out.println("in_buff = " + in_buff);
    System.out.println("charBuff length: " + charBuff.length);
    if (in_buff != -1) {
    System.out.println("End of file");
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    System.exit(1);
    System.out.println("reading XML file:");
    StringBuffer display = new StringBuffer();
    display.append(charBuff, 0, in_buff);
    System.out.println(display.toString());
    * Create BufferedReader from the charBuff
    * in order to put into XML parser.
    car = new CharArrayReader(charBuff, 0, in_buff); // these two lines have to be here.
    br_car = new BufferedReader(car);
    * Create a JAXP SAXParserFactory and configure it
    * This section is standard handling of XML document by SAX XML parser.
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(validation);
    XMLReader xmlReader = null;
    try {
    // Create a JAXP SAXParser
    SAXParser saxParser = spf.newSAXParser();
    // Get the encapsulated SAX XMLReader
    xmlReader = saxParser.getXMLReader();
    } catch (Exception ex) {
    System.err.println(ex);
    System.exit(1);
    // Set the ContentHandler of the XMLReader
    xmlReader.setContentHandler(new MyXMLHandler());
    // Set an ErrorHandler before parsing
    xmlReader.setErrorHandler(new MyErrorHandler(System.err));
    try {
    * Tell the XMLReader to parse the XML document
    xmlReader.parse(new InputSource(br_car));
    } catch (SAXException se) {
    System.err.println(se.getMessage());
    System.exit(1);
    } catch (IOException ioe) {
    System.err.println(ioe);
    System.exit(1);
    * Clearance of i/o functions after parsing.
    try {
    br_socket.close();
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    try {
    socket.close();
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    try {
    br_car.close();
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    * The XML handler used by this program
    class MyXMLHandler extends DefaultHandler {
    // A Hashtable with tag names as keys and Integers as values
    private Hashtable tags;
    // Parser calls this once at the beginning of a document
    public void startDocument() throws SAXException {
    System.out.println("startDocument()");
    tags = new Hashtable();
    // Parser calls this for each element in a document
    public void startElement(String namespaceURI, String localName,
    String rawName, Attributes atts)
    throws SAXException
    String key = localName;
    Object value = tags.get(key);
    System.out.println("startElement()");
    System.out.println("namespaceURI: " + namespaceURI);
    System.out.println("localName: " + localName);
    System.out.println("rawName: " + rawName);
    if (value == null) {
    // Add a new entry
    tags.put(key, new Integer(1));
    } else {
    // Get the current count and increment it
    int count = ((Integer)value).intValue();
    count++;
    tags.put(key, new Integer(count));
    // Parser calls this once after parsing a document
    public void endDocument() throws SAXException {
    Enumeration e = tags.keys();
    System.out.println("endDocument()");
    while (e.hasMoreElements()) {
    String tag = (String)e.nextElement();
    int count = ((Integer)tags.get(tag)).intValue();
    System.out.println("Tag <" + tag + "> occurs " + count
    + " times");
    * Error handler of XML parser to report errors and warnings
    * This is standard handling.
    class MyErrorHandler implements ErrorHandler {
    /** Error handler output goes here */
    private PrintStream out;
    MyErrorHandler(PrintStream out) {
    this.out = out;
    * Returns a string describing parse exception details
    private String getParseExceptionInfo(SAXParseException spe) {
    String systemId = spe.getSystemId();
    if (systemId == null) {
    systemId = "null";
    String info = "URI=" + systemId +
    " Line=" + spe.getLineNumber() +
    ": " + spe.getMessage();
    return info;
    * The following methods are standard SAX ErrorHandler methods.
    * See SAX documentation for more info.
    public void warning(SAXParseException spe) throws SAXException {
    out.println("Warning: " + getParseExceptionInfo(spe));
    public void error(SAXParseException spe) throws SAXException {
    String message = "Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);
    public void fatalError(SAXParseException spe) throws SAXException {
    String message = "Fatal Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);

Maybe you are looking for

  • How to determine data type of cell in Excel file

    I have a company standard Excel file that needs to be read to determine what tests to run.  I have no control over its format.  I need to be able to tell what the data type is in order to read it using the LabView sample code.  It is a hodge poge of

  • Can't turn launch in camera raw off, part 2

    My problem was I wanted to batch process jpgs but they kept opening in ACR. Thanks to all for your suggestions. I ended up uninstalling and reinstalling PS and Bridge. Still I got the same results. I think that if the jpg has been processed in ACR, i

  • Number of TB displays you can add to MBP with TB

    Simple enough I guess. Is it possible to daisy chain 3 monitors with TB to a MBP with thunderbolt display port. 

  • Display issue or DVD player issue?

    I have a project which is aspected 16 x 9. When it plays on one DVD player it forces it to 4 x 3 and displays it as letterbox and nothing is squashed or stretched. No problem. On another DVD player (playing on a 4 x 3 monitor) it plays the 16 x 9 DVD

  • ERD - i'm not sure i understand

    i'm looking at a simple model in Bachman notation. and i'm not sure how is the optionality on the parent in 1:N relation is translated into Relational diagram. Example: drop 2 entities A and B. create to attributes marking them PK . drop 1:N, mark pa