1 22 23 package org.continuent.sequoia.common.util; 24 25 import java.io.IOException ; 26 import java.io.OutputStream ; 27 28 import org.apache.log4j.Category; 29 import org.apache.log4j.Priority; 30 31 43 public class LoggingOutputStream extends OutputStream 44 { 45 protected static final String LINE_SEPARATOR = System 46 .getProperty("line.separator"); 47 50 protected boolean hasBeenClosed = false; 51 54 protected byte[] buf; 55 60 protected int count; 61 64 private int bufLength; 65 68 public static final int DEFAULT_BUFFER_LENGTH = 2048; 69 72 protected Category category; 73 76 protected Priority priority; 77 78 private LoggingOutputStream() 79 { 80 } 82 83 90 public LoggingOutputStream(Category cat, Priority priority) 91 throws IllegalArgumentException 92 { 93 if (cat == null) 94 { 95 throw new IllegalArgumentException ("cat == null"); 96 } 97 if (priority == null) 98 { 99 throw new IllegalArgumentException ("priority == null"); 100 } 101 this.priority = priority; 102 category = cat; 103 bufLength = DEFAULT_BUFFER_LENGTH; 104 buf = new byte[DEFAULT_BUFFER_LENGTH]; 105 count = 0; 106 } 107 108 114 public void close() 115 { 116 flush(); 117 hasBeenClosed = true; 118 } 119 120 130 public void write(final int b) throws IOException 131 { 132 if (hasBeenClosed) 133 { 134 throw new IOException ("The stream has been closed."); 135 } 136 if (b == 0) 138 { 139 return; 140 } 141 if (count == bufLength) 143 { 144 final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH; 146 final byte[] newBuf = new byte[newBufLength]; 147 System.arraycopy(buf, 0, newBuf, 0, bufLength); 148 buf = newBuf; 149 bufLength = newBufLength; 150 } 151 buf[count] = (byte) b; 152 count++; 153 } 154 155 162 public void flush() 163 { 164 if (count == 0) 165 { 166 return; 167 } 168 if (count == LINE_SEPARATOR.length()) 170 { 171 if (((char) buf[0]) == LINE_SEPARATOR.charAt(0) && ((count == 1) || ((count == 2) && ((char) buf[1]) == LINE_SEPARATOR.charAt(1)))) 178 { 179 reset(); 180 return; 181 } 182 } 183 final byte[] theBytes = new byte[count]; 184 System.arraycopy(buf, 0, theBytes, 0, count); 185 186 String bytes = new String (theBytes).trim(); 188 int line = -1; 189 while((line = bytes.indexOf(LINE_SEPARATOR))!=-1) 190 { 191 bytes = bytes.substring(0, line) + bytes.substring(line+LINE_SEPARATOR.length()); 192 } 193 195 category.log(priority, bytes); 196 reset(); 197 } 198 199 private void reset() 200 { 201 count = 0; 204 } 205 } | Popular Tags |