diff --git a/pom.xml b/pom.xml
index c77468b82..7a3cc0215 100644
--- a/pom.xml
+++ b/pom.xml
@@ -66,7 +66,7 @@
net.openhft
chronicle-wire
- 1.0.0-alpha-SNAPSHOT
+ 1.0.1-alpha-SNAPSHOT
@@ -75,6 +75,7 @@
+
net.openhft
compiler
diff --git a/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java b/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java
index f552148d7..7eb7652fb 100644
--- a/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java
+++ b/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java
@@ -135,4 +135,21 @@ public class BytesChronicleMap implements AbstractChronicleMap {
public Set> entrySet() {
throw new UnsupportedOperationException();
}
+
+ public Bytes put(Bytes key, Bytes value, long timestamp, byte id) {
+ // todo
+ try (ReplicatedChronicleMap.BytesReplicatedContext c = (ReplicatedChronicleMap.BytesReplicatedContext) context(key)) {
+ // We cannot read the previous value using just a read lock, because then we will need
+ // to release the read lock -> acquire write lock, the value might be updated in
+ // between, that will break ConcurrentMap.put() atomicity guarantee. So, we acquire
+ // update lock from the start:
+ c.updateLock().lock();
+ Bytes prevValue = prevValueOnPut(c);
+ c.newTimestamp = timestamp;
+ c.newIdentifier = id;
+ c.writeReplicationBytes();
+ c.put(value);
+ return prevValue;
+ }
+ }
}
diff --git a/src/test/java/eg/MapWireProtocol.java b/src/main/java/net/openhft/chronicle/map/ChannelListProvider.java
similarity index 54%
rename from src/test/java/eg/MapWireProtocol.java
rename to src/main/java/net/openhft/chronicle/map/ChannelListProvider.java
index 4e19f798f..bd8dde12f 100644
--- a/src/test/java/eg/MapWireProtocol.java
+++ b/src/main/java/net/openhft/chronicle/map/ChannelListProvider.java
@@ -16,30 +16,13 @@
* limitations under the License.
*/
-package eg;
+package net.openhft.chronicle.map;
-import net.openhft.chronicle.wire.TextWire;
-import net.openhft.lang.io.AbstractBytes;
-import net.openhft.lang.io.ByteBufferBytes;
-import net.openhft.lang.io.IByteBufferBytes;
-import org.junit.Test;
-
-import java.nio.ByteBuffer;
+import java.util.List;
/**
* Created by Rob Austin
*/
-public class MapWireProtocol {
-
-
- @Test
- public void test() throws Exception {
-
- IByteBufferBytes bytes = ByteBufferBytes.wrap(ByteBuffer.wrap(new byte[1024]));
- new TextWire(bytes).write(() -> "type").text("stateless-map");
- bytes.flip();
-
- System.out.println("XXX" + AbstractBytes.toHex(bytes));
-
- }
+public interface ChannelListProvider {
+ List chronicleChannelList();
}
diff --git a/src/main/java/net/openhft/chronicle/map/ChannelProvider.java b/src/main/java/net/openhft/chronicle/map/ChannelProvider.java
index a175ab469..df180beb2 100644
--- a/src/main/java/net/openhft/chronicle/map/ChannelProvider.java
+++ b/src/main/java/net/openhft/chronicle/map/ChannelProvider.java
@@ -48,7 +48,7 @@ import static net.openhft.chronicle.map.Replica.ModificationNotifier.NOP;
/**
* @author Rob Austin.
*/
-final class ChannelProvider implements Closeable {
+final class ChannelProvider implements Closeable, ChannelListProvider {
private static final Logger LOG = LoggerFactory.getLogger(ChannelProvider.class.getName());
static final Map implMapping = new IdentityHashMap<>();
@@ -66,7 +66,12 @@ final class ChannelProvider implements Closeable {
final TcpReplicator tcpReplicator = new TcpReplicator(
channelProvider.asReplica,
channelProvider.asEntryExternalizable,
- tcpConfig, hub.remoteNodeValidator(), null, hub.name());
+ tcpConfig,
+ hub.remoteNodeValidator(),
+ null,
+ hub.name(),
+ null);
+
channelProvider.add(tcpReplicator);
}
@@ -262,6 +267,12 @@ final class ChannelProvider implements Closeable {
// start of channel data
private final Replica[] chronicleChannels;
+
+ @Override
+ public List chronicleChannelList() {
+ return Collections.unmodifiableList(chronicleChannelList);
+ }
+
private final List chronicleChannelList;
private final List chronicleChannelIds;
private final EntryExternalizable[] channelEntryExternalizables;
diff --git a/src/main/java/net/openhft/chronicle/map/Replica.java b/src/main/java/net/openhft/chronicle/map/Replica.java
index 5f233fac0..c3643fd4d 100644
--- a/src/main/java/net/openhft/chronicle/map/Replica.java
+++ b/src/main/java/net/openhft/chronicle/map/Replica.java
@@ -164,9 +164,8 @@ interface Replica extends Closeable {
* writeExternalEntry()}. This method is typically called when we receive a remote
* replication event, this event could originate from either a remote {@code put(K key, V
*value)} or {@code remove(Object key)}
- * @param copies
- * @param context
- * @param source bytes to read an entry from
+ * @param context a replicated context
+ * @param source bytes to read an entry from
*/
void readExternalEntry(
@NotNull ReplicatedChronicleMap.BytesReplicatedContext context, @NotNull Bytes source);
@@ -210,7 +209,7 @@ interface Replica extends Closeable {
/**
* Called whenever a put() or remove() has occurred to a replicating map.
*
- * @param context the entry you will receive, this does not have to be locked, as
+ * @param entry the entry you will receive, this does not have to be locked, as
* locking is already provided from the caller.
* @param chronicleId only assigned when clustering
* @return {@code false} if this entry should be ignored because the identifier of the
@@ -220,13 +219,13 @@ interface Replica extends Closeable {
public abstract boolean onEntry(final Bytes entry, final int chronicleId);
/**
- * Called just after {@link #onEntry(VanillaContext, int)}. No-op by default.
+ * Called just after {@link #onEntry(net.openhft.lang.io.Bytes, int)}. No-op by default.
*/
public void onAfterEntry() {
}
/**
- * Called just before {@link #onEntry(VanillaContext, int)}. No-op by default.
+ * Called just before {@link #onEntry(net.openhft.lang.io.Bytes, int)}. No-op by default.
*/
public void onBeforeEntry() {
}
diff --git a/src/main/java/net/openhft/chronicle/map/Replicators.java b/src/main/java/net/openhft/chronicle/map/Replicators.java
index d72209de9..3b235658d 100644
--- a/src/main/java/net/openhft/chronicle/map/Replicators.java
+++ b/src/main/java/net/openhft/chronicle/map/Replicators.java
@@ -127,7 +127,8 @@ final class Replicators {
return new TcpReplicator(replica, entryExternalizable,
tcpConfig,
replication.remoteNodeValidator(), statelessClientParameters,
- replication.name());
+ replication.name(),
+ null);
}
};
}
diff --git a/src/main/java/net/openhft/chronicle/map/StatelessWiredConnector.java b/src/main/java/net/openhft/chronicle/map/StatelessWiredConnector.java
index b20d43c2d..9b616971f 100644
--- a/src/main/java/net/openhft/chronicle/map/StatelessWiredConnector.java
+++ b/src/main/java/net/openhft/chronicle/map/StatelessWiredConnector.java
@@ -22,801 +22,241 @@ package net.openhft.chronicle.map;
* Created by Rob Austin
*/
-import net.openhft.chronicle.hash.function.SerializableFunction;
-import net.openhft.chronicle.hash.serialization.BytesReader;
-import net.openhft.chronicle.hash.serialization.internal.ReaderWithSize;
-import net.openhft.chronicle.hash.serialization.internal.SerializationBuilder;
+import net.openhft.chronicle.bytes.Bytes;
+import net.openhft.chronicle.bytes.BytesMarshallable;
import net.openhft.chronicle.wire.TextWire;
-import net.openhft.chronicle.wire.ValueIn;
-import net.openhft.lang.io.AbstractBytes;
-import net.openhft.lang.io.ByteBufferBytes;
-import net.openhft.lang.io.Bytes;
-import net.openhft.lang.model.DataValueClasses;
-import net.openhft.lang.model.DataValueGenerator;
-import net.openhft.lang.threadlocal.ThreadLocalCopies;
-import net.openhft.lang.values.LongValue;
-import net.openhft.xstream.converters.DataValueConverter;
+import net.openhft.chronicle.wire.Wire;
+import net.openhft.lang.io.DirectStore;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import java.util.*;
-import java.util.function.LongConsumer;
-
-import static net.openhft.chronicle.map.AbstractChannelReplicator.SIZE_OF_SIZE;
-import static net.openhft.chronicle.map.AbstractChannelReplicator.SIZE_OF_TRANSACTION_ID;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.ByteBuffer;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.SocketChannel;
+import java.util.ArrayList;
+import java.util.List;
/**
* @author Rob Austin.
*/
-class StatelessWiredConnector {
-
- public static final StatelessChronicleMap.EventId[] VALUES
- = StatelessChronicleMap.EventId.values();
- public static final int SIZE_OF_IS_EXCEPTION = 1;
- public static final int HEADER_SIZE = SIZE_OF_SIZE + SIZE_OF_IS_EXCEPTION +
- SIZE_OF_TRANSACTION_ID;
- private static final Logger LOG = LoggerFactory.getLogger(StatelessServerConnector.class
- .getName());
- @NotNull
- private final ReaderWithSize keyReaderWithSize;
-
- @NotNull
- private final WriterWithSize keyWriterWithSize;
-
- @NotNull
- private final ReaderWithSize valueReaderWithSize;
-
- @NotNull
- private final WriterWithSize valueWriterWithSize;
-
- @NotNull
- private final VanillaChronicleMap map;
- private final BytesChronicleMap bytesMap;
- private final SerializationBuilder keySerializationBuilder;
- private final SerializationBuilder valueSerializationBuilder;
- private final int tcpBufferSize;
+class StatelessWiredConnector {
- StatelessWiredConnector(
- @NotNull VanillaChronicleMap map,
- @NotNull final BufferResizer bufferResizer, int tcpBufferSize,
- final SerializationBuilder keySerializationBuilder,
- final SerializationBuilder valueSerializationBuilder) {
- this.tcpBufferSize = tcpBufferSize;
+ private boolean handshingComplete;
+ // private final byte identifier;
- this.keySerializationBuilder = keySerializationBuilder;
- this.valueSerializationBuilder = valueSerializationBuilder;
- keyReaderWithSize = new ReaderWithSize<>(keySerializationBuilder);
- keyWriterWithSize = new WriterWithSize<>(keySerializationBuilder, bufferResizer);
- valueReaderWithSize = new ReaderWithSize<>(valueSerializationBuilder);
- valueWriterWithSize = new WriterWithSize<>(valueSerializationBuilder, bufferResizer);
- this.map = map;
- bytesMap = new BytesChronicleMap(map);
+ @Nullable
+ // maybe null if the server has not been set up to use channel
+ private List channelList;
+
+ private ArrayList bytesChronicleMaps = new ArrayList<>();
+ private TextWire inWire = new TextWire(Bytes.elasticByteBuffer());
+ private TextWire outWire = new TextWire(Bytes.elasticByteBuffer());
+
+ private byte identifier;
+ private long transactionId;
+ private long timestamp;
+ private short channelId;
+ private String methodName;
+
+ public StatelessWiredConnector(@Nullable List channelList) {
+ this.channelList = channelList;
+ // final TextWire inWire = new TextWire(toChronicleBytes(inBytes));
+ // this.identifier = inWire.read(() -> "IDENTIFIER").int8();
+ }
+
+ public void onRead(SocketChannel socketChannel, SelectionKey key) throws IOException {
+ socketChannel.read(inWireBuffer());
+
+ if (nextWireMessage() == null)
+ return;
+
+ if (handshingComplete) {
+ onEvent();
+ } else
+ onHandShaking();
+
+ }
+
+ public void onWrite(SocketChannel socketChannel, SelectionKey key) throws IOException {
+ socketChannel.write((ByteBuffer) outWire.bytes());
+ if (outWire.bytes().remaining() == 0) {
+ ((ByteBuffer) outWire.bytes().underlyingObject()).clear();
+ outWire.bytes().clear();
+ }
+ }
+
+
+ private Wire nextWireMessage() {
+ if (inWireBuffer().remaining() < 4)
+ return null;
+
+ final Bytes> bytes = inWire.bytes();
+ int size = bytes.readInt(bytes.position());
+
+ inWire.bytes().ensureCapacity(bytes.position() + size);
+
+ if (bytes.remaining() < size) {
+ return null;
+ }
+
+ inWire.bytes().limit(bytes.position() + size);
+ inWire.bytes().position(inWire.bytes().position() + 2);
+ return inWire;
+ }
+
+ private ByteBuffer inWireBuffer() {
+ return (ByteBuffer) inWire.bytes().underlyingObject();
+ }
+
+
+ void onHandShaking() {
+ identifier = inWire.read(() -> "IDENTIFIER").int8();
+ handshingComplete = true;
}
@Nullable
- Work processStatelessEvent(final TextWire textWire,
- @NotNull final TcpReplicator.TcpSocketChannelEntryWriter writer,
- @NotNull final ByteBufferBytes reader) {
+ Work onEvent() {
+ // it is assumed by this point that the buffer has all the bytes in it for this message
+ transactionId = inWire.read(() -> "TRANSACTION_ID").int64();
+ timestamp = inWire.read(() -> "TIME_STAMP").int64();
+ channelId = inWire.read(() -> "CHANNEL_ID").int16();
+ methodName = inWire.read(() -> "METHOD_NAME").text();
- final String methodName = textWire.read(() -> "METHOD_NAME").text();
+ // for the length
+ outWire.bytes().skip(4);
- long transactionId;
-
- ValueIn read = textWire.read(() -> "TRANSACTION_ID");
-
- LongValue longValue = DataValueClasses.newDirectInstance(LongValue.class);
- textWire.read(() -> "TRANSACTION_ID").int64(longValue);
- long transacationId = longValue.getValue();
-
-
- final String identifier = textWire.read(() -> "IDENTIFIER").text();
- final String timestamp = textWire.read(() -> "TIMESTAMP").text();
-
-
- // these methods don't return a result to the client or don't return a result to the
- // client immediately
- switch (methodName) {
- case "KEY_SET":
- return keySet(reader, writer, transactionId);
-
- case "VALUES":
- return values(reader, writer, transactionId);
-
- case "ENTRY_SET":
- return entrySet(reader, writer, transactionId);
-
- case "PUT_WITHOUT_ACC":
- return put(reader, timestamp, identifier);
-
- case "PUT_ALL_WITHOUT_ACC":
- return putAll(reader, timestamp, identifier);
-
- case "REMOVE_WITHOUT_ACC":
- return remove(reader, timestamp, identifier);
- }
-
- final long sizeLocation = reflectTransactionId(writer.in(), transactionId);
-
-
- // these methods return a result
+ // write the transaction id
+ outWire.write(() -> "TRANSACTION_ID").int64(transactionId);
switch (methodName) {
- case "LONG_SIZE":
- return longSize(writer, sizeLocation);
-
- case "IS_EMPTY":
- return isEmpty(writer, sizeLocation);
-
- case "CONTAINS_KEY":
- return containsKey(reader, writer, sizeLocation);
-
- case "CONTAINS_VALUE":
- return containsValue(reader, writer, sizeLocation);
-
- case "GET":
- return get(reader, writer, sizeLocation, timestamp);
case "PUT":
- return put(reader, writer, sizeLocation, timestamp, identifier);
-
- case "REMOVE":
- return remove(reader, writer, sizeLocation, timestamp, identifier);
-
- case "CLEAR":
- return clear(writer, sizeLocation, timestamp, identifier);
-
- case "REPLACE":
- return replace(reader, writer, sizeLocation, timestamp, identifier);
-
- case "REPLACE_WITH_OLD_AND_NEW_VALUE":
- return replaceWithOldAndNew(reader, writer,
- sizeLocation, timestamp, identifier);
-
- case "PUT_IF_ABSENT":
- return putIfAbsent(reader, writer, sizeLocation, timestamp, identifier);
-
- case "REMOVE_WITH_VALUE":
- return removeWithValue(reader, writer, sizeLocation, timestamp, identifier);
-
- case "TO_STRING":
- return toString(writer, sizeLocation);
-
- case "APPLICATION_VERSION":
- return applicationVersion(writer, sizeLocation);
-
- case "PERSISTED_DATA_VERSION":
- return persistedDataVersion(writer, sizeLocation);
-
- case "PUT_ALL":
- return putAll(reader, writer, sizeLocation, timestamp, identifier);
-
- case "HASH_CODE":
- return hashCode(writer, sizeLocation);
-
- case "MAP_FOR_KEY":
- return mapForKey(reader, writer, sizeLocation);
-
- case "PUT_MAPPED":
- return putMapped(reader, writer, sizeLocation);
-
- case "KEY_BUILDER":
- return writeBuilder(writer, sizeLocation, keySerializationBuilder);
-
- case "VALUE_BUILDER":
- return writeBuilder(writer, sizeLocation, valueSerializationBuilder);
+ return put();
default:
- throw new IllegalStateException("unsupported event=" + event);
+ throw new IllegalStateException("unsupported event=" + methodName);
}
}
- private void writeObject(TcpReplicator.TcpSocketChannelEntryWriter writer, Object o) {
- for (; ; ) {
- long position = writer.in().position();
+ /**
+ * gets the map for this channel id
+ *
+ * @param channelId the ID of the map
+ * @return the chronicle map with this {@code channelId}
+ */
+ private ReplicatedChronicleMap map(short channelId) {
- try {
- writer.in().writeObject(o);
- return;
- } catch (IllegalStateException e) {
- if (e.getMessage().contains("Not enough available space")) {
- writer.resizeToMessage(e);
- writer.in().position(position);
- } else
- throw e;
- }
- }
+ // todo this cast is a bit of a hack, improve later
+ final ReplicatedChronicleMap replicas =
+ (ReplicatedChronicleMap) channelList.get(channelId - 1);
+
+ if (replicas != null)
+ return replicas;
+
+ throw new IllegalStateException();
}
- private Work writeBuilder(TcpReplicator.TcpSocketChannelEntryWriter writer,
- long sizeLocation, SerializationBuilder builder) {
+ /**
+ * this is used to push the data straight into the entry in memory
+ *
+ * @param channelId the ID of the map
+ * @return a BytesChronicleMap used to update the memory which holds the chronicle map
+ */
+ private BytesChronicleMap bytesMap(short channelId) {
- try {
- writeObject(writer, builder);
- } catch (Exception e) {
- LOG.info("", e);
+ final BytesChronicleMap bytesChronicleMap = bytesChronicleMaps.get(channelId - 1);
- return sendException(writer, sizeLocation, e);
+ if (bytesChronicleMap != null)
+ return bytesChronicleMap;
+
+ // grow the array
+ for (int i = bytesChronicleMaps.size(); i < channelId; i++) {
+ bytesChronicleMaps.add(null);
}
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
+ final ReplicatedChronicleMap delegate = map(channelId);
+ final BytesChronicleMap element = new BytesChronicleMap(delegate);
+ bytesChronicleMaps.set(channelId - 1, element);
+ return element;
+
}
+ private void writeLength(@NotNull final Wire textWire,
+ @NotNull final TcpReplicator.TcpSocketChannelEntryWriter writer) {
+
+ if (writer.in().position() > Integer.MAX_VALUE)
+ throw new IllegalStateException("position too large");
+
+ // write the size
+ textWire.bytes().writeInt(0, (int) textWire.bytes().position());
+ }
+
+ /**
+ * creates a lang buffer that holds just the payload of the args
+ *
+ * @param wire the inbound wire
+ * @param args the key names of the {@code wire} args
+ * @return a new lang buffer containing the bytes of the args
+ */
+ private net.openhft.lang.io.Bytes toReader(@NotNull Wire wire, @NotNull String... args) {
+
+ long inSize = wire.bytes().limit();
+ final net.openhft.lang.io.Bytes bytes = DirectStore.allocate(inSize).bytes();
+
+ // copy the bytes to the reader
+ for (final String field : args) {
+ wire.read(() -> field).bytes(source -> {
+ bytes.writeStopBit(source.length);
+ bytes.write(source);
+ });
+ }
+
+ return bytes.flip();
+ }
+
@Nullable
- public Work mapForKey(@NotNull ByteBufferBytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- long sizeLocation) {
- final K key = keyReaderWithSize.read(reader, null, null);
- final SerializableFunction function = (SerializableFunction) reader.readObject();
- try {
- Object result = map.getMapped(key, function);
- writeObject(writer, result);
- } catch (Throwable e) {
- LOG.info("", e);
- return sendException(writer, sizeLocation, e);
- }
-
- writeSizeAndFlags(sizeLocation, false, writer.in());
+ private Work sendException(@NotNull Wire wire, @NotNull Throwable e) {
+ final StringWriter sw = new StringWriter();
+ final PrintWriter pw = new PrintWriter(sw);
+ e.printStackTrace(pw);
+ wire.write(() -> "EXCEPTION").text(sw.toString());
return null;
}
@Nullable
- public Work putMapped(@NotNull ByteBufferBytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- long sizeLocation) {
- final K key = keyReaderWithSize.read(reader, null, null);
- final UnaryOperator unaryOperator = (UnaryOperator) reader.readObject();
- try {
- Object result = map.putMapped(key, unaryOperator);
- writeObject(writer, result);
- } catch (Throwable e) {
- LOG.info("", e);
- return sendException(writer, sizeLocation, e);
- }
+ private Work put() {
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work removeWithValue(Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long timestamp, byte id) {
- try {
- writer.ensureBufferSize(1L);
- writer.in().writeBoolean(bytesMap.remove(reader, reader));
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work replaceWithOldAndNew(Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long timestamp, byte id) {
- try {
- writer.ensureBufferSize(1L);
- writer.in().writeBoolean(bytesMap.replace(reader, reader, reader));
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work longSize(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
- try {
- writer.in().writeLong(map.longSize());
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work hashCode(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
- try {
- writer.in().writeInt(map.hashCode());
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
-
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work toString(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
- final String str;
-
- final long remaining = writer.in().remaining();
- try {
- str = map.toString();
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
-
- assert remaining > 4;
-
- // this stops the toString overflowing the buffer
- final String result = (str.length() < remaining) ?
- str :
- str.substring(0, (int) (remaining - 4)) + "...";
-
- writeObject(writer, result);
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
+ final net.openhft.lang.io.Bytes reader = toReader(inWire, "ARG_1", "ARG_2");
- @Nullable
- private Work applicationVersion(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
+ // move the lang bytes to the same location as the chronicle bytes
- final long remaining = writer.in().remaining();
- try {
- String result = map.applicationVersion();
- writeObject(writer, result);
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
+ // todo - in comment code below
+ /* writer.in().position(out.bytes().position());
- assert remaining > 4;
-
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
-
- @Nullable
- private Work persistedDataVersion(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
- final long remaining = writer.in().remaining();
- try {
- String result = map.persistedDataVersion();
- writeObject(writer, result);
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
-
- assert remaining > 4;
-
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @SuppressWarnings("SameReturnValue")
- @Nullable
- private Work sendException(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- long sizeLocation, @NotNull Throwable e) {
- // move the position to ignore any bytes written so far
- writer.in().position(sizeLocation + HEADER_SIZE);
-
- writeException(writer, e);
-
- writeSizeAndFlags(sizeLocation + SIZE_OF_TRANSACTION_ID, true, writer.in());
- return null;
- }
-
- @Nullable
- private Work isEmpty(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
- try {
- writer.in().writeBoolean(map.isEmpty());
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
-
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work containsKey(Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
- try {
- writer.in().writeBoolean(bytesMap.containsKey(reader));
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work containsValue(Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation) {
- // todo optimize -- eliminate
- final V v = valueReaderWithSize.read(reader, null, null);
-
- try {
- writer.in().writeBoolean(map.containsValue(v));
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work get(Bytes reader,
- TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long transactionId) {
+ final BytesChronicleMap bytesMap = bytesMap(channelId);
bytesMap.output = writer;
+
try {
- bytesMap.get(reader);
+ bytesMap.put(reader, reader, timestamp, identifier);
} catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
+ // move back to the start
+ out.bytes().position(2);
+ return sendException(out, e);
} finally {
bytesMap.output = null;
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
+ writeLength(out, writer);
+ }*/
+
return null;
}
- @SuppressWarnings("SameReturnValue")
- @Nullable
- private Work put(Bytes reader, long timestamp, byte id) {
- bytesMap.put(reader, reader);
- return null;
- }
-
- @Nullable
- private Work put(Bytes reader, TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long timestamp, byte id) {
- bytesMap.output = writer;
- try {
- bytesMap.put(reader, reader);
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- } finally {
- bytesMap.output = null;
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @SuppressWarnings("SameReturnValue")
- @Nullable
- private Work remove(Bytes reader, long timestamp, byte id) {
- bytesMap.remove(reader);
- return null;
- }
-
- @Nullable
- private Work remove(Bytes reader, TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long timestamp, byte id) {
- bytesMap.output = writer;
- try {
- bytesMap.remove(reader);
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- } finally {
- bytesMap.output = null;
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work putAll(@NotNull Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation,
- long timestamp, byte id) {
- try {
- bytesMap.putAll(reader);
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @SuppressWarnings("SameReturnValue")
- @Nullable
- private Work putAll(@NotNull Bytes reader, long timestamp, byte id) {
- bytesMap.putAll(reader);
- return null;
- }
-
- @Nullable
- private Work clear(@NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long timestamp, byte id) {
- try {
- map.clear();
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- }
-
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work values(@NotNull Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long transactionId) {
-
- Collection values;
-
- try {
- values = map.values();
- } catch (Throwable e) {
- return sendException(reader, writer, e);
- }
-
- final Iterator iterator = values.iterator();
-
- // this allows us to write more data than the buffer will allow
- return new Work() {
- @Override
- public boolean doWork(@NotNull Bytes out) {
- final long sizeLocation = header(out, transactionId);
-
- ThreadLocalCopies copies = valueWriterWithSize.getCopies(null);
- Object valueWriter = valueWriterWithSize.writerForLoop(copies);
-
- int count = 0;
- while (iterator.hasNext()) {
- // we've filled up the buffer, so lets give another channel a chance to send
- // some data, we don't know the max key size, we will use the entrySize instead
- if (out.position() > tcpBufferSize) {
- writeHeader(out, sizeLocation, count, true);
- return false;
- }
-
- count++;
-
- valueWriterWithSize.writeInLoop(out, iterator.next(), valueWriter, copies);
- }
-
- writeHeader(out, sizeLocation, count, false);
- return true;
- }
- };
- }
-
- @Nullable
- private Work keySet(@NotNull Bytes reader,
- @NotNull final TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long transactionId) {
-
- Set ks;
-
- try {
- ks = map.keySet();
- } catch (Throwable e) {
- return sendException(reader, writer, e);
- }
-
- final Iterator iterator = ks.iterator();
-
- // this allows us to write more data than the buffer will allow
- return new Work() {
- @Override
- public boolean doWork(@NotNull Bytes out) {
- final long sizeLocation = header(out, transactionId);
-
- ThreadLocalCopies copies = keyWriterWithSize.getCopies(null);
- Object keyWriter = keyWriterWithSize.writerForLoop(copies);
-
- int count = 0;
- while (iterator.hasNext()) {
- // we've filled up the buffer, so lets give another channel a chance to send
- // some data, we don't know the max key size, we will use the entrySize instead
- if (out.position() > tcpBufferSize) {
- writeHeader(out, sizeLocation, count, true);
- return false;
- }
-
- count++;
- K key = iterator.next();
- keyWriterWithSize.writeInLoop(out, key, keyWriter, copies);
- }
-
- writeHeader(out, sizeLocation, count, false);
- return true;
- }
- };
- }
-
- @Nullable
- private Work entrySet(@NotNull final Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long transactionId) {
-
- final Set> entries;
-
- try {
- entries = map.entrySet();
- } catch (Throwable e) {
- return sendException(reader, writer, e);
- }
-
- final Iterator> iterator = entries.iterator();
-
- // this allows us to write more data than the buffer will allow
- return new Work() {
- @Override
- public boolean doWork(@NotNull Bytes out) {
- if (out.position() > tcpBufferSize)
- return false;
-
- final long sizeLocation = header(out, transactionId);
-
- ThreadLocalCopies copies = keyWriterWithSize.getCopies(null);
- Object keyWriter = keyWriterWithSize.writerForLoop(copies);
- copies = valueWriterWithSize.getCopies(copies);
- Object valueWriter = valueWriterWithSize.writerForLoop(copies);
-
- int count = 0;
- while (iterator.hasNext()) {
- // we've filled up the buffer, so lets give another channel a chance to send
- // some data, we don't know the max key size, we will use the entrySize instead
- if (out.position() > tcpBufferSize) {
- writeHeader(out, sizeLocation, count, true);
- return false;
- }
-
- count++;
- final Map.Entry next = iterator.next();
- keyWriterWithSize.writeInLoop(out, next.getKey(), keyWriter, copies);
- valueWriterWithSize.writeInLoop(out, next.getValue(), valueWriter, copies);
- }
-
- writeHeader(out, sizeLocation, count, false);
- return true;
- }
- };
- }
-
- @Nullable
- private Work putIfAbsent(Bytes reader, TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long timestamp, byte id) {
- bytesMap.output = writer;
- try {
- bytesMap.putIfAbsent(reader, reader);
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- } finally {
- bytesMap.output = null;
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- @Nullable
- private Work replace(Bytes reader, TcpReplicator.TcpSocketChannelEntryWriter writer,
- final long sizeLocation, long timestamp, byte id) {
- bytesMap.output = writer;
- try {
- bytesMap.replace(reader, reader);
- } catch (Throwable e) {
- return sendException(writer, sizeLocation, e);
- } finally {
- bytesMap.output = null;
- }
- writeSizeAndFlags(sizeLocation, false, writer.in());
- return null;
- }
-
- private long reflectTransactionId(@NotNull Bytes writer, final long transactionId) {
- final long sizeLocation = writer.position();
- writer.skip(SIZE_OF_SIZE);
- assert transactionId != 0;
- writer.writeLong(transactionId);
- writer.writeBoolean(false); // isException
- return sizeLocation;
- }
-
- private void writeSizeAndFlags(long locationOfSize, boolean isException, @NotNull Bytes out) {
- final long size = out.position() - locationOfSize;
-
- out.writeInt(locationOfSize, (int) size); // size
-
- // write isException
- out.writeBoolean(locationOfSize + SIZE_OF_SIZE + SIZE_OF_TRANSACTION_ID, isException);
-
- long pos = out.position();
- long limit = out.limit();
-
- // System.out.println("Sending with size=" + size);
-
- if (LOG.isDebugEnabled()) {
- out.position(locationOfSize);
- out.limit(pos);
- LOG.info("Sending to the stateless client, bytes=" + AbstractBytes.toHex(out) + "," +
- "len=" + out.remaining());
- out.limit(limit);
- out.position(pos);
- }
-
-
- }
-
- private void writeException(@NotNull TcpReplicator.TcpSocketChannelEntryWriter out,
- Throwable e) {
- writeObject(out, e);
- }
-
- @NotNull
- private Map readEntries(@NotNull Bytes reader) {
- final long numberOfEntries = reader.readStopBit();
- final Map result = new HashMap();
-
- ThreadLocalCopies copies = keyReaderWithSize.getCopies(null);
- BytesReader keyReader = keyReaderWithSize.readerForLoop(copies);
- copies = valueReaderWithSize.getCopies(copies);
- BytesReader valueReader = valueReaderWithSize.readerForLoop(copies);
-
- for (long i = 0; i < numberOfEntries; i++) {
- K key = keyReaderWithSize.readInLoop(reader, keyReader);
- V value = valueReaderWithSize.readInLoop(reader, valueReader);
- result.put(key, value);
- }
- return result;
- }
-
- @Nullable
- private Work sendException(@NotNull Bytes reader,
- @NotNull TcpReplicator.TcpSocketChannelEntryWriter writer,
- @NotNull Throwable e) {
- final long sizeLocation = reflectTransactionId(writer.in(), reader.readLong());
- return sendException(writer, sizeLocation, e);
- }
-
- private long header(@NotNull Bytes writer, final long transactionId) {
- final long sizeLocation = writer.position();
-
- writer.skip(SIZE_OF_SIZE);
- writer.writeLong(transactionId);
-
- // exception
- writer.skip(1);
-
- // hasAnotherChunk
- writer.skip(1);
-
- // count
- writer.skip(4);
- return sizeLocation;
- }
-
- private void writeHeader(@NotNull Bytes writer, long sizeLocation, int count,
- final boolean hasAnotherChunk) {
- final long end = writer.position();
- final int size = (int) (end - sizeLocation);
- writer.position(sizeLocation);
-
- // size in bytes
- writer.writeInt(size);
-
- //transaction id;
- writer.skip(8);
-
- // is exception
- writer.writeBoolean(false);
-
- writer.writeBoolean(hasAnotherChunk);
-
- // count
- writer.writeInt(count);
- writer.position(end);
- }
}
diff --git a/src/main/java/net/openhft/chronicle/map/TcpReplicator.java b/src/main/java/net/openhft/chronicle/map/TcpReplicator.java
index 813321950..f361ed981 100644
--- a/src/main/java/net/openhft/chronicle/map/TcpReplicator.java
+++ b/src/main/java/net/openhft/chronicle/map/TcpReplicator.java
@@ -72,11 +72,11 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
public static final long TIMESTAMP_FACTOR = 10000;
private static final int STATELESS_CLIENT = -127;
+ private static final int WIRED_CONNECTION = -126;
private static final byte NOT_SET = (byte) HEARTBEAT.ordinal();
private static final Logger LOG = LoggerFactory.getLogger(TcpReplicator.class.getName());
private static final int BUFFER_SIZE = 0x100000; // 1MB
- private static int USE_WIRE = ByteBufferBytes.wrap(ByteBuffer.wrap(new byte[]{74, 79, 70, 65})).readInt();
- private final WireStatelessServerMap wiredStatelessServer = new WireStatelessServerMap();
+
public static final long SPIN_LOOP_TIME_IN_NONOSECONDS = TimeUnit.MICROSECONDS.toNanos(500);
private final SelectionKey[] selectionKeysStore = new SelectionKey[Byte.MAX_VALUE + 1];
// used to instruct the selector thread to set OP_WRITE on a key correlated by the bit index
@@ -85,6 +85,10 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
new KeyInterestUpdater(OP_WRITE, selectionKeysStore);
private final BitSet activeKeys = new BitSet(selectionKeysStore.length);
private final long heartBeatIntervalMillis;
+
+ @Nullable
+ final List channelList;
+
private long largestEntrySoFar = 128;
@NotNull
@@ -128,12 +132,14 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
@NotNull final TcpTransportAndNetworkConfig replicationConfig,
@Nullable final RemoteNodeValidator remoteNodeValidator,
@Nullable final StatelessClientParameters statelessClientParameters,
- String name)
+ String name,
+ @Nullable final List channelList)
throws IOException {
super("TcpSocketReplicator-" + replica.identifier(), replicationConfig.throttlingConfig());
this.statelessClientParameters = statelessClientParameters;
+ this.channelList = channelList;
final ThrottlingConfig throttlingConfig = replicationConfig.throttlingConfig();
long throttleBucketInterval = throttlingConfig.bucketInterval(MILLISECONDS);
@@ -585,24 +591,14 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
socketChannel.register(selector, OP_READ | OP_WRITE, attached);
- if (reader.out.limit() < 6)
- return;
-
- if (reader.out.readInt(2) == USE_WIRE && reader.out.position() == 0) {
-
- if (reader.out.remaining() < reader.out.readUnsignedShort(0))
- return;
-
- // skip the len
- reader.out.skip(2);
-
- wiredStatelessServer.doHandshaking(reader.out);
- }
-
-
if (attached.remoteIdentifier == Byte.MIN_VALUE) {
final byte remoteIdentifier = reader.identifierFromBuffer();
+ if (remoteIdentifier == WIRED_CONNECTION) {
+ attached.handShakingComplete = true;
+ return;
+ }
+
if (remoteIdentifier == STATELESS_CLIENT) {
attached.handShakingComplete = true;
attached.hasRemoteHeartbeatInterval = false;
@@ -626,7 +622,6 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
// this can occur sometimes when if 2 or more remote node attempt to use node discovery
// at the same time
-
final SocketAddress remoteAddress = socketChannel.getRemoteAddress();
if ((remoteNodeValidator != null &&
@@ -724,6 +719,12 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
return;
}
+ if (attached.useWire) {
+ attached.statelessWiredConnector.onWrite(socketChannel, key);
+ return;
+ }
+
+
TcpSocketChannelEntryWriter entryWriter = attached.entryWriter;
if (entryWriter == null) throw
@@ -775,6 +776,29 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
return;
}
+ boolean forceRead = false;
+
+ if (!attached.isHandShakingComplete()) {
+ byte[] data = new byte[1];
+
+ // sniff just a single byte from the socket and write it to attached.entryReader.in
+ // this way we can switch to StatelessWiredConnector without reading any other data
+ socketChannel.read(ByteBuffer.wrap(data));
+ byte b = data[0];
+ attached.entryReader.in.put(b);
+ attached.entryReader.out.limit(1);
+
+ if (b == WIRED_CONNECTION)
+ attached.useWire = true;
+ forceRead = true;
+ attached.statelessWiredConnector = new StatelessWiredConnector(channelList);
+ }
+
+ if (attached.useWire) {
+ attached.statelessWiredConnector.onRead(socketChannel, key);
+ return;
+ }
+
try {
int len = attached.entryReader.readSocketToBuffer(socketChannel);
@@ -789,7 +813,7 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
return;
}
- if (len == 0)
+ if (len == 0 && !forceRead)
return;
if (attached.entryWriter.isWorkIncomplete())
@@ -1013,20 +1037,22 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
*/
class Attached implements Replica.ModificationNotifier {
- public TcpSocketChannelEntryReader entryReader;
- public TcpSocketChannelEntryWriter entryWriter;
+ TcpSocketChannelEntryReader entryReader;
+ TcpSocketChannelEntryWriter entryWriter;
@Nullable
- public Replica.ModificationIterator remoteModificationIterator;
- public AbstractConnector connector;
- public long remoteBootstrapTimestamp = Long.MIN_VALUE;
- public byte remoteIdentifier = Byte.MIN_VALUE;
- public boolean hasRemoteHeartbeatInterval;
+ Replica.ModificationIterator remoteModificationIterator;
+ AbstractConnector connector;
+ long remoteBootstrapTimestamp = Long.MIN_VALUE;
+ byte remoteIdentifier = Byte.MIN_VALUE;
+ boolean hasRemoteHeartbeatInterval;
// true if its socket is a ServerSocket
- public boolean isServer; // the frequency the remote node will send a heartbeat
- public boolean handShakingComplete;
- public String serverVersion;
- public long remoteHeartbeatInterval = heartBeatIntervalMillis;
+ boolean isServer; // the frequency the remote node will send a heartbeat
+ boolean handShakingComplete;
+ String serverVersion;
+ long remoteHeartbeatInterval = heartBeatIntervalMillis;
+ boolean useWire;
+ StatelessWiredConnector statelessWiredConnector;
boolean isHandShakingComplete() {
return handShakingComplete;
@@ -1351,11 +1377,33 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo
/**
* reads entries from the buffer till empty
*
- * @param attached
+ * @param attached * @param key the selection key
+ channel
* @param key
* @throws InterruptedException
*/
void entriesFromBuffer(@NotNull Attached attached, @NotNull SelectionKey key) {
+/*
+ if (attached.useWire) {
+
+ if (out.remaining() >= 4) {
+ int size = out.readInt(out.position());
+ if (out.remaining() >= size) {
+
+ long end = out.position() + size;
+
+ try {
+ out.skip(4); // for the size
+ wiredStatelessServer.processStatelessEvent(out, attached.entryWriter);
+ } finally {
+ out.position(end);
+ }
+
+ }
+ }
+ return;
+ }*/
+
int entriesRead = 0;
try {
for (; ; entriesRead++) {
diff --git a/src/main/java/net/openhft/chronicle/map/WireStatelessServerMap.java b/src/main/java/net/openhft/chronicle/map/WireStatelessServerMap.java
deleted file mode 100644
index 40034f9c5..000000000
--- a/src/main/java/net/openhft/chronicle/map/WireStatelessServerMap.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright 2014 Higher Frequency Trading
- *
- * http://www.higherfrequencytrading.com
- *
- * 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 net.openhft.chronicle.map;
-
-import net.openhft.chronicle.wire.TextWire;
-import net.openhft.lang.io.Bytes;
-
-/**
- * Created by Rob Austin
- */
-class WireStatelessServerMap {
-
- StatelessWiredConnector statelessWiredConnector = new StatelessWiredConnector();
-
- boolean doHandshaking(Bytes bytes) {
-
- TextWire textWire = new TextWire(bytes);
-
- final String type = textWire.read(() -> "TYPE").text();
-
-
- switch (type) {
-
-
- case "stateless-map":
-
- statelessWiredConnector.processStatelessEvent(textWire);
-
- return true;
-
- default:
- throw new UnsupportedOperationException("type=" + type + "is not currently supported");
-
- }
-
- }
-
- private void handshakeStatelessMap() {
-
- statelessWiredConnector.
- }
-
-
-}
diff --git a/src/main/java/net/openhft/chronicle/map/WiredChronicleMapStatelessClientBuilder.java b/src/main/java/net/openhft/chronicle/map/WiredChronicleMapStatelessClientBuilder.java
new file mode 100644
index 000000000..25d232109
--- /dev/null
+++ b/src/main/java/net/openhft/chronicle/map/WiredChronicleMapStatelessClientBuilder.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright 2014 Higher Frequency Trading
+ *
+ * http://www.higherfrequencytrading.com
+ *
+ * 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 net.openhft.chronicle.map;
+
+import net.openhft.chronicle.hash.ChronicleHashStatelessClientBuilder;
+import net.openhft.chronicle.hash.serialization.internal.SerializationBuilder;
+import net.openhft.lang.MemoryUnit;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * @author Rob Austin.
+ */
+public final class WiredChronicleMapStatelessClientBuilder implements
+ ChronicleHashStatelessClientBuilder,
+ ChronicleMap>,
+ MapBuilder> {
+
+ public WiredStatelessClientTcpConnectionHub hub;
+ public SerializationBuilder keyBuilder;
+ public SerializationBuilder valueBuilder;
+
+ public WiredStatelessClientTcpConnectionHub hub() {
+ return hub;
+ }
+
+ public void hub(WiredStatelessClientTcpConnectionHub hub) {
+ this.hub = hub;
+ }
+
+ static WiredChronicleMapStatelessClientBuilder of(
+ InetSocketAddress serverAddress) {
+ return new WiredChronicleMapStatelessClientBuilder<>(serverAddress);
+ }
+
+ // This method is meaningful, despite you could call of().create(), because Java 7 doesn't
+ // infer type parameters if case of chained calls, like this; and then you couldn't omit class
+ // name. Then it is
+ // ChronicleMapStatelessClientBuilder..of(addr).create()
+ // vs
+ // createClientOf(addr) // static import
+ // -- the second is really shorter.
+
+ /**
+ * Equivalent of {@code ChronicleMapStatelessClientBuilder.of(serverAddress).create()}.
+ *
+ * @param serverAddress address of the server map
+ * @param key type of the map
+ * @param value type of the map
+ * @return stateless client of the ChronicleMap of server
+ */
+ public static ChronicleMap createClientOf(InetSocketAddress serverAddress)
+ throws IOException {
+ return WiredChronicleMapStatelessClientBuilder.of(serverAddress).create();
+ }
+
+ private final InetSocketAddress remoteAddress;
+ private boolean putReturnsNull = false;
+ private boolean removeReturnsNull = false;
+ private long timeoutMs = TimeUnit.SECONDS.toMillis(10);
+ private String name;
+ private int tcpBufferSize = (int) MemoryUnit.KILOBYTES.toBytes(64);
+
+ private final AtomicBoolean used = new AtomicBoolean(false);
+
+ WiredChronicleMapStatelessClientBuilder(InetSocketAddress remoteAddress) {
+ this.remoteAddress = remoteAddress;
+ }
+
+ InetSocketAddress remoteAddress() {
+ return remoteAddress;
+ }
+
+ @Override
+ public WiredChronicleMapStatelessClientBuilder putReturnsNull(boolean putReturnsNull) {
+ this.putReturnsNull = putReturnsNull;
+ return this;
+ }
+
+ boolean putReturnsNull() {
+ return putReturnsNull;
+ }
+
+ @Override
+ public WiredChronicleMapStatelessClientBuilder removeReturnsNull(boolean removeReturnsNull) {
+ this.removeReturnsNull = removeReturnsNull;
+ return this;
+ }
+
+ boolean removeReturnsNull() {
+ return removeReturnsNull;
+ }
+
+ @Override
+ public WiredChronicleMapStatelessClientBuilder timeout(long timeout, TimeUnit units) {
+ this.timeoutMs = units.toMillis(timeout);
+ return this;
+ }
+
+ long timeoutMs() {
+ return timeoutMs;
+ }
+
+ @Override
+ public WiredChronicleMapStatelessClientBuilder name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ String name() {
+ return name;
+ }
+
+ @Override
+ public WiredChronicleMapStatelessClientBuilder tcpBufferSize(int tcpBufferSize) {
+ this.tcpBufferSize = tcpBufferSize;
+ return this;
+ }
+
+ int tcpBufferSize() {
+ return tcpBufferSize;
+ }
+
+ @Override
+ public ChronicleMap create() throws IOException {
+
+ // todo clean this up
+ if (hub == null)
+ hub = new WiredStatelessClientTcpConnectionHub(this);
+
+ if (!used.getAndSet(true)) {
+ return new WiredStatelessChronicleMap(this);
+
+ } else {
+ throw new IllegalStateException(
+ "A stateless client has already been created using this builder. " +
+ "Create a new ChronicleMapStatelessClientBuilder " +
+ "to create a new stateless client");
+ }
+ }
+}
diff --git a/src/main/java/net/openhft/chronicle/map/WiredStatelessChronicleMap.java b/src/main/java/net/openhft/chronicle/map/WiredStatelessChronicleMap.java
new file mode 100644
index 000000000..e71833344
--- /dev/null
+++ b/src/main/java/net/openhft/chronicle/map/WiredStatelessChronicleMap.java
@@ -0,0 +1,726 @@
+/*
+ * Copyright 2014 Higher Frequency Trading
+ *
+ * http://www.higherfrequencytrading.com
+ *
+ * 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 net.openhft.chronicle.map;
+
+import net.openhft.chronicle.hash.function.SerializableFunction;
+import net.openhft.chronicle.wire.Marshallable;
+import net.openhft.chronicle.wire.Wire;
+import net.openhft.lang.threadlocal.ThreadLocalCopies;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.function.Predicate;
+
+import static java.util.Collections.emptyList;
+import static net.openhft.chronicle.map.WiredStatelessChronicleMap.EventId.*;
+
+
+/**
+ * @author Rob Austin.
+ */
+class WiredStatelessChronicleMap implements ChronicleMap, Cloneable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(WiredStatelessChronicleMap.class);
+ private final WiredStatelessClientTcpConnectionHub hub;
+
+
+ protected Class kClass;
+ protected Class vClass;
+
+ private boolean putReturnsNull;
+ private boolean removeReturnsNull;
+
+
+ WiredStatelessChronicleMap(@NotNull final WiredChronicleMapStatelessClientBuilder config) {
+ hub = config.hub;
+ this.putReturnsNull = config.putReturnsNull();
+ this.removeReturnsNull = config.removeReturnsNull();
+ kClass = config.keyBuilder.eClass;
+ vClass = config.valueBuilder.eClass;
+ }
+
+
+ @SuppressWarnings("UnusedDeclaration")
+ void identifier(int identifier) {
+ hub.identifier = identifier;
+ }
+
+ @Override
+ public void getAll(File toFile) throws IOException {
+ JsonSerializer.getAll(toFile, this, emptyList());
+ }
+
+ @Override
+ public void putAll(File fromFile) throws IOException {
+ JsonSerializer.putAll(fromFile, this, emptyList());
+ }
+
+ @Override
+ public V newValueInstance() {
+ return VanillaChronicleMap.newInstance(vClass, false);
+ }
+
+ @Override
+ public K newKeyInstance() {
+ return VanillaChronicleMap.newInstance(kClass, true);
+ }
+
+ @Override
+ public Class keyClass() {
+ return kClass;
+ }
+
+ @Override
+ public boolean forEachEntryWhile(Predicate super MapKeyContext> predicate) {
+ // TODO implement!
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void forEachEntry(Consumer super MapKeyContext> action) {
+ // TODO implement!
+ throw new UnsupportedOperationException();
+ }
+
+
+ public String serverApplicationVersion() {
+ return hub.serverApplicationVersion();
+ }
+
+ @Override
+ public void close() {
+ // todo add ref count
+ }
+
+ @Override
+ public Class valueClass() {
+ return vClass;
+ }
+
+
+ @NotNull
+ public File file() {
+ throw new UnsupportedOperationException();
+ }
+
+ @SuppressWarnings("NullableProblems")
+ public V putIfAbsent(K key, V value) {
+
+ if (key == null || value == null)
+ throw new NullPointerException();
+
+ return proxyReturnObject(PUT_IF_ABSENT.toString(), key, value, vClass);
+ }
+
+ @SuppressWarnings("NullableProblems")
+ public boolean remove(Object key, Object value) {
+
+ if (key == null)
+ throw new NullPointerException();
+
+ return value != null && proxyReturnBoolean(REMOVE_WITH_VALUE.toString(), (K) key, (V) value);
+
+ }
+
+ @SuppressWarnings("NullableProblems")
+ public boolean replace(K key, V oldValue, V newValue) {
+ if (key == null || oldValue == null || newValue == null)
+ throw new NullPointerException();
+ return proxyReturnBoolean(REPLACE_WITH_OLD_AND_NEW_VALUE.toString(), key, oldValue, newValue);
+ }
+
+ @SuppressWarnings("NullableProblems")
+ public V replace(K key, V value) {
+ if (key == null || value == null)
+ throw new NullPointerException();
+ return proxyReturnObject(REPLACE.toString(), key, value, vClass);
+ }
+
+ public int size() {
+ return (int) longSize();
+ }
+
+ /**
+ * calling this method should be avoided at all cost, as the entire {@code object} is
+ * serialized. This equals can be used to compare map that extends ChronicleMap. So two
+ * Chronicle Maps that contain the same data are considered equal, even if the instances of the
+ * chronicle maps were of different types
+ *
+ * @param object the object that you are comparing against
+ * @return true if the contain the same data
+ */
+ @Override
+ public boolean equals(@Nullable Object object) {
+ if (this == object) return true;
+ if (object == null || object.getClass().isAssignableFrom(Map.class))
+ return false;
+
+ final Map extends K, ? extends V> that = (Map extends K, ? extends V>) object;
+
+ final int size = size();
+
+ if (that.size() != size)
+ return false;
+
+ final Set> entries = entrySet();
+ return that.entrySet().equals(entries);
+ }
+
+ @Override
+ public int hashCode() {
+ return proxyReturnInt(HASH_CODE.toString());
+ }
+
+ @NotNull
+ public String toString() {
+ return hub.proxyReturnString(TO_STRING.toString());
+ }
+
+ @NotNull
+ public String serverPersistedDataVersion() {
+ return hub.proxyReturnString(PERSISTED_DATA_VERSION.toString());
+ }
+
+ public boolean isEmpty() {
+ return proxyReturnBoolean(IS_EMPTY.toString());
+ }
+
+ public boolean containsKey(Object key) {
+ return proxyReturnBooleanK(CONTAINS_KEY.toString(), (K) key);
+ }
+
+ @NotNull
+ private NullPointerException keyNotNullNPE() {
+ return new NullPointerException("key can not be null");
+ }
+
+ public boolean containsValue(Object value) {
+ return proxyReturnBooleanV(CONTAINS_VALUE.toString(), (V) value);
+ }
+
+ public long longSize() {
+ return proxyReturnLong(LONG_SIZE.toString());
+ }
+
+ @Override
+ public MapKeyContext context(K key) {
+ throw new UnsupportedOperationException("Contexts are not supported by stateless clients");
+ }
+
+ public V get(Object key) {
+ return proxyReturnObject(vClass, GET.toString(), (K) key);
+ }
+
+ @Nullable
+ public V getUsing(K key, V usingValue) {
+ throw new UnsupportedOperationException();
+ }
+
+ @NotNull
+ public V acquireUsing(@NotNull K key, V usingValue) {
+ throw new UnsupportedOperationException(
+ "acquireUsing() is not supported for stateless clients");
+ }
+
+ @NotNull
+ @Override
+ public MapKeyContext acquireContext(@NotNull K key, @NotNull V usingValue) {
+ throw new UnsupportedOperationException("Contexts are not supported by stateless clients");
+ }
+
+ public V remove(Object key) {
+ if (key == null)
+ throw keyNotNullNPE();
+ return proxyReturnObject(vClass, removeReturnsNull ? REMOVE_WITHOUT_ACC.toString() : REMOVE.toString(), (K) key);
+ }
+
+ public V put(K key, V value) {
+ if (key == null || value == null)
+ throw new NullPointerException();
+ return proxyReturnObject(putReturnsNull ? PUT_WITHOUT_ACC.toString() : PUT.toString(), key, value, vClass);
+ }
+
+ @Nullable
+ public R getMapped(@Nullable K key, @NotNull SerializableFunction super V, R> function) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Nullable
+ @Override
+ public V putMapped(@Nullable K key, @NotNull UnaryOperator unaryOperator) {
+ throw new UnsupportedOperationException();
+ }
+
+ public void clear() {
+ proxyReturnVoid(CLEAR.toString());
+ }
+
+ @NotNull
+ public Collection values() {
+ throw new UnsupportedOperationException();
+ }
+
+ @NotNull
+ public Set> entrySet() {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @param callback each entry is passed to the callback
+ */
+ void entrySet(@NotNull MapEntryCallback callback) {
+ throw new UnsupportedOperationException();
+
+ }
+
+ public void putAll(@NotNull Map extends K, ? extends V> map) {
+
+ throw new UnsupportedOperationException();
+ }
+
+ @NotNull
+ public Set keySet() {
+ throw new UnsupportedOperationException("todo");
+ }
+
+ private long readLong(long transactionId, long startTime) {
+ assert !hub.outBytesLock().isHeldByCurrentThread();
+ final long timeoutTime = startTime + hub.timeoutMs;
+
+ // receive
+ hub.inBytesLock().lock();
+ try {
+ return hub.proxyReply(timeoutTime, transactionId).read(() -> "RESULT").int64();
+ } finally {
+ hub.inBytesLock().unlock();
+ }
+ }
+
+
+ private void writeField(String fieldName, Object value) {
+
+ assert hub.outBytesLock().isHeldByCurrentThread();
+ assert !hub.inBytesLock().isHeldByCurrentThread();
+
+ if (value instanceof CharSequence) {
+ hub.outWire().write(() -> fieldName).text((CharSequence) value);
+ } else if (value instanceof Marshallable) {
+ hub.outWire().write(() -> fieldName).marshallable((Marshallable) value);
+ } else {
+ throw new IllegalStateException("type=" + value.getClass() + " is unsupported, it must either be of type Marshallable or CharSequence");
+ }
+ }
+
+
+ private V readValue(long transactionId, long startTime, V usingValue) {
+ assert !hub.outBytesLock().isHeldByCurrentThread();
+ long timeoutTime = startTime + hub.timeoutMs;
+
+ hub.inBytesLock().lock();
+ try {
+
+ final Wire wireIn = hub.proxyReply(timeoutTime, transactionId);
+
+ if (usingValue == null) {
+ usingValue = newValueInstance();
+ }
+
+ if (usingValue instanceof StringBuilder) {
+ wireIn.read(() -> "RESULT").text((StringBuilder) usingValue);
+ return usingValue;
+ } else if (usingValue instanceof Marshallable) {
+ wireIn.read(() -> "RESULT").marshallable((Marshallable) usingValue);
+ return usingValue;
+ } else {
+ throw new IllegalStateException("unsupported type");
+ }
+
+ } finally {
+ hub.inBytesLock().unlock();
+ }
+ }
+
+
+ private boolean readBoolean(long transactionId, long startTime) {
+ assert !hub.outBytesLock().isHeldByCurrentThread();
+
+ long timeoutTime = startTime + hub.timeoutMs;
+
+ // receive
+ hub.inBytesLock().lock();
+ try {
+ final Wire wireIn = hub.proxyReply(timeoutTime, transactionId);
+ return wireIn.read(() -> "RESULT").bool();
+ } finally {
+ hub.inBytesLock().unlock();
+ }
+ }
+
+ private int readInt(long transactionId, long startTime) {
+ assert !hub.outBytesLock().isHeldByCurrentThread();
+
+ long timeoutTime = startTime + hub.timeoutMs;
+
+ // receive
+ hub.inBytesLock().lock();
+ try {
+ final Wire wireIn = hub.proxyReply(timeoutTime, transactionId);
+ return wireIn.read(() -> "RESULT").int32();
+ } finally {
+ hub.inBytesLock().unlock();
+ }
+ }
+
+
+ @SuppressWarnings("SameParameterValue")
+ private boolean proxyReturnBoolean(@NotNull final String methodName, K key, V value) {
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ writeField("ARG_1", key);
+ writeField("ARG_2", value);
+
+
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ return readBoolean(transactionId, startTime);
+
+ }
+
+
+
+ @SuppressWarnings("SameParameterValue")
+ private boolean proxyReturnBoolean(@NotNull final String methodName, K key, V value1, V value2) {
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ writeField("ARG_1", value1);
+ writeField("ARG_2", value2);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ return readBoolean(transactionId, startTime);
+
+ }
+
+ @SuppressWarnings("SameParameterValue")
+ private boolean proxyReturnBooleanV(@NotNull final String methodName, V value) {
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ writeField("ARG_1", value);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ return readBoolean(transactionId, startTime);
+ }
+
+ @SuppressWarnings("SameParameterValue")
+ private boolean proxyReturnBooleanK(@NotNull final String methodName, K key) {
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ writeField("ARG_1", key);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ return readBoolean(transactionId, startTime);
+ }
+
+ @SuppressWarnings("SameParameterValue")
+ private long proxyReturnLong(@NotNull final String methodName) {
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ return readLong(transactionId, startTime);
+ }
+
+ @SuppressWarnings("SameParameterValue")
+ private boolean proxyReturnBoolean(@NotNull final String methodName) {
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ return readBoolean(transactionId, startTime);
+ }
+
+ @SuppressWarnings("SameParameterValue")
+ private void proxyReturnVoid(@NotNull final String methodName) {
+
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ readVoid(transactionId, startTime);
+ }
+
+
+ @SuppressWarnings("SameParameterValue")
+ private int proxyReturnInt(@NotNull final String methodName) {
+ final long startTime = System.currentTimeMillis();
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ return readInt(transactionId, startTime);
+ }
+
+ @Nullable
+ private R proxyReturnObject(@NotNull final String methodName, K key, V value, Class resultType) {
+ final long startTime = System.currentTimeMillis();
+
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ assert hub.outBytesLock().isHeldByCurrentThread();
+ assert !hub.inBytesLock().isHeldByCurrentThread();
+
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ writeField("ARG_2", key);
+ writeField("ARG_2", value);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+
+ if (eventReturnsNull(methodName))
+ return null;
+
+ if (resultType == vClass)
+ return (R) readValue(transactionId, startTime, null);
+ else
+ throw new UnsupportedOperationException("class of type class=" + resultType + " is not " +
+ "supported");
+ }
+
+ @Nullable
+ private R proxyReturnObject(Class rClass, @NotNull final String methodName, Object key) {
+ final long startTime = System.currentTimeMillis();
+ ThreadLocalCopies copies;
+
+ long transactionId;
+
+ hub.outBytesLock().lock();
+ try {
+ transactionId = hub.writeHeader(startTime);
+ writeField("METHOD_NAME", methodName);
+ writeField("ARG_1", key);
+ hub.writeSocket();
+ } finally {
+ hub.outBytesLock().unlock();
+ }
+
+ if (eventReturnsNull(methodName))
+ return null;
+
+ if (rClass == vClass)
+ return (R) readValue(transactionId, startTime, null);
+ else
+ throw new UnsupportedOperationException("class of type class=" + rClass + " is not " +
+ "supported");
+ }
+
+ private boolean eventReturnsNull(@NotNull String methodName) {
+
+ switch (methodName) {
+ case "PUT_ALL_WITHOUT_ACC":
+ case "PUT_WITHOUT_ACC":
+ case "REMOVE_WITHOUT_ACC":
+ return true;
+ default:
+ return false;
+ }
+
+ }
+
+ private void readVoid(long transactionId, long startTime) {
+ long timeoutTime = startTime + hub.timeoutMs;
+
+ // receive
+ hub.inBytesLock().lock();
+ try {
+ hub.proxyReply(timeoutTime, transactionId);
+ } finally {
+ hub.inBytesLock().unlock();
+ }
+ }
+
+
+ static enum EventId {
+ HEARTBEAT,
+ STATEFUL_UPDATE,
+ LONG_SIZE,
+ SIZE,
+ IS_EMPTY,
+ CONTAINS_KEY,
+ CONTAINS_VALUE,
+ GET,
+ PUT,
+ PUT_WITHOUT_ACC,
+ REMOVE,
+ REMOVE_WITHOUT_ACC,
+ CLEAR,
+ KEY_SET,
+ VALUES,
+ ENTRY_SET,
+ REPLACE,
+ REPLACE_WITH_OLD_AND_NEW_VALUE,
+ PUT_IF_ABSENT,
+ REMOVE_WITH_VALUE,
+ TO_STRING,
+ APPLICATION_VERSION,
+ PERSISTED_DATA_VERSION,
+ PUT_ALL,
+ PUT_ALL_WITHOUT_ACC,
+ HASH_CODE,
+ MAP_FOR_KEY,
+ PUT_MAPPED,
+ KEY_BUILDER,
+ VALUE_BUILDER
+ }
+
+ class Entry implements Map.Entry {
+
+ final K key;
+ final V value;
+
+ /**
+ * Creates new entry.
+ */
+ Entry(K k1, V v) {
+ value = v;
+ key = k1;
+ }
+
+ public final K getKey() {
+ return key;
+ }
+
+ public final V getValue() {
+ return value;
+ }
+
+ public final V setValue(V newValue) {
+ V oldValue = value;
+ WiredStatelessChronicleMap.this.put(getKey(), newValue);
+ return oldValue;
+ }
+
+ public final boolean equals(Object o) {
+ if (!(o instanceof Map.Entry))
+ return false;
+ final Map.Entry e = (Map.Entry) o;
+ final Object k1 = getKey();
+ final Object k2 = e.getKey();
+ if (k1 == k2 || (k1 != null && k1.equals(k2))) {
+ Object v1 = getValue();
+ Object v2 = e.getValue();
+ if (v1 == v2 || (v1 != null && v1.equals(v2)))
+ return true;
+ }
+ return false;
+ }
+
+ public final int hashCode() {
+ return (key == null ? 0 : key.hashCode()) ^
+ (value == null ? 0 : value.hashCode());
+ }
+
+ @NotNull
+ public final String toString() {
+ return getKey() + "=" + getValue();
+ }
+ }
+}
+
diff --git a/src/main/java/net/openhft/chronicle/map/WiredStatelessClientTcpConnectionHub.java b/src/main/java/net/openhft/chronicle/map/WiredStatelessClientTcpConnectionHub.java
new file mode 100644
index 000000000..090e3f0d3
--- /dev/null
+++ b/src/main/java/net/openhft/chronicle/map/WiredStatelessClientTcpConnectionHub.java
@@ -0,0 +1,678 @@
+/*
+ * Copyright 2014 Higher Frequency Trading
+ *
+ * http://www.higherfrequencytrading.com
+ *
+ * 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 net.openhft.chronicle.map;
+
+import com.sun.jdi.connect.spi.ClosedConnectionException;
+import net.openhft.chronicle.bytes.Bytes;
+import net.openhft.chronicle.hash.RemoteCallTimeoutException;
+import net.openhft.chronicle.hash.impl.util.BuildVersion;
+import net.openhft.chronicle.hash.impl.util.CloseablesManager;
+import net.openhft.chronicle.wire.Marshallable;
+import net.openhft.chronicle.wire.TextWire;
+import net.openhft.chronicle.wire.Wire;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.ReentrantLock;
+
+import static net.openhft.chronicle.map.AbstractChannelReplicator.SIZE_OF_SIZE;
+import static net.openhft.chronicle.map.WiredStatelessChronicleMap.EventId.APPLICATION_VERSION;
+
+/**
+ * Created by Rob Austin
+ */
+public class WiredStatelessClientTcpConnectionHub {
+
+ private static final Logger LOG = LoggerFactory.getLogger(StatelessChronicleMap.class);
+ private static final byte WIRE_STATELESS_CLIENT_IDENTIFIER = (byte) -126;
+
+ protected final String name;
+ protected final InetSocketAddress remoteAddress;
+ protected final long timeoutMs;
+ protected final int tcpBufferSize;
+ private final ReentrantLock inBytesLock = new ReentrantLock(true);
+ private final ReentrantLock outBytesLock = new ReentrantLock();
+ private final byte[] connectionByte = new byte[1];
+ private final ByteBuffer connectionOutBuffer = ByteBuffer.wrap(connectionByte);
+
+ @NotNull
+ private final AtomicLong transactionID = new AtomicLong(0);
+ @Nullable
+ protected CloseablesManager closeables;
+ // used by the enterprise version
+ protected int identifier;
+ long largestChunkSoFar = 0;
+
+
+ //private net.openhft.chronicle.bytes.Bytes outBytes;
+ private Wire outWire = new TextWire(Bytes.elasticByteBuffer());
+
+ private Wire intWire = new TextWire(Bytes.elasticByteBuffer());
+
+
+ private SocketChannel clientChannel;
+ // this is a transaction id and size that has been read by another thread.
+ private volatile long parkedTransactionId;
+
+ private volatile long parkedTransactionTimeStamp;
+ private long limitOfLast = 0;
+
+ // set up in the header
+ private long sizeMark;
+ private long startTime;
+
+ public WiredStatelessClientTcpConnectionHub(WiredChronicleMapStatelessClientBuilder config) {
+ this.remoteAddress = config.remoteAddress();
+ this.tcpBufferSize = config.tcpBufferSize();
+ this.name = config.name();
+
+ // outBytes = Bytes.wrap(outBuffer.slice()).bytes();
+ this.timeoutMs = config.timeoutMs();
+
+ attemptConnect(remoteAddress);
+ checkVersion();
+
+ }
+
+ private synchronized void attemptConnect(final InetSocketAddress remoteAddress) {
+
+ // ensures that the excising connection are closed
+ closeExisting();
+
+ try {
+ SocketChannel socketChannel = AbstractChannelReplicator.openSocketChannel(closeables);
+
+ if (socketChannel.connect(remoteAddress)) {
+ doHandShaking(socketChannel);
+ clientChannel = socketChannel;
+ }
+
+ } catch (IOException e) {
+ if (closeables != null) closeables.closeQuietly();
+ clientChannel = null;
+ }
+ }
+
+ ReentrantLock inBytesLock() {
+ return inBytesLock;
+ }
+
+ ReentrantLock outBytesLock() {
+ return outBytesLock;
+ }
+
+ protected void checkVersion() {
+
+ String serverVersion = serverApplicationVersion();
+ String clientVersion = clientVersion();
+
+ if (!serverVersion.equals(clientVersion)) {
+ LOG.warn("DIFFERENT CHRONICLE-MAP VERSIONS: The Chronicle-Map-Server and " +
+ "Stateless-Client are on different " +
+ "versions, " +
+ " we suggest that you use the same version, server=" + serverApplicationVersion() + ", " +
+ "client=" + clientVersion);
+ }
+ }
+
+
+ private void checkTimeout(long timeoutTime) {
+ if (timeoutTime < System.currentTimeMillis())
+ throw new RemoteCallTimeoutException();
+ }
+
+ protected synchronized void lazyConnect(final long timeoutMs,
+ final InetSocketAddress remoteAddress) {
+ if (clientChannel != null)
+ return;
+
+ if (LOG.isDebugEnabled())
+ LOG.debug("attempting to connect to " + remoteAddress + " ,name=" + name);
+
+ SocketChannel result;
+
+ long timeoutAt = System.currentTimeMillis() + timeoutMs;
+
+ for (; ; ) {
+ checkTimeout(timeoutAt);
+
+ // ensures that the excising connection are closed
+ closeExisting();
+
+ try {
+ result = AbstractChannelReplicator.openSocketChannel(closeables);
+ if (!result.connect(remoteAddress)) {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ continue;
+ }
+
+ result.socket().setTcpNoDelay(true);
+ doHandShaking(result);
+ break;
+ } catch (IOException e) {
+ if (closeables != null) closeables.closeQuietly();
+ } catch (Exception e) {
+ if (closeables != null) closeables.closeQuietly();
+ throw e;
+ }
+ }
+ clientChannel = result;
+
+ // clear in and out buffer
+ intWire.clear();
+ inWireByteBuffer().clear();
+ outWire.clear();
+ outWireByteBuffer().clear();
+ try {
+ checkVersion();
+ } finally {
+ // clear in and out buffer
+ intWire.clear();
+ outWire.clear();
+ }
+
+ }
+
+ private ByteBuffer outWireByteBuffer() {
+ return (ByteBuffer) outWire.bytes().underlyingObject();
+ }
+
+ /**
+ * closes the existing connections and establishes a new closeables
+ */
+ protected void closeExisting() {
+ // ensure that any excising connection are first closed
+ if (closeables != null)
+ closeables.closeQuietly();
+
+ closeables = new CloseablesManager();
+ }
+
+ /**
+ * initiates a very simple level of handshaking with the remote server, we send a special ID of
+ * -127 ( when the server receives this it knows its dealing with a stateless client, receive
+ * back an identifier from the server
+ *
+ * @param clientChannel clientChannel
+ * @throws java.io.IOException
+ */
+ protected synchronized void doHandShaking(@NotNull final SocketChannel clientChannel) throws IOException {
+
+ connectionByte[0] = 0;
+ this.connectionOutBuffer.clear();
+
+ long timeoutTime = System.currentTimeMillis() + timeoutMs;
+
+ // write a single byte
+ while (connectionOutBuffer.hasRemaining()) {
+ clientChannel.write(connectionOutBuffer);
+ checkTimeout(timeoutTime);
+ }
+
+ this.connectionOutBuffer.clear();
+
+ if (!clientChannel.finishConnect() || !clientChannel.socket().isBound())
+ return;
+
+ // read a single byte back
+ while (this.connectionOutBuffer.position() <= 0) {
+ int read = clientChannel.read(this.connectionOutBuffer);// the remote identifier
+ if (read == -1)
+ throw new IOException("server conncetion closed");
+ checkTimeout(timeoutTime);
+ }
+
+ byte remoteIdentifier = connectionByte[0];
+
+ if (LOG.isDebugEnabled())
+ LOG.debug("Attached to a map with a remote identifier=" + remoteIdentifier + " ,name=" + name);
+
+ }
+
+ public synchronized void close() {
+
+ if (closeables != null)
+ closeables.closeQuietly();
+
+ closeables = null;
+ clientChannel = null;
+
+ }
+
+ /**
+ * the transaction id are generated as unique timestamps
+ *
+ * @param time in milliseconds
+ * @return a unique transactionId
+ */
+ long nextUniqueTransaction(long time) {
+ long id = time * TcpReplicator.TIMESTAMP_FACTOR;
+ for (; ; ) {
+ long old = transactionID.get();
+ if (old >= id) id = old + 1;
+ if (transactionID.compareAndSet(old, id))
+ break;
+ }
+ return id;
+ }
+
+ @NotNull
+ public String serverApplicationVersion() {
+ String result = proxyReturnString(APPLICATION_VERSION.toString());
+ return (result == null) ? "" : result;
+ }
+
+ @SuppressWarnings("WeakerAccess")
+ @NotNull
+ String clientVersion() {
+ return BuildVersion.version();
+ }
+
+
+ /**
+ * sends data to the server via TCP/IP
+ */
+ void writeSocket() {
+
+ assert outBytesLock().isHeldByCurrentThread();
+ assert !inBytesLock().isHeldByCurrentThread();
+
+
+ final long timeoutTime = startTime + this.timeoutMs;
+ try {
+
+ for (; ; ) {
+ if (clientChannel == null) {
+ lazyConnect(timeoutMs, remoteAddress);
+ }
+ try {
+
+ writeLength(outWire);
+
+ // send out all the bytes
+ writeSocket(outWire, timeoutTime);
+
+ break;
+
+ } catch (@NotNull java.nio.channels.ClosedChannelException | ClosedConnectionException e) {
+ checkTimeout(timeoutTime);
+ lazyConnect(timeoutMs, remoteAddress);
+ }
+ }
+ } catch (IOException e) {
+ close();
+ throw new IORuntimeException(e);
+ } catch (Exception e) {
+ close();
+ throw e;
+ }
+ }
+
+ private void writeLength(Wire outWire) {
+ long position = outWire.bytes().position();
+ if (position > Integer.MAX_VALUE || position < Integer.MIN_VALUE)
+ throw new IllegalStateException("message too large");
+
+ outWire.bytes().writeInt(0, (int) position);
+ }
+
+ protected Wire proxyReply(long timeoutTime, final long transactionId) {
+
+ assert inBytesLock().isHeldByCurrentThread();
+ // assert !outBytesLock.isHeldByCurrentThread();
+ try {
+ return proxyReplyThrowable(timeoutTime, transactionId);
+ } catch (IOException e) {
+ close();
+ throw new IORuntimeException(e);
+ } catch (RuntimeException e) {
+ close();
+ throw e;
+ } catch (Exception e) {
+ close();
+ throw new RuntimeException(e);
+ } catch (AssertionError e) {
+ LOG.error("name=" + name, e);
+ throw e;
+ }
+ }
+
+
+ private Wire proxyReplyThrowable(long timeoutTime, long transactionId) throws IOException {
+
+ assert inBytesLock().isHeldByCurrentThread();
+
+ for (; ; ) {
+
+ // read the next item from the socket
+ if (parkedTransactionId == 0) {
+
+ assert parkedTransactionTimeStamp == 0;
+
+ inWireClear();
+
+ // todo change the size to include the meta data bit
+ // reads just the size
+ readSocket(SIZE_OF_SIZE, timeoutTime);
+
+ final int messageSize = intWire.bytes().readInt();
+
+ assert messageSize > 0 : "Invalid message size " + messageSize;
+ assert messageSize < 16 << 20 : "Invalid message size " + messageSize;
+
+ final int remainingBytes0 = messageSize - SIZE_OF_SIZE;
+ readSocket(remainingBytes0, timeoutTime);
+ intWire.bytes().limit(messageSize);
+ final long transactionId0 = intWire.read(() -> "TRANSACTION_ID").int64();
+
+ // check the transaction id is reasonable
+ assert transactionId0 > 1410000000000L * TcpReplicator.TIMESTAMP_FACTOR :
+ "TransactionId too small " + transactionId0 + " messageSize " + messageSize;
+ assert transactionId0 < 2100000000000L * TcpReplicator.TIMESTAMP_FACTOR :
+ "TransactionId too large " + transactionId0 + " messageSize " + messageSize;
+
+ // if the transaction id is for this thread process it
+ if (transactionId0 == transactionId) {
+ clearParked();
+ return intWire;
+
+ } else {
+
+ // if the transaction id is not for this thread, park it
+ // and allow another thread to pick it up
+ parkedTransactionTimeStamp = System.currentTimeMillis();
+ parkedTransactionId = transactionId0;
+ pause();
+ continue;
+ }
+ }
+
+ // the transaction id was read by another thread, but is for this thread, process it
+ if (parkedTransactionId == transactionId) {
+ clearParked();
+ return intWire;
+ }
+
+ // time out the old transaction id
+ if (System.currentTimeMillis() - timeoutTime >
+ parkedTransactionTimeStamp) {
+
+ LOG.error("name=" + name, new IllegalStateException("Skipped Message with " +
+ "transaction-id=" +
+ parkedTransactionTimeStamp +
+ ", this can occur when you have another thread which has called the " +
+ "stateless client and terminated abruptly before the message has been " +
+ "returned from the server and hence consumed by the other thread."));
+
+ // read the the next message
+ clearParked();
+ pause();
+ }
+
+ }
+
+ }
+
+ /**
+ * clears the wire and its underlying byte buffer
+ */
+ private void inWireClear() {
+ inWireByteBuffer().clear();
+ intWire.bytes().clear();
+ }
+
+ private void clearParked() {
+ assert inBytesLock().isHeldByCurrentThread();
+ parkedTransactionId = 0;
+ parkedTransactionTimeStamp = 0;
+ }
+
+ private void pause() {
+
+ assert !outBytesLock().isHeldByCurrentThread();
+ assert inBytesLock().isHeldByCurrentThread();
+
+ /// don't call inBytesLock.isHeldByCurrentThread() as it not atomic
+ inBytesLock().unlock();
+
+ // allows another thread to enter hear
+ inBytesLock().lock();
+ }
+
+ /**
+ * reads up to the number of byte in {@code requiredNumberOfBytes} from the socket
+ *
+ * @param requiredNumberOfBytes the number of bytes to read
+ * @param timeoutTime timeout in milliseconds
+ * @return bytes read from the TCP/IP socket
+ * @throws java.io.IOException socket failed to read data
+ */
+ @SuppressWarnings("UnusedReturnValue")
+ private Bytes readSocket(int requiredNumberOfBytes, long timeoutTime) throws IOException {
+
+ assert inBytesLock().isHeldByCurrentThread();
+ ByteBuffer buffer = inWireByteBuffer();
+
+ while (buffer.remaining() > requiredNumberOfBytes) {
+
+ int len = clientChannel.read(inWireByteBuffer());
+
+ if (len == -1)
+ throw new IORuntimeException("Disconnection to server");
+
+ checkTimeout(timeoutTime);
+ }
+
+ return intWire.bytes();
+ }
+
+ private ByteBuffer inWireByteBuffer() {
+ return (ByteBuffer) intWire.bytes().underlyingObject();
+ }
+
+ /**
+ * writes the bytes to the socket
+ *
+ * @param outWire the data that you wish to write
+ * @param timeoutTime how long before a we timeout
+ * @throws IOException
+ */
+ private void writeSocket(Wire outWire, long timeoutTime) throws IOException {
+
+ assert outBytesLock().isHeldByCurrentThread();
+ assert !inBytesLock().isHeldByCurrentThread();
+
+
+ long outBytesPosition = outWire.bytes().position();
+
+
+ // if we have other threads waiting to send and the buffer is not full, let the other threads
+ // write to the buffer
+ if (outBytesLock().hasQueuedThreads() &&
+ outBytesPosition + largestChunkSoFar <= tcpBufferSize) {
+ return;
+ }
+
+ ByteBuffer outBuffer = outWireByteBuffer();
+ outBuffer.limit((int) outWire.bytes().position());
+ outBuffer.position(0);
+
+ upateLargestChunkSoFarSize(outBuffer);
+
+ while (outBuffer.remaining() > 0) {
+
+ int len = clientChannel.write(outBuffer);
+ if (len == -1)
+ throw new IORuntimeException("Disconnection to server");
+
+
+ // if we have queued threads then we don't have to write all the bytes as the other
+ // threads will write the remains bytes.
+ if (outBuffer.remaining() > 0 && outBytesLock().hasQueuedThreads() &&
+ outBuffer.remaining() + largestChunkSoFar <= tcpBufferSize) {
+
+ if (LOG.isDebugEnabled())
+ LOG.debug("continuing - without all the data being written to the buffer as " +
+ "it will be written by the next thread");
+ outBuffer.compact();
+ outWire.bytes().limit(outBuffer.limit());
+ outWire.bytes().position(outBuffer.position());
+ return;
+ }
+
+ checkTimeout(timeoutTime);
+
+ }
+
+ outBuffer.clear();
+ outWire.bytes().clear();
+
+ }
+
+ /**
+ * calculates the size of each chunk
+ *
+ * @param outBuffer
+ */
+ private void upateLargestChunkSoFarSize(ByteBuffer outBuffer) {
+ int sizeOfThisChunk = (int) (outBuffer.limit() - limitOfLast);
+ if (largestChunkSoFar < sizeOfThisChunk)
+ largestChunkSoFar = sizeOfThisChunk;
+
+ limitOfLast = outBuffer.limit();
+ }
+
+
+ private long proxySend(@NotNull final String methodName, final long startTime) {
+
+ assert outBytesLock().isHeldByCurrentThread();
+ assert !inBytesLock().isHeldByCurrentThread();
+
+ // send
+ outBytesLock().lock();
+ try {
+ long transactionId = writeHeader(startTime);
+ outWire.write(() -> "METHOD_NAME").text(methodName);
+ writeSocket();
+ return transactionId;
+ } finally {
+ outBytesLock().unlock();
+ }
+ }
+
+ @SuppressWarnings("SameParameterValue")
+ @Nullable
+ O fetchObject(final Class tClass,
+ @NotNull final String methodName) {
+ final long startTime = System.currentTimeMillis();
+ long transactionId;
+
+ outBytesLock().lock();
+ try {
+ transactionId = proxySend(methodName, startTime);
+ } finally {
+ outBytesLock().unlock();
+ }
+
+ long timeoutTime = startTime + this.timeoutMs;
+
+ // receive
+ inBytesLock().lock();
+ try {
+ O result = tClass.newInstance();
+ proxyReply(timeoutTime, transactionId).read(() -> "RESULT")
+ .marshallable(result);
+ return result;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ inBytesLock().unlock();
+ }
+ }
+
+ @SuppressWarnings("SameParameterValue")
+ @Nullable
+ String proxyReturnString(@NotNull final String messageId) {
+ final long startTime = System.currentTimeMillis();
+ long transactionId;
+
+ outBytesLock().lock();
+ try {
+ transactionId = proxySend(messageId, startTime);
+ } finally {
+ outBytesLock().unlock();
+ }
+
+ long timeoutTime = startTime + this.timeoutMs;
+
+ // receive
+ inBytesLock().lock();
+ try {
+ return proxyReply(timeoutTime, transactionId).read(() -> messageId).text();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ inBytesLock().unlock();
+ }
+ }
+
+
+ Wire outWire() {
+ return outWire;
+ }
+
+ long writeHeader(long startTime) {
+ markSize();
+ startTime(startTime);
+ long transactionId = nextUniqueTransaction(startTime);
+ outWire().write(() -> "TRANSACTION_ID").int64(transactionId);
+ outWire().write(() -> "TIME_STAMP").int64(startTime);
+ outWire().write(() -> "CHANNEL_ID").int64(startTime);
+ return transactionId;
+ }
+
+
+ /**
+ * mark the location of the outWire size
+ */
+ void markSize() {
+
+ // this is where the size will go
+ sizeMark = outWire.bytes().position();
+
+
+ // skip the 4 bytes for the size
+ outWire.bytes().skip(4);
+ }
+
+ void startTime(long startTime) {
+ this.startTime = startTime;
+ }
+}
diff --git a/src/test/java/net/openhft/chronicle/wire/TestWire.java b/src/test/java/net/openhft/chronicle/wire/TestWire.java
new file mode 100644
index 000000000..30233acac
--- /dev/null
+++ b/src/test/java/net/openhft/chronicle/wire/TestWire.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2014 Higher Frequency Trading
+ *
+ * http://www.higherfrequencytrading.com
+ *
+ * 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 net.openhft.chronicle.wire;
+
+import net.openhft.chronicle.bytes.BytesStore;
+import net.openhft.chronicle.hash.replication.ReplicationHub;
+import net.openhft.chronicle.hash.replication.TcpTransportAndNetworkConfig;
+import net.openhft.chronicle.map.ChronicleMap;
+import net.openhft.chronicle.util.ShortConsumer;
+import net.openhft.lang.io.ByteBufferBytes;
+import net.openhft.lang.io.Bytes;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static java.nio.ByteBuffer.allocate;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static net.openhft.chronicle.map.ChronicleMapBuilder.of;
+import static net.openhft.chronicle.map.ChronicleMapStatelessClientBuilder.createClientOf;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Created by Rob Austin
+ */
+public class TestWire {
+
+ public static class Details {
+ Class keyClass;
+ Class valueClass;
+ short channelID;
+ }
+
+ private ChronicleMap map1a;
+ private ChronicleMap map2a;
+ private ChronicleMap map3a;
+
+
+ private ReplicationHub hubA;
+
+ public static ChronicleMap localClient(int port) throws IOException {
+ return createClientOf(new InetSocketAddress("localhost", port));
+ }
+
+
+
+
+ @Before
+ public void setup() throws IOException {
+
+ {
+ final TcpTransportAndNetworkConfig tcpConfig = TcpTransportAndNetworkConfig
+ .of(8086)
+ .heartBeatInterval(1, SECONDS);
+
+ hubA = ReplicationHub.builder().tcpTransportAndNetwork(tcpConfig)
+ .createWithId((byte) 1);
+
+ // this is how you add maps after the custer is created
+ map1a = of(String.class, Details.class)
+ .instance().replicatedViaChannel(hubA.createChannel((short) 1)).create();
+
+ map2a = of(byte[].class, byte[].class)
+ .entries(1000)
+ .instance().replicatedViaChannel(hubA.createChannel((short) 2)).create();
+
+ map3a = of(byte[].class, byte[].class)
+ .entries(1000)
+ .instance().replicatedViaChannel(hubA.createChannel((short) 2)).create();
+
+
+ byte[] key = new byte[4];
+ Bytes keyBuffer = new ByteBufferBytes(ByteBuffer.wrap(key));
+
+
+ try (ChronicleMap statelessMap = localClient(8086)) {
+
+ for (int i = 0; i < 10; i++) {
+ keyBuffer.clear();
+ keyBuffer.writeInt(i);
+ statelessMap.put(key, key);
+ }
+
+ assertEquals(10, statelessMap.size());
+ }
+
+
+
+
+ net.openhft.chronicle.bytes.Bytes bytes = BytesStore.wrap(allocate(128)).bytes();
+ TextWire textWire = new TextWire(bytes);
+ textWire.write(() -> "TYPE").text("TextWire");
+
+ }
+
+
+ }
+
+
+
+
+}