1 24 25 package org.objectweb.cjdbc.common.util; 26 27 import java.io.IOException ; 28 import java.io.OutputStream ; 29 30 import org.apache.log4j.Category; 31 import org.apache.log4j.Priority; 32 33 45 public class LoggingOutputStream extends OutputStream 46 { 47 protected static final String LINE_SEPERATOR = System 48 .getProperty("line.separator"); 49 52 protected boolean hasBeenClosed = false; 53 56 protected byte[] buf; 57 62 protected int count; 63 66 private int bufLength; 67 70 public static final int DEFAULT_BUFFER_LENGTH = 2048; 71 74 protected Category category; 75 78 protected Priority priority; 79 80 private LoggingOutputStream() 81 { 82 } 84 85 92 public LoggingOutputStream(Category cat, Priority priority) 93 throws IllegalArgumentException 94 { 95 if (cat == null) 96 { 97 throw new IllegalArgumentException ("cat == null"); 98 } 99 if (priority == null) 100 { 101 throw new IllegalArgumentException ("priority == null"); 102 } 103 this.priority = priority; 104 category = cat; 105 bufLength = DEFAULT_BUFFER_LENGTH; 106 buf = new byte[DEFAULT_BUFFER_LENGTH]; 107 count = 0; 108 } 109 110 116 public void close() 117 { 118 flush(); 119 hasBeenClosed = true; 120 } 121 122 132 public void write(final int b) throws IOException 133 { 134 if (hasBeenClosed) 135 { 136 throw new IOException ("The stream has been closed."); 137 } 138 if (b == 0) 140 { 141 return; 142 } 143 if (count == bufLength) 145 { 146 final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH; 148 final byte[] newBuf = new byte[newBufLength]; 149 System.arraycopy(buf, 0, newBuf, 0, bufLength); 150 buf = newBuf; 151 bufLength = newBufLength; 152 } 153 buf[count] = (byte) b; 154 count++; 155 } 156 157 164 public void flush() 165 { 166 if (count == 0) 167 { 168 return; 169 } 170 if (count == LINE_SEPERATOR.length()) 172 { 173 if (((char) buf[0]) == LINE_SEPERATOR.charAt(0) && ((count == 1) || ((count == 2) && ((char) buf[1]) == LINE_SEPERATOR.charAt(1)))) 180 { 181 reset(); 182 return; 183 } 184 } 185 final byte[] theBytes = new byte[count]; 186 System.arraycopy(buf, 0, theBytes, 0, count); 187 188 String bytes = new String (theBytes).trim(); 190 int line = -1; 191 while((line = bytes.indexOf(LINE_SEPERATOR))!=-1) 192 { 193 bytes = bytes.substring(0, line) + bytes.substring(line+LINE_SEPERATOR.length()); 194 } 195 197 category.log(priority, bytes); 198 reset(); 199 } 200 201 private void reset() 202 { 203 count = 0; 206 } 207 } | Popular Tags |