Apache Solr open-source search software
merged with trunk
Simon Willnauer4be688e68dd5
diff --cc lucene/contrib/misc/src/java/org/apache/lucene/store/NRTCachingDirectory.javaindex e36fbb9f516,738397b76aa..98356b4d89e--- a/lucene/contrib/misc/src/java/org/apache/lucene/store/NRTCachingDirectory.java+++ b/lucene/contrib/misc/src/java/org/apache/lucene/store/NRTCachingDirectory.java@@@ -21,13 -21,13 +21,8 @@@ import java.io.IOExceptionimport java.util.Collection;import java.util.HashSet;import java.util.Set;--import java.util.concurrent.ConcurrentHashMap;--import org.apache.lucene.index.ConcurrentMergeScheduler;import org.apache.lucene.index.IndexFileNames;--import org.apache.lucene.index.IndexWriter; // javadocs--import org.apache.lucene.index.MergePolicy;--import org.apache.lucene.index.MergeScheduler;import org.apache.lucene.store.RAMDirectory; // javadocsimport org.apache.lucene.util.IOUtils;@@@ -221,6 -233,34 +216,26 @@@ public class NRTCachingDirectory extend}}+ @Override- public synchronized CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {++ public synchronized CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {+ if (cache.fileExists(name)) {- return cache.openCompoundInput(name, bufferSize);++ return cache.openCompoundInput(name, context);+ } else {- return delegate.openCompoundInput(name, bufferSize);++ return delegate.openCompoundInput(name, context);+ }+ }++ @Override- public synchronized CompoundFileDirectory createCompoundOutput(String name)++ public synchronized CompoundFileDirectory createCompoundOutput(String name, IOContext context)+ throws IOException {+ if (cache.fileExists(name)) {+ throw new IOException("File " + name + "already exists");+ } else {- return delegate.createCompoundOutput(name);++ return delegate.createCompoundOutput(name, context);+ }+ }+- @Override- public synchronized IndexInput openInput(String name, int bufferSize) throws IOException {- if (cache.fileExists(name)) {- return cache.openInput(name, bufferSize);- } else {- return delegate.openInput(name, bufferSize);- }- }+/** Close this directory, which flushes any cached files* to the delegate and then closes the delegate. */@Overridediff --cc lucene/src/java/org/apache/lucene/index/CheckIndex.javaindex de1ade56183,07545129eed..a3fec4d2f58--- a/lucene/src/java/org/apache/lucene/index/CheckIndex.java+++ b/lucene/src/java/org/apache/lucene/index/CheckIndex.java@@@ -17,13 -17,16 +17,23 @@@ package org.apache.lucene.index* limitations under the License.*/+import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.store.FSDirectory;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;+import org.apache.lucene.store.IndexInput;+ import java.io.File;+ import java.io.IOException;+ import java.io.PrintStream;+ import java.text.NumberFormat;+ import java.util.ArrayList;+ import java.util.Collection;+ import java.util.Comparator;+ import java.util.List;+ import java.util.Map;+import org.apache.lucene.document.AbstractField; // for javadocsimport org.apache.lucene.document.Document;import org.apache.lucene.index.codecs.CodecProvider;@@@ -31,18 -34,15 +41,9 @@@ import org.apache.lucene.index.codecs.Dimport org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.index.values.IndexDocValues;import org.apache.lucene.index.values.ValuesEnum;-import org.apache.lucene.search.DocIdSetIterator;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.TermQuery;-import org.apache.lucene.store.Directory;-import org.apache.lucene.store.FSDirectory;-import org.apache.lucene.store.IndexInput;import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;-- import java.text.NumberFormat;- import java.io.PrintStream;- import java.io.IOException;- import java.io.File;- import java.util.Collection;- import java.util.Comparator;- import java.util.List;- import java.util.ArrayList;- import java.util.Map;+ import org.apache.lucene.util.StringHelper;/*** Basic tool and API to check the health of an index anddiff --cc lucene/src/java/org/apache/lucene/index/IndexReader.javaindex fa876265fdf,c3df887ec4e..f843409b046--- a/lucene/src/java/org/apache/lucene/index/IndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/IndexReader.java@@@ -1432,15 -1434,14 +1434,15 @@@ public abstract class IndexReader imple}Directory dir = null;- CompoundFileReader cfr = null;+ CompoundFileDirectory cfr = null;+ IOContext context = IOContext.READ;try {File file = new File(filename);String dirname = file.getAbsoluteFile().getParent();filename = file.getName();dir = FSDirectory.open(new File(dirname));- cfr = new CompoundFileReader(dir, filename, context);- cfr = dir.openCompoundInput(filename, BufferedIndexInput.BUFFER_SIZE);++ cfr = dir.openCompoundInput(filename, IOContext.DEFAULT);String [] files = cfr.listAll();ArrayUtil.mergeSort(files); // sort the array of filename so that the output is more readablediff --cc lucene/src/java/org/apache/lucene/index/IndexWriter.javaindex 2a48e9ba03e,8efa46cdfca..32c8c9731ac--- a/lucene/src/java/org/apache/lucene/index/IndexWriter.java+++ b/lucene/src/java/org/apache/lucene/index/IndexWriter.java@@@ -45,14 -45,11 +45,13 @@@ import org.apache.lucene.index.SegmentCimport org.apache.lucene.index.codecs.CodecProvider;import org.apache.lucene.search.Query;import org.apache.lucene.store.AlreadyClosedException;--import org.apache.lucene.store.BufferedIndexInput;+ import org.apache.lucene.store.CompoundFileDirectory;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FlushInfo;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.Lock;import org.apache.lucene.store.LockObtainFailedException;+import org.apache.lucene.store.MergeInfo;- import org.apache.lucene.store.IOContext.Context;import org.apache.lucene.util.BitVector;import org.apache.lucene.util.Bits;import org.apache.lucene.util.Constants;@@@ -209,15 -207,15 +209,6 @@@ public class IndexWriter implements Clo* #setInfoStream}).*/public final static int MAX_TERM_LENGTH = DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8;---- // The normal read buffer size defaults to 1024, but-- // increasing this during merging seems to yield-- // performance gains. However we don't want to increase-- // it too much because there are quite a few-- // BufferedIndexInputs created during merging. See-- // LUCENE-888 for details.-- private final static int MERGE_READ_BUFFER_SIZE = 4096;--// Used for printing messagesprivate static final AtomicInteger MESSAGE_ID = new AtomicInteger();private int messageID = MESSAGE_ID.getAndIncrement();@@@ -2198,13 -2192,19 +2189,19 @@@String compoundFileName = IndexFileNames.segmentFileName(newSegment.name, "", IndexFileNames.COMPOUND_FILE_EXTENSION);message("creating compound file " + compoundFileName);// Now build compound file- CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, compoundFileName, context);- for(String fileName : newSegment.files()) {- cfsWriter.addFile(fileName);- final Directory cfsDir = directory.createCompoundOutput(compoundFileName);++ final Directory cfsDir = directory.createCompoundOutput(compoundFileName, context);+ IOException prior = null;+ try {+ for(String fileName : newSegment.files()) {- directory.copy(cfsDir, fileName, fileName);++ directory.copy(cfsDir, fileName, fileName, context);+ }+ } catch(IOException ex) {+ prior = ex;+ } finally {+ IOUtils.closeSafely(prior, cfsDir);}-// Perform the merge- cfsWriter.close();+synchronized(this) {deleter.deleteNewFiles(newSegment.files());}@@@ -2230,7 -2230,7 +2227,7 @@@// shortly-to-be-opened SegmentReader and let it// carry the changes; there's no reason to use// filesystem as intermediary here.- flushedSegment.deletedDocuments.write(directory, delFileName, context);- flushedSegment.liveDocs.write(directory, delFileName);++ flushedSegment.liveDocs.write(directory, delFileName, context);success2 = true;} finally {if (!success2) {@@@ -2514,24 -2507,25 +2511,25 @@@}/** Copies the segment into the IndexWriter's directory, as a compound segment. */- private void copySegmentIntoCFS(SegmentInfo info, String segName) throws IOException {+ private void copySegmentIntoCFS(SegmentInfo info, String segName, IOContext context) throws IOException {String segFileName = IndexFileNames.segmentFileName(segName, "", IndexFileNames.COMPOUND_FILE_EXTENSION);Collection<String> files = info.files();- CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, segFileName, context);- for (String file : files) {- String newFileName = segName + IndexFileNames.stripSegmentName(file);- if (!IndexFileNames.matchesExtension(file, IndexFileNames.DELETES_EXTENSION)- && !IndexFileNames.isSeparateNormsFile(file)) {- cfsWriter.addFile(file, info.dir);- } else {- assert !directory.fileExists(newFileName): "file \"" + newFileName + "\" already exists";- info.dir.copy(directory, file, newFileName, context);- final CompoundFileDirectory cfsdir = directory.createCompoundOutput(segFileName);++ final CompoundFileDirectory cfsdir = directory.createCompoundOutput(segFileName, context);+ try {+ for (String file : files) {+ String newFileName = segName + IndexFileNames.stripSegmentName(file);+ if (!IndexFileNames.matchesExtension(file, IndexFileNames.DELETES_EXTENSION)+ && !IndexFileNames.isSeparateNormsFile(file)) {- info.dir.copy(cfsdir, file, file);++ info.dir.copy(cfsdir, file, file, context);+ } else {+ assert !directory.fileExists(newFileName): "file \"" + newFileName + "\" already exists";- info.dir.copy(directory, file, newFileName);++ info.dir.copy(directory, file, newFileName, context);+ }}+ } finally {+ IOUtils.closeSafely(true, cfsdir);}- // Create the .cfs- cfsWriter.close();-info.dir = directory;info.name = segName;info.setUseCompoundFile(true);diff --cc lucene/src/java/org/apache/lucene/index/SegmentCoreReaders.javaindex e2437a97f61,35f8f94fe32..d478f856b51--- a/lucene/src/java/org/apache/lucene/index/SegmentCoreReaders.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentCoreReaders.java@@@ -23,8 -23,8 +23,9 @@@ import java.util.concurrent.atomic.Atomimport org.apache.lucene.index.codecs.Codec;import org.apache.lucene.index.codecs.FieldsProducer;import org.apache.lucene.index.codecs.PerDocValues;+ import org.apache.lucene.store.CompoundFileDirectory;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;/** Holds core readers that are shared (unchanged) when* SegmentReader is cloned or reopened */@@@ -74,7 -74,7 +75,7 @@@ final class SegmentCoreReaderstry {Directory dir0 = dir;if (si.getUseCompoundFile()) {- cfsReader = new CompoundFileReader(dir, IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context);- cfsReader = dir.openCompoundInput(IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION), readBufferSize);++ cfsReader = dir.openCompoundInput(IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context);dir0 = cfsReader;}cfsDir = dir0;@@@ -162,9 -162,9 +163,9 @@@if (si.getDocStoreOffset() != -1) {if (si.getDocStoreIsCompoundFile()) {assert storeCFSReader == null;- storeCFSReader = new CompoundFileReader(dir,+ storeCFSReader = dir.openCompoundInput(IndexFileNames.segmentFileName(si.getDocStoreSegment(), "", IndexFileNames.COMPOUND_FILE_STORE_EXTENSION),- readBufferSize);+ context);storeDir = storeCFSReader;assert storeDir != null;} else {@@@ -176,7 -176,7 +177,7 @@@// was not used, but then we are asked to open doc// stores after the segment has switched to CFSif (cfsReader == null) {- cfsReader = new CompoundFileReader(dir, IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context);- cfsReader = dir.openCompoundInput(IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION), readBufferSize);++ cfsReader = dir.openCompoundInput(IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context);}storeDir = cfsReader;assert storeDir != null;diff --cc lucene/src/java/org/apache/lucene/index/SegmentInfo.javaindex f924e6b3329,e25f0807a28..629165164da--- a/lucene/src/java/org/apache/lucene/index/SegmentInfo.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentInfo.java@@@ -30,8 -30,8 +30,9 @@@ import java.util.Setimport org.apache.lucene.index.codecs.Codec;import org.apache.lucene.index.codecs.CodecProvider;import org.apache.lucene.index.codecs.DefaultSegmentInfosWriter;+ import org.apache.lucene.store.BufferedIndexInput;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.Constants;@@@ -246,7 -247,7 +248,7 @@@ public final class SegmentInfo implemen}final Directory dirToTest;if (isCompoundFile) {- dirToTest = new CompoundFileReader(dir, IndexFileNames.segmentFileName(storesSegment, "", ext), IOContext.READONCE);- dirToTest = dir.openCompoundInput(IndexFileNames.segmentFileName(storesSegment, "", ext), BufferedIndexInput.BUFFER_SIZE);++ dirToTest = dir.openCompoundInput(IndexFileNames.segmentFileName(storesSegment, "", ext), IOContext.READONCE );} else {dirToTest = dir;}@@@ -264,8 -265,8 +266,8 @@@if (fieldInfos == null) {Directory dir0 = dir;if (isCompoundFile && checkCompoundFile) {- dir0 = new CompoundFileReader(dir, IndexFileNames.segmentFileName(name,+ dir0 = dir.openCompoundInput(IndexFileNames.segmentFileName(name,- "", IndexFileNames.COMPOUND_FILE_EXTENSION), BufferedIndexInput.BUFFER_SIZE);+ "", IndexFileNames.COMPOUND_FILE_EXTENSION), IOContext.READONCE);}try {fieldInfos = new FieldInfos(dir0, IndexFileNames.segmentFileName(name,diff --cc lucene/src/java/org/apache/lucene/index/SegmentMerger.javaindex f388f156e7f,30e02f11db4..beb7361aa58--- a/lucene/src/java/org/apache/lucene/index/SegmentMerger.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentMerger.java@@@ -31,8 -31,8 +31,9 @@@ import org.apache.lucene.index.codecs.Fimport org.apache.lucene.index.codecs.MergeState;import org.apache.lucene.index.codecs.PerDocConsumer;import org.apache.lucene.index.codecs.PerDocValues;+ import org.apache.lucene.store.CompoundFileDirectory;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.Bits;@@@ -136,18 -133,20 +137,20 @@@ final class SegmentMerger// Now merge all added filesCollection<String> files = info.files();- CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, fileName, context, checkAbort);- for (String file : files) {- assert !IndexFileNames.matchesExtension(file, IndexFileNames.DELETES_EXTENSION)- : ".del file is not allowed in .cfs: " + file;- assert !IndexFileNames.isSeparateNormsFile(file)- : "separate norms file (.s[0-9]+) is not allowed in .cfs: " + file;- cfsWriter.addFile(file);- CompoundFileDirectory cfsDir = directory.createCompoundOutput(fileName);++ CompoundFileDirectory cfsDir = directory.createCompoundOutput(fileName, context);+ try {+ for (String file : files) {+ assert !IndexFileNames.matchesExtension(file, IndexFileNames.DELETES_EXTENSION)+ : ".del file is not allowed in .cfs: " + file;+ assert !IndexFileNames.isSeparateNormsFile(file)+ : "separate norms file (.s[0-9]+) is not allowed in .cfs: " + file;- directory.copy(cfsDir, file, file);++ directory.copy(cfsDir, file, file, context);+ checkAbort.work(directory.fileLength(file));+ }+ } finally {+ cfsDir.close();}- // Perform the merge- cfsWriter.close();-return files;}diff --cc lucene/src/java/org/apache/lucene/index/SegmentReader.javaindex 967d4dff32a,456d46f850c..e1aa5dae01c--- a/lucene/src/java/org/apache/lucene/index/SegmentReader.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentReader.java@@@ -30,8 -30,8 +30,9 @@@ import java.util.concurrent.atomic.Atomimport org.apache.lucene.document.Document;import org.apache.lucene.document.FieldSelector;import org.apache.lucene.index.codecs.PerDocValues;+ import org.apache.lucene.store.BufferedIndexInput;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.util.BitVector;import org.apache.lucene.util.Bits;@@@ -114,8 -116,8 +115,8 @@@ public class SegmentReader extends Indeif (doOpenStores) {instance.core.openDocStores(si);}- instance.loadDeletedDocs();+ instance.loadLiveDocs();- instance.openNorms(instance.core.cfsDir, readBufferSize);+ instance.openNorms(instance.core.cfsDir, context);success = true;} finally {@@@ -156,14 -158,17 +157,17 @@@return true;}- private void loadDeletedDocs() throws IOException {+ private void loadLiveDocs() throws IOException {// NOTE: the bitvector is stored using the regular directory, not cfsif (hasDeletions(si)) {- deletedDocs = new BitVector(directory(), si.getDelFileName(), IOContext.DEFAULT);- deletedDocsRef = new AtomicInteger(1);- assert checkDeletedCounts();- if (deletedDocs.size() != si.docCount) {- throw new CorruptIndexException("document count mismatch: deleted docs count " + deletedDocs.size() + " vs segment doc count " + si.docCount + " segment=" + si.name);- liveDocs = new BitVector(directory(), si.getDelFileName());++ liveDocs = new BitVector(directory(), si.getDelFileName(), IOContext.DEFAULT);+ if (liveDocs.getVersion() < BitVector.VERSION_DGAPS_CLEARED) {+ liveDocs.invertAll();+ }+ liveDocsRef = new AtomicInteger(1);+ assert checkLiveCounts();+ if (liveDocs.size() != si.docCount) {+ throw new CorruptIndexException("document count mismatch: deleted docs count " + liveDocs.size() + " vs segment doc count " + si.docCount + " segment=" + si.name);}} elseassert si.getDelCount() == 0;@@@ -334,7 -340,7 +338,7 @@@final String delFileName = si.getDelFileName();boolean success = false;try {- deletedDocs.write(directory(), delFileName, IOContext.DEFAULT);- liveDocs.write(directory(), delFileName);++ liveDocs.write(directory(), delFileName, IOContext.DEFAULT);success = true;} finally {if (!success) {diff --cc lucene/src/java/org/apache/lucene/index/codecs/DefaultDocValuesProducer.javaindex 8755bb6f364,9daf244fa42..663df35c036--- a/lucene/src/java/org/apache/lucene/index/codecs/DefaultDocValuesProducer.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/DefaultDocValuesProducer.java@@@ -120,26 -119,30 +120,30 @@@ public class DefaultDocValuesProducer e* if the given {@link ValueType} is not supported*/protected IndexDocValues loadDocValues(int docCount, Directory dir, String id,- ValueType type) throws IOException {+ ValueType type, IOContext context) throws IOException {switch (type) {- case INTS:- return Ints.getValues(dir, id, false, context);+ case FIXED_INTS_16:+ case FIXED_INTS_32:+ case FIXED_INTS_64:+ case FIXED_INTS_8:+ case VAR_INTS:- return Ints.getValues(dir, id, docCount);++ return Ints.getValues(dir, id, docCount, context);case FLOAT_32:- return Floats.getValues(dir, id, docCount);+ return Floats.getValues(dir, id, docCount, context);case FLOAT_64:- return Floats.getValues(dir, id, docCount);+ return Floats.getValues(dir, id, docCount, context);case BYTES_FIXED_STRAIGHT:- return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, true, docCount);+ return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, true, docCount, context);case BYTES_FIXED_DEREF:- return Bytes.getValues(dir, id, Bytes.Mode.DEREF, true, docCount);+ return Bytes.getValues(dir, id, Bytes.Mode.DEREF, true, docCount, context);case BYTES_FIXED_SORTED:- return Bytes.getValues(dir, id, Bytes.Mode.SORTED, true, docCount);+ return Bytes.getValues(dir, id, Bytes.Mode.SORTED, true, docCount, context);case BYTES_VAR_STRAIGHT:- return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, false, docCount);+ return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, false, docCount, context);case BYTES_VAR_DEREF:- return Bytes.getValues(dir, id, Bytes.Mode.DEREF, false, docCount);+ return Bytes.getValues(dir, id, Bytes.Mode.DEREF, false, docCount, context);case BYTES_VAR_SORTED:- return Bytes.getValues(dir, id, Bytes.Mode.SORTED, false, docCount);+ return Bytes.getValues(dir, id, Bytes.Mode.SORTED, false, docCount, context);default:throw new IllegalStateException("unrecognized index values mode " + type);}diff --cc lucene/src/java/org/apache/lucene/index/codecs/DefaultSegmentInfosReader.javaindex efa8e9a166a,b21fb781671..443d41d3f93--- a/lucene/src/java/org/apache/lucene/index/codecs/DefaultSegmentInfosReader.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/DefaultSegmentInfosReader.java@@@ -69,13 -67,13 +68,13 @@@ public class DefaultSegmentInfosReaderDirectory dir = directory;if (si.getDocStoreOffset() != -1) {if (si.getDocStoreIsCompoundFile()) {- dir = new CompoundFileReader(dir, IndexFileNames.segmentFileName(+ dir = dir.openCompoundInput(IndexFileNames.segmentFileName(si.getDocStoreSegment(), "",- IndexFileNames.COMPOUND_FILE_STORE_EXTENSION), 1024);+ IndexFileNames.COMPOUND_FILE_STORE_EXTENSION), context);}} else if (si.getUseCompoundFile()) {- dir = new CompoundFileReader(dir, IndexFileNames.segmentFileName(+ dir = dir.openCompoundInput(IndexFileNames.segmentFileName(- si.name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), 1024);+ si.name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context);}try {diff --cc lucene/src/java/org/apache/lucene/index/codecs/preflex/PreFlexFields.javaindex 61f67bb110c,78253acdd13..ac3962d50e4--- a/lucene/src/java/org/apache/lucene/index/codecs/preflex/PreFlexFields.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/preflex/PreFlexFields.java@@@ -37,8 -36,8 +36,9 @@@ import org.apache.lucene.index.Termimport org.apache.lucene.index.Terms;import org.apache.lucene.index.TermsEnum;import org.apache.lucene.index.codecs.FieldsProducer;+ import org.apache.lucene.store.CompoundFileDirectory;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;@@@ -178,8 -177,8 +178,8 @@@ public class PreFlexFields extends Fiel// terms reader with index, the segment has switched// to CFS- if (!(dir instanceof CompoundFileReader)) {- dir0 = cfsReader = new CompoundFileReader(dir, IndexFileNames.segmentFileName(si.name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context);+ if (!(dir instanceof CompoundFileDirectory)) {- dir0 = cfsReader = dir.openCompoundInput(IndexFileNames.segmentFileName(si.name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), readBufferSize);++ dir0 = cfsReader = dir.openCompoundInput(IndexFileNames.segmentFileName(si.name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), context);} else {dir0 = dir;}diff --cc lucene/src/java/org/apache/lucene/index/codecs/preflex/TermInfosReader.javaindex 8dfd1de7da6,ab99c160bfb..3ca8ca617f4--- a/lucene/src/java/org/apache/lucene/index/codecs/preflex/TermInfosReader.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/preflex/TermInfosReader.java@@@ -21,10 -22,10 +22,11 @@@ import java.util.Comparatorimport org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.index.FieldInfos;- import org.apache.lucene.index.Term;import org.apache.lucene.index.IndexFileNames;+ import org.apache.lucene.index.Term;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;+ import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.CloseableThreadLocal;import org.apache.lucene.util.DoubleBarrelLRUCache;diff --cc lucene/src/java/org/apache/lucene/index/values/Bytes.javaindex a7d80fcce26,4cd44751d35..9735c69a0dc--- a/lucene/src/java/org/apache/lucene/index/values/Bytes.java+++ b/lucene/src/java/org/apache/lucene/index/values/Bytes.java@@@ -102,14 -100,13 +101,14 @@@ public final class Bytes* {@link Writer}. A call to {@link Writer#finish(int)} will release* all internally used resources and frees the memeory tracking* reference.++ * @param context* @return a new {@link Writer} instance* @throws IOException* if the files for the writer can not be created.*/public static Writer getWriter(Directory dir, String id, Mode mode,- Comparator<BytesRef> comp, boolean fixedSize, AtomicLong bytesUsed)+ Comparator<BytesRef> comp, boolean fixedSize, AtomicLong bytesUsed, IOContext context)throws IOException {-// TODO -- i shouldn't have to specify fixed? can// track itself & do the write thing at write time?if (comp == null) {@@@ -118,11 -115,11 +117,11 @@@if (fixedSize) {if (mode == Mode.STRAIGHT) {- return new FixedStraightBytesImpl.Writer(dir, id, context);- return new FixedStraightBytesImpl.Writer(dir, id, bytesUsed);++ return new FixedStraightBytesImpl.Writer(dir, id, bytesUsed, context);} else if (mode == Mode.DEREF) {- return new FixedDerefBytesImpl.Writer(dir, id, bytesUsed);+ return new FixedDerefBytesImpl.Writer(dir, id, bytesUsed, context);} else if (mode == Mode.SORTED) {- return new FixedSortedBytesImpl.Writer(dir, id, comp, bytesUsed);+ return new FixedSortedBytesImpl.Writer(dir, id, comp, bytesUsed, context);}} else {if (mode == Mode.STRAIGHT) {@@@ -340,28 -336,47 +339,48 @@@// TODO: open up this API?!static abstract class BytesWriterBase extends Writer {private final String id;- protected IndexOutput idxOut;- protected IndexOutput datOut;+ private IndexOutput idxOut;+ private IndexOutput datOut;protected BytesRef bytesRef;- protected final ByteBlockPool pool;+ private final Directory dir;+ private final String codecName;+ private final int version;++ private final IOContext context;protected BytesWriterBase(Directory dir, String id, String codecName,- int version, boolean initIndex, ByteBlockPool pool,- AtomicLong bytesUsed, IOContext context) throws IOException {- int version,- AtomicLong bytesUsed) throws IOException {++ int version, AtomicLong bytesUsed, IOContext context) throws IOException {super(bytesUsed);this.id = id;- this.pool = pool;- datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- DATA_EXTENSION), context);+ this.dir = dir;+ this.codecName = codecName;+ this.version = version;++ this.context = context;+ }++ protected IndexOutput getDataOut() throws IOException {+ if (datOut == null) {+ boolean success = false;+ try {+ datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- DATA_EXTENSION));++ DATA_EXTENSION), context);+ CodecUtil.writeHeader(datOut, codecName, version);+ success = true;+ } finally {+ if (!success) {+ IOUtils.closeSafely(true, datOut);+ }+ }+ }+ return datOut;+ }++ protected IndexOutput getIndexOut() throws IOException {boolean success = false;try {- CodecUtil.writeHeader(datOut, codecName, version);- if (initIndex) {+ if (idxOut == null) {idxOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- INDEX_EXTENSION));+ INDEX_EXTENSION), context);CodecUtil.writeHeader(idxOut, codecName, version);- } else {- idxOut = null;}success = true;} finally {diff --cc lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.javaindex fe7addc67a6,f11186f6edb..704c7f06ff3--- a/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java@@@ -24,8 -24,8 +24,9 @@@ import org.apache.lucene.index.values.Bimport org.apache.lucene.index.values.Bytes.BytesReaderBase;import org.apache.lucene.index.values.Bytes.BytesWriterBase;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.ByteBlockPool;@@@ -52,22 -53,21 +54,21 @@@ class FixedDerefBytesImplstatic class Writer extends BytesWriterBase {private int size = -1;private int[] docToID;- private final BytesRefHash hash = new BytesRefHash(pool,- BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(- BytesRefHash.DEFAULT_CAPACITY, bytesUsed));+ private final BytesRefHash hash;- public Writer(Directory dir, String id, AtomicLong bytesUsed)+ public Writer(Directory dir, String id, AtomicLong bytesUsed, IOContext context)throws IOException {this(dir, id, new DirectTrackingAllocator(ByteBlockPool.BYTE_BLOCK_SIZE, bytesUsed),- bytesUsed);+ bytesUsed, context);}public Writer(Directory dir, String id, Allocator allocator,- AtomicLong bytesUsed) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed);+ AtomicLong bytesUsed, IOContext context) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, true,- new ByteBlockPool(allocator), bytesUsed, context);++ super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed, context);+ hash = new BytesRefHash(new ByteBlockPool(allocator),+ BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(+ BytesRefHash.DEFAULT_CAPACITY, bytesUsed));docToID = new int[1];- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT); // TODO BytesRefHash- // uses bytes too!+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);}@Overridediff --cc lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.javaindex 294eb7ce224,d1dc0f83c83..afaf533c621--- a/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java@@@ -26,8 -26,8 +26,9 @@@ import org.apache.lucene.index.values.Bimport org.apache.lucene.index.values.Bytes.BytesWriterBase;import org.apache.lucene.index.values.FixedDerefBytesImpl.Reader.DerefBytesEnum;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.ByteBlockPool;@@@ -57,23 -58,22 +59,22 @@@ class FixedSortedBytesImplprivate int size = -1;private int[] docToEntry;private final Comparator<BytesRef> comp;-- private final BytesRefHash hash = new BytesRefHash(pool,- BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(- BytesRefHash.DEFAULT_CAPACITY, bytesUsed));+ private final BytesRefHash hash;public Writer(Directory dir, String id, Comparator<BytesRef> comp,- AtomicLong bytesUsed) throws IOException {+ AtomicLong bytesUsed, IOContext context) throws IOException {this(dir, id, comp, new DirectTrackingAllocator(ByteBlockPool.BYTE_BLOCK_SIZE, bytesUsed),- bytesUsed);+ bytesUsed, context);}public Writer(Directory dir, String id, Comparator<BytesRef> comp,- Allocator allocator, AtomicLong bytesUsed) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed);+ Allocator allocator, AtomicLong bytesUsed, IOContext context) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, true,- new ByteBlockPool(allocator), bytesUsed, context);++ super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed, context);+ ByteBlockPool pool = new ByteBlockPool(allocator);+ hash = new BytesRefHash(pool, BytesRefHash.DEFAULT_CAPACITY,+ new TrackingDirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY,+ bytesUsed));docToEntry = new int[1];- // docToEntry[0] = -1;bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);this.comp = comp;}diff --cc lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.javaindex 53e1d4d7726,a50002762b1..1e93d7730a6--- a/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java@@@ -23,9 -26,11 +26,12 @@@ import org.apache.lucene.index.values.Bimport org.apache.lucene.index.values.Bytes.BytesReaderBase;import org.apache.lucene.index.values.Bytes.BytesWriterBase;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.AttributeSource;+ import org.apache.lucene.util.ByteBlockPool;+ import org.apache.lucene.util.ByteBlockPool.DirectTrackingAllocator;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.PagedBytes;@@@ -45,19 -50,27 +51,27 @@@ class FixedStraightBytesImplprivate int size = -1;// start at -1 if the first added value is > 0private int lastDocID = -1;- private byte[] oneRecord;+ private final ByteBlockPool pool;+ private boolean merge;+ private final int byteBlockSize;+ private IndexOutput datOut;- public Writer(Directory dir, String id, IOContext context) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, null, null, context);- public Writer(Directory dir, String id, AtomicLong bytesUsed) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed);++ public Writer(Directory dir, String id, AtomicLong bytesUsed, IOContext context) throws IOException {++ super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed, context);+ pool = new ByteBlockPool(new DirectTrackingAllocator(bytesUsed));+ byteBlockSize = BYTE_BLOCK_SIZE;}-@Overridepublic void add(int docID, BytesRef bytes) throws IOException {+ assert lastDocID < docID;+ assert !merge;if (size == -1) {+ if (bytes.length > BYTE_BLOCK_SIZE) {+ throw new IllegalArgumentException("bytes arrays > " + Short.MAX_VALUE + " are not supported");+ }size = bytes.length;- datOut.writeInt(size);- oneRecord = new byte[size];+ pool.nextBuffer();} else if (bytes.length != size) {throw new IllegalArgumentException("expected bytes size=" + size+ " but got " + bytes.length);diff --cc lucene/src/java/org/apache/lucene/index/values/Floats.javaindex b55ea70011c,6a35a855bca..a8c1e2e04ef--- a/lucene/src/java/org/apache/lucene/index/values/Floats.java+++ b/lucene/src/java/org/apache/lucene/index/values/Floats.java@@@ -23,9 -23,9 +23,10 @@@ import java.util.concurrent.atomic.Atomimport org.apache.lucene.index.IndexFileNames;import org.apache.lucene.index.values.IndexDocValues.Source;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;+ import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.CodecUtil;import org.apache.lucene.util.FloatsRef;@@@ -45,14 -46,10 +47,10 @@@ public class Floatsprivate static final String CODEC_NAME = "SimpleFloats";static final int VERSION_START = 0;static final int VERSION_CURRENT = VERSION_START;- private static final int INT_DEFAULT = Float- .floatToRawIntBits(0.0f);- private static final long LONG_DEFAULT = Double- .doubleToRawLongBits(0.0d);-+ private static final byte[] DEFAULTS = new byte[] {0,0,0,0,0,0,0,0};public static Writer getWriter(Directory dir, String id, int precisionBytes,- AtomicLong bytesUsed) throws IOException {+ AtomicLong bytesUsed, IOContext context) throws IOException {if (precisionBytes != 4 && precisionBytes != 8) {throw new IllegalArgumentException("precisionBytes must be 4 or 8; got "+ precisionBytes);@@@ -75,14 -72,25 +73,27 @@@protected int lastDocId = -1;protected IndexOutput datOut;private final byte precision;+ private final Directory dir;++ private final IOContext context;protected FloatsWriter(Directory dir, String id, int precision,- AtomicLong bytesUsed) throws IOException {+ AtomicLong bytesUsed, IOContext context) throws IOException {super(bytesUsed);this.id = id;this.precision = (byte) precision;+ this.dir = dir;++ this.context = context;++ }++ public long ramBytesUsed() {+ return 0;+ }++ final void initDataOut() throws IOException {+ assert datOut == null;datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- Writer.DATA_EXTENSION));+ Writer.DATA_EXTENSION), context);boolean success = false;try {CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);@@@ -143,11 -156,13 +159,13 @@@}// Writes 4 bytes (float) per value- static class Float4Writer extends FloatsWriter {-+ static final class Float4Writer extends FloatsWriter {+ private int[] values;- protected Float4Writer(Directory dir, String id, AtomicLong bytesUsed)+ protected Float4Writer(Directory dir, String id, AtomicLong bytesUsed, IOContext context)throws IOException {- super(dir, id, 4, bytesUsed);+ super(dir, id, 4, bytesUsed, context);+ values = new int[1];+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);}@Override@@@ -186,11 -219,13 +222,13 @@@}// Writes 8 bytes (double) per value- static class Float8Writer extends FloatsWriter {-+ static final class Float8Writer extends FloatsWriter {+ private long[] values;- protected Float8Writer(Directory dir, String id, AtomicLong bytesUsed)+ protected Float8Writer(Directory dir, String id, AtomicLong bytesUsed, IOContext context)throws IOException {- super(dir, id, 8, bytesUsed);+ super(dir, id, 8, bytesUsed, context);+ values = new long[1];+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG);}@Overridediff --cc lucene/src/java/org/apache/lucene/index/values/Ints.javaindex ec802f265d7,84316575c06..ba576401f68--- a/lucene/src/java/org/apache/lucene/index/values/Ints.java+++ b/lucene/src/java/org/apache/lucene/index/values/Ints.java@@@ -34,14 -33,11 +34,13 @@@ public class Intsprivate Ints() {}- public static Writer getWriter(Directory dir, String id, AtomicLong bytesUsed, ValueType type) throws IOException {- return new IntsWriter(dir, id, bytesUsed, type);+ public static Writer getWriter(Directory dir, String id,- boolean useFixedArray, AtomicLong bytesUsed, IOContext context) throws IOException {- // TODO - implement fixed?!- return new IntsWriter(dir, id, bytesUsed, context);++ AtomicLong bytesUsed, ValueType type, IOContext context) throws IOException {++ return new IntsWriter(dir, id, bytesUsed, type, context);}- public static IndexDocValues getValues(Directory dir, String id, int numDocs) throws IOException {- return new IntsReader(dir, id, numDocs);+ public static IndexDocValues getValues(Directory dir, String id,- boolean useFixedArray, IOContext context) throws IOException {- return new IntsReader(dir, id, context);++ int numDocs, IOContext context) throws IOException {++ return new IntsReader(dir, id, numDocs, context);}}diff --cc lucene/src/java/org/apache/lucene/index/values/IntsImpl.javaindex 5a67c22873f,0e64e25f18a..56e9ad98977--- a/lucene/src/java/org/apache/lucene/index/values/IntsImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/IntsImpl.java@@@ -21,11 -21,16 +21,17 @@@ import java.util.Collectionimport java.util.concurrent.atomic.AtomicLong;import org.apache.lucene.index.IndexFileNames;+ import org.apache.lucene.index.values.IndexDocValuesArray;+ import org.apache.lucene.index.values.IndexDocValues.Source;+ import org.apache.lucene.index.values.IndexDocValues.SourceEnum;+ import org.apache.lucene.index.values.IndexDocValuesArray.ByteValues;+ import org.apache.lucene.index.values.IndexDocValuesArray.IntValues;+ import org.apache.lucene.index.values.IndexDocValuesArray.LongValues;+ import org.apache.lucene.index.values.IndexDocValuesArray.ShortValues;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;- import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.CodecUtil;import org.apache.lucene.util.IOUtils;@@@ -57,30 -63,43 +64,45 @@@ class IntsImplprivate boolean started;private final String id;private int lastDocId = -1;+ private final Directory dir;+ private final byte typeOrd;private IndexOutput datOut;+ private boolean merging;++ private final IOContext context;+- protected IntsWriter(Directory dir, String id, AtomicLong bytesUsed, IOContext context)- throws IOException {+ protected IntsWriter(Directory dir, String id, AtomicLong bytesUsed,- ValueType valueType) throws IOException {++ ValueType valueType, IOContext context) throws IOException {super(bytesUsed);- datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- DATA_EXTENSION), context);- boolean success = false;- try {- CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);- this.id = id;- docToValue = new long[1];- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG); // TODO the- // bitset- // needs memory- // too- success = true;- } finally {- if (!success) {- datOut.close();- }++ this.context = context;+ this.dir = dir;+ this.id = id;+ switch (valueType) {+ case FIXED_INTS_16:+ array= new ShortValues(bytesUsed);+ typeOrd = FIXED_16;+ break;+ case FIXED_INTS_32:+ array = new IntValues(bytesUsed);+ typeOrd = FIXED_32;+ break;+ case FIXED_INTS_64:+ array = new LongValues(bytesUsed);+ typeOrd = FIXED_64;+ break;+ case FIXED_INTS_8:+ array = new ByteValues(bytesUsed);+ typeOrd = FIXED_8;+ break;+ case VAR_INTS:+ array = new LongValues(bytesUsed);+ typeOrd = PACKED;+ break;+ default:+ throw new IllegalStateException("unknown type " + valueType);}}-+@Overridepublic void add(int docID, long v) throws IOException {assert lastDocId < docID;@@@ -95,14 -114,25 +117,25 @@@}}lastDocId = docID;-- if (docID >= docToValue.length) {- final long len = docToValue.length;- docToValue = ArrayUtil.grow(docToValue, 1 + docID);- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG- * ((docToValue.length) - len));+ array.set(docID, v);+ }++ private final void initDataOut(byte typeOrd) throws IOException {+ if (datOut == null) {+ boolean success = false;+ try {+ datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- DATA_EXTENSION));++ DATA_EXTENSION), context);+ CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);+ datOut.writeByte(typeOrd);+ success = true;++ } finally {+ if (!success) {+ IOUtils.closeSafely(true, datOut);+ }+ }}- docToValue[docID] = v;}@Override@@@ -184,11 -270,13 +273,13 @@@*/static class IntsReader extends IndexDocValues {private final IndexInput datIn;- private final boolean packed;+ private final byte type;+ private final int numDocs;- protected IntsReader(Directory dir, String id, IOContext context) throws IOException {- protected IntsReader(Directory dir, String id, int numDocs) throws IOException {++ protected IntsReader(Directory dir, String id, int numDocs, IOContext context) throws IOException {datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",- Writer.DATA_EXTENSION));+ Writer.DATA_EXTENSION), context);+ this.numDocs = numDocs;boolean success = false;try {CodecUtil.checkHeader(datIn, CODEC_NAME, VERSION_START, VERSION_START);diff --cc lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.javaindex 76ca1146620,ced6ebea999..c862dd1103c--- a/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java@@@ -26,8 -26,8 +26,9 @@@ import org.apache.lucene.index.values.Bimport org.apache.lucene.index.values.FixedDerefBytesImpl.Reader.DerefBytesEnum;import org.apache.lucene.store.DataOutput;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.ByteBlockPool;@@@ -114,18 -115,18 +116,18 @@@ class VarDerefBytesImplprivate final AddressByteStartArray array = new AddressByteStartArray(1,bytesUsed);- private final BytesRefHash hash = new BytesRefHash(pool, 16, array);+ private final BytesRefHash hash;- public Writer(Directory dir, String id, AtomicLong bytesUsed)+ public Writer(Directory dir, String id, AtomicLong bytesUsed, IOContext context)throws IOException {this(dir, id, new DirectTrackingAllocator(ByteBlockPool.BYTE_BLOCK_SIZE, bytesUsed),- bytesUsed);+ bytesUsed, context);}public Writer(Directory dir, String id, Allocator allocator,- AtomicLong bytesUsed) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed);+ AtomicLong bytesUsed, IOContext context) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, true,- new ByteBlockPool(allocator), bytesUsed, context);++ super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed, context);+ hash = new BytesRefHash(new ByteBlockPool(allocator), 16, array);docToAddress = new int[1];bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);}diff --cc lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.javaindex cbbbb0d3781,905cf9f7862..b452f45b006--- a/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java@@@ -26,8 -26,8 +26,9 @@@ import org.apache.lucene.index.values.Bimport org.apache.lucene.index.values.Bytes.BytesReaderBase;import org.apache.lucene.index.values.Bytes.BytesWriterBase;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.ByteBlockPool;@@@ -57,20 -58,20 +59,20 @@@ class VarSortedBytesImplprivate int[] docToEntry;private final Comparator<BytesRef> comp;- private final BytesRefHash hash = new BytesRefHash(pool,- BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(- BytesRefHash.DEFAULT_CAPACITY, bytesUsed));+ private final BytesRefHash hash;public Writer(Directory dir, String id, Comparator<BytesRef> comp,- AtomicLong bytesUsed) throws IOException {+ AtomicLong bytesUsed, IOContext context) throws IOException {this(dir, id, comp, new DirectTrackingAllocator(ByteBlockPool.BYTE_BLOCK_SIZE, bytesUsed),- bytesUsed);+ bytesUsed, context);}public Writer(Directory dir, String id, Comparator<BytesRef> comp,- Allocator allocator, AtomicLong bytesUsed) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed);+ Allocator allocator, AtomicLong bytesUsed, IOContext context) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, true,- new ByteBlockPool(allocator), bytesUsed, context);++ super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed, context);+ this.hash = new BytesRefHash(new ByteBlockPool(allocator),+ BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(+ BytesRefHash.DEFAULT_CAPACITY, bytesUsed));this.comp = comp;docToEntry = new int[1];docToEntry[0] = -1;diff --cc lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.javaindex 3cd8f3576cf,6128100dc8f..5cb90ff42c0--- a/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java@@@ -24,14 -24,18 +24,19 @@@ import org.apache.lucene.index.values.Bimport org.apache.lucene.index.values.Bytes.BytesReaderBase;import org.apache.lucene.index.values.Bytes.BytesWriterBase;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;+ import org.apache.lucene.util.ByteBlockPool;import org.apache.lucene.util.BytesRef;+ import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.PagedBytes;import org.apache.lucene.util.RamUsageEstimator;+ import org.apache.lucene.util.ByteBlockPool.DirectTrackingAllocator;import org.apache.lucene.util.packed.PackedInts;+ import org.apache.lucene.util.packed.PackedInts.ReaderIterator;// Variable length byte[] per document, no sharing@@@ -49,11 -53,15 +54,15 @@@ class VarStraightBytesImpl// start at -1 if the first added value is > 0private int lastDocID = -1;private long[] docToAddress;-+ private final ByteBlockPool pool;+ private IndexOutput datOut;+ private boolean merge = false;- public Writer(Directory dir, String id, AtomicLong bytesUsed)+ public Writer(Directory dir, String id, AtomicLong bytesUsed, IOContext context)throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, true, null, bytesUsed, context);- super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed);++ super(dir, id, CODEC_NAME, VERSION_CURRENT, bytesUsed, context);+ pool = new ByteBlockPool(new DirectTrackingAllocator(bytesUsed));docToAddress = new long[1];+ pool.nextBuffer(); // initbytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);}diff --cc lucene/src/java/org/apache/lucene/index/values/Writer.javaindex ab5dbab603d,abcbbcef87c..5a7217cea25--- a/lucene/src/java/org/apache/lucene/index/values/Writer.java+++ b/lucene/src/java/org/apache/lucene/index/values/Writer.java@@@ -198,30 -197,35 +198,35 @@@ public abstract class Writer extends Docomp = BytesRef.getUTF8SortedAsUnicodeComparator();}switch (type) {- case INTS:- return Ints.getWriter(directory, id, true, bytesUsed, context);+ case FIXED_INTS_16:+ case FIXED_INTS_32:+ case FIXED_INTS_64:+ case FIXED_INTS_8:+ case VAR_INTS:- return Ints.getWriter(directory, id, bytesUsed, type);++ return Ints.getWriter(directory, id, bytesUsed, type, context);case FLOAT_32:- return Floats.getWriter(directory, id, 4, bytesUsed);+ return Floats.getWriter(directory, id, 4, bytesUsed, context);case FLOAT_64:- return Floats.getWriter(directory, id, 8, bytesUsed);+ return Floats.getWriter(directory, id, 8, bytesUsed, context);case BYTES_FIXED_STRAIGHT:return Bytes.getWriter(directory, id, Bytes.Mode.STRAIGHT, comp, true,- bytesUsed);+ bytesUsed, context);case BYTES_FIXED_DEREF:return Bytes.getWriter(directory, id, Bytes.Mode.DEREF, comp, true,- bytesUsed);+ bytesUsed, context);case BYTES_FIXED_SORTED:return Bytes.getWriter(directory, id, Bytes.Mode.SORTED, comp, true,- bytesUsed);+ bytesUsed, context);case BYTES_VAR_STRAIGHT:return Bytes.getWriter(directory, id, Bytes.Mode.STRAIGHT, comp, false,- bytesUsed);+ bytesUsed, context);case BYTES_VAR_DEREF:return Bytes.getWriter(directory, id, Bytes.Mode.DEREF, comp, false,- bytesUsed);+ bytesUsed, context);case BYTES_VAR_SORTED:return Bytes.getWriter(directory, id, Bytes.Mode.SORTED, comp, false,- bytesUsed);+ bytesUsed, context);+default:throw new IllegalArgumentException("Unknown Values: " + type);}diff --cc lucene/src/java/org/apache/lucene/store/CompoundFileDirectory.javaindex 00000000000,0e8458ccebf..371425f2c1bmode 000000,100644..100644--- a/lucene/src/java/org/apache/lucene/store/CompoundFileDirectory.java+++ b/lucene/src/java/org/apache/lucene/store/CompoundFileDirectory.java@@@ -1,0 -1,313 +1,307 @@@+ package org.apache.lucene.store;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++ import org.apache.lucene.index.CorruptIndexException;+ import org.apache.lucene.index.IndexFileNames;+ import org.apache.lucene.store.Directory;+ import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;+ import org.apache.lucene.store.Lock;+ import org.apache.lucene.util.IOUtils;++ import java.util.Collection;+ import java.util.Collections;+ import java.util.HashMap;+ import java.util.Map;+ import java.io.FileNotFoundException;+ import java.io.IOException;++ /**+ * Class for accessing a compound stream.+ * This class implements a directory, but is limited to only read operations.+ * Directory methods that would normally modify data throw an exception.+ * @lucene.experimental+ */+ public abstract class CompoundFileDirectory extends Directory {++ /** Offset/Length for a slice inside of a compound file */+ public static final class FileEntry {+ long offset;+ long length;+ }++ private final Directory directory;+ private final String fileName;- private final int readBufferSize;++ protected final int readBufferSize;+ private Map<String,FileEntry> entries;+ private boolean openForWrite;+ private static final Map<String,FileEntry> SENTINEL = Collections.emptyMap();+ private CompoundFileWriter writer;++ /**+ * Create a new CompoundFileDirectory.+ * <p>+ * NOTE: subclasses must call {@link #initForRead(Map)} before the directory can be used.+ */- public CompoundFileDirectory(Directory directory, String fileName, int readBufferSize) throws IOException {++ public CompoundFileDirectory(Directory directory, String fileName, IOContext context) throws IOException {+ assert !(directory instanceof CompoundFileDirectory) : "compound file inside of compound file: " + fileName;+ this.directory = directory;+ this.fileName = fileName;- this.readBufferSize = readBufferSize;++ this.readBufferSize = BufferedIndexInput.bufferSize(context);+ this.isOpen = false;+ }++ /** Initialize with a map of filename->slices */+ protected final void initForRead(Map<String,FileEntry> entries) {+ this.entries = entries;+ this.isOpen = true;+ this.openForWrite = false;+ }++ protected final void initForWrite() {+ this.entries = SENTINEL;+ this.openForWrite = true;+ this.isOpen = true;+ }++ /** Helper method that reads CFS entries from an input stream */+ public static final Map<String,FileEntry> readEntries(IndexInput stream, Directory dir, String name) throws IOException {+ // read the first VInt. If it is negative, it's the version number+ // otherwise it's the count (pre-3.1 indexes)+ final int firstInt = stream.readVInt();+ if (firstInt == CompoundFileWriter.FORMAT_CURRENT) {+ IndexInput input = null;+ try {+ input = dir.openInput(IndexFileNames.segmentFileName(IndexFileNames.stripExtension(name), "",- IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION));++ IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION), IOContext.READONCE);+ final int readInt = input.readInt(); // unused right now+ assert readInt == CompoundFileWriter.ENTRY_FORMAT_CURRENT;+ final int numEntries = input.readVInt();+ final Map<String, FileEntry> mapping = new HashMap<String, CompoundFileDirectory.FileEntry>(+ numEntries);+ for (int i = 0; i < numEntries; i++) {+ final FileEntry fileEntry = new FileEntry();+ mapping.put(input.readString(), fileEntry);+ fileEntry.offset = input.readLong();+ fileEntry.length = input.readLong();+ }+ return mapping;+ } finally {+ IOUtils.closeSafely(true, input);+ }+ }++ // TODO remove once 3.x is not supported anymore+ return readLegacyEntries(stream, firstInt);+ }++ private static Map<String, FileEntry> readLegacyEntries(IndexInput stream,+ int firstInt) throws CorruptIndexException, IOException {+ final Map<String,FileEntry> entries = new HashMap<String,FileEntry>();+ final int count;+ final boolean stripSegmentName;+ if (firstInt < CompoundFileWriter.FORMAT_PRE_VERSION) {+ if (firstInt < CompoundFileWriter.FORMAT_CURRENT) {+ throw new CorruptIndexException("Incompatible format version: "+ + firstInt + " expected " + CompoundFileWriter.FORMAT_CURRENT);+ }+ // It's a post-3.1 index, read the count.+ count = stream.readVInt();+ stripSegmentName = false;+ } else {+ count = firstInt;+ stripSegmentName = true;+ }++ // read the directory and init files+ long streamLength = stream.length();+ FileEntry entry = null;+ for (int i=0; i<count; i++) {+ long offset = stream.readLong();+ if (offset < 0 || offset > streamLength) {+ throw new CorruptIndexException("Invalid CFS entry offset: " + offset);+ }+ String id = stream.readString();++ if (stripSegmentName) {+ // Fix the id to not include the segment names. This is relevant for+ // pre-3.1 indexes.+ id = IndexFileNames.stripSegmentName(id);+ }++ if (entry != null) {+ // set length of the previous entry+ entry.length = offset - entry.offset;+ }++ entry = new FileEntry();+ entry.offset = offset;+ entries.put(id, entry);+ }++ // set the length of the final entry+ if (entry != null) {+ entry.length = streamLength - entry.offset;+ }++ return entries;+ }++ public Directory getDirectory() {+ return directory;+ }++ public String getName() {+ return fileName;+ }++ @Override+ public synchronized void close() throws IOException {+ ensureOpen();+ entries = null;+ isOpen = false;+ if (writer != null) {+ assert openForWrite;+ writer.close();+ }+ }++ @Override- public synchronized IndexInput openInput(String id) throws IOException {- // Default to readBufferSize passed in when we were opened- return openInput(id, readBufferSize);- }-- @Override- public synchronized IndexInput openInput(String id, int readBufferSize) throws IOException {++ public synchronized IndexInput openInput(String id, IOContext context) throws IOException {+ ensureOpen();+ assert !openForWrite;+ id = IndexFileNames.stripSegmentName(id);+ final FileEntry entry = entries.get(id);+ if (entry == null)+ throw new IOException("No sub-file with id " + id + " found (files: " + entries.keySet() + ")");++ return openInputSlice(id, entry.offset, entry.length, readBufferSize);+ }++ /** Return an IndexInput that represents a "slice" or portion of the CFS file. */+ public abstract IndexInput openInputSlice(String id, long offset, long length, int readBufferSize) throws IOException;++ /** Returns an array of strings, one for each file in the directory. */+ @Override+ public String[] listAll() {+ ensureOpen();+ String[] res;+ if (writer != null) {+ res = writer.listAll();+ } else {+ res = entries.keySet().toArray(new String[entries.size()]);+ // Add the segment name+ String seg = fileName.substring(0, fileName.indexOf('.'));+ for (int i = 0; i < res.length; i++) {+ res[i] = seg + res[i];+ }+ }+ return res;+ }++ /** Returns true iff a file with the given name exists. */+ @Override+ public boolean fileExists(String name) {+ ensureOpen();+ if (this.writer != null) {+ return writer.fileExists(name);+ }+ return entries.containsKey(IndexFileNames.stripSegmentName(name));+ }+++ /** Returns the time the compound file was last modified. */+ @Override+ public long fileModified(String name) throws IOException {+ ensureOpen();+ return directory.fileModified(fileName);+ }++ /** Not implemented+ * @throws UnsupportedOperationException */+ @Override+ public void deleteFile(String name) {+ throw new UnsupportedOperationException();+ }++ /** Not implemented+ * @throws UnsupportedOperationException */+ public void renameFile(String from, String to) {+ throw new UnsupportedOperationException();+ }++ /** Returns the length of a file in the directory.+ * @throws IOException if the file does not exist */+ @Override+ public long fileLength(String name) throws IOException {+ ensureOpen();+ if (this.writer != null) {+ return writer.fileLenght(name);+ }+ FileEntry e = entries.get(IndexFileNames.stripSegmentName(name));+ if (e == null)+ throw new FileNotFoundException(name);+ return e.length;+ }++ @Override- public IndexOutput createOutput(String name) throws IOException {++ public IndexOutput createOutput(String name, IOContext context) throws IOException {+ ensureOpen();+ initWriter();- return writer.createOutput(name);++ return writer.createOutput(name, context);+ }++ @Override+ public void sync(Collection<String> names) throws IOException {+ throw new UnsupportedOperationException();+ }++ /** Not implemented+ * @throws UnsupportedOperationException */+ @Override+ public Lock makeLock(String name) {+ throw new UnsupportedOperationException();+ }++ /** Not implemented+ * @throws UnsupportedOperationException */+ @Override- public final CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {++ public final CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {+ // NOTE: final to make nested compounding impossible.+ throw new UnsupportedOperationException();+ }++ /** Not implemented+ * @throws UnsupportedOperationException */+ @Override- public CompoundFileDirectory createCompoundOutput(String name)++ public CompoundFileDirectory createCompoundOutput(String name, IOContext context)+ throws IOException {+ // NOTE: final to make nested compounding impossible.+ throw new UnsupportedOperationException();+ }++ private final void initWriter() {+ assert openForWrite;+ assert entries == SENTINEL;+ if (writer == null) {+ writer = new CompoundFileWriter(directory, fileName);+ }+ }++ }diff --cc lucene/src/java/org/apache/lucene/store/CompoundFileWriter.javaindex 00000000000,748a1787eda..7587a981310mode 000000,100644..100644--- a/lucene/src/java/org/apache/lucene/store/CompoundFileWriter.java+++ b/lucene/src/java/org/apache/lucene/store/CompoundFileWriter.java@@@ -1,0 -1,367 +1,367 @@@+ package org.apache.lucene.store;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++ import java.io.FileNotFoundException;+ import java.io.IOException;+ import java.util.Collection;+ import java.util.HashMap;+ import java.util.LinkedList;+ import java.util.Map;+ import java.util.Queue;+ import java.util.concurrent.atomic.AtomicBoolean;++ import org.apache.lucene.index.IndexFileNames;+ import org.apache.lucene.index.MergePolicy.MergeAbortedException;+ import org.apache.lucene.util.IOUtils;++ /**+ * Combines multiple files into a single compound file.+ *+ * The file format data file:<br>+ * <ul>+ * <li>VInt Version</li>+ * <li>{File Data} fileCount entries with the raw data of the corresponding file+ * </li>+ * <ul>+ * File format entry table:<br>+ * <ul>+ * <li>int Version</li>+ * <li>VInt fileCount - number of entries with the following structure:</li>+ * <ul>+ * <li>String fileName</li>+ * <li>long dataOffset</li>+ * <li>long dataLength</li>+ * </ul>+ * </li> </ul> The fileCount integer indicates how many files are contained in+ * this compound file. The entry table that follows has that many entries. Each+ * directory entry contains a long pointer to the start of this file's data+ * section, the files length, and a String with that file's name.+ *+ * @lucene.internal+ */+ final class CompoundFileWriter {++ private static final class FileEntry {+ /** source file */+ String file;+ long length;+ /** temporary holder for the start of this file's data section */+ long offset;+ /** the directory which contains the file. */+ Directory dir;+ }++ // Before versioning started.+ static final int FORMAT_PRE_VERSION = 0;++ // Segment name is not written in the file names.+ static final int FORMAT_NO_SEGMENT_PREFIX = -1;+ static final int FORMAT_APPEND_FILES = -2;++ static final int ENTRY_FORMAT_CURRENT = -1;++ // NOTE: if you introduce a new format, make it 1 lower+ // than the current one, and always change this if you+ // switch to a new format!+ /** @lucene.internal */+ static final int FORMAT_CURRENT = FORMAT_APPEND_FILES;++ private final Directory directory;+ private final Map<String, FileEntry> entries = new HashMap<String, FileEntry>();+ // all entries that are written to a sep. file but not yet moved into CFS+ private final Queue<FileEntry> pendingEntries = new LinkedList<FileEntry>();+ private boolean closed = false;+ private volatile IndexOutput dataOut;+ private final AtomicBoolean outputTaken = new AtomicBoolean(false);+ private final String entryTableName;+ private final String dataFileName;++ /**+ * Create the compound stream in the specified file. The file name is the+ * entire name (no extensions are added).+ *+ * @throws NullPointerException+ * if <code>dir</code> or <code>name</code> is null+ */+ CompoundFileWriter(Directory dir, String name) {+ if (dir == null)+ throw new NullPointerException("directory cannot be null");+ if (name == null)+ throw new NullPointerException("name cannot be null");+ directory = dir;+ entryTableName = IndexFileNames.segmentFileName(+ IndexFileNames.stripExtension(name), "",+ IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION);+ dataFileName = name;+ }++ /** Returns the directory of the compound file. */+ Directory getDirectory() {+ return directory;+ }++ /** Returns the name of the compound file. */+ String getName() {+ return dataFileName;+ }++ /**+ * Closes all resources and writes the entry table+ *+ * @throws IllegalStateException+ * if close() had been called before or if no file has been added to+ * this object+ */+ void close() throws IOException {+ if (closed) {+ throw new IllegalStateException("already closed");+ }+ IOException priorException = null;+ IndexOutput entryTableOut = null;+ try {+ if (entries.isEmpty()) {+ throw new IllegalStateException("CFS has no entries");+ }++ if (!pendingEntries.isEmpty() || outputTaken.get()) {+ throw new IllegalStateException("CFS has pending open files");+ }+ closed = true;+ // open the compound stream+ assert dataOut != null;+ long finalLength = dataOut.getFilePointer();+ assert assertFileLength(finalLength, dataOut);- entryTableOut = directory.createOutput(entryTableName);++ entryTableOut = directory.createOutput(entryTableName, IOContext.DEFAULT);+ writeEntryTable(entries.values(), entryTableOut);+ } catch (IOException e) {+ priorException = e;+ } finally {+ IOUtils.closeSafely(priorException, dataOut, entryTableOut);+ }+ }++ private static boolean assertFileLength(long expected, IndexOutput out)+ throws IOException {+ out.flush();+ assert expected == out.length() : "expected: " + expected + " was "+ + out.length();+ return true;+ }++ private final void ensureOpen() {+ if (closed) {+ throw new IllegalStateException("CFS Directory is already closed");+ }+ }++ /**+ * Copy the contents of the file with specified extension into the provided+ * output stream.+ */+ private final long copyFileEntry(IndexOutput dataOut, FileEntry fileEntry)+ throws IOException, MergeAbortedException {- final IndexInput is = fileEntry.dir.openInput(fileEntry.file);++ final IndexInput is = fileEntry.dir.openInput(fileEntry.file, IOContext.READONCE);+ try {+ final long startPtr = dataOut.getFilePointer();+ final long length = fileEntry.length;+ dataOut.copyBytes(is, length);+ // Verify that the output length diff is equal to original file+ long endPtr = dataOut.getFilePointer();+ long diff = endPtr - startPtr;+ if (diff != length)+ throw new IOException("Difference in the output file offsets " + diff+ + " does not match the original file length " + length);+ fileEntry.offset = startPtr;+ // copy successful - delete file+ fileEntry.dir.deleteFile(fileEntry.file);+ return length;+ } finally {+ is.close();+ }++ }++ protected void writeEntryTable(Collection<FileEntry> entries,+ IndexOutput entryOut) throws IOException {+ entryOut.writeInt(ENTRY_FORMAT_CURRENT);+ entryOut.writeVInt(entries.size());+ for (FileEntry fe : entries) {+ entryOut.writeString(IndexFileNames.stripSegmentName(fe.file));+ entryOut.writeLong(fe.offset);+ entryOut.writeLong(fe.length);+ }+ }+- IndexOutput createOutput(String name) throws IOException {++ IndexOutput createOutput(String name, IOContext context) throws IOException {+ ensureOpen();+ boolean success = false;+ try {+ assert name != null : "name must not be null";+ if (entries.containsKey(name)) {+ throw new IllegalArgumentException("File " + name + " already exists");+ }+ final FileEntry entry = new FileEntry();+ entry.file = name;+ entries.put(name, entry);+ final DirectCFSIndexOutput out;+ if (outputTaken.compareAndSet(false, true)) {- initDataOut();++ initDataOut(context);+ success = true;+ out = new DirectCFSIndexOutput(dataOut, entry, false);+ } else {+ entry.dir = this.directory;+ if (directory.fileExists(name)) {+ throw new IOException("File already exists");+ }- out = new DirectCFSIndexOutput(directory.createOutput(name), entry,++ out = new DirectCFSIndexOutput(directory.createOutput(name, context), entry,+ true);+ }+ success = true;+ return out;+ } finally {+ if (!success) {+ entries.remove(name);+ }+ }+ }++ final void releaseOutputLock() {+ outputTaken.compareAndSet(true, false);+ }+- private synchronized final void initDataOut() throws IOException {++ private synchronized final void initDataOut(IOContext context) throws IOException {+ if (dataOut == null) {+ boolean success = false;+ try {- dataOut = directory.createOutput(dataFileName);++ dataOut = directory.createOutput(dataFileName, context);+ dataOut.writeVInt(FORMAT_CURRENT);+ success = true;+ } finally {+ if (!success) {+ IOUtils.closeSafely(true, dataOut);+ }+ }+ }+ }++ private final void prunePendingEntries() throws IOException {+ // claim the output and copy all pending files in+ if (outputTaken.compareAndSet(false, true)) {+ try {+ while (!pendingEntries.isEmpty()) {+ FileEntry entry = pendingEntries.poll();+ copyFileEntry(dataOut, entry);+ entries.put(entry.file, entry);+ }+ } finally {+ final boolean compareAndSet = outputTaken.compareAndSet(true, false);+ assert compareAndSet;+ }+ }+ }++ long fileLenght(String name) throws IOException {+ FileEntry fileEntry = entries.get(name);+ if (fileEntry == null) {+ throw new FileNotFoundException(name + " does not exist");+ }+ return fileEntry.length;+ }++ boolean fileExists(String name) {+ return entries.containsKey(name);+ }++ String[] listAll() {+ return entries.keySet().toArray(new String[0]);+ }++ private final class DirectCFSIndexOutput extends IndexOutput {+ private final IndexOutput delegate;+ private final long offset;+ private boolean closed;+ private FileEntry entry;+ private long writtenBytes;+ private final boolean isSeparate;++ DirectCFSIndexOutput(IndexOutput delegate, FileEntry entry,+ boolean isSeparate) {+ super();+ this.delegate = delegate;+ this.entry = entry;+ entry.offset = offset = delegate.getFilePointer();+ this.isSeparate = isSeparate;++ }++ @Override+ public void flush() throws IOException {+ delegate.flush();+ }++ @Override+ public void close() throws IOException {+ if (!closed) {+ closed = true;+ entry.length = writtenBytes;+ if (isSeparate) {+ // we are a separate file - push into the pending entries+ pendingEntries.add(entry);+ } else {+ // we have been written into the CFS directly - release the lock+ releaseOutputLock();+ }+ // now prune all pending entries and push them into the CFS+ prunePendingEntries();+ }+ }++ @Override+ public long getFilePointer() {+ return delegate.getFilePointer() - offset;+ }++ @Override+ public void seek(long pos) throws IOException {+ assert !closed;+ delegate.seek(offset + pos);+ }++ @Override+ public long length() throws IOException {+ assert !closed;+ return delegate.length() - offset;+ }++ @Override+ public void writeByte(byte b) throws IOException {+ assert !closed;+ writtenBytes++;+ delegate.writeByte(b);+ }++ @Override+ public void writeBytes(byte[] b, int offset, int length) throws IOException {+ assert !closed;+ writtenBytes += length;+ delegate.writeBytes(b, offset, length);+ }+ }++ }diff --cc lucene/src/java/org/apache/lucene/store/DefaultCompoundFileDirectory.javaindex 00000000000,e1c35cbb3ef..35c036b664amode 000000,100644..100644--- a/lucene/src/java/org/apache/lucene/store/DefaultCompoundFileDirectory.java+++ b/lucene/src/java/org/apache/lucene/store/DefaultCompoundFileDirectory.java@@@ -1,0 -1,140 +1,140 @@@+ package org.apache.lucene.store;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++ import java.io.IOException;++ import org.apache.lucene.util.IOUtils;++ /**+ * Default implementation of {@link CompoundFileDirectory}.+ * <p>+ * This implementation returns a BufferedIndexInput that wraps the underlying+ * Directory's IndexInput for the compound file (using unbuffered reads).+ * @lucene.experimental+ */+ public class DefaultCompoundFileDirectory extends CompoundFileDirectory {+ protected IndexInput stream;+- public DefaultCompoundFileDirectory(Directory directory, String fileName, int readBufferSize, boolean writeable) throws IOException {- super(directory, fileName, readBufferSize);++ public DefaultCompoundFileDirectory(Directory directory, String fileName, IOContext context, boolean writeable) throws IOException {++ super(directory, fileName, context);+ if (!writeable) {+ try {- stream = directory.openInput(fileName, readBufferSize);++ stream = directory.openInput(fileName, context);+ initForRead(CompoundFileDirectory.readEntries(stream, directory, fileName));+ } catch (IOException e) {+ IOUtils.closeSafely(e, stream);+ }+ } else {+ initForWrite();+ }+ }++ @Override+ public IndexInput openInputSlice(String id, long offset, long length, int readBufferSize) throws IOException {+ return new CSIndexInput(stream, offset, length, readBufferSize);+ }++ @Override+ public synchronized void close() throws IOException {+ try {+ IOUtils.closeSafely(false, stream);+ } finally {+ super.close();+ }+ }++ /** Implementation of an IndexInput that reads from a portion of the+ * compound file.+ */+ static final class CSIndexInput extends BufferedIndexInput {+ IndexInput base;+ long fileOffset;+ long length;++ CSIndexInput(final IndexInput base, final long fileOffset, final long length) {+ this(base, fileOffset, length, BufferedIndexInput.BUFFER_SIZE);+ }++ CSIndexInput(final IndexInput base, final long fileOffset, final long length, int readBufferSize) {+ super(readBufferSize);+ this.base = (IndexInput)base.clone();+ this.fileOffset = fileOffset;+ this.length = length;+ }++ @Override+ public Object clone() {+ CSIndexInput clone = (CSIndexInput)super.clone();+ clone.base = (IndexInput)base.clone();+ clone.fileOffset = fileOffset;+ clone.length = length;+ return clone;+ }++ /** Expert: implements buffer refill. Reads bytes from the current+ * position in the input.+ * @param b the array to read bytes into+ * @param offset the offset in the array to start storing bytes+ * @param len the number of bytes to read+ */+ @Override+ protected void readInternal(byte[] b, int offset, int len) throws IOException {+ long start = getFilePointer();+ if(start + len > length)+ throw new IOException("read past EOF");+ base.seek(fileOffset + start);+ base.readBytes(b, offset, len, false);+ }++ /** Expert: implements seek. Sets current position in this file, where+ * the next {@link #readInternal(byte[],int,int)} will occur.+ * @see #readInternal(byte[],int,int)+ */+ @Override+ protected void seekInternal(long pos) {}++ /** Closes the stream to further operations. */+ @Override+ public void close() throws IOException {+ base.close();+ }++ @Override+ public long length() {+ return length;+ }++ @Override+ public void copyBytes(IndexOutput out, long numBytes) throws IOException {+ // Copy first whatever is in the buffer+ numBytes -= flushBuffer(out, numBytes);++ // If there are more bytes left to copy, delegate the copy task to the+ // base IndexInput, in case it can do an optimized copy.+ if (numBytes > 0) {+ long start = getFilePointer();+ if (start + numBytes > length) {+ throw new IOException("read past EOF");+ }+ base.seek(fileOffset + start);+ base.copyBytes(out, numBytes);+ }+ }+ }+ }diff --cc lucene/src/java/org/apache/lucene/store/Directory.javaindex 51862e91659,964f502b4e8..cd82f3fd90f--- a/lucene/src/java/org/apache/lucene/store/Directory.java+++ b/lucene/src/java/org/apache/lucene/store/Directory.java@@@ -108,9 -112,35 +108,33 @@@ public abstract class Directory impleme* implementation may ignore the buffer size. Currently* the only Directory implementations that respect this* parameter are {@link FSDirectory} and {@link- * org.apache.lucene.index.CompoundFileReader}.+ * CompoundFileDirectory}.*/- public IndexInput openInput(String name, int bufferSize) throws IOException {- return openInput(name);- }+ public abstract IndexInput openInput(String name, IOContext context) throws IOException;++ /**+ * Returns a {@link CompoundFileDirectory} capable of+ * reading the Lucene compound file format.+ * <p>+ * The default implementation returns+ * {@link DefaultCompoundFileDirectory}.+ * @lucene.experimental+ */- public CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {- return new DefaultCompoundFileDirectory(this, name, bufferSize, false);++ public CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {++ return new DefaultCompoundFileDirectory(this, name, context, false);+ }++ /**+ * Returns a {@link CompoundFileDirectory} capable of+ * writing the Lucene compound file format.+ * <p>+ * The default implementation returns+ * {@link DefaultCompoundFileDirectory}.+ * @lucene.experimental+ */- public CompoundFileDirectory createCompoundOutput(String name) throws IOException {- return new DefaultCompoundFileDirectory(this, name, 1024, true);++ public CompoundFileDirectory createCompoundOutput(String name, IOContext context) throws IOException {++ return new DefaultCompoundFileDirectory(this, name, context, true);+ }/** Construct a {@link Lock}.* @param name the name of the lock file@@@ -193,11 -223,13 +217,13 @@@* <b>NOTE:</b> this method does not check whether <i>dest<i> exist and will* overwrite it if it does.*/- public void copy(Directory to, String src, String dest) throws IOException {+ public void copy(Directory to, String src, String dest, IOContext context) throws IOException {- IndexOutput os = to.createOutput(dest, context);- IndexInput is = openInput(src, context);+ IndexOutput os = null;+ IndexInput is = null;IOException priorException = null;try {- os = to.createOutput(dest);- is = openInput(src);++ os = to.createOutput(dest, context);++ is = openInput(src, context);is.copyBytes(os, is.length());} catch (IOException ioe) {priorException = ioe;diff --cc lucene/src/java/org/apache/lucene/store/FileSwitchDirectory.javaindex 51676a77aa0,c1701632b1d..5b76e46a47a--- a/lucene/src/java/org/apache/lucene/store/FileSwitchDirectory.java+++ b/lucene/src/java/org/apache/lucene/store/FileSwitchDirectory.java@@@ -146,7 -145,17 +146,17 @@@ public class FileSwitchDirectory extend}@Override- public IndexInput openInput(String name) throws IOException {- return getDirectory(name).openInput(name);+ public IndexInput openInput(String name, IOContext context) throws IOException {+ return getDirectory(name).openInput(name, context);}++ @Override- public CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {- return getDirectory(name).openCompoundInput(name, bufferSize);++ public CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {++ return getDirectory(name).openCompoundInput(name, context);+ }++ @Override- public CompoundFileDirectory createCompoundOutput(String name) throws IOException {- return getDirectory(name).createCompoundOutput(name);++ public CompoundFileDirectory createCompoundOutput(String name, IOContext context) throws IOException {++ return getDirectory(name).createCompoundOutput(name, context);+ }}diff --cc lucene/src/java/org/apache/lucene/store/MMapDirectory.javaindex 6439b22fa01,91f5386731a..1b8cb5ad0eb--- a/lucene/src/java/org/apache/lucene/store/MMapDirectory.java+++ b/lucene/src/java/org/apache/lucene/store/MMapDirectory.java@@@ -218,6 -219,44 +219,44 @@@ public class MMapDirectory extends FSDiraf.close();}}++ @Override- public CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {- return new MMapCompoundFileDirectory(name, bufferSize);++ public CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {++ return new MMapCompoundFileDirectory(name, context);+ }++ private final class MMapCompoundFileDirectory extends CompoundFileDirectory {+ private RandomAccessFile raf = null;+- public MMapCompoundFileDirectory(String fileName, int readBufferSize) throws IOException {- super(MMapDirectory.this, fileName, readBufferSize);++ public MMapCompoundFileDirectory(String fileName, IOContext context) throws IOException {++ super(MMapDirectory.this, fileName, context);+ IndexInput stream = null;+ try {+ File f = new File(MMapDirectory.this.getDirectory(), fileName);+ raf = new RandomAccessFile(f, "r");+ stream = new MMapIndexInput(raf, 0, raf.length(), chunkSizePower);+ initForRead(CompoundFileDirectory.readEntries(stream, MMapDirectory.this, fileName));+ stream.close();+ } catch (IOException e) {+ // throw our original exception+ IOUtils.closeSafely(e, raf, stream);+ }+ }++ @Override+ public IndexInput openInputSlice(String id, long offset, long length, int readBufferSize) throws IOException {+ return new MMapIndexInput(raf, offset, length, chunkSizePower);+ }++ @Override+ public synchronized void close() throws IOException {+ try {+ raf.close();+ } finally {+ super.close();+ }+ }+ }// Because Java's ByteBuffer uses an int to address the// values, it's necessary to access a file >diff --cc lucene/src/java/org/apache/lucene/store/NIOFSDirectory.javaindex 6a2ff16c645,40f2a9992ef..6ac4380b55f--- a/lucene/src/java/org/apache/lucene/store/NIOFSDirectory.java+++ b/lucene/src/java/org/apache/lucene/store/NIOFSDirectory.java@@@ -73,10 -76,51 +76,51 @@@ public class NIOFSDirectory extends FSD/** Creates an IndexInput for the file with the given name. */@Override- public IndexInput openInput(String name, int bufferSize) throws IOException {+ public IndexInput openInput(String name, IOContext context) throws IOException {ensureOpen();- return new NIOFSIndexInput(new File(getDirectory(), name), bufferSize, getReadChunkSize());+ return new NIOFSIndexInput(new File(getDirectory(), name), context, getReadChunkSize());}++ @Override- public CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {- return new NIOFSCompoundFileDirectory(name, bufferSize);++ public CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {++ return new NIOFSCompoundFileDirectory(name, context);+ }++ private final class NIOFSCompoundFileDirectory extends CompoundFileDirectory {+ private SimpleFSIndexInput.Descriptor fd;+ private FileChannel fc;+- public NIOFSCompoundFileDirectory(String fileName, int readBufferSize) throws IOException {- super(NIOFSDirectory.this, fileName, readBufferSize);++ public NIOFSCompoundFileDirectory(String fileName, IOContext context) throws IOException {++ super(NIOFSDirectory.this, fileName, context);+ IndexInput stream = null;+ try {+ File f = new File(NIOFSDirectory.this.getDirectory(), fileName);+ fd = new SimpleFSIndexInput.Descriptor(f, "r");+ fc = fd.getChannel();+ stream = new NIOFSIndexInput(fd, fc, 0, fd.length, readBufferSize,+ getReadChunkSize());+ initForRead(CompoundFileDirectory.readEntries(stream, NIOFSDirectory.this, fileName));+ stream.close();+ } catch (IOException e) {+ // throw our original exception+ IOUtils.closeSafely(e, fc, fd, stream);+ }+ }++ @Override+ public IndexInput openInputSlice(String id, long offset, long length, int readBufferSize) throws IOException {+ return new NIOFSIndexInput(fd, fc, offset, length, readBufferSize, getReadChunkSize());+ }++ @Override+ public synchronized void close() throws IOException {+ try {+ IOUtils.closeSafely(false, fc, fd);+ } finally {+ super.close();+ }+ }+ }protected static class NIOFSIndexInput extends SimpleFSDirectory.SimpleFSIndexInput {@@@ -87,10 -131,16 +131,16 @@@final FileChannel channel;- public NIOFSIndexInput(File path, int bufferSize, int chunkSize) throws IOException {- super(path, bufferSize, chunkSize);+ public NIOFSIndexInput(File path, IOContext context, int chunkSize) throws IOException {+ super(path, context, chunkSize);channel = file.getChannel();}++ public NIOFSIndexInput(Descriptor file, FileChannel fc, long off, long length, int bufferSize, int chunkSize) throws IOException {+ super(file, off, length, bufferSize, chunkSize);+ channel = fc;+ isClone = true;+ }@Overrideprotected void newBuffer(byte[] newBuffer) {diff --cc lucene/src/java/org/apache/lucene/store/SimpleFSDirectory.javaindex eeda25e05c4,07cb321c95b..8174fa4b2b7--- a/lucene/src/java/org/apache/lucene/store/SimpleFSDirectory.java+++ b/lucene/src/java/org/apache/lucene/store/SimpleFSDirectory.java@@@ -21,9 -21,8 +21,9 @@@ import java.io.Fileimport java.io.IOException;import java.io.RandomAccessFile;- import org.apache.lucene.store.IOContext.Context;+ import org.apache.lucene.util.IOUtils;+/** A straightforward implementation of {@link FSDirectory}* using java.io.RandomAccessFile. However, this class has* poor concurrent performance (multiple threads will@@@ -54,10 -53,49 +54,49 @@@ public class SimpleFSDirectory extends/** Creates an IndexInput for the file with the given name. */@Override- public IndexInput openInput(String name, int bufferSize) throws IOException {+ public IndexInput openInput(String name, IOContext context) throws IOException {ensureOpen();- return new SimpleFSIndexInput(new File(directory, name), bufferSize, getReadChunkSize());+ return new SimpleFSIndexInput(new File(directory, name), context, getReadChunkSize());}++ @Override- public CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {- return new SimpleFSCompoundFileDirectory(name, bufferSize);++ public CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {++ return new SimpleFSCompoundFileDirectory(name, context);+ }++ private final class SimpleFSCompoundFileDirectory extends CompoundFileDirectory {+ private SimpleFSIndexInput.Descriptor fd;+- public SimpleFSCompoundFileDirectory(String fileName, int readBufferSize) throws IOException {- super(SimpleFSDirectory.this, fileName, readBufferSize);++ public SimpleFSCompoundFileDirectory(String fileName, IOContext context) throws IOException {++ super(SimpleFSDirectory.this, fileName, context);+ IndexInput stream = null;+ try {+ final File f = new File(SimpleFSDirectory.this.getDirectory(), fileName);+ fd = new SimpleFSIndexInput.Descriptor(f, "r");+ stream = new SimpleFSIndexInput(fd, 0, fd.length, readBufferSize,+ getReadChunkSize());+ initForRead(CompoundFileDirectory.readEntries(stream, SimpleFSDirectory.this, fileName));+ stream.close();+ } catch (IOException e) {+ // throw our original exception+ IOUtils.closeSafely(e, fd, stream);+ }+ }++ @Override+ public IndexInput openInputSlice(String id, long offset, long length, int readBufferSize) throws IOException {+ return new SimpleFSIndexInput(fd, offset, length, readBufferSize, getReadChunkSize());+ }++ @Override+ public synchronized void close() throws IOException {+ try {+ fd.close();+ } finally {+ super.close();+ }+ }+ }protected static class SimpleFSIndexInput extends BufferedIndexInput {@@@ -87,11 -125,24 +126,24 @@@boolean isClone;// LUCENE-1566 - maximum read length on a 32bit JVM to prevent incorrect OOMprotected final int chunkSize;+ protected final long off;+ protected final long end;- public SimpleFSIndexInput(File path, int bufferSize, int chunkSize) throws IOException {- super(bufferSize);+ public SimpleFSIndexInput(File path, IOContext context, int chunkSize) throws IOException {+ super(context);- file = new Descriptor(path, "r");+ this.file = new Descriptor(path, "r");+ this.chunkSize = chunkSize;+ this.off = 0L;+ this.end = file.length;+ }++ public SimpleFSIndexInput(Descriptor file, long off, long length, int bufferSize, int chunkSize) throws IOException {+ super(bufferSize);+ this.file = file;this.chunkSize = chunkSize;+ this.off = off;+ this.end = off + length;+ this.isClone = true; // well, we are sorta?}/** IndexInput methods */diff --cc lucene/src/java/org/apache/lucene/util/BitVector.javaindex b24a64962ff,c664df06782..b58c7af3877--- a/lucene/src/java/org/apache/lucene/util/BitVector.java+++ b/lucene/src/java/org/apache/lucene/util/BitVector.java@@@ -18,23 -18,23 +18,26 @@@ package org.apache.lucene.util*/import java.io.IOException;+ import java.util.Arrays;+import org.apache.lucene.index.MergePolicy.OneMerge;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.IOContext.Context;/** Optimized implementation of a vector of bits. This is more-or-less like- java.util.BitSet, but also includes the following:- <ul>- <li>a count() method, which efficiently computes the number of one bits;</li>- <li>optimized read from and write to disk;</li>- <li>inlinable get() method;</li>- <li>store and load, as bit set or d-gaps, depending on sparseness;</li>- </ul>- */+ * java.util.BitSet, but also includes the following:+ * <ul>+ * <li>a count() method, which efficiently computes the number of one bits;</li>+ * <li>optimized read from and write to disk;</li>+ * <li>inlinable get() method;</li>+ * <li>store and load, as bit set or d-gaps, depending on sparseness;</li>+ * </ul>+ *+ * @lucene.internal+ */public final class BitVector implements Cloneable, Bits {private byte[] bits;@@@ -165,11 -215,14 +218,14 @@@/** Writes this vector to the file <code>name</code> in Directory<code>d</code>, in a format that can be read by the constructor {@link#BitVector(Directory, String)}. */- public final void write(Directory d, String name) throws IOException {- IndexOutput output = d.createOutput(name);+ public final void write(Directory d, String name, IOContext context) throws IOException {+ IndexOutput output = d.createOutput(name, context);try {+ output.writeInt(-2);+ CodecUtil.writeHeader(output, CODEC, VERSION_CURRENT);if (isSparse()) {- writeDgaps(output); // sparse bit-set more efficiently saved as d-gaps.+ // sparse bit-set more efficiently saved as d-gaps.+ writeClearedDgaps(output);} else {writeBits(output);}@@@ -223,12 -328,26 +331,26 @@@/** Constructs a bit vector from the file <code>name</code> in Directory<code>d</code>, as written by the {@link #write} method.*/- public BitVector(Directory d, String name) throws IOException {- IndexInput input = d.openInput(name);+ public BitVector(Directory d, String name, IOContext context) throws IOException {+ IndexInput input = d.openInput(name, context);+try {- size = input.readInt(); // read size+ final int firstInt = input.readInt();++ if (firstInt == -2) {+ // New format, with full header & version:+ version = CodecUtil.checkHeader(input, CODEC, VERSION_START, VERSION_CURRENT);+ size = input.readInt();+ } else {+ version = VERSION_PRE;+ size = firstInt;+ }if (size == -1) {- readDgaps(input);+ if (version >= VERSION_DGAPS_CLEARED) {+ readClearedDgaps(input);+ } else {+ readSetDgaps(input);+ }} else {readBits(input);}diff --cc lucene/src/test-framework/org/apache/lucene/store/MockCompoundFileDirectoryWrapper.javaindex 00000000000,cd0f498e78f..c7a592e89c7mode 000000,100644..100644--- a/lucene/src/test-framework/org/apache/lucene/store/MockCompoundFileDirectoryWrapper.java+++ b/lucene/src/test-framework/org/apache/lucene/store/MockCompoundFileDirectoryWrapper.java@@@ -1,0 -1,151 +1,151 @@@+ package org.apache.lucene.store;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++ import java.io.IOException;+ import java.util.Collection;+ import java.util.Collections;++ public class MockCompoundFileDirectoryWrapper extends CompoundFileDirectory {+ private final MockDirectoryWrapper parent;+ private final CompoundFileDirectory delegate;+ private final String name;++ public MockCompoundFileDirectoryWrapper(String name, MockDirectoryWrapper parent, CompoundFileDirectory delegate, boolean forWrite) throws IOException {- super(parent, name, 1024);++ super(parent, name, IOContext.DEFAULT);+ this.name = name;+ this.parent = parent;+ this.delegate = delegate;+ if (forWrite) {+ super.initForWrite();+ } else {+ super.initForRead(Collections.<String,FileEntry>emptyMap());+ }+ parent.addFileHandle(this, name, !forWrite);+ }++ @Override+ public Directory getDirectory() {+ return delegate.getDirectory();+ }++ @Override+ public String getName() {+ return delegate.getName();+ }++ @Override+ public synchronized void close() throws IOException {+ try {+ delegate.close();+ parent.removeOpenFile(this, name);+ } finally {+ super.close();+ }+ }++ @Override- public synchronized IndexInput openInput(String id, int readBufferSize) throws IOException {- return delegate.openInput(id, readBufferSize);++ public synchronized IndexInput openInput(String id, IOContext context) throws IOException {++ return delegate.openInput(id, context);+ }++ @Override+ public String[] listAll() {+ return delegate.listAll();+ }++ @Override+ public boolean fileExists(String name) {+ return delegate.fileExists(name);+ }++ @Override+ public long fileModified(String name) throws IOException {+ return delegate.fileModified(name);+ }++ @Override+ public void deleteFile(String name) {+ delegate.deleteFile(name);+ }++ @Override+ public void renameFile(String from, String to) {+ delegate.renameFile(from, to);+ }++ @Override+ public long fileLength(String name) throws IOException {+ return delegate.fileLength(name);+ }++ @Override- public IndexOutput createOutput(String name) throws IOException {- return delegate.createOutput(name);++ public IndexOutput createOutput(String name, IOContext context) throws IOException {++ return delegate.createOutput(name, context);+ }++ @Override+ public void sync(Collection<String> names) throws IOException {+ delegate.sync(names);+ }++ @Override+ public Lock makeLock(String name) {+ return delegate.makeLock(name);+ }++ @Override+ public void clearLock(String name) throws IOException {+ delegate.clearLock(name);+ }++ @Override+ public void setLockFactory(LockFactory lockFactory) throws IOException {+ delegate.setLockFactory(lockFactory);+ }++ @Override+ public LockFactory getLockFactory() {+ return delegate.getLockFactory();+ }++ @Override+ public String getLockID() {+ return delegate.getLockID();+ }++ @Override+ public String toString() {+ return "MockCompoundFileDirectoryWrapper(" + super.toString() + ")";+ }++ @Override- public void copy(Directory to, String src, String dest) throws IOException {- delegate.copy(to, src, dest);++ public void copy(Directory to, String src, String dest, IOContext context) throws IOException {++ delegate.copy(to, src, dest, context);+ }++ @Override+ public IndexInput openInputSlice(String id, long offset, long length, int readBufferSize) throws IOException {+ return delegate.openInputSlice(id, offset, length, readBufferSize);+ }++ @Override- public CompoundFileDirectory createCompoundOutput(String name) throws IOException {- return delegate.createCompoundOutput(name);++ public CompoundFileDirectory createCompoundOutput(String name, IOContext context) throws IOException {++ return delegate.createCompoundOutput(name, context);+ }+ }diff --cc lucene/src/test-framework/org/apache/lucene/store/MockDirectoryWrapper.javaindex 073e448ac43,a3d87456beb..3a05b3f30c4--- a/lucene/src/test-framework/org/apache/lucene/store/MockDirectoryWrapper.java+++ b/lucene/src/test-framework/org/apache/lucene/store/MockDirectoryWrapper.java@@@ -416,6 -416,18 +416,18 @@@ public class MockDirectoryWrapper extenaddFileHandle(ii, name, true);return ii;}++ @Override- public synchronized CompoundFileDirectory openCompoundInput(String name, int bufferSize) throws IOException {++ public synchronized CompoundFileDirectory openCompoundInput(String name, IOContext context) throws IOException {+ maybeYield();- return new MockCompoundFileDirectoryWrapper(name, this, delegate.openCompoundInput(name, bufferSize), false);++ return new MockCompoundFileDirectoryWrapper(name, this, delegate.openCompoundInput(name, context), false);+ }++ @Override- public CompoundFileDirectory createCompoundOutput(String name) throws IOException {++ public CompoundFileDirectory createCompoundOutput(String name, IOContext context) throws IOException {+ maybeYield();- return new MockCompoundFileDirectoryWrapper(name, this, delegate.createCompoundOutput(name), true);++ return new MockCompoundFileDirectoryWrapper(name, this, delegate.createCompoundOutput(name, context), true);+ }/** Provided for testing purposes. Use sizeInBytes() instead. */public synchronized final long getRecomputedSizeInBytes() throws IOException {diff --cc lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.javaindex e9890cd2ede,bdd53b3e9aa..44bff09084f--- a/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java+++ b/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java@@@ -538,7 -536,7 +536,7 @@@ public class TestBackwardsCompatibilit// figure out which field number corresponds to// "content", and then set our expected file names below// accordingly:- CompoundFileReader cfsReader = new CompoundFileReader(dir, "_0.cfs", newIOContext(random));- CompoundFileDirectory cfsReader = dir.openCompoundInput("_0.cfs", 1024);++ CompoundFileDirectory cfsReader = dir.openCompoundInput("_0.cfs", newIOContext(random));FieldInfos fieldInfos = new FieldInfos(cfsReader, "_0.fnm");int contentFieldIndex = -1;for (FieldInfo fi : fieldInfos) {diff --cc lucene/src/test/org/apache/lucene/index/TestCompoundFile.javaindex bee5513803e,8b2deed6858..262a1a3d7e2--- a/lucene/src/test/org/apache/lucene/index/TestCompoundFile.java+++ b/lucene/src/test/org/apache/lucene/index/TestCompoundFile.java@@@ -203,13 -202,13 +202,13 @@@ public class TestCompoundFile extends Lfor (int i=0; i<data.length; i++) {String name = "t" + data[i];createSequenceFile(dir, name, (byte) 0, data[i]);- CompoundFileWriter csw = new CompoundFileWriter(dir, name + ".cfs", newIOContext(random));- csw.addFile(name);- CompoundFileDirectory csw = dir.createCompoundOutput(name + ".cfs");- dir.copy(csw, name, name);++ CompoundFileDirectory csw = dir.createCompoundOutput(name + ".cfs", newIOContext(random));++ dir.copy(csw, name, name, newIOContext(random));csw.close();- CompoundFileReader csr = new CompoundFileReader(dir, name + ".cfs", newIOContext(random));- CompoundFileDirectory csr = dir.openCompoundInput(name + ".cfs", 1024);- IndexInput expected = dir.openInput(name);- IndexInput actual = csr.openInput(name);++ CompoundFileDirectory csr = dir.openCompoundInput(name + ".cfs", newIOContext(random));+ IndexInput expected = dir.openInput(name, newIOContext(random));+ IndexInput actual = csr.openInput(name, newIOContext(random));assertSameStreams(name, expected, actual);assertSameSeekBehavior(name, expected, actual);expected.close();@@@ -226,14 -225,14 +225,14 @@@createSequenceFile(dir, "d1", (byte) 0, 15);createSequenceFile(dir, "d2", (byte) 0, 114);- CompoundFileWriter csw = new CompoundFileWriter(dir, "d.csf", newIOContext(random));- csw.addFile("d1");- csw.addFile("d2");- CompoundFileDirectory csw = dir.createCompoundOutput("d.cfs");- dir.copy(csw, "d1", "d1");- dir.copy(csw, "d2", "d2");++ CompoundFileDirectory csw = dir.createCompoundOutput("d.cfs", newIOContext(random));++ dir.copy(csw, "d1", "d1", newIOContext(random));++ dir.copy(csw, "d2", "d2", newIOContext(random));csw.close();- CompoundFileReader csr = new CompoundFileReader(dir, "d.csf", newIOContext(random));- CompoundFileDirectory csr = dir.openCompoundInput("d.cfs", 1024);- IndexInput expected = dir.openInput("d1");- IndexInput actual = csr.openInput("d1");++ CompoundFileDirectory csr = dir.openCompoundInput("d.cfs", newIOContext(random));+ IndexInput expected = dir.openInput("d1", newIOContext(random));+ IndexInput actual = csr.openInput("d1", newIOContext(random));assertSameStreams("d1", expected, actual);assertSameSeekBehavior("d1", expected, actual);expected.close();@@@ -276,20 -275,21 +275,21 @@@createRandomFile(dir, segment + ".notIn2", 51);// Now test- CompoundFileWriter csw = new CompoundFileWriter(dir, "test.cfs", newIOContext(random));- CompoundFileDirectory csw = dir.createCompoundOutput("test.cfs");++ CompoundFileDirectory csw = dir.createCompoundOutput("test.cfs", newIOContext(random));final String data[] = new String[] {".zero", ".one", ".ten", ".hundred", ".big1", ".big2", ".big3",".big4", ".big5", ".big6", ".big7"};for (int i=0; i<data.length; i++) {- csw.addFile(segment + data[i]);+ String fileName = segment + data[i];- dir.copy(csw, fileName, fileName);++ dir.copy(csw, fileName, fileName, newIOContext(random));}csw.close();- CompoundFileReader csr = new CompoundFileReader(dir, "test.cfs", newIOContext(random));- CompoundFileDirectory csr = dir.openCompoundInput("test.cfs", 1024);++ CompoundFileDirectory csr = dir.openCompoundInput("test.cfs", newIOContext(random));for (int i=0; i<data.length; i++) {- IndexInput check = dir.openInput(segment + data[i]);- IndexInput test = csr.openInput(segment + data[i]);+ IndexInput check = dir.openInput(segment + data[i], newIOContext(random));+ IndexInput test = csr.openInput(segment + data[i], newIOContext(random));assertSameStreams(data[i], check, test);assertSameSeekBehavior(data[i], check, test);test.close();@@@ -305,10 -305,11 +305,11 @@@* the size of each file is 1000 bytes.*/private void setUp_2() throws IOException {- CompoundFileWriter cw = new CompoundFileWriter(dir, "f.comp", newIOContext(random));- CompoundFileDirectory cw = dir.createCompoundOutput("f.comp");++ CompoundFileDirectory cw = dir.createCompoundOutput("f.comp", newIOContext(random));for (int i=0; i<20; i++) {createSequenceFile(dir, "f" + i, (byte) 0, 2000);- cw.addFile("f" + i);+ String fileName = "f" + i;- dir.copy(cw, fileName, fileName);++ dir.copy(cw, fileName, fileName, newIOContext(random));}cw.close();}@@@ -321,15 -322,14 +322,14 @@@private void demo_FSIndexInputBug(Directory fsdir, String file)throws IOException{- // IOContext triggers different buffer sizes so we use default here// Setup the test file - we need more than 1024 bytes- IndexOutput os = fsdir.createOutput(file, IOContext.DEFAULT);- IndexOutput os = fsdir.createOutput(file);++ IndexOutput os = fsdir.createOutput(file, newIOContext(random));for(int i=0; i<2000; i++) {os.writeByte((byte) i);}os.close();- IndexInput in = fsdir.openInput(file, IOContext.DEFAULT);- IndexInput in = fsdir.openInput(file);++ IndexInput in = fsdir.openInput(file, newIOContext(random));// This read primes the buffer in IndexInputin.readByte();@@@ -354,39 -354,20 +354,20 @@@}}-- static boolean isCSIndexInput(IndexInput is) {- return is instanceof CompoundFileReader.CSIndexInput;- }-- static boolean isCSIndexInputOpen(IndexInput is) throws IOException {- if (isCSIndexInput(is)) {- CompoundFileReader.CSIndexInput cis =- (CompoundFileReader.CSIndexInput) is;-- return _TestHelper.isSimpleFSIndexInputOpen(cis.base);- } else {- return false;- }- }--public void testClonedStreamsClosing() throws IOException {setUp_2();- CompoundFileReader cr = new CompoundFileReader(dir, "f.comp", newIOContext(random));- CompoundFileDirectory cr = dir.openCompoundInput("f.comp", 1024);++ CompoundFileDirectory cr = dir.openCompoundInput("f.comp", newIOContext(random));// basic clone- IndexInput expected = dir.openInput("f11");+ IndexInput expected = dir.openInput("f11", newIOContext(random));// this test only works for FSIndexInputassertTrue(_TestHelper.isSimpleFSIndexInput(expected));assertTrue(_TestHelper.isSimpleFSIndexInputOpen(expected));- IndexInput one = cr.openInput("f11");+ IndexInput one = cr.openInput("f11", newIOContext(random));- assertTrue(isCSIndexInputOpen(one));IndexInput two = (IndexInput) one.clone();- assertTrue(isCSIndexInputOpen(two));assertSameStreams("basic clone one", expected, one);expected.seek(0);@@@ -430,14 -408,14 +408,14 @@@*/public void testRandomAccess() throws IOException {setUp_2();- CompoundFileReader cr = new CompoundFileReader(dir, "f.comp", newIOContext(random));- CompoundFileDirectory cr = dir.openCompoundInput("f.comp", 1024);++ CompoundFileDirectory cr = dir.openCompoundInput("f.comp", newIOContext(random));// Open two files- IndexInput e1 = dir.openInput("f11");- IndexInput e2 = dir.openInput("f3");+ IndexInput e1 = dir.openInput("f11", newIOContext(random));+ IndexInput e2 = dir.openInput("f3", newIOContext(random));- IndexInput a1 = cr.openInput("f11");- IndexInput a2 = dir.openInput("f3");+ IndexInput a1 = cr.openInput("f11", newIOContext(random));+ IndexInput a2 = dir.openInput("f3", newIOContext(random));// Seek the first paire1.seek(100);@@@ -509,11 -487,11 +487,11 @@@*/public void testRandomAccessClones() throws IOException {setUp_2();- CompoundFileReader cr = new CompoundFileReader(dir, "f.comp", newIOContext(random));- CompoundFileDirectory cr = dir.openCompoundInput("f.comp", 1024);++ CompoundFileDirectory cr = dir.openCompoundInput("f.comp", newIOContext(random));// Open two files- IndexInput e1 = cr.openInput("f11");- IndexInput e2 = cr.openInput("f3");+ IndexInput e1 = cr.openInput("f11", newIOContext(random));+ IndexInput e2 = cr.openInput("f3", newIOContext(random));IndexInput a1 = (IndexInput) e1.clone();IndexInput a2 = (IndexInput) e2.clone();@@@ -586,7 -564,7 +564,7 @@@public void testFileNotFound() throws IOException {setUp_2();- CompoundFileReader cr = new CompoundFileReader(dir, "f.comp", newIOContext(random));- CompoundFileDirectory cr = dir.openCompoundInput("f.comp", 1024);++ CompoundFileDirectory cr = dir.openCompoundInput("f.comp", newIOContext(random));// Open two filestry {@@@ -604,8 -582,8 +582,8 @@@public void testReadPastEOF() throws IOException {setUp_2();- CompoundFileReader cr = new CompoundFileReader(dir, "f.comp", newIOContext(random));- CompoundFileDirectory cr = dir.openCompoundInput("f.comp", 1024);- IndexInput is = cr.openInput("f2");++ CompoundFileDirectory cr = dir.openCompoundInput("f.comp", newIOContext(random));+ IndexInput is = cr.openInput("f2", newIOContext(random));is.seek(is.length() - 10);byte b[] = new byte[100];is.readBytes(b, 0, 10);@@@ -657,13 -635,13 +635,13 @@@createSequenceFile(dir, "d1", (byte) 0, 15);Directory newDir = newDirectory();- CompoundFileWriter csw = new CompoundFileWriter(newDir, "d.csf", newIOContext(random));- csw.addFile("d1", dir);- CompoundFileDirectory csw = newDir.createCompoundOutput("d.cfs");- dir.copy(csw, "d1", "d1");++ CompoundFileDirectory csw = newDir.createCompoundOutput("d.cfs", newIOContext(random));++ dir.copy(csw, "d1", "d1", newIOContext(random));csw.close();- CompoundFileReader csr = new CompoundFileReader(newDir, "d.csf", newIOContext(random));- CompoundFileDirectory csr = newDir.openCompoundInput("d.cfs", 1024);- IndexInput expected = dir.openInput("d1");- IndexInput actual = csr.openInput("d1");++ CompoundFileDirectory csr = newDir.openCompoundInput("d.cfs", newIOContext(random));+ IndexInput expected = dir.openInput("d1", newIOContext(random));+ IndexInput actual = csr.openInput("d1", newIOContext(random));assertSameStreams("d1", expected, actual);assertSameSeekBehavior("d1", expected, actual);expected.close();@@@ -672,5 -650,72 +650,72 @@@newDir.close();}+++ public void testAppend() throws IOException {+ Directory newDir = newDirectory();- CompoundFileDirectory csw = newDir.createCompoundOutput("d.cfs");++ CompoundFileDirectory csw = newDir.createCompoundOutput("d.cfs", newIOContext(random));+ int size = 5 + random.nextInt(128);+ for (int j = 0; j < 2; j++) {- IndexOutput os = csw.createOutput("seg" + j + "_foo.txt");++ IndexOutput os = csw.createOutput("seg" + j + "_foo.txt", newIOContext(random));+ for (int i = 0; i < size; i++) {+ os.writeInt(i);+ }+ os.close();+ String[] listAll = newDir.listAll();+ assertEquals(1, listAll.length);+ assertEquals("d.cfs", listAll[0]);+ }+ createSequenceFile(dir, "d1", (byte) 0, 15);- dir.copy(csw, "d1", "d1");++ dir.copy(csw, "d1", "d1", newIOContext(random));+ String[] listAll = newDir.listAll();+ assertEquals(1, listAll.length);+ assertEquals("d.cfs", listAll[0]);+ csw.close();- CompoundFileDirectory csr = newDir.openCompoundInput("d.cfs", 1024);++ CompoundFileDirectory csr = newDir.openCompoundInput("d.cfs", newIOContext(random));+ for (int j = 0; j < 2; j++) {- IndexInput openInput = csr.openInput("seg" + j + "_foo.txt");++ IndexInput openInput = csr.openInput("seg" + j + "_foo.txt", newIOContext(random));+ assertEquals(size * 4, openInput.length());+ for (int i = 0; i < size; i++) {+ assertEquals(i, openInput.readInt());+ }++ openInput.close();++ }- IndexInput expected = dir.openInput("d1");- IndexInput actual = csr.openInput("d1");++ IndexInput expected = dir.openInput("d1", newIOContext(random));++ IndexInput actual = csr.openInput("d1", newIOContext(random));+ assertSameStreams("d1", expected, actual);+ assertSameSeekBehavior("d1", expected, actual);+ expected.close();+ actual.close();+ csr.close();+ newDir.close();+ }++ public void testAppendTwice() throws IOException {+ Directory newDir = newDirectory();- CompoundFileDirectory csw = newDir.createCompoundOutput("d.cfs");++ CompoundFileDirectory csw = newDir.createCompoundOutput("d.cfs", newIOContext(random));+ createSequenceFile(newDir, "d1", (byte) 0, 15);- IndexOutput out = csw.createOutput("d.xyz");++ IndexOutput out = csw.createOutput("d.xyz", newIOContext(random));+ out.writeInt(0);+ try {- newDir.copy(csw, "d1", "d1");++ newDir.copy(csw, "d1", "d1", newIOContext(random));+ fail("file does already exist");+ } catch (IOException e) {+ //+ }+ out.close();+ assertEquals(1, csw.listAll().length);+ assertEquals("d.xyz", csw.listAll()[0]);++ csw.close();+- CompoundFileDirectory cfr = newDir.openCompoundInput("d.cfs", 1024);++ CompoundFileDirectory cfr = newDir.openCompoundInput("d.cfs", newIOContext(random));+ assertEquals(1, cfr.listAll().length);+ assertEquals("d.xyz", cfr.listAll()[0]);+ cfr.close();+ newDir.close();+ }}diff --cc lucene/src/test/org/apache/lucene/index/TestDocumentWriter.javaindex bd6adfbef97,9ec66d545a2..61894fe720c--- a/lucene/src/test/org/apache/lucene/index/TestDocumentWriter.java+++ b/lucene/src/test/org/apache/lucene/index/TestDocumentWriter.java@@@ -131,9 -129,9 +131,9 @@@ public class TestDocumentWriter extendwriter.commit();SegmentInfo info = writer.newestSegment();writer.close();- SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);+ SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR, newIOContext(random));- DocsAndPositionsEnum termPositions = MultiFields.getTermPositionsEnum(reader, MultiFields.getDeletedDocs(reader),+ DocsAndPositionsEnum termPositions = MultiFields.getTermPositionsEnum(reader, MultiFields.getLiveDocs(reader),"repeated", new BytesRef("repeated"));assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);int freq = termPositions.freq();@@@ -195,9 -193,9 +195,9 @@@writer.commit();SegmentInfo info = writer.newestSegment();writer.close();- SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);+ SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR, newIOContext(random));- DocsAndPositionsEnum termPositions = reader.fields().terms("f1").docsAndPositions(reader.getDeletedDocs(), new BytesRef("a"), null);+ DocsAndPositionsEnum termPositions = reader.fields().terms("f1").docsAndPositions(reader.getLiveDocs(), new BytesRef("a"), null);assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);int freq = termPositions.freq();assertEquals(3, freq);@@@ -239,9 -237,9 +239,9 @@@writer.commit();SegmentInfo info = writer.newestSegment();writer.close();- SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);+ SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR, newIOContext(random));- DocsAndPositionsEnum termPositions = reader.fields().terms("preanalyzed").docsAndPositions(reader.getDeletedDocs(), new BytesRef("term1"), null);+ DocsAndPositionsEnum termPositions = reader.fields().terms("preanalyzed").docsAndPositions(reader.getLiveDocs(), new BytesRef("term1"), null);assertTrue(termPositions.nextDoc() != termPositions.NO_MORE_DOCS);assertEquals(1, termPositions.freq());assertEquals(0, termPositions.nextPosition());diff --cc lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.javaindex fa4e1e6dee7,6ea632e1341..9561b5194ea--- a/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java@@@ -92,7 -92,7 +92,7 @@@ public class TestIndexFileDeleter exten// figure out which field number corresponds to// "content", and then set our expected file names below// accordingly:- CompoundFileReader cfsReader = new CompoundFileReader(dir, "_2.cfs", newIOContext(random));- CompoundFileDirectory cfsReader = dir.openCompoundInput("_2.cfs", 1024);++ CompoundFileDirectory cfsReader = dir.openCompoundInput("_2.cfs", newIOContext(random));FieldInfos fieldInfos = new FieldInfos(cfsReader, "_2.fnm");int contentFieldIndex = -1;for (FieldInfo fi : fieldInfos) {diff --cc lucene/src/test/org/apache/lucene/index/TestSegmentTermDocs.javaindex 895b5b37b3b,17dbae5a054..9ffa8b4ce7a--- a/lucene/src/test/org/apache/lucene/index/TestSegmentTermDocs.java+++ b/lucene/src/test/org/apache/lucene/index/TestSegmentTermDocs.java@@@ -79,9 -78,9 +79,9 @@@ public class TestSegmentTermDocs extendpublic void testBadSeek(int indexDivisor) throws IOException {{//After adding the document, we should be able to read it back in- SegmentReader reader = SegmentReader.get(true, info, indexDivisor);+ SegmentReader reader = SegmentReader.get(true, info, indexDivisor, newIOContext(random));assertTrue(reader != null);- DocsEnum termDocs = reader.termDocsEnum(reader.getDeletedDocs(),+ DocsEnum termDocs = reader.termDocsEnum(reader.getLiveDocs(),"textField2",new BytesRef("bad"));@@@ -90,9 -89,9 +90,9 @@@}{//After adding the document, we should be able to read it back in- SegmentReader reader = SegmentReader.get(true, info, indexDivisor);+ SegmentReader reader = SegmentReader.get(true, info, indexDivisor, newIOContext(random));assertTrue(reader != null);- DocsEnum termDocs = reader.termDocsEnum(reader.getDeletedDocs(),+ DocsEnum termDocs = reader.termDocsEnum(reader.getLiveDocs(),"junk",new BytesRef("bad"));assertNull(termDocs);diff --cc lucene/src/test/org/apache/lucene/index/values/TestDocValues.javaindex ce400bdc865,a72a28b9820..d4981aa3093--- a/lucene/src/test/org/apache/lucene/index/values/TestDocValues.java+++ b/lucene/src/test/org/apache/lucene/index/values/TestDocValues.java@@@ -62,10 -61,10 +61,10 @@@ public class TestDocValues extends LuceDirectory dir = newDirectory();final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Bytes.getWriter(dir, "test", mode, comp, fixedSize, trackBytes);+ Writer w = Bytes.getWriter(dir, "test", mode, comp, fixedSize, trackBytes, newIOContext(random));int maxDoc = 220;final String[] values = new String[maxDoc];- final int fixedLength = 3 + random.nextInt(7);+ final int fixedLength = 1 + atLeast(50);for (int i = 0; i < 100; i++) {final String s;if (i > 0 && random.nextInt(5) <= 2) {@@@ -171,76 -170,241 +170,241 @@@dir.close();}- public void testInts() throws IOException {- long[] maxMin = new long[] {- Long.MIN_VALUE, Long.MAX_VALUE,- 1, Long.MAX_VALUE,- 0, Long.MAX_VALUE,- -1, Long.MAX_VALUE,- Long.MIN_VALUE, -1,- random.nextInt(), random.nextInt() };- for (int j = 0; j < maxMin.length; j+=2) {- long maxV = 1;- final int NUM_VALUES = 777 + random.nextInt(777);- final long[] values = new long[NUM_VALUES];- for (int rx = 1; rx < 63; rx++, maxV *= 2) {- Directory dir = newDirectory();- final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Ints.getWriter(dir, "test", false, trackBytes, newIOContext(random));- values[0] = maxMin[j];- w.add(0, values[0]);- values[1] = maxMin[j+1];- w.add(1, values[1]);- for (int i = 2; i < NUM_VALUES; i++) {- final long v = random.nextLong() % (1 + maxV);- values[i] = v;- w.add(i, v);- }- final int additionalDocs = 1 + random.nextInt(9);- w.finish(NUM_VALUES + additionalDocs);- assertEquals(0, trackBytes.get());+ public void testVariableIntsLimits() throws IOException {+ long[][] minMax = new long[][] { { Long.MIN_VALUE, Long.MAX_VALUE },+ { Long.MIN_VALUE + 1, 1 }, { -1, Long.MAX_VALUE },+ { Long.MIN_VALUE, -1 }, { 1, Long.MAX_VALUE },+ { -1, Long.MAX_VALUE - 1 }, { Long.MIN_VALUE + 2, 1 }, };+ ValueType[] expectedTypes = new ValueType[] { ValueType.FIXED_INTS_64,+ ValueType.FIXED_INTS_64, ValueType.FIXED_INTS_64,+ ValueType.FIXED_INTS_64, ValueType.VAR_INTS, ValueType.VAR_INTS,+ ValueType.VAR_INTS, };+ for (int i = 0; i < minMax.length; i++) {+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.VAR_INTS);++ Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.VAR_INTS, newIOContext(random));+ w.add(0, minMax[i][0]);+ w.add(1, minMax[i][1]);+ w.finish(2);+ assertEquals(0, trackBytes.get());- IndexDocValues r = Ints.getValues(dir, "test", 2);++ IndexDocValues r = Ints.getValues(dir, "test", 2, newIOContext(random));+ Source source = getSource(r);+ assertEquals(i + " with min: " + minMax[i][0] + " max: " + minMax[i][1],+ expectedTypes[i], source.type());+ assertEquals(minMax[i][0], source.getInt(0));+ assertEquals(minMax[i][1], source.getInt(1));+ ValuesEnum iEnum = getEnum(r);+ assertEquals(i + " with min: " + minMax[i][0] + " max: " + minMax[i][1],+ expectedTypes[i], iEnum.type());+ assertEquals(0, iEnum.nextDoc());+ assertEquals(minMax[i][0], iEnum.intsRef.get());+ assertEquals(1, iEnum.nextDoc());+ assertEquals(minMax[i][1], iEnum.intsRef.get());+ assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.nextDoc());- IndexDocValues r = Ints.getValues(dir, "test", false, newIOContext(random));- for (int iter = 0; iter < 2; iter++) {- Source s = getSource(r);- for (int i = 0; i < NUM_VALUES; i++) {- final long v = s.getInt(i);- assertEquals("index " + i, values[i], v);- }+ r.close();+ dir.close();+ }+ }++ public void testVInts() throws IOException {+ testInts(ValueType.VAR_INTS, 63);+ }++ public void testFixedInts() throws IOException {+ testInts(ValueType.FIXED_INTS_64, 63);+ testInts(ValueType.FIXED_INTS_32, 31);+ testInts(ValueType.FIXED_INTS_16, 15);+ testInts(ValueType.FIXED_INTS_8, 7);++ }++ public void testGetInt8Array() throws IOException {+ byte[] sourceArray = new byte[] {1,2,3};+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_8);++ Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_8, newIOContext(random));+ for (int i = 0; i < sourceArray.length; i++) {+ w.add(i, (long) sourceArray[i]);+ }+ w.finish(sourceArray.length);- IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length);++ IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length, newIOContext(random));+ Source source = r.getSource();+ assertTrue(source.hasArray());+ byte[] loaded = ((byte[])source.getArray());+ assertEquals(loaded.length, sourceArray.length);+ for (int i = 0; i < loaded.length; i++) {+ assertEquals("value didn't match at index " + i, sourceArray[i], loaded[i]);+ }+ r.close();+ dir.close();+ }++ public void testGetInt16Array() throws IOException {+ short[] sourceArray = new short[] {1,2,3};+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_16);++ Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_16, newIOContext(random));+ for (int i = 0; i < sourceArray.length; i++) {+ w.add(i, (long) sourceArray[i]);+ }+ w.finish(sourceArray.length);- IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length);++ IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length, newIOContext(random));+ Source source = r.getSource();+ assertTrue(source.hasArray());+ short[] loaded = ((short[])source.getArray());+ assertEquals(loaded.length, sourceArray.length);+ for (int i = 0; i < loaded.length; i++) {+ assertEquals("value didn't match at index " + i, sourceArray[i], loaded[i]);+ }+ r.close();+ dir.close();+ }++ public void testGetInt64Array() throws IOException {+ long[] sourceArray = new long[] {1,2,3};+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_64);++ Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_64, newIOContext(random));+ for (int i = 0; i < sourceArray.length; i++) {+ w.add(i, sourceArray[i]);+ }+ w.finish(sourceArray.length);- IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length);++ IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length, newIOContext(random));+ Source source = r.getSource();+ assertTrue(source.hasArray());+ long[] loaded = ((long[])source.getArray());+ assertEquals(loaded.length, sourceArray.length);+ for (int i = 0; i < loaded.length; i++) {+ assertEquals("value didn't match at index " + i, sourceArray[i], loaded[i]);+ }+ r.close();+ dir.close();+ }++ public void testGetInt32Array() throws IOException {+ int[] sourceArray = new int[] {1,2,3};+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_32);++ Writer w = Ints.getWriter(dir, "test", trackBytes, ValueType.FIXED_INTS_32, newIOContext(random));+ for (int i = 0; i < sourceArray.length; i++) {+ w.add(i, (long) sourceArray[i]);+ }+ w.finish(sourceArray.length);- IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length);++ IndexDocValues r = Ints.getValues(dir, "test", sourceArray.length, newIOContext(random));+ Source source = r.getSource();+ assertTrue(source.hasArray());+ int[] loaded = ((int[])source.getArray());+ assertEquals(loaded.length, sourceArray.length);+ for (int i = 0; i < loaded.length; i++) {+ assertEquals("value didn't match at index " + i, sourceArray[i], loaded[i]);+ }+ r.close();+ dir.close();+ }++ public void testGetFloat32Array() throws IOException {+ float[] sourceArray = new float[] {1,2,3};+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Floats.getWriter(dir, "test", 4, trackBytes);++ Writer w = Floats.getWriter(dir, "test", 4, trackBytes, newIOContext(random));+ for (int i = 0; i < sourceArray.length; i++) {+ w.add(i, sourceArray[i]);+ }+ w.finish(sourceArray.length);- IndexDocValues r = Floats.getValues(dir, "test", 3);++ IndexDocValues r = Floats.getValues(dir, "test", 3, newIOContext(random));+ Source source = r.getSource();+ assertTrue(source.hasArray());+ float[] loaded = ((float[])source.getArray());+ assertEquals(loaded.length, sourceArray.length);+ for (int i = 0; i < loaded.length; i++) {+ assertEquals("value didn't match at index " + i, sourceArray[i], loaded[i], 0.0f);+ }+ r.close();+ dir.close();+ }++ public void testGetFloat64Array() throws IOException {+ double[] sourceArray = new double[] {1,2,3};+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Floats.getWriter(dir, "test", 8, trackBytes);++ Writer w = Floats.getWriter(dir, "test", 8, trackBytes, newIOContext(random));+ for (int i = 0; i < sourceArray.length; i++) {+ w.add(i, sourceArray[i]);+ }+ w.finish(sourceArray.length);- IndexDocValues r = Floats.getValues(dir, "test", 3);++ IndexDocValues r = Floats.getValues(dir, "test", 3, newIOContext(random));+ Source source = r.getSource();+ assertTrue(source.hasArray());+ double[] loaded = ((double[])source.getArray());+ assertEquals(loaded.length, sourceArray.length);+ for (int i = 0; i < loaded.length; i++) {+ assertEquals("value didn't match at index " + i, sourceArray[i], loaded[i], 0.0d);+ }+ r.close();+ dir.close();+ }++ private void testInts(ValueType type, int maxBit) throws IOException {+ long maxV = 1;+ final int NUM_VALUES = 333 + random.nextInt(333);+ final long[] values = new long[NUM_VALUES];+ for (int rx = 1; rx < maxBit; rx++, maxV *= 2) {+ Directory dir = newDirectory();+ final AtomicLong trackBytes = new AtomicLong(0);- Writer w = Ints.getWriter(dir, "test", trackBytes, type);++ Writer w = Ints.getWriter(dir, "test", trackBytes, type, newIOContext(random));+ for (int i = 0; i < NUM_VALUES; i++) {+ final long v = random.nextLong() % (1 + maxV);+ values[i] = v;+ w.add(i, v);+ }+ final int additionalDocs = 1 + random.nextInt(9);+ w.finish(NUM_VALUES + additionalDocs);+ assertEquals(0, trackBytes.get());+- IndexDocValues r = Ints.getValues(dir, "test", NUM_VALUES + additionalDocs);++ IndexDocValues r = Ints.getValues(dir, "test", NUM_VALUES + additionalDocs, newIOContext(random));+ for (int iter = 0; iter < 2; iter++) {+ Source s = getSource(r);+ assertEquals(type, s.type());+ for (int i = 0; i < NUM_VALUES; i++) {+ final long v = s.getInt(i);+ assertEquals("index " + i, values[i], v);}+ }- for (int iter = 0; iter < 2; iter++) {- ValuesEnum iEnum = getEnum(r);- LongsRef ints = iEnum.getInt();- for (int i = 0; i < NUM_VALUES + additionalDocs; i++) {- assertEquals(i, iEnum.nextDoc());- if (i < NUM_VALUES) {- assertEquals(values[i], ints.get());- } else {- assertEquals(0, ints.get());- }+ for (int iter = 0; iter < 2; iter++) {+ ValuesEnum iEnum = getEnum(r);+ assertEquals(type, iEnum.type());+ LongsRef ints = iEnum.getInt();+ for (int i = 0; i < NUM_VALUES + additionalDocs; i++) {+ assertEquals(i, iEnum.nextDoc());+ if (i < NUM_VALUES) {+ assertEquals(values[i], ints.get());+ } else {+ assertEquals(0, ints.get());}- assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.nextDoc());- iEnum.close();}+ assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.nextDoc());+ iEnum.close();+ }- for (int iter = 0; iter < 2; iter++) {- ValuesEnum iEnum = getEnum(r);- LongsRef ints = iEnum.getInt();- for (int i = 0; i < NUM_VALUES + additionalDocs; i += 1 + random.nextInt(25)) {- assertEquals(i, iEnum.advance(i));- if (i < NUM_VALUES) {- assertEquals(values[i], ints.get());- } else {- assertEquals(0, ints.get());- }+ for (int iter = 0; iter < 2; iter++) {+ ValuesEnum iEnum = getEnum(r);+ assertEquals(type, iEnum.type());+ LongsRef ints = iEnum.getInt();+ for (int i = 0; i < NUM_VALUES + additionalDocs; i += 1 + random.nextInt(25)) {+ assertEquals(i, iEnum.advance(i));+ if (i < NUM_VALUES) {+ assertEquals(values[i], ints.get());+ } else {+ assertEquals(0, ints.get());}- assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.advance(NUM_VALUES + additionalDocs));- iEnum.close();}- r.close();- dir.close();+ assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.advance(NUM_VALUES + additionalDocs));+ iEnum.close();}+ r.close();+ dir.close();}}diff --cc lucene/src/test/org/apache/lucene/search/TestBoolean2.javaindex f42fceabce3,98999ae7af4..2a460a57083--- a/lucene/src/test/org/apache/lucene/search/TestBoolean2.java+++ b/lucene/src/test/org/apache/lucene/search/TestBoolean2.java@@@ -26,10 -26,7 +26,8 @@@ import org.apache.lucene.document.Fieldimport org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;import org.apache.lucene.index.IndexReader;- import org.apache.lucene.queryParser.ParseException;- import org.apache.lucene.queryParser.QueryParser;import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;import org.apache.lucene.store.MockDirectoryWrapper;import org.apache.lucene.store.RAMDirectory;import org.apache.lucene.util.LuceneTestCase;diff --cc lucene/src/test/org/apache/lucene/util/TestBitVector.javaindex 8b6cae7bb4b,45d473b9f89..1944cc0a854--- a/lucene/src/test/org/apache/lucene/util/TestBitVector.java+++ b/lucene/src/test/org/apache/lucene/util/TestBitVector.java@@@ -171,28 -170,29 +171,29 @@@ public class TestBitVector extends LuceMockDirectoryWrapper d = new MockDirectoryWrapper(random, new RAMDirectory());d.setPreventDoubleWrite(false);BitVector bv = new BitVector(size);+ bv.invertAll();for (int i=0; i<count1; i++) {- bv.set(i);- assertEquals(i+1,bv.count());+ bv.clear(i);+ assertEquals(i+1,size-bv.count());}- bv.write(d, "TESTBV");+ bv.write(d, "TESTBV", newIOContext(random));// gradually increase number of set bitsfor (int i=count1; i<count2; i++) {- BitVector bv2 = new BitVector(d, "TESTBV");+ BitVector bv2 = new BitVector(d, "TESTBV", newIOContext(random));assertTrue(doCompare(bv,bv2));bv = bv2;- bv.set(i);- assertEquals(i+1,bv.count());+ bv.clear(i);+ assertEquals(i+1,size-bv.count());- bv.write(d, "TESTBV");+ bv.write(d, "TESTBV", newIOContext(random));}// now start decreasing number of set bitsfor (int i=count2-1; i>=count1; i--) {- BitVector bv2 = new BitVector(d, "TESTBV");+ BitVector bv2 = new BitVector(d, "TESTBV", newIOContext(random));assertTrue(doCompare(bv,bv2));bv = bv2;- bv.clear(i);- assertEquals(i,bv.count());+ bv.set(i);+ assertEquals(i,size-bv.count());- bv.write(d, "TESTBV");+ bv.write(d, "TESTBV", newIOContext(random));}}/**diff --cc lucene/src/test/org/apache/lucene/util/TestByteBlockPool.javaindex 00000000000,ef12523f06c..92ff5b7cf32mode 000000,100644..100644--- a/lucene/src/test/org/apache/lucene/util/TestByteBlockPool.java+++ b/lucene/src/test/org/apache/lucene/util/TestByteBlockPool.java@@@ -1,0 -1,67 +1,67 @@@+ package org.apache.lucene.util;++ import java.io.IOException;+ import java.util.ArrayList;+ import java.util.List;++ import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;+ import org.apache.lucene.store.RAMDirectory;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with this+ * work for additional information regarding copyright ownership. The ASF+ * licenses this file to You under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+ * License for the specific language governing permissions and limitations under+ * the License.+ */+ public class TestByteBlockPool extends LuceneTestCase {++ public void testCopyRefAndWrite() throws IOException {+ List<String> list = new ArrayList<String>();+ int maxLength = atLeast(500);+ ByteBlockPool pool = new ByteBlockPool(new ByteBlockPool.DirectAllocator());+ pool.nextBuffer();+ final int numValues = atLeast(100);+ BytesRef ref = new BytesRef();+ for (int i = 0; i < numValues; i++) {+ final String value = _TestUtil.randomRealisticUnicodeString(random,+ maxLength);+ list.add(value);+ ref.copy(value);+ pool.copy(ref);+ }+ RAMDirectory dir = new RAMDirectory();- IndexOutput stream = dir.createOutput("foo.txt");++ IndexOutput stream = dir.createOutput("foo.txt", newIOContext(random));+ pool.writePool(stream);+ stream.flush();+ stream.close();- IndexInput input = dir.openInput("foo.txt");++ IndexInput input = dir.openInput("foo.txt", newIOContext(random));+ assertEquals(pool.byteOffset + pool.byteUpto, stream.length());+ BytesRef expected = new BytesRef();+ BytesRef actual = new BytesRef();+ for (String string : list) {+ expected.copy(string);+ actual.grow(expected.length);+ actual.length = expected.length;+ input.readBytes(actual.bytes, 0, actual.length);+ assertEquals(expected, actual);+ }+ try {+ input.readByte();+ fail("must be EOF");+ } catch (IOException e) {+ // expected - read past EOF+ }+ dir.close();+ }+ }diff --cc modules/facet/src/test/org/apache/lucene/util/SlowRAMDirectory.javaindex 00000000000,11e51b6d214..33b0010f599mode 000000,100644..100644--- a/modules/facet/src/test/org/apache/lucene/util/SlowRAMDirectory.java+++ b/modules/facet/src/test/org/apache/lucene/util/SlowRAMDirectory.java@@@ -1,0 -1,167 +1,160 @@@+ package org.apache.lucene.util;++ import java.io.IOException;+ import java.util.Random;+++import org.apache.lucene.store.IOContext;+ import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.store.IndexOutput;+ import org.apache.lucene.store.RAMDirectory;+ import org.apache.lucene.util.ThreadInterruptedException;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++ /**+ * Test utility - slow directory+ */+ // TODO: move to test-framework and sometimes use in tests?+ public class SlowRAMDirectory extends RAMDirectory {++ private static final int IO_SLEEP_THRESHOLD = 50;++ private Random random;+ private int sleepMillis;++ public void setSleepMillis(int sleepMillis) {+ this.sleepMillis = sleepMillis;+ }++ public SlowRAMDirectory(int sleepMillis, Random random) {+ this.sleepMillis = sleepMillis;+ this.random = random;+ }++ @Override- public IndexOutput createOutput(String name) throws IOException {++ public IndexOutput createOutput(String name, IOContext context) throws IOException {+ if (sleepMillis != -1) {- return new SlowIndexOutput(super.createOutput(name));++ return new SlowIndexOutput(super.createOutput(name, context));+ }+- return super.createOutput(name);++ return super.createOutput(name, context);+ }++ @Override- public IndexInput openInput(String name) throws IOException {++ public IndexInput openInput(String name, IOContext context) throws IOException {+ if (sleepMillis != -1) {- return new SlowIndexInput(super.openInput(name));++ return new SlowIndexInput(super.openInput(name, context));+ }- return super.openInput(name);- }-- @Override- public IndexInput openInput(String name, int bufferSize) throws IOException {- if (sleepMillis != -1) {- return new SlowIndexInput(super.openInput(name, bufferSize));- }- return super.openInput(name, bufferSize);++ return super.openInput(name, context);+ }++ void doSleep(int length) {+ int sTime = length<10 ? sleepMillis : (int) (sleepMillis * Math.log(length));+ if (random!=null) {+ sTime = random.nextInt(sTime);+ }+ try {+ Thread.sleep(sTime);+ } catch (InterruptedException e) {+ throw new ThreadInterruptedException(e);+ }+ }++ /**+ * Delegate class to wrap an IndexInput and delay reading bytes by some+ * specified time.+ */+ private class SlowIndexInput extends IndexInput {+ private IndexInput ii;+ private int numRead = 0;++ public SlowIndexInput(IndexInput ii) {+ this.ii = ii;+ }++ @Override+ public byte readByte() throws IOException {+ if (numRead >= IO_SLEEP_THRESHOLD) {+ doSleep(0);+ numRead = 0;+ }+ ++numRead;+ return ii.readByte();+ }++ @Override+ public void readBytes(byte[] b, int offset, int len) throws IOException {+ if (numRead >= IO_SLEEP_THRESHOLD) {+ doSleep(len);+ numRead = 0;+ }+ numRead += len;+ ii.readBytes(b, offset, len);+ }++ @Override public Object clone() { return ii.clone(); }+ @Override public void close() throws IOException { ii.close(); }+ @Override public boolean equals(Object o) { return ii.equals(o); }+ @Override public long getFilePointer() { return ii.getFilePointer(); }+ @Override public int hashCode() { return ii.hashCode(); }+ @Override public long length() { return ii.length(); }+ @Override public void seek(long pos) throws IOException { ii.seek(pos); }++ }++ /**+ * Delegate class to wrap an IndexOutput and delay writing bytes by some+ * specified time.+ */+ private class SlowIndexOutput extends IndexOutput {++ private IndexOutput io;+ private int numWrote;++ public SlowIndexOutput(IndexOutput io) {+ this.io = io;+ }++ @Override+ public void writeByte(byte b) throws IOException {+ if (numWrote >= IO_SLEEP_THRESHOLD) {+ doSleep(0);+ numWrote = 0;+ }+ ++numWrote;+ io.writeByte(b);+ }++ @Override+ public void writeBytes(byte[] b, int offset, int length) throws IOException {+ if (numWrote >= IO_SLEEP_THRESHOLD) {+ doSleep(length);+ numWrote = 0;+ }+ numWrote += length;+ io.writeBytes(b, offset, length);+ }++ @Override public void close() throws IOException { io.close(); }+ @Override public void flush() throws IOException { io.flush(); }+ @Override public long getFilePointer() { return io.getFilePointer(); }+ @Override public long length() throws IOException { return io.length(); }+ @Override public void seek(long pos) throws IOException { io.seek(pos); }+ }++ }