001    package com.skype.ipc;
002    
003    import java.io.BufferedInputStream;
004    import java.io.FileOutputStream;
005    import java.io.IOException;
006    import java.io.InputStream;
007    
008    public class LoggedBufferedInputStream extends BufferedInputStream implements InputTransporting {
009    
010        public LoggedBufferedInputStream(InputStream in, ClientConfiguration cfg) {
011            super(in);
012            if (cfg.generateTransportLog()) {
013                try {
014                    mTransportLog = new FileOutputStream(cfg.getInputTransportLogName());
015                } catch (IOException e) {
016                    mTransportLog = null;
017                }
018            }
019        }
020    
021        public void skipBytes(final int numBytes) throws IOException {
022            if (mTransportLog != null) {
023                byte[] chunk = new byte[numBytes];
024                readBytes(chunk, 0, numBytes);
025            } else {
026               super.skip(numBytes);
027            }
028        }
029    
030        public void readBytes(final byte [] dest) throws IOException {
031            readBytes(dest, 0, dest.length);
032        }
033    
034        public void readBytes(final byte [] dest, final int offset, final int numBytes) throws IOException {
035            int consumed = 0;
036            while (consumed < numBytes) {
037                int r = super.read(dest, offset+consumed, numBytes - consumed);
038                if (r == -1) {
039                    throw new IOException("EOF");
040                } else {
041                    if (mTransportLog != null) {
042                        try {
043                            mTransportLog.write(dest, offset+consumed, r);
044                        } catch (IOException e) {
045                            mTransportLog = null; 
046                        }
047                    }
048                    consumed += r;
049                    if (consumed < numBytes) Thread.yield();
050                }
051            }
052        }
053    
054        public int readByte() throws IOException {
055            int b = super.read();
056            if (mTransportLog != null && b != -1) {
057                try {
058                    mTransportLog.write(b);
059                } catch (IOException e) {
060                    mTransportLog = null;
061                }
062            }
063            return b;
064        }
065    
066        public void close() throws IOException {
067            try {
068                if (mTransportLog != null) 
069                     mTransportLog.close();
070            } catch (IOException e) {
071            }
072            super.close();
073        }
074    
075        private FileOutputStream mTransportLog;
076    }
077