1 2 package com.jofti.store; 3 4 import java.io.File ; 5 import java.io.FileNotFoundException ; 6 import java.io.IOException ; 7 import java.io.RandomAccessFile ; 8 import java.nio.channels.FileChannel ; 9 import java.nio.channels.FileLock ; 10 11 import org.apache.commons.logging.Log; 12 import org.apache.commons.logging.LogFactory; 13 14 import com.jofti.exception.JoftiException; 15 16 17 class FileStore 18 { 19 File file = null; 20 21 24 String fileMode = "rw"; 25 26 32 FileChannel channel = null; 33 34 35 protected int fileId =0; 36 37 38 private static Log log = LogFactory.getLog(FileManager.class); 39 40 41 46 long nextPosition = 0; 47 48 52 boolean newFile = true; 53 54 57 58 FileLock lock = null; 59 60 Object recordLock = new Object (); 61 62 63 long writes =0; 64 65 66 67 71 FileStore(File file, int id) 72 { 73 this.file = file; 74 this.fileId =id; 75 } 76 77 78 79 80 93 FileStore open(String fileMode) throws JoftiException, FileNotFoundException 94 { 95 this.fileMode = fileMode; 96 97 newFile = !file.exists(); 99 100 if (!newFile) newFile = file.length() == 0; 102 103 channel = new RandomAccessFile (file, fileMode).getChannel(); 104 105 try { 106 lock = channel.tryLock(); 107 } catch (IOException e) { 108 throw new JoftiException(e); 109 } 110 if (lock == null) 111 log.info("Unable to obtain lock on " + file.getAbsolutePath()); 112 113 return this; 114 } 115 116 122 FileStore close() throws IOException 123 { 124 if (channel.isOpen()) 125 { 126 if (lock != null) 127 { 128 lock.release(); 129 } 130 channel.close(); 131 } 132 return this; 133 } 134 135 141 void write(BlockBuffer lb) throws IOException 142 { 143 144 channel.write(lb.buffer,lb.positionHolder.position); 145 146 if (writes %10000 == 0){ 148 force(true); 149 } 150 writes++; 151 } 152 153 159 void force(boolean forceMetadata) throws IOException 160 { 161 channel.force(forceMetadata); 162 } 163 164 165 } 166 | Popular Tags |