1 29 30 package com.caucho.db.store; 31 32 import com.caucho.vfs.TempBuffer; 33 34 import java.io.IOException ; 35 import java.io.OutputStream ; 36 import java.util.logging.Logger ; 37 38 public class BlobOutputStream extends OutputStream { 39 private static final Logger log 40 = Logger.getLogger(BlobOutputStream.class.getName()); 41 42 private StoreTransaction _xa; 43 private Store _store; 44 45 private TempBuffer _tempBuffer; 46 private byte []_buffer; 47 private int _offset; 48 private int _bufferEnd; 49 50 private Inode _inode; 51 52 private byte []_inodeBuffer; 53 private int _inodeOffset; 54 55 60 public BlobOutputStream(Transaction xa, Store store, 61 byte []inode, int inodeOffset) 62 { 63 init(store, inode, inodeOffset); 64 65 _xa = xa; 66 } 67 68 73 public BlobOutputStream(Store store, byte []inode, int inodeOffset) 74 { 75 init(store, inode, inodeOffset); 76 } 77 78 83 BlobOutputStream(Inode inode) 84 { 85 init(inode.getStore(), inode.getBuffer(), 0); 86 87 _inode = inode; 88 } 89 90 93 public void init(Store store, byte []inode, int inodeOffset) 94 { 95 _store = store; 96 _xa = RawTransaction.create(); 97 98 _inodeBuffer = inode; 99 _inodeOffset = inodeOffset; 100 101 Inode.clear(_inodeBuffer, _inodeOffset); 102 103 _offset = 0; 104 105 _tempBuffer = TempBuffer.allocate(); 106 _buffer = _tempBuffer.getBuffer(); 107 _bufferEnd = _buffer.length; 108 } 109 110 113 public void write(int v) 114 throws IOException 115 { 116 if (_bufferEnd <= _offset) { 117 flushBlock(); 118 } 119 120 _buffer[_offset++] = (byte) v; 121 } 122 123 126 public void write(byte []buffer, int offset, int length) 127 throws IOException 128 { 129 while (length > 0) { 130 if (_bufferEnd <= _offset) { 131 flushBlock(); 132 } 133 134 int sublen = _bufferEnd - _offset; 135 if (length < sublen) 136 sublen = length; 137 138 System.arraycopy(buffer, offset, _buffer, _offset, sublen); 139 140 offset += sublen; 141 _offset += sublen; 142 143 length -= sublen; 144 } 145 } 146 147 150 public void close() 151 throws IOException 152 { 153 try { 154 if (_tempBuffer == null) 155 return; 156 157 flushBlock(); 158 } finally { 159 Inode inode = _inode; 160 _inode = null; 161 162 if (inode != null) 163 inode.closeOutputStream(); 164 165 _inodeBuffer = null; 166 167 TempBuffer tempBuffer = _tempBuffer; 168 _tempBuffer = null; 169 170 if (tempBuffer != null) 171 TempBuffer.free(tempBuffer); 172 } 173 } 174 175 178 private void flushBlock() 179 throws IOException 180 { 181 int length = _offset; 182 _offset = 0; 183 184 Inode.append(_inodeBuffer, _inodeOffset, 185 _store, _xa, 186 _buffer, 0, length); 187 } 188 } 189 | Popular Tags |