diff --git a/k8s/seaweedfs/Chart.yaml b/k8s/seaweedfs/Chart.yaml
index 73d9a67e4..0744d5051 100644
--- a/k8s/seaweedfs/Chart.yaml
+++ b/k8s/seaweedfs/Chart.yaml
@@ -1,4 +1,4 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
-version: 1.88
\ No newline at end of file
+version: 1.90
\ No newline at end of file
diff --git a/k8s/seaweedfs/values.yaml b/k8s/seaweedfs/values.yaml
index 6fb25e0a3..e87bc0fcb 100644
--- a/k8s/seaweedfs/values.yaml
+++ b/k8s/seaweedfs/values.yaml
@@ -4,7 +4,7 @@ global:
registry: ""
repository: ""
imageName: chrislusf/seaweedfs
- imageTag: "1.88"
+ imageTag: "1.90"
imagePullPolicy: IfNotPresent
imagePullSecrets: imagepullsecret
restartPolicy: Always
diff --git a/other/java/client/pom.xml b/other/java/client/pom.xml
index 6727f749f..c8e90c96a 100644
--- a/other/java/client/pom.xml
+++ b/other/java/client/pom.xml
@@ -5,7 +5,7 @@
com.github.chrislusfseaweedfs-client
- 1.4.5
+ 1.4.6org.sonatype.oss
diff --git a/other/java/client/pom.xml.deploy b/other/java/client/pom.xml.deploy
index 6727f749f..c8e90c96a 100644
--- a/other/java/client/pom.xml.deploy
+++ b/other/java/client/pom.xml.deploy
@@ -5,7 +5,7 @@
com.github.chrislusfseaweedfs-client
- 1.4.5
+ 1.4.6org.sonatype.oss
diff --git a/other/java/client/pom_debug.xml b/other/java/client/pom_debug.xml
index ed3f07298..395efa984 100644
--- a/other/java/client/pom_debug.xml
+++ b/other/java/client/pom_debug.xml
@@ -5,7 +5,7 @@
com.github.chrislusfseaweedfs-client
- 1.4.5
+ 1.4.6org.sonatype.oss
diff --git a/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java b/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java
index cd2f55678..045751717 100644
--- a/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java
+++ b/other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java
@@ -23,7 +23,7 @@ public class SeaweedRead {
// returns bytesRead
public static long read(FilerGrpcClient filerGrpcClient, List visibleIntervals,
final long position, final byte[] buffer, final int bufferOffset,
- final int bufferLength) throws IOException {
+ final int bufferLength, final long fileSize) throws IOException {
List chunkViews = viewFromVisibles(visibleIntervals, position, bufferLength);
@@ -42,6 +42,14 @@ public class SeaweedRead {
long readCount = 0;
int startOffset = bufferOffset;
for (ChunkView chunkView : chunkViews) {
+
+ if (startOffset < chunkView.logicOffset) {
+ long gap = chunkView.logicOffset - startOffset;
+ LOG.debug("zero [{},{})", startOffset, startOffset + gap);
+ readCount += gap;
+ startOffset += gap;
+ }
+
FilerProto.Locations locations = vid2Locations.get(parseVolumeId(chunkView.fileId));
if (locations == null || locations.getLocationsCount() == 0) {
LOG.error("failed to locate {}", chunkView.fileId);
@@ -51,11 +59,22 @@ public class SeaweedRead {
int len = readChunkView(position, buffer, startOffset, chunkView, locations);
+ LOG.debug("read [{},{}) {} size {}", startOffset, startOffset + len, chunkView.fileId, chunkView.size);
+
readCount += len;
startOffset += len;
}
+ long limit = Math.min(bufferLength, fileSize);
+
+ if (startOffset < limit) {
+ long gap = limit - startOffset;
+ LOG.debug("zero2 [{},{})", startOffset, startOffset + gap);
+ readCount += gap;
+ startOffset += gap;
+ }
+
return readCount;
}
@@ -71,7 +90,7 @@ public class SeaweedRead {
int len = (int) chunkView.size;
LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView.offset:{} buffer.length:{} startOffset:{} len:{}",
chunkView.fileId, chunkData.length, chunkView.offset, buffer.length, startOffset, len);
- System.arraycopy(chunkData, (int) chunkView.offset, buffer, startOffset, len);
+ System.arraycopy(chunkData, startOffset - (int) (chunkView.logicOffset - chunkView.offset), buffer, startOffset, len);
return len;
}
@@ -93,7 +112,7 @@ public class SeaweedRead {
Header contentEncodingHeader = entity.getContentEncoding();
if (contentEncodingHeader != null) {
- HeaderElement[] encodings =contentEncodingHeader.getElements();
+ HeaderElement[] encodings = contentEncodingHeader.getElements();
for (int i = 0; i < encodings.length; i++) {
if (encodings[i].getName().equalsIgnoreCase("gzip")) {
entity = new GzipDecompressingEntity(entity);
@@ -134,18 +153,19 @@ public class SeaweedRead {
long stop = offset + size;
for (VisibleInterval chunk : visibleIntervals) {
- if (chunk.start <= offset && offset < chunk.stop && offset < stop) {
+ long chunkStart = Math.max(offset, chunk.start);
+ long chunkStop = Math.min(stop, chunk.stop);
+ if (chunkStart < chunkStop) {
boolean isFullChunk = chunk.isFullChunk && chunk.start == offset && chunk.stop <= stop;
views.add(new ChunkView(
chunk.fileId,
- offset - chunk.start,
- Math.min(chunk.stop, stop) - offset,
- offset,
+ chunkStart - chunk.start + chunk.chunkOffset,
+ chunkStop - chunkStart,
+ chunkStart,
isFullChunk,
chunk.cipherKey,
chunk.isCompressed
));
- offset = Math.min(chunk.stop, stop);
}
}
return views;
@@ -160,7 +180,13 @@ public class SeaweedRead {
Arrays.sort(chunks, new Comparator() {
@Override
public int compare(FilerProto.FileChunk a, FilerProto.FileChunk b) {
- return (int) (a.getMtime() - b.getMtime());
+ // if just a.getMtime() - b.getMtime(), it will overflow!
+ if (a.getMtime() < b.getMtime()) {
+ return -1;
+ } else if (a.getMtime() > b.getMtime()) {
+ return 1;
+ }
+ return 0;
}
});
@@ -181,6 +207,7 @@ public class SeaweedRead {
chunk.getOffset() + chunk.getSize(),
chunk.getFileId(),
chunk.getMtime(),
+ 0,
true,
chunk.getCipherKey().toByteArray(),
chunk.getIsCompressed()
@@ -203,6 +230,7 @@ public class SeaweedRead {
chunk.getOffset(),
v.fileId,
v.modifiedTime,
+ v.chunkOffset,
false,
v.cipherKey,
v.isCompressed
@@ -215,6 +243,7 @@ public class SeaweedRead {
v.stop,
v.fileId,
v.modifiedTime,
+ v.chunkOffset + (chunkStop - v.start),
false,
v.cipherKey,
v.isCompressed
@@ -247,6 +276,10 @@ public class SeaweedRead {
return fileId;
}
+ public static long fileSize(FilerProto.Entry entry) {
+ return Math.max(totalSize(entry.getChunksList()), entry.getAttributes().getFileSize());
+ }
+
public static long totalSize(List chunksList) {
long size = 0;
for (FilerProto.FileChunk chunk : chunksList) {
@@ -263,15 +296,17 @@ public class SeaweedRead {
public final long stop;
public final long modifiedTime;
public final String fileId;
+ public final long chunkOffset;
public final boolean isFullChunk;
public final byte[] cipherKey;
public final boolean isCompressed;
- public VisibleInterval(long start, long stop, String fileId, long modifiedTime, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) {
+ public VisibleInterval(long start, long stop, String fileId, long modifiedTime, long chunkOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) {
this.start = start;
this.stop = stop;
this.modifiedTime = modifiedTime;
this.fileId = fileId;
+ this.chunkOffset = chunkOffset;
this.isFullChunk = isFullChunk;
this.cipherKey = cipherKey;
this.isCompressed = isCompressed;
diff --git a/other/java/hdfs2/dependency-reduced-pom.xml b/other/java/hdfs2/dependency-reduced-pom.xml
index c54f8d2a7..1f48d8390 100644
--- a/other/java/hdfs2/dependency-reduced-pom.xml
+++ b/other/java/hdfs2/dependency-reduced-pom.xml
@@ -301,7 +301,7 @@
- 1.4.5
+ 1.4.62.9.2
diff --git a/other/java/hdfs2/pom.xml b/other/java/hdfs2/pom.xml
index 2c8d4ce32..a8de5bca0 100644
--- a/other/java/hdfs2/pom.xml
+++ b/other/java/hdfs2/pom.xml
@@ -5,7 +5,7 @@
4.0.0
- 1.4.5
+ 1.4.62.9.2
diff --git a/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java b/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java
index 0db6a1f49..53185367a 100644
--- a/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java
+++ b/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java
@@ -124,7 +124,7 @@ public class SeaweedFileSystemStore {
private FileStatus doGetFileStatus(Path path, FilerProto.Entry entry) {
FilerProto.FuseAttributes attributes = entry.getAttributes();
- long length = SeaweedRead.totalSize(entry.getChunksList());
+ long length = SeaweedRead.fileSize(entry);
boolean isDir = entry.getIsDirectory();
int block_replication = 1;
int blocksize = 512;
@@ -185,7 +185,7 @@ public class SeaweedFileSystemStore {
entry.mergeFrom(existingEntry);
entry.getAttributesBuilder().setMtime(now);
LOG.debug("createFile merged entry path:{} entry:{} from:{}", path, entry, existingEntry);
- writePosition = SeaweedRead.totalSize(existingEntry.getChunksList());
+ writePosition = SeaweedRead.fileSize(existingEntry);
replication = existingEntry.getAttributes().getReplication();
}
}
diff --git a/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedInputStream.java b/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedInputStream.java
index 6b3c72f7d..36c0766a4 100644
--- a/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedInputStream.java
+++ b/other/java/hdfs2/src/main/java/seaweed/hdfs/SeaweedInputStream.java
@@ -41,7 +41,7 @@ public class SeaweedInputStream extends FSInputStream {
this.statistics = statistics;
this.path = path;
this.entry = entry;
- this.contentLength = SeaweedRead.totalSize(entry.getChunksList());
+ this.contentLength = SeaweedRead.fileSize(entry);
this.bufferSize = bufferSize;
this.visibleIntervalList = SeaweedRead.nonOverlappingVisibleIntervals(filerGrpcClient, entry.getChunksList());
@@ -87,7 +87,7 @@ public class SeaweedInputStream extends FSInputStream {
throw new IllegalArgumentException("requested read length is more than will fit after requested offset in buffer");
}
- long bytesRead = SeaweedRead.read(this.filerGrpcClient, this.visibleIntervalList, this.position, b, off, len);
+ long bytesRead = SeaweedRead.read(this.filerGrpcClient, this.visibleIntervalList, this.position, b, off, len, SeaweedRead.fileSize(entry));
if (bytesRead > Integer.MAX_VALUE) {
throw new IOException("Unexpected Content-Length");
}
diff --git a/other/java/hdfs3/dependency-reduced-pom.xml b/other/java/hdfs3/dependency-reduced-pom.xml
index 5f1e278f8..25de9dfc0 100644
--- a/other/java/hdfs3/dependency-reduced-pom.xml
+++ b/other/java/hdfs3/dependency-reduced-pom.xml
@@ -120,6 +120,188 @@
+
+
+ org.apache.hadoop
+ hadoop-client
+ 3.1.1
+ provided
+
+
+ hadoop-hdfs-client
+ org.apache.hadoop
+
+
+ hadoop-yarn-api
+ org.apache.hadoop
+
+
+ hadoop-yarn-client
+ org.apache.hadoop
+
+
+ hadoop-mapreduce-client-core
+ org.apache.hadoop
+
+
+ hadoop-mapreduce-client-jobclient
+ org.apache.hadoop
+
+
+ hadoop-annotations
+ org.apache.hadoop
+
+
+
+
+ org.apache.hadoop
+ hadoop-common
+ 3.1.1
+ provided
+
+
+ commons-cli
+ commons-cli
+
+
+ commons-math3
+ org.apache.commons
+
+
+ commons-io
+ commons-io
+
+
+ commons-net
+ commons-net
+
+
+ commons-collections
+ commons-collections
+
+
+ javax.servlet-api
+ javax.servlet
+
+
+ jetty-server
+ org.eclipse.jetty
+
+
+ jetty-util
+ org.eclipse.jetty
+
+
+ jetty-servlet
+ org.eclipse.jetty
+
+
+ jetty-webapp
+ org.eclipse.jetty
+
+
+ jsp-api
+ javax.servlet.jsp
+
+
+ jersey-core
+ com.sun.jersey
+
+
+ jersey-servlet
+ com.sun.jersey
+
+
+ jersey-json
+ com.sun.jersey
+
+
+ jersey-server
+ com.sun.jersey
+
+
+ log4j
+ log4j
+
+
+ commons-lang
+ commons-lang
+
+
+ commons-beanutils
+ commons-beanutils
+
+
+ commons-configuration2
+ org.apache.commons
+
+
+ commons-lang3
+ org.apache.commons
+
+
+ slf4j-log4j12
+ org.slf4j
+
+
+ avro
+ org.apache.avro
+
+
+ re2j
+ com.google.re2j
+
+
+ hadoop-auth
+ org.apache.hadoop
+
+
+ jsch
+ com.jcraft
+
+
+ curator-client
+ org.apache.curator
+
+
+ curator-recipes
+ org.apache.curator
+
+
+ htrace-core4
+ org.apache.htrace
+
+
+ zookeeper
+ org.apache.zookeeper
+
+
+ commons-compress
+ org.apache.commons
+
+
+ kerb-simplekdc
+ org.apache.kerby
+
+
+ jackson-databind
+ com.fasterxml.jackson.core
+
+
+ stax2-api
+ org.codehaus.woodstox
+
+
+ woodstox-core
+ com.fasterxml.woodstox
+
+
+ hadoop-annotations
+ org.apache.hadoop
+
+
+
+ ossrh
@@ -127,7 +309,7 @@
- 1.4.5
+ 1.4.63.1.1
diff --git a/other/java/hdfs3/pom.xml b/other/java/hdfs3/pom.xml
index b1bd27f74..afb6ef309 100644
--- a/other/java/hdfs3/pom.xml
+++ b/other/java/hdfs3/pom.xml
@@ -5,7 +5,7 @@
4.0.0
- 1.4.5
+ 1.4.63.1.1
diff --git a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java
index 0db6a1f49..53185367a 100644
--- a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java
+++ b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedFileSystemStore.java
@@ -124,7 +124,7 @@ public class SeaweedFileSystemStore {
private FileStatus doGetFileStatus(Path path, FilerProto.Entry entry) {
FilerProto.FuseAttributes attributes = entry.getAttributes();
- long length = SeaweedRead.totalSize(entry.getChunksList());
+ long length = SeaweedRead.fileSize(entry);
boolean isDir = entry.getIsDirectory();
int block_replication = 1;
int blocksize = 512;
@@ -185,7 +185,7 @@ public class SeaweedFileSystemStore {
entry.mergeFrom(existingEntry);
entry.getAttributesBuilder().setMtime(now);
LOG.debug("createFile merged entry path:{} entry:{} from:{}", path, entry, existingEntry);
- writePosition = SeaweedRead.totalSize(existingEntry.getChunksList());
+ writePosition = SeaweedRead.fileSize(existingEntry);
replication = existingEntry.getAttributes().getReplication();
}
}
diff --git a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedInputStream.java b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedInputStream.java
index 6b3c72f7d..36c0766a4 100644
--- a/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedInputStream.java
+++ b/other/java/hdfs3/src/main/java/seaweed/hdfs/SeaweedInputStream.java
@@ -41,7 +41,7 @@ public class SeaweedInputStream extends FSInputStream {
this.statistics = statistics;
this.path = path;
this.entry = entry;
- this.contentLength = SeaweedRead.totalSize(entry.getChunksList());
+ this.contentLength = SeaweedRead.fileSize(entry);
this.bufferSize = bufferSize;
this.visibleIntervalList = SeaweedRead.nonOverlappingVisibleIntervals(filerGrpcClient, entry.getChunksList());
@@ -87,7 +87,7 @@ public class SeaweedInputStream extends FSInputStream {
throw new IllegalArgumentException("requested read length is more than will fit after requested offset in buffer");
}
- long bytesRead = SeaweedRead.read(this.filerGrpcClient, this.visibleIntervalList, this.position, b, off, len);
+ long bytesRead = SeaweedRead.read(this.filerGrpcClient, this.visibleIntervalList, this.position, b, off, len, SeaweedRead.fileSize(entry));
if (bytesRead > Integer.MAX_VALUE) {
throw new IOException("Unexpected Content-Length");
}
diff --git a/test/random_access/pom.xml b/test/random_access/pom.xml
new file mode 100644
index 000000000..6c5c90eea
--- /dev/null
+++ b/test/random_access/pom.xml
@@ -0,0 +1,58 @@
+
+
+ 4.0.0
+ com.seaweedfs.test
+ random_access
+ jar
+ 1.0-SNAPSHOT
+
+
+ 28.0-jre
+
+
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+ org.slf4j
+ slf4j-api
+ 1.7.25
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ com.esotericsoftware.kryo
+ kryo
+ 2.24.0
+
+
+
+
+
+
+ kr.motd.maven
+ os-maven-plugin
+ 1.6.2
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ 8
+
+
+
+
+
+
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/BTreePersistentIndexedCache.java b/test/random_access/src/main/java/seaweedfs/client/btree/BTreePersistentIndexedCache.java
new file mode 100644
index 000000000..8409c40b3
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/BTreePersistentIndexedCache.java
@@ -0,0 +1,753 @@
+/*
+ * Copyright 2010 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import com.google.common.collect.ImmutableSet;
+import seaweedfs.client.btree.serialize.Serializer;
+import seaweedfs.client.btree.serialize.kryo.KryoBackedDecoder;
+import seaweedfs.client.btree.serialize.kryo.KryoBackedEncoder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+// todo - stream serialised value to file
+// todo - handle hash collisions (properly, this time)
+// todo - don't store null links to child blocks in leaf index blocks
+// todo - align block boundaries
+// todo - thread safety control
+// todo - merge small values into a single data block
+// todo - discard when file corrupt
+// todo - include data directly in index entry when serializer can guarantee small fixed sized data
+// todo - free list leaks disk space
+// todo - merge adjacent free blocks
+// todo - use more efficient lookup for free block with nearest size
+@SuppressWarnings("unchecked")
+public class BTreePersistentIndexedCache {
+ private static final Logger LOGGER = LoggerFactory.getLogger(BTreePersistentIndexedCache.class);
+ private final File cacheFile;
+ private final KeyHasher keyHasher;
+ private final Serializer serializer;
+ private final short maxChildIndexEntries;
+ private final int minIndexChildNodes;
+ private final StateCheckBlockStore store;
+ private HeaderBlock header;
+
+ public BTreePersistentIndexedCache(File cacheFile, Serializer keySerializer, Serializer valueSerializer) {
+ this(cacheFile, keySerializer, valueSerializer, (short) 512, 512);
+ }
+
+ public BTreePersistentIndexedCache(File cacheFile, Serializer keySerializer, Serializer valueSerializer,
+ short maxChildIndexEntries, int maxFreeListEntries) {
+ this.cacheFile = cacheFile;
+ this.keyHasher = new KeyHasher(keySerializer);
+ this.serializer = valueSerializer;
+ this.maxChildIndexEntries = maxChildIndexEntries;
+ this.minIndexChildNodes = maxChildIndexEntries / 2;
+ BlockStore cachingStore = new CachingBlockStore(new FileBackedBlockStore(cacheFile), ImmutableSet.of(IndexBlock.class, FreeListBlockStore.FreeListBlock.class));
+ this.store = new StateCheckBlockStore(new FreeListBlockStore(cachingStore, maxFreeListEntries));
+ try {
+ open();
+ } catch (Exception e) {
+ throw new UncheckedIOException(String.format("Could not open %s.", this), e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "cache " + cacheFile.getName() + " (" + cacheFile + ")";
+ }
+
+ private void open() throws Exception {
+ LOGGER.debug("Opening {}", this);
+ try {
+ doOpen();
+ } catch (CorruptedCacheException e) {
+ rebuild();
+ }
+ }
+
+ private void doOpen() throws Exception {
+ BlockStore.Factory factory = new BlockStore.Factory() {
+ @Override
+ public Object create(Class extends BlockPayload> type) {
+ if (type == HeaderBlock.class) {
+ return new HeaderBlock();
+ }
+ if (type == IndexBlock.class) {
+ return new IndexBlock();
+ }
+ if (type == DataBlock.class) {
+ return new DataBlock();
+ }
+ throw new UnsupportedOperationException();
+ }
+ };
+ Runnable initAction = new Runnable() {
+ @Override
+ public void run() {
+ header = new HeaderBlock();
+ store.write(header);
+ header.index.newRoot();
+ store.flush();
+ }
+ };
+
+ store.open(initAction, factory);
+ header = store.readFirst(HeaderBlock.class);
+ }
+
+ public V get(K key) {
+ try {
+ try {
+ DataBlock block = header.getRoot().get(key);
+ if (block != null) {
+ return block.getValue();
+ }
+ return null;
+ } catch (CorruptedCacheException e) {
+ rebuild();
+ return null;
+ }
+ } catch (Exception e) {
+ throw new UncheckedIOException(String.format("Could not read entry '%s' from %s.", key, this), e);
+ }
+ }
+
+ public void put(K key, V value) {
+ try {
+ long hashCode = keyHasher.getHashCode(key);
+ Lookup lookup = header.getRoot().find(hashCode);
+ DataBlock newBlock = null;
+ if (lookup.entry != null) {
+ DataBlock block = store.read(lookup.entry.dataBlock, DataBlock.class);
+ DataBlockUpdateResult updateResult = block.useNewValue(value);
+ if (updateResult.isFailed()) {
+ store.remove(block);
+ newBlock = new DataBlock(value, updateResult.getSerializedValue());
+ }
+ } else {
+ newBlock = new DataBlock(value);
+ }
+ if (newBlock != null) {
+ store.write(newBlock);
+ lookup.indexBlock.put(hashCode, newBlock.getPos());
+ }
+ store.flush();
+ } catch (Exception e) {
+ throw new UncheckedIOException(String.format("Could not add entry '%s' to %s.", key, this), e);
+ }
+ }
+
+ public void remove(K key) {
+ try {
+ Lookup lookup = header.getRoot().find(key);
+ if (lookup.entry == null) {
+ return;
+ }
+ lookup.indexBlock.remove(lookup.entry);
+ DataBlock block = store.read(lookup.entry.dataBlock, DataBlock.class);
+ store.remove(block);
+ store.flush();
+ } catch (Exception e) {
+ throw new UncheckedIOException(String.format("Could not remove entry '%s' from %s.", key, this), e);
+ }
+ }
+
+ private IndexBlock load(BlockPointer pos, IndexRoot root, IndexBlock parent, int index) {
+ IndexBlock block = store.read(pos, IndexBlock.class);
+ block.root = root;
+ block.parent = parent;
+ block.parentEntryIndex = index;
+ return block;
+ }
+
+ public void reset() {
+ close();
+ try {
+ open();
+ } catch (Exception e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ public void close() {
+ LOGGER.debug("Closing {}", this);
+ try {
+ store.close();
+ } catch (Exception e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ public boolean isOpen() {
+ return store.isOpen();
+ }
+
+ private void rebuild() {
+ LOGGER.warn("{} is corrupt. Discarding.", this);
+ try {
+ clear();
+ } catch (Exception e) {
+ LOGGER.warn("{} couldn't be rebuilt. Closing.", this);
+ close();
+ }
+ }
+
+ public void verify() {
+ try {
+ doVerify();
+ } catch (Exception e) {
+ throw new UncheckedIOException(String.format("Some problems were found when checking the integrity of %s.",
+ this), e);
+ }
+ }
+
+ private void doVerify() throws Exception {
+ List blocks = new ArrayList();
+
+ HeaderBlock header = store.readFirst(HeaderBlock.class);
+ blocks.add(header);
+ verifyTree(header.getRoot(), "", blocks, Long.MAX_VALUE, true);
+
+ Collections.sort(blocks, new Comparator() {
+ @Override
+ public int compare(BlockPayload block, BlockPayload block1) {
+ return block.getPos().compareTo(block1.getPos());
+ }
+ });
+
+ for (int i = 0; i < blocks.size() - 1; i++) {
+ Block b1 = blocks.get(i).getBlock();
+ Block b2 = blocks.get(i + 1).getBlock();
+ if (b1.getPos().getPos() + b1.getSize() > b2.getPos().getPos()) {
+ throw new IOException(String.format("%s overlaps with %s", b1, b2));
+ }
+ }
+ }
+
+ private void verifyTree(IndexBlock current, String prefix, Collection blocks, long maxValue,
+ boolean loadData) throws Exception {
+ blocks.add(current);
+
+ if (!prefix.equals("") && current.entries.size() < maxChildIndexEntries / 2) {
+ throw new IOException(String.format("Too few entries found in %s", current));
+ }
+ if (current.entries.size() > maxChildIndexEntries) {
+ throw new IOException(String.format("Too many entries found in %s", current));
+ }
+
+ boolean isLeaf = current.entries.size() == 0 || current.entries.get(0).childIndexBlock.isNull();
+ if (isLeaf ^ current.tailPos.isNull()) {
+ throw new IOException(String.format("Mismatched leaf/tail-node in %s", current));
+ }
+
+ long min = Long.MIN_VALUE;
+ for (IndexEntry entry : current.entries) {
+ if (isLeaf ^ entry.childIndexBlock.isNull()) {
+ throw new IOException(String.format("Mismatched leaf/non-leaf entry in %s", current));
+ }
+ if (entry.hashCode >= maxValue || entry.hashCode <= min) {
+ throw new IOException(String.format("Out-of-order key in %s", current));
+ }
+ min = entry.hashCode;
+ if (!entry.childIndexBlock.isNull()) {
+ IndexBlock child = store.read(entry.childIndexBlock, IndexBlock.class);
+ verifyTree(child, " " + prefix, blocks, entry.hashCode, loadData);
+ }
+ if (loadData) {
+ DataBlock block = store.read(entry.dataBlock, DataBlock.class);
+ blocks.add(block);
+ }
+ }
+ if (!current.tailPos.isNull()) {
+ IndexBlock tail = store.read(current.tailPos, IndexBlock.class);
+ verifyTree(tail, " " + prefix, blocks, maxValue, loadData);
+ }
+ }
+
+ public void clear() {
+ store.clear();
+ close();
+ try {
+ doOpen();
+ } catch (Exception e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ private class IndexRoot {
+ private BlockPointer rootPos = BlockPointer.start();
+ private HeaderBlock owner;
+
+ private IndexRoot(HeaderBlock owner) {
+ this.owner = owner;
+ }
+
+ public void setRootPos(BlockPointer rootPos) {
+ this.rootPos = rootPos;
+ store.write(owner);
+ }
+
+ public IndexBlock getRoot() {
+ return load(rootPos, this, null, 0);
+ }
+
+ public IndexBlock newRoot() {
+ IndexBlock block = new IndexBlock();
+ store.write(block);
+ setRootPos(block.getPos());
+ return block;
+ }
+ }
+
+ private class HeaderBlock extends BlockPayload {
+ private IndexRoot index;
+
+ private HeaderBlock() {
+ index = new IndexRoot(this);
+ }
+
+ @Override
+ protected byte getType() {
+ return 0x55;
+ }
+
+ @Override
+ protected int getSize() {
+ return Block.LONG_SIZE + Block.SHORT_SIZE;
+ }
+
+ @Override
+ protected void read(DataInputStream instr) throws Exception {
+ index.rootPos = BlockPointer.pos(instr.readLong());
+
+ short actualChildIndexEntries = instr.readShort();
+ if (actualChildIndexEntries != maxChildIndexEntries) {
+ throw blockCorruptedException();
+ }
+ }
+
+ @Override
+ protected void write(DataOutputStream outstr) throws Exception {
+ outstr.writeLong(index.rootPos.getPos());
+ outstr.writeShort(maxChildIndexEntries);
+ }
+
+ public IndexBlock getRoot() throws Exception {
+ return index.getRoot();
+ }
+ }
+
+ private class IndexBlock extends BlockPayload {
+ private final List entries = new ArrayList();
+ private BlockPointer tailPos = BlockPointer.start();
+ // Transient fields
+ private IndexBlock parent;
+ private int parentEntryIndex;
+ private IndexRoot root;
+
+ @Override
+ protected byte getType() {
+ return 0x77;
+ }
+
+ @Override
+ protected int getSize() {
+ return Block.INT_SIZE + Block.LONG_SIZE + (3 * Block.LONG_SIZE) * maxChildIndexEntries;
+ }
+
+ @Override
+ public void read(DataInputStream instr) throws IOException {
+ int count = instr.readInt();
+ entries.clear();
+ for (int i = 0; i < count; i++) {
+ IndexEntry entry = new IndexEntry();
+ entry.hashCode = instr.readLong();
+ entry.dataBlock = BlockPointer.pos(instr.readLong());
+ entry.childIndexBlock = BlockPointer.pos(instr.readLong());
+ entries.add(entry);
+ }
+ tailPos = BlockPointer.pos(instr.readLong());
+ }
+
+ @Override
+ public void write(DataOutputStream outstr) throws IOException {
+ outstr.writeInt(entries.size());
+ for (IndexEntry entry : entries) {
+ outstr.writeLong(entry.hashCode);
+ outstr.writeLong(entry.dataBlock.getPos());
+ outstr.writeLong(entry.childIndexBlock.getPos());
+ }
+ outstr.writeLong(tailPos.getPos());
+ }
+
+ public void put(long hashCode, BlockPointer pos) throws Exception {
+ int index = Collections.binarySearch(entries, new IndexEntry(hashCode));
+ IndexEntry entry;
+ if (index >= 0) {
+ entry = entries.get(index);
+ } else {
+ assert tailPos.isNull();
+ entry = new IndexEntry();
+ entry.hashCode = hashCode;
+ entry.childIndexBlock = BlockPointer.start();
+ index = -index - 1;
+ entries.add(index, entry);
+ }
+
+ entry.dataBlock = pos;
+ store.write(this);
+
+ maybeSplit();
+ }
+
+ private void maybeSplit() throws Exception {
+ if (entries.size() > maxChildIndexEntries) {
+ int splitPos = entries.size() / 2;
+ IndexEntry splitEntry = entries.remove(splitPos);
+ if (parent == null) {
+ parent = root.newRoot();
+ }
+ IndexBlock sibling = new IndexBlock();
+ store.write(sibling);
+ List siblingEntries = entries.subList(splitPos, entries.size());
+ sibling.entries.addAll(siblingEntries);
+ siblingEntries.clear();
+ sibling.tailPos = tailPos;
+ tailPos = splitEntry.childIndexBlock;
+ splitEntry.childIndexBlock = BlockPointer.start();
+ parent.add(this, splitEntry, sibling);
+ }
+ }
+
+ private void add(IndexBlock left, IndexEntry entry, IndexBlock right) throws Exception {
+ int index = left.parentEntryIndex;
+ if (index < entries.size()) {
+ IndexEntry parentEntry = entries.get(index);
+ assert parentEntry.childIndexBlock.equals(left.getPos());
+ parentEntry.childIndexBlock = right.getPos();
+ } else {
+ assert index == entries.size() && (tailPos.isNull() || tailPos.equals(left.getPos()));
+ tailPos = right.getPos();
+ }
+ entries.add(index, entry);
+ entry.childIndexBlock = left.getPos();
+ store.write(this);
+
+ maybeSplit();
+ }
+
+ public DataBlock get(K key) throws Exception {
+ Lookup lookup = find(key);
+ if (lookup.entry == null) {
+ return null;
+ }
+
+ return store.read(lookup.entry.dataBlock, DataBlock.class);
+ }
+
+ public Lookup find(K key) throws Exception {
+ long checksum = keyHasher.getHashCode(key);
+ return find(checksum);
+ }
+
+ private Lookup find(long hashCode) throws Exception {
+ int index = Collections.binarySearch(entries, new IndexEntry(hashCode));
+ if (index >= 0) {
+ return new Lookup(this, entries.get(index));
+ }
+
+ index = -index - 1;
+ BlockPointer childBlockPos;
+ if (index == entries.size()) {
+ childBlockPos = tailPos;
+ } else {
+ childBlockPos = entries.get(index).childIndexBlock;
+ }
+ if (childBlockPos.isNull()) {
+ return new Lookup(this, null);
+ }
+
+ IndexBlock childBlock = load(childBlockPos, root, this, index);
+ return childBlock.find(hashCode);
+ }
+
+ public void remove(IndexEntry entry) throws Exception {
+ int index = entries.indexOf(entry);
+ assert index >= 0;
+ entries.remove(index);
+ store.write(this);
+
+ if (entry.childIndexBlock.isNull()) {
+ maybeMerge();
+ } else {
+ // Not a leaf node. Move up an entry from a leaf node, then possibly merge the leaf node
+ IndexBlock leafBlock = load(entry.childIndexBlock, root, this, index);
+ leafBlock = leafBlock.findHighestLeaf();
+ IndexEntry highestEntry = leafBlock.entries.remove(leafBlock.entries.size() - 1);
+ highestEntry.childIndexBlock = entry.childIndexBlock;
+ entries.add(index, highestEntry);
+ store.write(leafBlock);
+ leafBlock.maybeMerge();
+ }
+ }
+
+ private void maybeMerge() throws Exception {
+ if (parent == null) {
+ // This is the root block. Can have any number of children <= maxChildIndexEntries
+ if (entries.size() == 0 && !tailPos.isNull()) {
+ // This is an empty root block, discard it
+ header.index.setRootPos(tailPos);
+ store.remove(this);
+ }
+ return;
+ }
+
+ // This is not the root block. Must have children >= minIndexChildNodes
+ if (entries.size() >= minIndexChildNodes) {
+ return;
+ }
+
+ // Attempt to merge with the left sibling
+ IndexBlock left = parent.getPrevious(this);
+ if (left != null) {
+ assert entries.size() + left.entries.size() <= maxChildIndexEntries * 2;
+ if (left.entries.size() > minIndexChildNodes) {
+ // There are enough entries in this block and the left sibling to make up 2 blocks, so redistribute
+ // the entries evenly between them
+ left.mergeFrom(this);
+ left.maybeSplit();
+ return;
+ } else {
+ // There are only enough entries to make up 1 block, so move the entries of the left sibling into
+ // this block and discard the left sibling. Might also need to merge the parent
+ left.mergeFrom(this);
+ parent.maybeMerge();
+ return;
+ }
+ }
+
+ // Attempt to merge with the right sibling
+ IndexBlock right = parent.getNext(this);
+ if (right != null) {
+ assert entries.size() + right.entries.size() <= maxChildIndexEntries * 2;
+ if (right.entries.size() > minIndexChildNodes) {
+ // There are enough entries in this block and the right sibling to make up 2 blocks, so redistribute
+ // the entries evenly between them
+ mergeFrom(right);
+ maybeSplit();
+ return;
+ } else {
+ // There are only enough entries to make up 1 block, so move the entries of the right sibling into
+ // this block and discard this block. Might also need to merge the parent
+ mergeFrom(right);
+ parent.maybeMerge();
+ return;
+ }
+ }
+
+ // Should not happen
+ throw new IllegalStateException(String.format("%s does not have any siblings.", getBlock()));
+ }
+
+ private void mergeFrom(IndexBlock right) throws Exception {
+ IndexEntry newChildEntry = parent.entries.remove(parentEntryIndex);
+ if (right.getPos().equals(parent.tailPos)) {
+ parent.tailPos = getPos();
+ } else {
+ IndexEntry newParentEntry = parent.entries.get(parentEntryIndex);
+ assert newParentEntry.childIndexBlock.equals(right.getPos());
+ newParentEntry.childIndexBlock = getPos();
+ }
+ entries.add(newChildEntry);
+ entries.addAll(right.entries);
+ newChildEntry.childIndexBlock = tailPos;
+ tailPos = right.tailPos;
+ store.write(parent);
+ store.write(this);
+ store.remove(right);
+ }
+
+ private IndexBlock getNext(IndexBlock indexBlock) throws Exception {
+ int index = indexBlock.parentEntryIndex + 1;
+ if (index > entries.size()) {
+ return null;
+ }
+ if (index == entries.size()) {
+ return load(tailPos, root, this, index);
+ }
+ return load(entries.get(index).childIndexBlock, root, this, index);
+ }
+
+ private IndexBlock getPrevious(IndexBlock indexBlock) throws Exception {
+ int index = indexBlock.parentEntryIndex - 1;
+ if (index < 0) {
+ return null;
+ }
+ return load(entries.get(index).childIndexBlock, root, this, index);
+ }
+
+ private IndexBlock findHighestLeaf() throws Exception {
+ if (tailPos.isNull()) {
+ return this;
+ }
+ return load(tailPos, root, this, entries.size()).findHighestLeaf();
+ }
+ }
+
+ private static class IndexEntry implements Comparable {
+ long hashCode;
+ BlockPointer dataBlock;
+ BlockPointer childIndexBlock;
+
+ private IndexEntry() {
+ }
+
+ private IndexEntry(long hashCode) {
+ this.hashCode = hashCode;
+ }
+
+ @Override
+ public int compareTo(IndexEntry indexEntry) {
+ if (hashCode > indexEntry.hashCode) {
+ return 1;
+ }
+ if (hashCode < indexEntry.hashCode) {
+ return -1;
+ }
+ return 0;
+ }
+ }
+
+ private class Lookup {
+ final IndexBlock indexBlock;
+ final IndexEntry entry;
+
+ private Lookup(IndexBlock indexBlock, IndexEntry entry) {
+ this.indexBlock = indexBlock;
+ this.entry = entry;
+ }
+ }
+
+ private class DataBlock extends BlockPayload {
+ private int size;
+ private StreamByteBuffer buffer;
+ private V value;
+
+ private DataBlock() {
+ }
+
+ public DataBlock(V value) throws Exception {
+ this.value = value;
+ setValue(value);
+ size = buffer.totalBytesUnread();
+ }
+
+ public DataBlock(V value, StreamByteBuffer buffer) throws Exception {
+ this.value = value;
+ this.buffer = buffer;
+ size = buffer.totalBytesUnread();
+ }
+
+ public void setValue(V value) throws Exception {
+ buffer = StreamByteBuffer.createWithChunkSizeInDefaultRange(size);
+ KryoBackedEncoder encoder = new KryoBackedEncoder(buffer.getOutputStream());
+ serializer.write(encoder, value);
+ encoder.flush();
+ }
+
+ public V getValue() throws Exception {
+ if (value == null) {
+ value = serializer.read(new KryoBackedDecoder(buffer.getInputStream()));
+ buffer = null;
+ }
+ return value;
+ }
+
+ @Override
+ protected byte getType() {
+ return 0x33;
+ }
+
+ @Override
+ protected int getSize() {
+ return 2 * Block.INT_SIZE + size;
+ }
+
+ @Override
+ public void read(DataInputStream instr) throws Exception {
+ size = instr.readInt();
+ int bytes = instr.readInt();
+ buffer = StreamByteBuffer.of(instr, bytes);
+ }
+
+ @Override
+ public void write(DataOutputStream outstr) throws Exception {
+ outstr.writeInt(size);
+ outstr.writeInt(buffer.totalBytesUnread());
+ buffer.writeTo(outstr);
+ buffer = null;
+ }
+
+ public DataBlockUpdateResult useNewValue(V value) throws Exception {
+ setValue(value);
+ boolean ok = buffer.totalBytesUnread() <= size;
+ if (ok) {
+ this.value = value;
+ store.write(this);
+ return DataBlockUpdateResult.success();
+ } else {
+ return DataBlockUpdateResult.failed(buffer);
+ }
+ }
+ }
+
+ private static class DataBlockUpdateResult {
+ private static final DataBlockUpdateResult SUCCESS = new DataBlockUpdateResult(true, null);
+ private final boolean success;
+ private final StreamByteBuffer serializedValue;
+
+ private DataBlockUpdateResult(boolean success, StreamByteBuffer serializedValue) {
+ this.success = success;
+ this.serializedValue = serializedValue;
+ }
+
+ static DataBlockUpdateResult success() {
+ return SUCCESS;
+ }
+
+ static DataBlockUpdateResult failed(StreamByteBuffer serializedValue) {
+ return new DataBlockUpdateResult(false, serializedValue);
+ }
+
+ public boolean isFailed() {
+ return !success;
+ }
+
+ public StreamByteBuffer getSerializedValue() {
+ return serializedValue;
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/Block.java b/test/random_access/src/main/java/seaweedfs/client/btree/Block.java
new file mode 100644
index 000000000..f3ecb2421
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/Block.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+public abstract class Block {
+ static final int LONG_SIZE = 8;
+ static final int INT_SIZE = 4;
+ static final int SHORT_SIZE = 2;
+
+ private BlockPayload payload;
+
+ protected Block(BlockPayload payload) {
+ this.payload = payload;
+ payload.setBlock(this);
+ }
+
+ public BlockPayload getPayload() {
+ return payload;
+ }
+
+ protected void detach() {
+ payload.setBlock(null);
+ payload = null;
+ }
+
+ public abstract BlockPointer getPos();
+
+ public abstract int getSize();
+
+ public abstract RuntimeException blockCorruptedException();
+
+ @Override
+ public String toString() {
+ return payload.getClass().getSimpleName() + " " + getPos();
+ }
+
+ public BlockPointer getNextPos() {
+ return BlockPointer.pos(getPos().getPos() + getSize());
+ }
+
+ public abstract boolean hasPos();
+
+ public abstract void setPos(BlockPointer pos);
+
+ public abstract void setSize(int size);
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/BlockPayload.java b/test/random_access/src/main/java/seaweedfs/client/btree/BlockPayload.java
new file mode 100644
index 000000000..d14af26c7
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/BlockPayload.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+
+public abstract class BlockPayload {
+ private Block block;
+
+ public Block getBlock() {
+ return block;
+ }
+
+ public void setBlock(Block block) {
+ this.block = block;
+ }
+
+ public BlockPointer getPos() {
+ return getBlock().getPos();
+ }
+
+ public BlockPointer getNextPos() {
+ return getBlock().getNextPos();
+ }
+
+ protected abstract int getSize();
+
+ protected abstract byte getType();
+
+ protected abstract void read(DataInputStream inputStream) throws Exception;
+
+ protected abstract void write(DataOutputStream outputStream) throws Exception;
+
+ protected RuntimeException blockCorruptedException() {
+ return getBlock().blockCorruptedException();
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/BlockPointer.java b/test/random_access/src/main/java/seaweedfs/client/btree/BlockPointer.java
new file mode 100644
index 000000000..38bff7d97
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/BlockPointer.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import com.google.common.primitives.Longs;
+
+public class BlockPointer implements Comparable {
+
+ private static final BlockPointer NULL = new BlockPointer(-1);
+
+ public static BlockPointer start() {
+ return NULL;
+ }
+
+ public static BlockPointer pos(long pos) {
+ if (pos < -1) {
+ throw new CorruptedCacheException("block pointer must be >= -1, but was" + pos);
+ }
+ if (pos == -1) {
+ return NULL;
+ }
+ return new BlockPointer(pos);
+ }
+
+ private final long pos;
+
+ private BlockPointer(long pos) {
+ this.pos = pos;
+ }
+
+ public boolean isNull() {
+ return pos < 0;
+ }
+
+ public long getPos() {
+ return pos;
+ }
+
+ @Override
+ public String toString() {
+ return String.valueOf(pos);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null || obj.getClass() != getClass()) {
+ return false;
+ }
+ BlockPointer other = (BlockPointer) obj;
+ return pos == other.pos;
+ }
+
+ @Override
+ public int hashCode() {
+ return Longs.hashCode(pos);
+ }
+
+ @Override
+ public int compareTo(BlockPointer o) {
+ return Longs.compare(pos, o.pos);
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/BlockStore.java b/test/random_access/src/main/java/seaweedfs/client/btree/BlockStore.java
new file mode 100644
index 000000000..141eb70fe
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/BlockStore.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+public interface BlockStore {
+ /**
+ * Opens this store, calling the given action if the store is empty.
+ */
+ void open(Runnable initAction, Factory factory);
+
+ /**
+ * Closes this store.
+ */
+ void close();
+
+ /**
+ * Discards all blocks from this store.
+ */
+ void clear();
+
+ /**
+ * Removes the given block from this store.
+ */
+ void remove(BlockPayload block);
+
+ /**
+ * Reads the first block from this store.
+ */
+ T readFirst(Class payloadType);
+
+ /**
+ * Reads a block from this store.
+ */
+ T read(BlockPointer pos, Class payloadType);
+
+ /**
+ * Writes a block to this store, adding the block if required.
+ */
+ void write(BlockPayload block);
+
+ /**
+ * Adds a new block to this store. Allocates space for the block, but does not write the contents of the block
+ * until {@link #write(BlockPayload)} is called.
+ */
+ void attach(BlockPayload block);
+
+ /**
+ * Flushes any pending updates for this store.
+ */
+ void flush();
+
+ interface Factory {
+ Object create(Class extends BlockPayload> type);
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/BufferCaster.java b/test/random_access/src/main/java/seaweedfs/client/btree/BufferCaster.java
new file mode 100644
index 000000000..a43160211
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/BufferCaster.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2018 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree;
+
+import java.nio.Buffer;
+
+public class BufferCaster {
+ /**
+ * Without this cast, when the code compiled by Java 9+ is executed on Java 8, it will throw
+ * java.lang.NoSuchMethodError: Method flip()Ljava/nio/ByteBuffer; does not exist in class java.nio.ByteBuffer
+ */
+ @SuppressWarnings("RedundantCast")
+ public static Buffer cast(T byteBuffer) {
+ return (Buffer) byteBuffer;
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/ByteInput.java b/test/random_access/src/main/java/seaweedfs/client/btree/ByteInput.java
new file mode 100644
index 000000000..2030a8cde
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/ByteInput.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2014 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree;
+
+import com.google.common.io.CountingInputStream;
+
+import java.io.BufferedInputStream;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+
+/**
+ * Allows a stream of bytes to be read from a particular location of some backing byte stream.
+ */
+class ByteInput {
+ private final RandomAccessFile file;
+ private final ResettableBufferedInputStream bufferedInputStream;
+ private CountingInputStream countingInputStream;
+
+ public ByteInput(RandomAccessFile file) {
+ this.file = file;
+ bufferedInputStream = new ResettableBufferedInputStream(new RandomAccessFileInputStream(file));
+ }
+
+ /**
+ * Starts reading from the given offset.
+ */
+ public DataInputStream start(long offset) throws IOException {
+ file.seek(offset);
+ bufferedInputStream.clear();
+ countingInputStream = new CountingInputStream(bufferedInputStream);
+ return new DataInputStream(countingInputStream);
+ }
+
+ /**
+ * Returns the number of bytes read since {@link #start(long)} was called.
+ */
+ public long getBytesRead() {
+ return countingInputStream.getCount();
+ }
+
+ /**
+ * Finishes reading, resetting any buffered state.
+ */
+ public void done() {
+ countingInputStream = null;
+ }
+
+ private static class ResettableBufferedInputStream extends BufferedInputStream {
+ ResettableBufferedInputStream(InputStream input) {
+ super(input);
+ }
+
+ void clear() {
+ count = 0;
+ pos = 0;
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/ByteOutput.java b/test/random_access/src/main/java/seaweedfs/client/btree/ByteOutput.java
new file mode 100644
index 000000000..dfb24cfd0
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/ByteOutput.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2014 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree;
+
+import com.google.common.io.CountingOutputStream;
+
+import java.io.BufferedOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+
+/**
+ * Allows a stream of bytes to be written to a particular location of some backing byte stream.
+ */
+class ByteOutput {
+ private final RandomAccessFile file;
+ private final ResettableBufferedOutputStream bufferedOutputStream;
+ private CountingOutputStream countingOutputStream;
+
+ public ByteOutput(RandomAccessFile file) {
+ this.file = file;
+ bufferedOutputStream = new ResettableBufferedOutputStream(new RandomAccessFileOutputStream(file));
+ }
+
+ /**
+ * Starts writing to the given offset. Can be beyond the current length of the file.
+ */
+ public DataOutputStream start(long offset) throws IOException {
+ file.seek(offset);
+ bufferedOutputStream.clear();
+ countingOutputStream = new CountingOutputStream(bufferedOutputStream);
+ return new DataOutputStream(countingOutputStream);
+ }
+
+ /**
+ * Returns the number of byte written since {@link #start(long)} was called.
+ */
+ public long getBytesWritten() {
+ return countingOutputStream.getCount();
+ }
+
+ /**
+ * Finishes writing, flushing and resetting any buffered state
+ */
+ public void done() throws IOException {
+ countingOutputStream.flush();
+ countingOutputStream = null;
+ }
+
+ private static class ResettableBufferedOutputStream extends BufferedOutputStream {
+ ResettableBufferedOutputStream(OutputStream output) {
+ super(output);
+ }
+
+ void clear() {
+ count = 0;
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/CachingBlockStore.java b/test/random_access/src/main/java/seaweedfs/client/btree/CachingBlockStore.java
new file mode 100644
index 000000000..308838b1d
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/CachingBlockStore.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.ImmutableSet;
+
+import javax.annotation.Nullable;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class CachingBlockStore implements BlockStore {
+ private final BlockStore store;
+ private final Map dirty = new LinkedHashMap();
+ private final Cache indexBlockCache = CacheBuilder.newBuilder().maximumSize(100).concurrencyLevel(1).build();
+ private final ImmutableSet> cacheableBlockTypes;
+
+ public CachingBlockStore(BlockStore store, Collection> cacheableBlockTypes) {
+ this.store = store;
+ this.cacheableBlockTypes = ImmutableSet.copyOf(cacheableBlockTypes);
+ }
+
+ @Override
+ public void open(Runnable initAction, Factory factory) {
+ store.open(initAction, factory);
+ }
+
+ @Override
+ public void close() {
+ flush();
+ indexBlockCache.invalidateAll();
+ store.close();
+ }
+
+ @Override
+ public void clear() {
+ dirty.clear();
+ indexBlockCache.invalidateAll();
+ store.clear();
+ }
+
+ @Override
+ public void flush() {
+ Iterator iterator = dirty.values().iterator();
+ while (iterator.hasNext()) {
+ BlockPayload block = iterator.next();
+ iterator.remove();
+ store.write(block);
+ }
+ store.flush();
+ }
+
+ @Override
+ public void attach(BlockPayload block) {
+ store.attach(block);
+ }
+
+ @Override
+ public void remove(BlockPayload block) {
+ dirty.remove(block.getPos());
+ if (isCacheable(block)) {
+ indexBlockCache.invalidate(block.getPos());
+ }
+ store.remove(block);
+ }
+
+ @Override
+ public T readFirst(Class payloadType) {
+ T block = store.readFirst(payloadType);
+ maybeCache(block);
+ return block;
+ }
+
+ @Override
+ public T read(BlockPointer pos, Class payloadType) {
+ T block = payloadType.cast(dirty.get(pos));
+ if (block != null) {
+ return block;
+ }
+ block = maybeGetFromCache(pos, payloadType);
+ if (block != null) {
+ return block;
+ }
+ block = store.read(pos, payloadType);
+ maybeCache(block);
+ return block;
+ }
+
+ @Nullable
+ private T maybeGetFromCache(BlockPointer pos, Class payloadType) {
+ if (cacheableBlockTypes.contains(payloadType)) {
+ return payloadType.cast(indexBlockCache.getIfPresent(pos));
+ }
+ return null;
+ }
+
+ @Override
+ public void write(BlockPayload block) {
+ store.attach(block);
+ maybeCache(block);
+ dirty.put(block.getPos(), block);
+ }
+
+ private void maybeCache(T block) {
+ if (isCacheable(block)) {
+ indexBlockCache.put(block.getPos(), block);
+ }
+ }
+
+ private boolean isCacheable(T block) {
+ return cacheableBlockTypes.contains(block.getClass());
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/CorruptedCacheException.java b/test/random_access/src/main/java/seaweedfs/client/btree/CorruptedCacheException.java
new file mode 100644
index 000000000..8f9ac1240
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/CorruptedCacheException.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+class CorruptedCacheException extends RuntimeException {
+ CorruptedCacheException(String message) {
+ super(message);
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/FileBackedBlockStore.java b/test/random_access/src/main/java/seaweedfs/client/btree/FileBackedBlockStore.java
new file mode 100644
index 000000000..556db3647
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/FileBackedBlockStore.java
@@ -0,0 +1,274 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+
+public class FileBackedBlockStore implements BlockStore {
+ private final File cacheFile;
+ private RandomAccessFile file;
+ private ByteOutput output;
+ private ByteInput input;
+ private long nextBlock;
+ private Factory factory;
+ private long currentFileSize;
+
+ public FileBackedBlockStore(File cacheFile) {
+ this.cacheFile = cacheFile;
+ }
+
+ @Override
+ public String toString() {
+ return "cache '" + cacheFile + "'";
+ }
+
+ @Override
+ public void open(Runnable runnable, Factory factory) {
+ this.factory = factory;
+ try {
+ cacheFile.getParentFile().mkdirs();
+ file = openRandomAccessFile();
+ output = new ByteOutput(file);
+ input = new ByteInput(file);
+ currentFileSize = file.length();
+ nextBlock = currentFileSize;
+ if (currentFileSize == 0) {
+ runnable.run();
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ private RandomAccessFile openRandomAccessFile() throws FileNotFoundException {
+ try {
+ return randomAccessFile("rw");
+ } catch (FileNotFoundException e) {
+ return randomAccessFile("r");
+ }
+ }
+
+ private RandomAccessFile randomAccessFile(String mode) throws FileNotFoundException {
+ return new RandomAccessFile(cacheFile, mode);
+ }
+
+ @Override
+ public void close() {
+ try {
+ file.close();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @Override
+ public void clear() {
+ try {
+ file.setLength(0);
+ currentFileSize = 0;
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ nextBlock = 0;
+ }
+
+ @Override
+ public void attach(BlockPayload block) {
+ if (block.getBlock() == null) {
+ block.setBlock(new BlockImpl(block));
+ }
+ }
+
+ @Override
+ public void remove(BlockPayload block) {
+ BlockImpl blockImpl = (BlockImpl) block.getBlock();
+ blockImpl.detach();
+ }
+
+ @Override
+ public void flush() {
+ }
+
+ @Override
+ public T readFirst(Class payloadType) {
+ return read(BlockPointer.pos(0), payloadType);
+ }
+
+ @Override
+ public T read(BlockPointer pos, Class payloadType) {
+ assert !pos.isNull();
+ try {
+ T payload = payloadType.cast(factory.create(payloadType));
+ BlockImpl block = new BlockImpl(payload, pos);
+ block.read();
+ return payload;
+ } catch (CorruptedCacheException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @Override
+ public void write(BlockPayload block) {
+ BlockImpl blockImpl = (BlockImpl) block.getBlock();
+ try {
+ blockImpl.write();
+ } catch (CorruptedCacheException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ private long alloc(long length) {
+ long pos = nextBlock;
+ nextBlock += length;
+ return pos;
+ }
+
+ private final class BlockImpl extends Block {
+ private static final int HEADER_SIZE = 1 + INT_SIZE; // type, payload size
+ private static final int TAIL_SIZE = INT_SIZE;
+
+ private BlockPointer pos;
+ private int payloadSize;
+
+ private BlockImpl(BlockPayload payload, BlockPointer pos) {
+ this(payload);
+ setPos(pos);
+ }
+
+ public BlockImpl(BlockPayload payload) {
+ super(payload);
+ pos = null;
+ payloadSize = -1;
+ }
+
+ @Override
+ public boolean hasPos() {
+ return pos != null;
+ }
+
+ @Override
+ public BlockPointer getPos() {
+ if (pos == null) {
+ pos = BlockPointer.pos(alloc(getSize()));
+ }
+ return pos;
+ }
+
+ @Override
+ public void setPos(BlockPointer pos) {
+ assert this.pos == null && !pos.isNull();
+ this.pos = pos;
+ }
+
+ @Override
+ public int getSize() {
+ if (payloadSize < 0) {
+ payloadSize = getPayload().getSize();
+ }
+ return payloadSize + HEADER_SIZE + TAIL_SIZE;
+ }
+
+ @Override
+ public void setSize(int size) {
+ int newPayloadSize = size - HEADER_SIZE - TAIL_SIZE;
+ assert newPayloadSize >= payloadSize;
+ payloadSize = newPayloadSize;
+ }
+
+ public void write() throws Exception {
+ long pos = getPos().getPos();
+
+ DataOutputStream outputStream = output.start(pos);
+
+ BlockPayload payload = getPayload();
+
+ // Write header
+ outputStream.writeByte(payload.getType());
+ outputStream.writeInt(payloadSize);
+ long finalSize = pos + HEADER_SIZE + TAIL_SIZE + payloadSize;
+
+ // Write body
+ payload.write(outputStream);
+
+ // Write count
+ long bytesWritten = output.getBytesWritten();
+ if (bytesWritten > Integer.MAX_VALUE) {
+ throw new IllegalArgumentException("Block payload exceeds maximum size");
+ }
+ outputStream.writeInt((int) bytesWritten);
+ output.done();
+
+ // System.out.println(String.format("wrote [%d,%d)", pos, pos + bytesWritten + 4));
+
+ // Pad
+ if (currentFileSize < finalSize) {
+ // System.out.println(String.format("pad length %d => %d", currentFileSize, finalSize));
+ file.setLength(finalSize);
+ currentFileSize = finalSize;
+ }
+ }
+
+ public void read() throws Exception {
+ long pos = getPos().getPos();
+ assert pos >= 0;
+ if (pos + HEADER_SIZE >= currentFileSize) {
+ throw blockCorruptedException();
+ }
+
+ DataInputStream inputStream = input.start(pos);
+
+ BlockPayload payload = getPayload();
+
+ // Read header
+ byte type = inputStream.readByte();
+ if (type != payload.getType()) {
+ throw blockCorruptedException();
+ }
+
+ // Read body
+ payloadSize = inputStream.readInt();
+ if (pos + HEADER_SIZE + TAIL_SIZE + payloadSize > currentFileSize) {
+ throw blockCorruptedException();
+ }
+ payload.read(inputStream);
+
+ // Read and verify count
+ long actualCount = input.getBytesRead();
+ long count = inputStream.readInt();
+ if (actualCount != count) {
+ System.out.println(String.format("read expected %d actual %d, pos %d payloadSize %d currentFileSize %d", count, actualCount, pos, payloadSize, currentFileSize));
+ throw blockCorruptedException();
+ }
+ input.done();
+ }
+
+ @Override
+ public RuntimeException blockCorruptedException() {
+ return new CorruptedCacheException(String.format("Corrupted %s found in %s.", this,
+ FileBackedBlockStore.this));
+ }
+ }
+
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/FreeListBlockStore.java b/test/random_access/src/main/java/seaweedfs/client/btree/FreeListBlockStore.java
new file mode 100644
index 000000000..c2cd640f9
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/FreeListBlockStore.java
@@ -0,0 +1,283 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class FreeListBlockStore implements BlockStore {
+ private final BlockStore store;
+ private final BlockStore freeListStore;
+ private final int maxBlockEntries;
+ private FreeListBlock freeListBlock;
+
+ public FreeListBlockStore(BlockStore store, int maxBlockEntries) {
+ this.store = store;
+ freeListStore = this;
+ this.maxBlockEntries = maxBlockEntries;
+ }
+
+ @Override
+ public void open(final Runnable initAction, final Factory factory) {
+ Runnable freeListInitAction = new Runnable() {
+ @Override
+ public void run() {
+ freeListBlock = new FreeListBlock();
+ store.write(freeListBlock);
+ store.flush();
+ initAction.run();
+ }
+ };
+ Factory freeListFactory = new Factory() {
+ @Override
+ public Object create(Class extends BlockPayload> type) {
+ if (type == FreeListBlock.class) {
+ return new FreeListBlock();
+ }
+ return factory.create(type);
+ }
+ };
+
+ store.open(freeListInitAction, freeListFactory);
+ freeListBlock = store.readFirst(FreeListBlock.class);
+ }
+
+ @Override
+ public void close() {
+ freeListBlock = null;
+ store.close();
+ }
+
+ @Override
+ public void clear() {
+ store.clear();
+ }
+
+ @Override
+ public void remove(BlockPayload block) {
+ Block container = block.getBlock();
+ store.remove(block);
+ freeListBlock.add(container.getPos(), container.getSize());
+ }
+
+ @Override
+ public T readFirst(Class payloadType) {
+ return store.read(freeListBlock.getNextPos(), payloadType);
+ }
+
+ @Override
+ public T read(BlockPointer pos, Class payloadType) {
+ return store.read(pos, payloadType);
+ }
+
+ @Override
+ public void write(BlockPayload block) {
+ attach(block);
+ store.write(block);
+ }
+
+ @Override
+ public void attach(BlockPayload block) {
+ store.attach(block);
+ freeListBlock.alloc(block.getBlock());
+ }
+
+ @Override
+ public void flush() {
+ store.flush();
+ }
+
+ private void verify() {
+ FreeListBlock block = store.readFirst(FreeListBlock.class);
+ verify(block, Integer.MAX_VALUE);
+ }
+
+ private void verify(FreeListBlock block, int maxValue) {
+ if (block.largestInNextBlock > maxValue) {
+ throw new RuntimeException("corrupt free list");
+ }
+ int current = 0;
+ for (FreeListEntry entry : block.entries) {
+ if (entry.size > maxValue) {
+ throw new RuntimeException("corrupt free list");
+ }
+ if (entry.size < block.largestInNextBlock) {
+ throw new RuntimeException("corrupt free list");
+ }
+ if (entry.size < current) {
+ throw new RuntimeException("corrupt free list");
+ }
+ current = entry.size;
+ }
+ if (!block.nextBlock.isNull()) {
+ verify(store.read(block.nextBlock, FreeListBlock.class), block.largestInNextBlock);
+ }
+ }
+
+ public class FreeListBlock extends BlockPayload {
+ private List entries = new ArrayList();
+ private int largestInNextBlock;
+ private BlockPointer nextBlock = BlockPointer.start();
+ // Transient fields
+ private FreeListBlock prev;
+ private FreeListBlock next;
+
+ @Override
+ protected int getSize() {
+ return Block.LONG_SIZE + Block.INT_SIZE + Block.INT_SIZE + maxBlockEntries * (Block.LONG_SIZE
+ + Block.INT_SIZE);
+ }
+
+ @Override
+ protected byte getType() {
+ return 0x44;
+ }
+
+ @Override
+ protected void read(DataInputStream inputStream) throws Exception {
+ nextBlock = BlockPointer.pos(inputStream.readLong());
+ largestInNextBlock = inputStream.readInt();
+ int count = inputStream.readInt();
+ for (int i = 0; i < count; i++) {
+ BlockPointer pos = BlockPointer.pos(inputStream.readLong());
+ int size = inputStream.readInt();
+ entries.add(new FreeListEntry(pos, size));
+ }
+ }
+
+ @Override
+ protected void write(DataOutputStream outputStream) throws Exception {
+ outputStream.writeLong(nextBlock.getPos());
+ outputStream.writeInt(largestInNextBlock);
+ outputStream.writeInt(entries.size());
+ for (FreeListEntry entry : entries) {
+ outputStream.writeLong(entry.pos.getPos());
+ outputStream.writeInt(entry.size);
+ }
+ }
+
+ public void add(BlockPointer pos, int size) {
+ assert !pos.isNull() && size >= 0;
+ if (size == 0) {
+ return;
+ }
+
+ if (size < largestInNextBlock) {
+ FreeListBlock next = getNextBlock();
+ next.add(pos, size);
+ return;
+ }
+
+ FreeListEntry entry = new FreeListEntry(pos, size);
+ int index = Collections.binarySearch(entries, entry);
+ if (index < 0) {
+ index = -index - 1;
+ }
+ entries.add(index, entry);
+
+ if (entries.size() > maxBlockEntries) {
+ FreeListBlock newBlock = new FreeListBlock();
+ newBlock.largestInNextBlock = largestInNextBlock;
+ newBlock.nextBlock = nextBlock;
+ newBlock.prev = this;
+ newBlock.next = next;
+ next = newBlock;
+
+ List newBlockEntries = entries.subList(0, entries.size() / 2);
+ newBlock.entries.addAll(newBlockEntries);
+ newBlockEntries.clear();
+ largestInNextBlock = newBlock.entries.get(newBlock.entries.size() - 1).size;
+ freeListStore.write(newBlock);
+ nextBlock = newBlock.getPos();
+ }
+
+ freeListStore.write(this);
+ }
+
+ private FreeListBlock getNextBlock() {
+ if (next == null) {
+ next = freeListStore.read(nextBlock, FreeListBlock.class);
+ next.prev = this;
+ }
+ return next;
+ }
+
+ public void alloc(Block block) {
+ if (block.hasPos()) {
+ return;
+ }
+
+ int requiredSize = block.getSize();
+
+ if (entries.isEmpty() || requiredSize <= largestInNextBlock) {
+ if (nextBlock.isNull()) {
+ return;
+ }
+ getNextBlock().alloc(block);
+ return;
+ }
+
+ int index = Collections.binarySearch(entries, new FreeListEntry(null, requiredSize));
+ if (index < 0) {
+ index = -index - 1;
+ }
+ if (index == entries.size()) {
+ // Largest free block is too small
+ return;
+ }
+
+ FreeListEntry entry = entries.remove(index);
+ block.setPos(entry.pos);
+ block.setSize(entry.size);
+ freeListStore.write(this);
+
+ if (entries.size() == 0 && prev != null) {
+ prev.nextBlock = nextBlock;
+ prev.largestInNextBlock = largestInNextBlock;
+ prev.next = next;
+ if (next != null) {
+ next.prev = prev;
+ }
+ freeListStore.write(prev);
+ freeListStore.remove(this);
+ }
+ }
+ }
+
+ private static class FreeListEntry implements Comparable {
+ final BlockPointer pos;
+ final int size;
+
+ private FreeListEntry(BlockPointer pos, int size) {
+ this.pos = pos;
+ this.size = size;
+ }
+
+ @Override
+ public int compareTo(FreeListEntry o) {
+ if (size > o.size) {
+ return 1;
+ }
+ if (size < o.size) {
+ return -1;
+ }
+ return 0;
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/KeyHasher.java b/test/random_access/src/main/java/seaweedfs/client/btree/KeyHasher.java
new file mode 100644
index 000000000..bdc78dde2
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/KeyHasher.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2014 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree;
+
+import seaweedfs.client.btree.serialize.Serializer;
+import seaweedfs.client.btree.serialize.kryo.KryoBackedEncoder;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+class KeyHasher {
+ private final Serializer serializer;
+ private final MessageDigestStream digestStream = new MessageDigestStream();
+ private final KryoBackedEncoder encoder = new KryoBackedEncoder(digestStream);
+
+ public KeyHasher(Serializer serializer) {
+ this.serializer = serializer;
+ }
+
+ long getHashCode(K key) throws Exception {
+ serializer.write(encoder, key);
+ encoder.flush();
+ return digestStream.getChecksum();
+ }
+
+ private static class MessageDigestStream extends OutputStream {
+ MessageDigest messageDigest;
+
+ private MessageDigestStream() {
+ try {
+ messageDigest = MessageDigest.getInstance("MD5");
+ } catch (NoSuchAlgorithmException e) {
+ throw UncheckedException.throwAsUncheckedException(e);
+ }
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ messageDigest.update((byte) b);
+ }
+
+ @Override
+ public void write(byte[] b) throws IOException {
+ messageDigest.update(b);
+ }
+
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException {
+ messageDigest.update(b, off, len);
+ }
+
+ long getChecksum() {
+ byte[] digest = messageDigest.digest();
+ assert digest.length == 16;
+ return new BigInteger(digest).longValue();
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/RandomAccessFileInputStream.java b/test/random_access/src/main/java/seaweedfs/client/btree/RandomAccessFileInputStream.java
new file mode 100644
index 000000000..5f876989f
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/RandomAccessFileInputStream.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+
+/**
+ * Reads from a {@link RandomAccessFile}. Each operation reads from and advances the current position of the file.
+ *
+ *
Closing this stream does not close the underlying file.
+ */
+public class RandomAccessFileInputStream extends InputStream {
+ private final RandomAccessFile file;
+
+ public RandomAccessFileInputStream(RandomAccessFile file) {
+ this.file = file;
+ }
+
+ @Override
+ public long skip(long n) throws IOException {
+ file.seek(file.getFilePointer() + n);
+ return n;
+ }
+
+ @Override
+ public int read(byte[] bytes) throws IOException {
+ return file.read(bytes);
+ }
+
+ @Override
+ public int read() throws IOException {
+ return file.read();
+ }
+
+ @Override
+ public int read(byte[] bytes, int offset, int length) throws IOException {
+ return file.read(bytes, offset, length);
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/RandomAccessFileOutputStream.java b/test/random_access/src/main/java/seaweedfs/client/btree/RandomAccessFileOutputStream.java
new file mode 100644
index 000000000..3327fe3c6
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/RandomAccessFileOutputStream.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+
+/**
+ * Writes to a {@link RandomAccessFile}. Each operation writes to and advances the current position of the file.
+ *
+ *
Closing this stream does not close the underlying file. Flushing this stream does nothing.
+ */
+public class RandomAccessFileOutputStream extends OutputStream {
+ private final RandomAccessFile file;
+
+ public RandomAccessFileOutputStream(RandomAccessFile file) {
+ this.file = file;
+ }
+
+ @Override
+ public void write(int i) throws IOException {
+ file.write(i);
+ }
+
+ @Override
+ public void write(byte[] bytes) throws IOException {
+ file.write(bytes);
+ }
+
+ @Override
+ public void write(byte[] bytes, int offset, int length) throws IOException {
+ file.write(bytes, offset, length);
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/StateCheckBlockStore.java b/test/random_access/src/main/java/seaweedfs/client/btree/StateCheckBlockStore.java
new file mode 100644
index 000000000..f720ebb2e
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/StateCheckBlockStore.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+public class StateCheckBlockStore implements BlockStore {
+ private final BlockStore blockStore;
+ private boolean open;
+
+ public StateCheckBlockStore(BlockStore blockStore) {
+ this.blockStore = blockStore;
+ }
+
+ @Override
+ public void open(Runnable initAction, Factory factory) {
+ assert !open;
+ open = true;
+ blockStore.open(initAction, factory);
+ }
+
+ public boolean isOpen() {
+ return open;
+ }
+
+ @Override
+ public void close() {
+ if (!open) {
+ return;
+ }
+ open = false;
+ blockStore.close();
+ }
+
+ @Override
+ public void clear() {
+ assert open;
+ blockStore.clear();
+ }
+
+ @Override
+ public void remove(BlockPayload block) {
+ assert open;
+ blockStore.remove(block);
+ }
+
+ @Override
+ public T readFirst(Class payloadType) {
+ assert open;
+ return blockStore.readFirst(payloadType);
+ }
+
+ @Override
+ public T read(BlockPointer pos, Class payloadType) {
+ assert open;
+ return blockStore.read(pos, payloadType);
+ }
+
+ @Override
+ public void write(BlockPayload block) {
+ assert open;
+ blockStore.write(block);
+ }
+
+ @Override
+ public void attach(BlockPayload block) {
+ assert open;
+ blockStore.attach(block);
+ }
+
+ @Override
+ public void flush() {
+ assert open;
+ blockStore.flush();
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/StreamByteBuffer.java b/test/random_access/src/main/java/seaweedfs/client/btree/StreamByteBuffer.java
new file mode 100644
index 000000000..8af6e14d8
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/StreamByteBuffer.java
@@ -0,0 +1,526 @@
+/*
+ * Copyright 2016 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+
+/**
+ * An in-memory buffer that provides OutputStream and InputStream interfaces.
+ *
+ * This is more efficient than using ByteArrayOutputStream/ByteArrayInputStream
+ *
+ * Reading the buffer will clear the buffer.
+ * This is not thread-safe, it is intended to be used by a single Thread.
+ */
+public class StreamByteBuffer {
+ private static final int DEFAULT_CHUNK_SIZE = 4096;
+ private static final int MAX_CHUNK_SIZE = 1024 * 1024;
+ private LinkedList chunks = new LinkedList();
+ private StreamByteBufferChunk currentWriteChunk;
+ private StreamByteBufferChunk currentReadChunk;
+ private int chunkSize;
+ private int nextChunkSize;
+ private int maxChunkSize;
+ private StreamByteBufferOutputStream output;
+ private StreamByteBufferInputStream input;
+ private int totalBytesUnreadInList;
+
+ public StreamByteBuffer() {
+ this(DEFAULT_CHUNK_SIZE);
+ }
+
+ public StreamByteBuffer(int chunkSize) {
+ this.chunkSize = chunkSize;
+ this.nextChunkSize = chunkSize;
+ this.maxChunkSize = Math.max(chunkSize, MAX_CHUNK_SIZE);
+ currentWriteChunk = new StreamByteBufferChunk(nextChunkSize);
+ output = new StreamByteBufferOutputStream();
+ input = new StreamByteBufferInputStream();
+ }
+
+ public static StreamByteBuffer of(InputStream inputStream) throws IOException {
+ StreamByteBuffer buffer = new StreamByteBuffer(chunkSizeInDefaultRange(inputStream.available()));
+ buffer.readFully(inputStream);
+ return buffer;
+ }
+
+ public static StreamByteBuffer of(InputStream inputStream, int len) throws IOException {
+ StreamByteBuffer buffer = new StreamByteBuffer(chunkSizeInDefaultRange(len));
+ buffer.readFrom(inputStream, len);
+ return buffer;
+ }
+
+ public static StreamByteBuffer createWithChunkSizeInDefaultRange(int value) {
+ return new StreamByteBuffer(chunkSizeInDefaultRange(value));
+ }
+
+ static int chunkSizeInDefaultRange(int value) {
+ return valueInRange(value, DEFAULT_CHUNK_SIZE, MAX_CHUNK_SIZE);
+ }
+
+ private static int valueInRange(int value, int min, int max) {
+ return Math.min(Math.max(value, min), max);
+ }
+
+ public OutputStream getOutputStream() {
+ return output;
+ }
+
+ public InputStream getInputStream() {
+ return input;
+ }
+
+ public void writeTo(OutputStream target) throws IOException {
+ while (prepareRead() != -1) {
+ currentReadChunk.writeTo(target);
+ }
+ }
+
+ public void readFrom(InputStream inputStream, int len) throws IOException {
+ int bytesLeft = len;
+ while (bytesLeft > 0) {
+ int spaceLeft = allocateSpace();
+ int limit = Math.min(spaceLeft, bytesLeft);
+ int readBytes = currentWriteChunk.readFrom(inputStream, limit);
+ if (readBytes == -1) {
+ throw new EOFException("Unexpected EOF");
+ }
+ bytesLeft -= readBytes;
+ }
+ }
+
+ public void readFully(InputStream inputStream) throws IOException {
+ while (true) {
+ int len = allocateSpace();
+ int readBytes = currentWriteChunk.readFrom(inputStream, len);
+ if (readBytes == -1) {
+ break;
+ }
+ }
+ }
+
+ public byte[] readAsByteArray() {
+ byte[] buf = new byte[totalBytesUnread()];
+ input.readImpl(buf, 0, buf.length);
+ return buf;
+ }
+
+ public List readAsListOfByteArrays() {
+ List listOfByteArrays = new ArrayList(chunks.size() + 1);
+ byte[] buf;
+ while ((buf = input.readNextBuffer()) != null) {
+ if (buf.length > 0) {
+ listOfByteArrays.add(buf);
+ }
+ }
+ return listOfByteArrays;
+ }
+
+ public String readAsString(String encoding) {
+ Charset charset = Charset.forName(encoding);
+ return readAsString(charset);
+ }
+
+ public String readAsString() {
+ return readAsString(Charset.defaultCharset());
+ }
+
+ public String readAsString(Charset charset) {
+ try {
+ return doReadAsString(charset);
+ } catch (CharacterCodingException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ private String doReadAsString(Charset charset) throws CharacterCodingException {
+ int unreadSize = totalBytesUnread();
+ if (unreadSize > 0) {
+ return readAsCharBuffer(charset).toString();
+ }
+ return "";
+ }
+
+ private CharBuffer readAsCharBuffer(Charset charset) throws CharacterCodingException {
+ CharsetDecoder decoder = charset.newDecoder().onMalformedInput(
+ CodingErrorAction.REPLACE).onUnmappableCharacter(
+ CodingErrorAction.REPLACE);
+ CharBuffer charbuffer = CharBuffer.allocate(totalBytesUnread());
+ ByteBuffer buf = null;
+ boolean wasUnderflow = false;
+ ByteBuffer nextBuf = null;
+ boolean needsFlush = false;
+ while (hasRemaining(nextBuf) || hasRemaining(buf) || prepareRead() != -1) {
+ if (hasRemaining(buf)) {
+ // handle decoding underflow, multi-byte unicode character at buffer chunk boundary
+ if (!wasUnderflow) {
+ throw new IllegalStateException("Unexpected state. Buffer has remaining bytes without underflow in decoding.");
+ }
+ if (!hasRemaining(nextBuf) && prepareRead() != -1) {
+ nextBuf = currentReadChunk.readToNioBuffer();
+ }
+ // copy one by one until the underflow has been resolved
+ buf = ByteBuffer.allocate(buf.remaining() + 1).put(buf);
+ buf.put(nextBuf.get());
+ BufferCaster.cast(buf).flip();
+ } else {
+ if (hasRemaining(nextBuf)) {
+ buf = nextBuf;
+ } else if (prepareRead() != -1) {
+ buf = currentReadChunk.readToNioBuffer();
+ if (!hasRemaining(buf)) {
+ throw new IllegalStateException("Unexpected state. Buffer is empty.");
+ }
+ }
+ nextBuf = null;
+ }
+ boolean endOfInput = !hasRemaining(nextBuf) && prepareRead() == -1;
+ int bufRemainingBefore = buf.remaining();
+ CoderResult result = decoder.decode(buf, charbuffer, false);
+ if (bufRemainingBefore > buf.remaining()) {
+ needsFlush = true;
+ }
+ if (endOfInput) {
+ result = decoder.decode(ByteBuffer.allocate(0), charbuffer, true);
+ if (!result.isUnderflow()) {
+ result.throwException();
+ }
+ break;
+ }
+ wasUnderflow = result.isUnderflow();
+ }
+ if (needsFlush) {
+ CoderResult result = decoder.flush(charbuffer);
+ if (!result.isUnderflow()) {
+ result.throwException();
+ }
+ }
+ clear();
+ // push back remaining bytes of multi-byte unicode character
+ while (hasRemaining(buf)) {
+ byte b = buf.get();
+ try {
+ getOutputStream().write(b);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+ BufferCaster.cast(charbuffer).flip();
+ return charbuffer;
+ }
+
+ private boolean hasRemaining(ByteBuffer nextBuf) {
+ return nextBuf != null && nextBuf.hasRemaining();
+ }
+
+ public int totalBytesUnread() {
+ int total = totalBytesUnreadInList;
+ if (currentReadChunk != null) {
+ total += currentReadChunk.bytesUnread();
+ }
+ if (currentWriteChunk != currentReadChunk && currentWriteChunk != null) {
+ total += currentWriteChunk.bytesUnread();
+ }
+ return total;
+ }
+
+ protected int allocateSpace() {
+ int spaceLeft = currentWriteChunk.spaceLeft();
+ if (spaceLeft == 0) {
+ addChunk(currentWriteChunk);
+ currentWriteChunk = new StreamByteBufferChunk(nextChunkSize);
+ if (nextChunkSize < maxChunkSize) {
+ nextChunkSize = Math.min(nextChunkSize * 2, maxChunkSize);
+ }
+ spaceLeft = currentWriteChunk.spaceLeft();
+ }
+ return spaceLeft;
+ }
+
+ protected int prepareRead() {
+ int bytesUnread = (currentReadChunk != null) ? currentReadChunk.bytesUnread() : 0;
+ if (bytesUnread == 0) {
+ if (!chunks.isEmpty()) {
+ currentReadChunk = chunks.removeFirst();
+ bytesUnread = currentReadChunk.bytesUnread();
+ totalBytesUnreadInList -= bytesUnread;
+ } else if (currentReadChunk != currentWriteChunk) {
+ currentReadChunk = currentWriteChunk;
+ bytesUnread = currentReadChunk.bytesUnread();
+ } else {
+ bytesUnread = -1;
+ }
+ }
+ return bytesUnread;
+ }
+
+ public static StreamByteBuffer of(List listOfByteArrays) {
+ StreamByteBuffer buffer = new StreamByteBuffer();
+ buffer.addChunks(listOfByteArrays);
+ return buffer;
+ }
+
+ private void addChunks(List listOfByteArrays) {
+ for (byte[] buf : listOfByteArrays) {
+ addChunk(new StreamByteBufferChunk(buf));
+ }
+ }
+
+ private void addChunk(StreamByteBufferChunk chunk) {
+ chunks.add(chunk);
+ totalBytesUnreadInList += chunk.bytesUnread();
+ }
+
+ static class StreamByteBufferChunk {
+ private int pointer;
+ private byte[] buffer;
+ private int size;
+ private int used;
+
+ public StreamByteBufferChunk(int size) {
+ this.size = size;
+ buffer = new byte[size];
+ }
+
+ public StreamByteBufferChunk(byte[] buf) {
+ this.size = buf.length;
+ this.buffer = buf;
+ this.used = buf.length;
+ }
+
+ public ByteBuffer readToNioBuffer() {
+ if (pointer < used) {
+ ByteBuffer result;
+ if (pointer > 0 || used < size) {
+ result = ByteBuffer.wrap(buffer, pointer, used - pointer);
+ } else {
+ result = ByteBuffer.wrap(buffer);
+ }
+ pointer = used;
+ return result;
+ }
+
+ return null;
+ }
+
+ public boolean write(byte b) {
+ if (used < size) {
+ buffer[used++] = b;
+ return true;
+ }
+
+ return false;
+ }
+
+ public void write(byte[] b, int off, int len) {
+ System.arraycopy(b, off, buffer, used, len);
+ used = used + len;
+ }
+
+ public void read(byte[] b, int off, int len) {
+ System.arraycopy(buffer, pointer, b, off, len);
+ pointer = pointer + len;
+ }
+
+ public void writeTo(OutputStream target) throws IOException {
+ if (pointer < used) {
+ target.write(buffer, pointer, used - pointer);
+ pointer = used;
+ }
+ }
+
+ public void reset() {
+ pointer = 0;
+ }
+
+ public int bytesUsed() {
+ return used;
+ }
+
+ public int bytesUnread() {
+ return used - pointer;
+ }
+
+ public int read() {
+ if (pointer < used) {
+ return buffer[pointer++] & 0xff;
+ }
+
+ return -1;
+ }
+
+ public int spaceLeft() {
+ return size - used;
+ }
+
+ public int readFrom(InputStream inputStream, int len) throws IOException {
+ int readBytes = inputStream.read(buffer, used, len);
+ if(readBytes > 0) {
+ used += readBytes;
+ }
+ return readBytes;
+ }
+
+ public void clear() {
+ used = pointer = 0;
+ }
+
+ public byte[] readBuffer() {
+ if (used == buffer.length && pointer == 0) {
+ pointer = used;
+ return buffer;
+ } else if (pointer < used) {
+ byte[] buf = new byte[used - pointer];
+ read(buf, 0, used - pointer);
+ return buf;
+ } else {
+ return new byte[0];
+ }
+ }
+ }
+
+ class StreamByteBufferOutputStream extends OutputStream {
+ private boolean closed;
+
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException {
+ if (b == null) {
+ throw new NullPointerException();
+ }
+
+ if ((off < 0) || (off > b.length) || (len < 0)
+ || ((off + len) > b.length) || ((off + len) < 0)) {
+ throw new IndexOutOfBoundsException();
+ }
+
+ if (len == 0) {
+ return;
+ }
+
+ int bytesLeft = len;
+ int currentOffset = off;
+ while (bytesLeft > 0) {
+ int spaceLeft = allocateSpace();
+ int writeBytes = Math.min(spaceLeft, bytesLeft);
+ currentWriteChunk.write(b, currentOffset, writeBytes);
+ bytesLeft -= writeBytes;
+ currentOffset += writeBytes;
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ closed = true;
+ }
+
+ public boolean isClosed() {
+ return closed;
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ allocateSpace();
+ currentWriteChunk.write((byte) b);
+ }
+
+ public StreamByteBuffer getBuffer() {
+ return StreamByteBuffer.this;
+ }
+ }
+
+ class StreamByteBufferInputStream extends InputStream {
+ @Override
+ public int read() throws IOException {
+ prepareRead();
+ return currentReadChunk.read();
+ }
+
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
+ return readImpl(b, off, len);
+ }
+
+ int readImpl(byte[] b, int off, int len) {
+ if (b == null) {
+ throw new NullPointerException();
+ }
+
+ if ((off < 0) || (off > b.length) || (len < 0)
+ || ((off + len) > b.length) || ((off + len) < 0)) {
+ throw new IndexOutOfBoundsException();
+ }
+
+ if (len == 0) {
+ return 0;
+ }
+
+ int bytesLeft = len;
+ int currentOffset = off;
+ int bytesUnread = prepareRead();
+ int totalBytesRead = 0;
+ while (bytesLeft > 0 && bytesUnread != -1) {
+ int readBytes = Math.min(bytesUnread, bytesLeft);
+ currentReadChunk.read(b, currentOffset, readBytes);
+ bytesLeft -= readBytes;
+ currentOffset += readBytes;
+ totalBytesRead += readBytes;
+ bytesUnread = prepareRead();
+ }
+ if (totalBytesRead > 0) {
+ return totalBytesRead;
+ }
+
+ return -1;
+ }
+
+ @Override
+ public int available() throws IOException {
+ return totalBytesUnread();
+ }
+
+ public StreamByteBuffer getBuffer() {
+ return StreamByteBuffer.this;
+ }
+
+ public byte[] readNextBuffer() {
+ if (prepareRead() != -1) {
+ return currentReadChunk.readBuffer();
+ }
+ return null;
+ }
+ }
+
+ public void clear() {
+ chunks.clear();
+ currentReadChunk = null;
+ totalBytesUnreadInList = 0;
+ currentWriteChunk.clear();
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/UncheckedException.java b/test/random_access/src/main/java/seaweedfs/client/btree/UncheckedException.java
new file mode 100644
index 000000000..ab57d8c95
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/UncheckedException.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2010 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.util.concurrent.Callable;
+
+/**
+ * Wraps a checked exception. Carries no other context.
+ */
+public final class UncheckedException extends RuntimeException {
+ private UncheckedException(Throwable cause) {
+ super(cause);
+ }
+
+ private UncheckedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Note: always throws the failure in some form. The return value is to keep the compiler happy.
+ */
+ public static RuntimeException throwAsUncheckedException(Throwable t) {
+ return throwAsUncheckedException(t, false);
+ }
+
+ /**
+ * Note: always throws the failure in some form. The return value is to keep the compiler happy.
+ */
+ public static RuntimeException throwAsUncheckedException(Throwable t, boolean preserveMessage) {
+ if (t instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ if (t instanceof RuntimeException) {
+ throw (RuntimeException) t;
+ }
+ if (t instanceof Error) {
+ throw (Error) t;
+ }
+ if (t instanceof IOException) {
+ if (preserveMessage) {
+ throw new UncheckedIOException(t.getMessage(), t);
+ } else {
+ throw new UncheckedIOException(t);
+ }
+ }
+ if (preserveMessage) {
+ throw new UncheckedException(t.getMessage(), t);
+ } else {
+ throw new UncheckedException(t);
+ }
+ }
+
+ public static T callUnchecked(Callable callable) {
+ try {
+ return callable.call();
+ } catch (Exception e) {
+ throw throwAsUncheckedException(e);
+ }
+ }
+
+ /**
+ * Unwraps passed InvocationTargetException hence making the stack of exceptions cleaner without losing information.
+ *
+ * Note: always throws the failure in some form. The return value is to keep the compiler happy.
+ *
+ * @param e to be unwrapped
+ * @return an instance of RuntimeException based on the target exception of the parameter.
+ */
+ public static RuntimeException unwrapAndRethrow(InvocationTargetException e) {
+ return UncheckedException.throwAsUncheckedException(e.getTargetException());
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/UncheckedIOException.java b/test/random_access/src/main/java/seaweedfs/client/btree/UncheckedIOException.java
new file mode 100644
index 000000000..1cf30df7a
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/UncheckedIOException.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2012 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree;
+
+/**
+ * UncheckedIOException is used to wrap an {@link java.io.IOException} into an unchecked exception.
+ */
+public class UncheckedIOException extends RuntimeException {
+ public UncheckedIOException() {
+ }
+
+ public UncheckedIOException(String message) {
+ super(message);
+ }
+
+ public UncheckedIOException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public UncheckedIOException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractDecoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractDecoder.java
new file mode 100644
index 000000000..d805f4654
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractDecoder.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import javax.annotation.Nullable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+public abstract class AbstractDecoder implements Decoder {
+ private DecoderStream stream;
+
+ @Override
+ public InputStream getInputStream() {
+ if (stream == null) {
+ stream = new DecoderStream();
+ }
+ return stream;
+ }
+
+ @Override
+ public void readBytes(byte[] buffer) throws IOException {
+ readBytes(buffer, 0, buffer.length);
+ }
+
+ @Override
+ public byte[] readBinary() throws EOFException, IOException {
+ int size = readSmallInt();
+ byte[] result = new byte[size];
+ readBytes(result);
+ return result;
+ }
+
+ @Override
+ public int readSmallInt() throws EOFException, IOException {
+ return readInt();
+ }
+
+ @Override
+ public long readSmallLong() throws EOFException, IOException {
+ return readLong();
+ }
+
+ @Nullable
+ @Override
+ public Integer readNullableSmallInt() throws IOException {
+ if (readBoolean()) {
+ return readSmallInt();
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public String readNullableString() throws EOFException, IOException {
+ if (readBoolean()) {
+ return readString();
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public void skipBytes(long count) throws EOFException, IOException {
+ long remaining = count;
+ while (remaining > 0) {
+ long skipped = maybeSkip(remaining);
+ if (skipped <= 0) {
+ break;
+ }
+ remaining -= skipped;
+ }
+ if (remaining > 0) {
+ throw new EOFException();
+ }
+ }
+
+ @Override
+ public T decodeChunked(DecodeAction decodeAction) throws EOFException, Exception {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void skipChunked() throws EOFException, IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ protected abstract int maybeReadBytes(byte[] buffer, int offset, int count) throws IOException;
+
+ protected abstract long maybeSkip(long count) throws IOException;
+
+ private class DecoderStream extends InputStream {
+ byte[] buffer = new byte[1];
+
+ @Override
+ public long skip(long n) throws IOException {
+ return maybeSkip(n);
+ }
+
+ @Override
+ public int read() throws IOException {
+ int read = maybeReadBytes(buffer, 0, 1);
+ if (read <= 0) {
+ return read;
+ }
+ return buffer[0] & 0xff;
+ }
+
+ @Override
+ public int read(byte[] buffer) throws IOException {
+ return maybeReadBytes(buffer, 0, buffer.length);
+ }
+
+ @Override
+ public int read(byte[] buffer, int offset, int count) throws IOException {
+ return maybeReadBytes(buffer, offset, count);
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractEncoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractEncoder.java
new file mode 100644
index 000000000..4caf3461d
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractEncoder.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.io.OutputStream;
+
+public abstract class AbstractEncoder implements Encoder {
+ private EncoderStream stream;
+
+ @Override
+ public OutputStream getOutputStream() {
+ if (stream == null) {
+ stream = new EncoderStream();
+ }
+ return stream;
+ }
+
+ @Override
+ public void writeBytes(byte[] bytes) throws IOException {
+ writeBytes(bytes, 0, bytes.length);
+ }
+
+ @Override
+ public void writeBinary(byte[] bytes) throws IOException {
+ writeBinary(bytes, 0, bytes.length);
+ }
+
+ @Override
+ public void writeBinary(byte[] bytes, int offset, int count) throws IOException {
+ writeSmallInt(count);
+ writeBytes(bytes, offset, count);
+ }
+
+ @Override
+ public void encodeChunked(EncodeAction writeAction) throws Exception {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeSmallInt(int value) throws IOException {
+ writeInt(value);
+ }
+
+ @Override
+ public void writeSmallLong(long value) throws IOException {
+ writeLong(value);
+ }
+
+ @Override
+ public void writeNullableSmallInt(@Nullable Integer value) throws IOException {
+ if (value == null) {
+ writeBoolean(false);
+ } else {
+ writeBoolean(true);
+ writeSmallInt(value);
+ }
+ }
+
+ @Override
+ public void writeNullableString(@Nullable CharSequence value) throws IOException {
+ if (value == null) {
+ writeBoolean(false);
+ } else {
+ writeBoolean(true);
+ writeString(value.toString());
+ }
+ }
+
+ private class EncoderStream extends OutputStream {
+ @Override
+ public void write(byte[] buffer) throws IOException {
+ writeBytes(buffer);
+ }
+
+ @Override
+ public void write(byte[] buffer, int offset, int length) throws IOException {
+ writeBytes(buffer, offset, length);
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ writeByte((byte) b);
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractSerializer.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractSerializer.java
new file mode 100644
index 000000000..a60980354
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/AbstractSerializer.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2016 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import com.google.common.base.Objects;
+
+/**
+ * This abstract class provide a sensible default implementation for {@code Serializer} equality. This equality
+ * implementation is required to enable cache instance reuse within the same Gradle runtime. Serializers are used
+ * as cache parameter which need to be compared to determine compatible cache.
+ */
+public abstract class AbstractSerializer implements Serializer {
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+
+ return Objects.equal(obj.getClass(), getClass());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(getClass());
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Cast.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Cast.java
new file mode 100644
index 000000000..4f962cea6
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Cast.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2012 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import javax.annotation.Nullable;
+
+public abstract class Cast {
+
+ /**
+ * Casts the given object to the given type, providing a better error message than the default.
+ *
+ * The standard {@link Class#cast(Object)} method produces unsatisfactory error messages on some platforms
+ * when it fails. All this method does is provide a better, consistent, error message.
+ *
+ * This should be used whenever there is a chance the cast could fail. If in doubt, use this.
+ *
+ * @param outputType The type to cast the input to
+ * @param object The object to be cast (must not be {@code null})
+ * @param The type to be cast to
+ * @param The type of the object to be vast
+ * @return The input object, cast to the output type
+ */
+ public static O cast(Class outputType, I object) {
+ try {
+ return outputType.cast(object);
+ } catch (ClassCastException e) {
+ throw new ClassCastException(String.format(
+ "Failed to cast object %s of type %s to target type %s", object, object.getClass().getName(), outputType.getName()
+ ));
+ }
+ }
+
+ /**
+ * Casts the given object to the given type, providing a better error message than the default.
+ *
+ * The standard {@link Class#cast(Object)} method produces unsatisfactory error messages on some platforms
+ * when it fails. All this method does is provide a better, consistent, error message.
+ *
+ * This should be used whenever there is a chance the cast could fail. If in doubt, use this.
+ *
+ * @param outputType The type to cast the input to
+ * @param object The object to be cast
+ * @param The type to be cast to
+ * @param The type of the object to be vast
+ * @return The input object, cast to the output type
+ */
+ @Nullable
+ public static O castNullable(Class outputType, @Nullable I object) {
+ if (object == null) {
+ return null;
+ }
+ return cast(outputType, object);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Nullable
+ public static T uncheckedCast(@Nullable Object object) {
+ return (T) object;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static T uncheckedNonnullCast(Object object) {
+ return (T) object;
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ClassLoaderObjectInputStream.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ClassLoaderObjectInputStream.java
new file mode 100644
index 000000000..5f9cb3052
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ClassLoaderObjectInputStream.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2010 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree.serialize;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectStreamClass;
+
+public class ClassLoaderObjectInputStream extends ObjectInputStream {
+ private final ClassLoader loader;
+
+ public ClassLoaderObjectInputStream(InputStream in, ClassLoader loader) throws IOException {
+ super(in);
+ this.loader = loader;
+ }
+
+ public ClassLoader getClassLoader() {
+ return loader;
+ }
+
+ @Override
+ protected Class> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
+ try {
+ return Class.forName(desc.getName(), false, loader);
+ } catch (ClassNotFoundException e) {
+ return super.resolveClass(desc);
+ }
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Decoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Decoder.java
new file mode 100644
index 000000000..e5251b8c2
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Decoder.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import javax.annotation.Nullable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Provides a way to decode structured data from a backing byte stream. Implementations may buffer incoming bytes read
+ * from the backing stream prior to decoding.
+ */
+public interface Decoder {
+ /**
+ * Returns an InputStream which can be used to read raw bytes.
+ */
+ InputStream getInputStream();
+
+ /**
+ * Reads a signed 64 bit long value. Can read any value that was written using {@link Encoder#writeLong(long)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the long value can be fully read.
+ */
+ long readLong() throws EOFException, IOException;
+
+ /**
+ * Reads a signed 64 bit int value. Can read any value that was written using {@link Encoder#writeSmallLong(long)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the int value can be fully read.
+ */
+ long readSmallLong() throws EOFException, IOException;
+
+ /**
+ * Reads a signed 32 bit int value. Can read any value that was written using {@link Encoder#writeInt(int)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the int value can be fully read.
+ */
+ int readInt() throws EOFException, IOException;
+
+ /**
+ * Reads a signed 32 bit int value. Can read any value that was written using {@link Encoder#writeSmallInt(int)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the int value can be fully read.
+ */
+ int readSmallInt() throws EOFException, IOException;
+
+ /**
+ * Reads a nullable signed 32 bit int value.
+ *
+ * @see #readSmallInt()
+ */
+ @Nullable
+ Integer readNullableSmallInt() throws EOFException, IOException;
+
+ /**
+ * Reads a boolean value. Can read any value that was written using {@link Encoder#writeBoolean(boolean)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the boolean value can be fully read.
+ */
+ boolean readBoolean() throws EOFException, IOException;
+
+ /**
+ * Reads a non-null string value. Can read any value that was written using {@link Encoder#writeString(CharSequence)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the string can be fully read.
+ */
+ String readString() throws EOFException, IOException;
+
+ /**
+ * Reads a nullable string value. Can reads any value that was written using {@link Encoder#writeNullableString(CharSequence)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the string can be fully read.
+ */
+ @Nullable
+ String readNullableString() throws EOFException, IOException;
+
+ /**
+ * Reads a byte value. Can read any byte value that was written using one of the raw byte methods on {@link Encoder}, such as {@link Encoder#writeByte(byte)} or {@link Encoder#getOutputStream()}
+ *
+ * @throws EOFException when the end of the byte stream is reached.
+ */
+ byte readByte() throws EOFException, IOException;
+
+ /**
+ * Reads bytes into the given buffer, filling the buffer. Can read any byte values that were written using one of the raw byte methods on {@link Encoder}, such as {@link
+ * Encoder#writeBytes(byte[])} or {@link Encoder#getOutputStream()}
+ *
+ * @throws EOFException when the end of the byte stream is reached before the buffer is full.
+ */
+ void readBytes(byte[] buffer) throws EOFException, IOException;
+
+ /**
+ * Reads the specified number of bytes into the given buffer. Can read any byte values that were written using one of the raw byte methods on {@link Encoder}, such as {@link
+ * Encoder#writeBytes(byte[])} or {@link Encoder#getOutputStream()}
+ *
+ * @throws EOFException when the end of the byte stream is reached before the specified number of bytes were read.
+ */
+ void readBytes(byte[] buffer, int offset, int count) throws EOFException, IOException;
+
+ /**
+ * Reads a byte array. Can read any byte array written using {@link Encoder#writeBinary(byte[])} or {@link Encoder#writeBinary(byte[], int, int)}.
+ *
+ * @throws EOFException when the end of the byte stream is reached before the byte array was fully read.
+ */
+ byte[] readBinary() throws EOFException, IOException;
+
+ /**
+ * Skips the given number of bytes. Can skip over any byte values that were written using one of the raw byte methods on {@link Encoder}.
+ */
+ void skipBytes(long count) throws EOFException, IOException;
+
+ /**
+ * Reads a byte stream written using {@link Encoder#encodeChunked(Encoder.EncodeAction)}.
+ */
+ T decodeChunked(DecodeAction decodeAction) throws EOFException, Exception;
+
+ /**
+ * Skips over a byte stream written using {@link Encoder#encodeChunked(Encoder.EncodeAction)}, discarding its content.
+ */
+ void skipChunked() throws EOFException, IOException;
+
+ interface DecodeAction {
+ OUT read(IN source) throws Exception;
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/DefaultSerializer.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/DefaultSerializer.java
new file mode 100644
index 000000000..15ba1c592
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/DefaultSerializer.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree.serialize;
+
+import com.google.common.base.Objects;
+
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.StreamCorruptedException;
+
+public class DefaultSerializer extends AbstractSerializer {
+ private ClassLoader classLoader;
+
+ public DefaultSerializer() {
+ classLoader = getClass().getClassLoader();
+ }
+
+ public DefaultSerializer(ClassLoader classLoader) {
+ this.classLoader = classLoader != null ? classLoader : getClass().getClassLoader();
+ }
+
+ public ClassLoader getClassLoader() {
+ return classLoader;
+ }
+
+ public void setClassLoader(ClassLoader classLoader) {
+ this.classLoader = classLoader;
+ }
+
+ @Override
+ public T read(Decoder decoder) throws Exception {
+ try {
+ return Cast.uncheckedNonnullCast(new ClassLoaderObjectInputStream(decoder.getInputStream(), classLoader).readObject());
+ } catch (StreamCorruptedException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public void write(Encoder encoder, T value) throws IOException {
+ ObjectOutputStream objectStr = new ObjectOutputStream(encoder.getOutputStream());
+ objectStr.writeObject(value);
+ objectStr.flush();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!super.equals(obj)) {
+ return false;
+ }
+
+ DefaultSerializer> rhs = (DefaultSerializer>) obj;
+ return Objects.equal(classLoader, rhs.classLoader);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(super.hashCode(), classLoader);
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Encoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Encoder.java
new file mode 100644
index 000000000..1cdea10af
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Encoder.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * Provides a way to encode structured data to a backing byte stream. Implementations may buffer outgoing encoded bytes prior
+ * to writing to the backing byte stream.
+ */
+public interface Encoder {
+ /**
+ * Returns an {@link OutputStream) that can be used to write raw bytes to the stream.
+ */
+ OutputStream getOutputStream();
+
+ /**
+ * Writes a raw byte value to the stream.
+ */
+ void writeByte(byte value) throws IOException;
+
+ /**
+ * Writes the given raw bytes to the stream. Does not encode any length information.
+ */
+ void writeBytes(byte[] bytes) throws IOException;
+
+ /**
+ * Writes the given raw bytes to the stream. Does not encode any length information.
+ */
+ void writeBytes(byte[] bytes, int offset, int count) throws IOException;
+
+ /**
+ * Writes the given byte array to the stream. Encodes the bytes and length information.
+ */
+ void writeBinary(byte[] bytes) throws IOException;
+
+ /**
+ * Writes the given byte array to the stream. Encodes the bytes and length information.
+ */
+ void writeBinary(byte[] bytes, int offset, int count) throws IOException;
+
+ /**
+ * Appends an encoded stream to this stream. Encodes the stream as a series of chunks with length information.
+ */
+ void encodeChunked(EncodeAction writeAction) throws Exception;
+
+ /**
+ * Writes a signed 64 bit long value. The implementation may encode the value as a variable number of bytes, not necessarily as 8 bytes.
+ */
+ void writeLong(long value) throws IOException;
+
+ /**
+ * Writes a signed 64 bit long value whose value is likely to be small and positive but may not be. The implementation may encode the value in a way that is more efficient for small positive
+ * values.
+ */
+ void writeSmallLong(long value) throws IOException;
+
+ /**
+ * Writes a signed 32 bit int value. The implementation may encode the value as a variable number of bytes, not necessarily as 4 bytes.
+ */
+ void writeInt(int value) throws IOException;
+
+ /**
+ * Writes a signed 32 bit int value whose value is likely to be small and positive but may not be. The implementation may encode the value in a way that
+ * is more efficient for small positive values.
+ */
+ void writeSmallInt(int value) throws IOException;
+
+ /**
+ * Writes a nullable signed 32 bit int value whose value is likely to be small and positive but may not be.
+ *
+ * @see #writeSmallInt(int)
+ */
+ void writeNullableSmallInt(@Nullable Integer value) throws IOException;
+
+ /**
+ * Writes a boolean value.
+ */
+ void writeBoolean(boolean value) throws IOException;
+
+ /**
+ * Writes a non-null string value.
+ */
+ void writeString(CharSequence value) throws IOException;
+
+ /**
+ * Writes a nullable string value.
+ */
+ void writeNullableString(@Nullable CharSequence value) throws IOException;
+
+ interface EncodeAction {
+ void write(T target) throws Exception;
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/FlushableEncoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/FlushableEncoder.java
new file mode 100644
index 000000000..ddef9f5c6
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/FlushableEncoder.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import java.io.Flushable;
+import java.io.IOException;
+
+/**
+ * Represents an {@link Encoder} that buffers encoded data prior to writing to the backing stream.
+ */
+public interface FlushableEncoder extends Encoder, Flushable {
+ /**
+ * Ensures that all buffered data has been written to the backing stream. Does not flush the backing stream.
+ */
+ @Override
+ void flush() throws IOException;
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ObjectReader.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ObjectReader.java
new file mode 100644
index 000000000..fdea08191
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ObjectReader.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2012 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+import java.io.EOFException;
+
+public interface ObjectReader {
+ /**
+ * Reads the next object from the stream.
+ *
+ * @throws EOFException When the next object cannot be fully read due to reaching the end of stream.
+ */
+ T read() throws EOFException, Exception;
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ObjectWriter.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ObjectWriter.java
new file mode 100644
index 000000000..482bdd0f8
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/ObjectWriter.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2012 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+public interface ObjectWriter {
+ void write(T value) throws Exception;
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Serializer.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Serializer.java
new file mode 100644
index 000000000..b474ba3ac
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/Serializer.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2009 the original author or authors.
+ *
+ * Licensed 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.
+ */
+package seaweedfs.client.btree.serialize;
+
+import java.io.EOFException;
+
+public interface Serializer {
+ /**
+ * Reads the next object from the given stream. The implementation must not perform any buffering, so that it reads only those bytes from the input stream that are
+ * required to deserialize the next object.
+ *
+ * @throws EOFException When the next object cannot be fully read due to reaching the end of stream.
+ */
+ T read(Decoder decoder) throws EOFException, Exception;
+
+ /**
+ * Writes the given object to the given stream. The implementation must not perform any buffering.
+ */
+ void write(Encoder encoder, T value) throws Exception;
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/StatefulSerializer.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/StatefulSerializer.java
new file mode 100644
index 000000000..ea677d2c0
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/StatefulSerializer.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2012 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize;
+
+/**
+ * Implementations must allow concurrent reading and writing, so that a thread can read and a thread can write at the same time.
+ * Implementations do not need to support multiple read threads or multiple write threads.
+ */
+public interface StatefulSerializer {
+ /**
+ * Should not perform any buffering
+ */
+ ObjectReader newReader(Decoder decoder);
+
+ /**
+ * Should not perform any buffering
+ */
+ ObjectWriter newWriter(Encoder encoder);
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/KryoBackedDecoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/KryoBackedDecoder.java
new file mode 100644
index 000000000..d8e44a0dc
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/KryoBackedDecoder.java
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize.kryo;
+
+import com.esotericsoftware.kryo.KryoException;
+import com.esotericsoftware.kryo.io.Input;
+import seaweedfs.client.btree.serialize.AbstractDecoder;
+import seaweedfs.client.btree.serialize.Decoder;
+
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Note that this decoder uses buffering, so will attempt to read beyond the end of the encoded data. This means you should use this type only when this decoder will be used to decode the entire
+ * stream.
+ */
+public class KryoBackedDecoder extends AbstractDecoder implements Decoder, Closeable {
+ private final Input input;
+ private final InputStream inputStream;
+ private long extraSkipped;
+ private KryoBackedDecoder nested;
+
+ public KryoBackedDecoder(InputStream inputStream) {
+ this(inputStream, 4096);
+ }
+
+ public KryoBackedDecoder(InputStream inputStream, int bufferSize) {
+ this.inputStream = inputStream;
+ input = new Input(this.inputStream, bufferSize);
+ }
+
+ @Override
+ protected int maybeReadBytes(byte[] buffer, int offset, int count) {
+ return input.read(buffer, offset, count);
+ }
+
+ @Override
+ protected long maybeSkip(long count) throws IOException {
+ // Work around some bugs in Input.skip()
+ int remaining = input.limit() - input.position();
+ if (remaining == 0) {
+ long skipped = inputStream.skip(count);
+ if (skipped > 0) {
+ extraSkipped += skipped;
+ }
+ return skipped;
+ } else if (count <= remaining) {
+ input.setPosition(input.position() + (int) count);
+ return count;
+ } else {
+ input.setPosition(input.limit());
+ return remaining;
+ }
+ }
+
+ private RuntimeException maybeEndOfStream(KryoException e) throws EOFException {
+ if (e.getMessage().equals("Buffer underflow.")) {
+ throw (EOFException) (new EOFException().initCause(e));
+ }
+ throw e;
+ }
+
+ @Override
+ public byte readByte() throws EOFException {
+ try {
+ return input.readByte();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public void readBytes(byte[] buffer, int offset, int count) throws EOFException {
+ try {
+ input.readBytes(buffer, offset, count);
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public long readLong() throws EOFException {
+ try {
+ return input.readLong();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public long readSmallLong() throws EOFException, IOException {
+ try {
+ return input.readLong(true);
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public int readInt() throws EOFException {
+ try {
+ return input.readInt();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public int readSmallInt() throws EOFException {
+ try {
+ return input.readInt(true);
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public boolean readBoolean() throws EOFException {
+ try {
+ return input.readBoolean();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public String readString() throws EOFException {
+ return readNullableString();
+ }
+
+ @Override
+ public String readNullableString() throws EOFException {
+ try {
+ return input.readString();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public void skipChunked() throws EOFException, IOException {
+ while (true) {
+ int count = readSmallInt();
+ if (count == 0) {
+ break;
+ }
+ skipBytes(count);
+ }
+ }
+
+ @Override
+ public T decodeChunked(DecodeAction decodeAction) throws EOFException, Exception {
+ if (nested == null) {
+ nested = new KryoBackedDecoder(new InputStream() {
+ @Override
+ public int read() throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int read(byte[] buffer, int offset, int length) throws IOException {
+ int count = readSmallInt();
+ if (count == 0) {
+ // End of stream has been reached
+ return -1;
+ }
+ if (count > length) {
+ // For now, assume same size buffers used to read and write
+ throw new UnsupportedOperationException();
+ }
+ readBytes(buffer, offset, count);
+ return count;
+ }
+ });
+ }
+ T value = decodeAction.read(nested);
+ if (readSmallInt() != 0) {
+ throw new IllegalStateException("Expecting the end of nested stream.");
+ }
+ return value;
+ }
+
+ /**
+ * Returns the total number of bytes consumed by this decoder. Some additional bytes may also be buffered by this decoder but have not been consumed.
+ */
+ public long getReadPosition() {
+ return input.total() + extraSkipped;
+ }
+
+ @Override
+ public void close() throws IOException {
+ input.close();
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/KryoBackedEncoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/KryoBackedEncoder.java
new file mode 100644
index 000000000..6de3c4db5
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/KryoBackedEncoder.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2013 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize.kryo;
+
+import com.esotericsoftware.kryo.io.Output;
+import seaweedfs.client.btree.serialize.AbstractEncoder;
+import seaweedfs.client.btree.serialize.Encoder;
+import seaweedfs.client.btree.serialize.FlushableEncoder;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class KryoBackedEncoder extends AbstractEncoder implements FlushableEncoder, Closeable {
+ private final Output output;
+ private KryoBackedEncoder nested;
+
+ public KryoBackedEncoder(OutputStream outputStream) {
+ this(outputStream, 4096);
+ }
+
+ public KryoBackedEncoder(OutputStream outputStream, int bufferSize) {
+ output = new Output(outputStream, bufferSize);
+ }
+
+ @Override
+ public void writeByte(byte value) {
+ output.writeByte(value);
+ }
+
+ @Override
+ public void writeBytes(byte[] bytes, int offset, int count) {
+ output.writeBytes(bytes, offset, count);
+ }
+
+ @Override
+ public void writeLong(long value) {
+ output.writeLong(value);
+ }
+
+ @Override
+ public void writeSmallLong(long value) {
+ output.writeLong(value, true);
+ }
+
+ @Override
+ public void writeInt(int value) {
+ output.writeInt(value);
+ }
+
+ @Override
+ public void writeSmallInt(int value) {
+ output.writeInt(value, true);
+ }
+
+ @Override
+ public void writeBoolean(boolean value) {
+ output.writeBoolean(value);
+ }
+
+ @Override
+ public void writeString(CharSequence value) {
+ if (value == null) {
+ throw new IllegalArgumentException("Cannot encode a null string.");
+ }
+ output.writeString(value);
+ }
+
+ @Override
+ public void writeNullableString(@Nullable CharSequence value) {
+ output.writeString(value);
+ }
+
+ @Override
+ public void encodeChunked(EncodeAction writeAction) throws Exception {
+ if (nested == null) {
+ nested = new KryoBackedEncoder(new OutputStream() {
+ @Override
+ public void write(byte[] buffer, int offset, int length) {
+ if (length == 0) {
+ return;
+ }
+ writeSmallInt(length);
+ writeBytes(buffer, offset, length);
+ }
+
+ @Override
+ public void write(byte[] buffer) throws IOException {
+ write(buffer, 0, buffer.length);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ });
+ }
+ writeAction.write(nested);
+ nested.flush();
+ writeSmallInt(0);
+ }
+
+ /**
+ * Returns the total number of bytes written by this encoder, some of which may still be buffered.
+ */
+ public long getWritePosition() {
+ return output.total();
+ }
+
+ @Override
+ public void flush() {
+ output.flush();
+ }
+
+ @Override
+ public void close() {
+ output.close();
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/StringDeduplicatingKryoBackedDecoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/StringDeduplicatingKryoBackedDecoder.java
new file mode 100644
index 000000000..f323daf43
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/StringDeduplicatingKryoBackedDecoder.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2018 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize.kryo;
+
+import com.esotericsoftware.kryo.KryoException;
+import com.esotericsoftware.kryo.io.Input;
+import seaweedfs.client.btree.serialize.AbstractDecoder;
+import seaweedfs.client.btree.serialize.Decoder;
+
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Note that this decoder uses buffering, so will attempt to read beyond the end of the encoded data. This means you should use this type only when this decoder will be used to decode the entire
+ * stream.
+ */
+public class StringDeduplicatingKryoBackedDecoder extends AbstractDecoder implements Decoder, Closeable {
+ public static final int INITIAL_CAPACITY = 32;
+ private final Input input;
+ private final InputStream inputStream;
+ private String[] strings;
+ private long extraSkipped;
+
+ public StringDeduplicatingKryoBackedDecoder(InputStream inputStream) {
+ this(inputStream, 4096);
+ }
+
+ public StringDeduplicatingKryoBackedDecoder(InputStream inputStream, int bufferSize) {
+ this.inputStream = inputStream;
+ input = new Input(this.inputStream, bufferSize);
+ }
+
+ @Override
+ protected int maybeReadBytes(byte[] buffer, int offset, int count) {
+ return input.read(buffer, offset, count);
+ }
+
+ @Override
+ protected long maybeSkip(long count) throws IOException {
+ // Work around some bugs in Input.skip()
+ int remaining = input.limit() - input.position();
+ if (remaining == 0) {
+ long skipped = inputStream.skip(count);
+ if (skipped > 0) {
+ extraSkipped += skipped;
+ }
+ return skipped;
+ } else if (count <= remaining) {
+ input.setPosition(input.position() + (int) count);
+ return count;
+ } else {
+ input.setPosition(input.limit());
+ return remaining;
+ }
+ }
+
+ private RuntimeException maybeEndOfStream(KryoException e) throws EOFException {
+ if (e.getMessage().equals("Buffer underflow.")) {
+ throw (EOFException) (new EOFException().initCause(e));
+ }
+ throw e;
+ }
+
+ @Override
+ public byte readByte() throws EOFException {
+ try {
+ return input.readByte();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public void readBytes(byte[] buffer, int offset, int count) throws EOFException {
+ try {
+ input.readBytes(buffer, offset, count);
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public long readLong() throws EOFException {
+ try {
+ return input.readLong();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public long readSmallLong() throws EOFException, IOException {
+ try {
+ return input.readLong(true);
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public int readInt() throws EOFException {
+ try {
+ return input.readInt();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public int readSmallInt() throws EOFException {
+ try {
+ return input.readInt(true);
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public boolean readBoolean() throws EOFException {
+ try {
+ return input.readBoolean();
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ @Override
+ public String readString() throws EOFException {
+ return readNullableString();
+ }
+
+ @Override
+ public String readNullableString() throws EOFException {
+ try {
+ int idx = readInt();
+ if (idx == -1) {
+ return null;
+ }
+ if (strings == null) {
+ strings = new String[INITIAL_CAPACITY];
+ }
+ String string = null;
+ if (idx >= strings.length) {
+ String[] grow = new String[strings.length * 3 / 2];
+ System.arraycopy(strings, 0, grow, 0, strings.length);
+ strings = grow;
+ } else {
+ string = strings[idx];
+ }
+ if (string == null) {
+ string = input.readString();
+ strings[idx] = string;
+ }
+ return string;
+ } catch (KryoException e) {
+ throw maybeEndOfStream(e);
+ }
+ }
+
+ /**
+ * Returns the total number of bytes consumed by this decoder. Some additional bytes may also be buffered by this decoder but have not been consumed.
+ */
+ public long getReadPosition() {
+ return input.total() + extraSkipped;
+ }
+
+ @Override
+ public void close() throws IOException {
+ strings = null;
+ input.close();
+ }
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/StringDeduplicatingKryoBackedEncoder.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/StringDeduplicatingKryoBackedEncoder.java
new file mode 100644
index 000000000..140933660
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/StringDeduplicatingKryoBackedEncoder.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2018 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize.kryo;
+
+import com.esotericsoftware.kryo.io.Output;
+import com.google.common.collect.Maps;
+import seaweedfs.client.btree.serialize.AbstractEncoder;
+import seaweedfs.client.btree.serialize.FlushableEncoder;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.io.OutputStream;
+import java.util.Map;
+
+public class StringDeduplicatingKryoBackedEncoder extends AbstractEncoder implements FlushableEncoder, Closeable {
+ private Map strings;
+
+ private final Output output;
+
+ public StringDeduplicatingKryoBackedEncoder(OutputStream outputStream) {
+ this(outputStream, 4096);
+ }
+
+ public StringDeduplicatingKryoBackedEncoder(OutputStream outputStream, int bufferSize) {
+ output = new Output(outputStream, bufferSize);
+ }
+
+ @Override
+ public void writeByte(byte value) {
+ output.writeByte(value);
+ }
+
+ @Override
+ public void writeBytes(byte[] bytes, int offset, int count) {
+ output.writeBytes(bytes, offset, count);
+ }
+
+ @Override
+ public void writeLong(long value) {
+ output.writeLong(value);
+ }
+
+ @Override
+ public void writeSmallLong(long value) {
+ output.writeLong(value, true);
+ }
+
+ @Override
+ public void writeInt(int value) {
+ output.writeInt(value);
+ }
+
+ @Override
+ public void writeSmallInt(int value) {
+ output.writeInt(value, true);
+ }
+
+ @Override
+ public void writeBoolean(boolean value) {
+ output.writeBoolean(value);
+ }
+
+ @Override
+ public void writeString(CharSequence value) {
+ if (value == null) {
+ throw new IllegalArgumentException("Cannot encode a null string.");
+ }
+ writeNullableString(value);
+ }
+
+ @Override
+ public void writeNullableString(@Nullable CharSequence value) {
+ if (value == null) {
+ output.writeInt(-1);
+ return;
+ } else {
+ if (strings == null) {
+ strings = Maps.newHashMapWithExpectedSize(1024);
+ }
+ }
+ String key = value.toString();
+ Integer index = strings.get(key);
+ if (index == null) {
+ index = strings.size();
+ output.writeInt(index);
+ strings.put(key, index);
+ output.writeString(key);
+ } else {
+ output.writeInt(index);
+ }
+ }
+
+ /**
+ * Returns the total number of bytes written by this encoder, some of which may still be buffered.
+ */
+ public long getWritePosition() {
+ return output.total();
+ }
+
+ @Override
+ public void flush() {
+ output.flush();
+ }
+
+ @Override
+ public void close() {
+ output.close();
+ }
+
+ public void done() {
+ strings = null;
+ }
+
+}
diff --git a/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/TypeSafeSerializer.java b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/TypeSafeSerializer.java
new file mode 100644
index 000000000..16c00cdf4
--- /dev/null
+++ b/test/random_access/src/main/java/seaweedfs/client/btree/serialize/kryo/TypeSafeSerializer.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2012 the original author or authors.
+ *
+ * Licensed 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.
+ */
+
+package seaweedfs.client.btree.serialize.kryo;
+
+import seaweedfs.client.btree.serialize.*;
+
+public class TypeSafeSerializer implements StatefulSerializer