1 21 22 27 28 29 package com.sun.mail.iap; 30 31 import java.io.*; 32 import com.sun.mail.iap.ByteArray; 33 import com.sun.mail.util.ASCIIUtility; 34 35 42 43 public class ResponseInputStream { 44 45 private static final int minIncrement = 256; 46 private static final int maxIncrement = 256 * 1024; 47 private byte[] buffer = null; 48 private int sz = 0; 49 private int idx= 0; 50 private BufferedInputStream bin; 51 52 55 public ResponseInputStream(InputStream in) { 56 bin = new BufferedInputStream(in, 2 * 1024); 57 } 58 59 63 public ByteArray readResponse() throws IOException { 64 buffer = new byte[128]; 65 idx = 0; 66 sz = 128; 67 read0(); 68 return new ByteArray(buffer, 0, idx); 69 } 70 71 75 private void read0() throws IOException { 76 int b = 0; 78 boolean gotCRLF=false; 79 80 while (!gotCRLF && 82 ((b = bin.read()) != -1)) { 83 switch (b) { 84 case '\n': 85 if ((idx > 0) && buffer[idx-1] == '\r') 86 gotCRLF = true; 87 default: 88 if (idx >= sz) { 89 if (sz < maxIncrement) 90 growBuffer(sz); else 92 growBuffer(maxIncrement); } 94 buffer[idx++] = (byte)b; 95 } 96 } 97 98 if (b == -1) 99 throw new IOException(); 101 if (idx >= 5 && buffer[idx-3] == '}') { 104 int i; 105 for (i = idx-4; i >=0; i--) 107 if (buffer[i] == '{') 108 break; 109 110 if (i < 0) return; 112 113 int count = 0; 114 try { 116 count = ASCIIUtility.parseInt(buffer, i+1, idx-3); 117 } catch (NumberFormatException e) { 118 return; 119 } 120 121 if (count > 0) { 123 int avail = sz - idx; if (count > avail) 125 growBuffer(minIncrement > count - avail ? 127 minIncrement : count - avail); 128 132 int actual; 133 while (count > 0) { 134 actual = bin.read(buffer, idx, count); 135 count -= actual; 136 idx += actual; 137 } 138 } 139 140 144 read0(); 145 } 146 return; 147 } 148 149 150 private void growBuffer(int incr) { 151 byte[] nbuf = new byte[sz + incr]; 152 if (buffer != null) 153 System.arraycopy(buffer, 0, nbuf, 0, idx); 154 buffer = nbuf; 155 sz += incr; 156 } 157 } 158 | Popular Tags |