diff --git a/src/main/java/net/openhft/chronicle/map/ClientWiredChronicleMapStatelessBuilder.java b/src/main/java/net/openhft/chronicle/map/ClientWiredChronicleMapStatelessBuilder.java deleted file mode 100644 index 80ff05882..000000000 --- a/src/main/java/net/openhft/chronicle/map/ClientWiredChronicleMapStatelessBuilder.java +++ /dev/null @@ -1,124 +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.engine.client.ClientWiredStatelessTcpConnectionHub; -import net.openhft.chronicle.hash.ChronicleHashStatelessClientBuilder; -import net.openhft.lang.MemoryUnit; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @author Rob Austin. - */ -public final class ClientWiredChronicleMapStatelessBuilder implements - ChronicleHashStatelessClientBuilder, - ChronicleMap>, - MapBuilder> { - - - private final ClientWiredStatelessTcpConnectionHub hub; - private Class keyClass; - private Class valueClass; - - public ClientWiredChronicleMapStatelessBuilder( - ClientWiredStatelessTcpConnectionHub hub, - Class keyClass, - Class valueClass, - String name) { - this.keyClass = keyClass; - this.valueClass = valueClass; - this.hub = hub; - this.name = name; - } - - 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); - - @Override - public ClientWiredChronicleMapStatelessBuilder putReturnsNull(boolean putReturnsNull) { - this.putReturnsNull = putReturnsNull; - return this; - } - - boolean putReturnsNull() { - return putReturnsNull; - } - - @Override - public ClientWiredChronicleMapStatelessBuilder removeReturnsNull( - boolean removeReturnsNull) { - this.removeReturnsNull = removeReturnsNull; - return this; - } - - boolean removeReturnsNull() { - return removeReturnsNull; - } - - @Override - public ClientWiredChronicleMapStatelessBuilder timeout(long timeout, TimeUnit units) { - this.timeoutMs = units.toMillis(timeout); - return this; - } - - @Override - public ClientWiredChronicleMapStatelessBuilder name(String name) { - this.name = name; - return this; - } - - String name() { - return name; - } - - @Override - public ClientWiredChronicleMapStatelessBuilder tcpBufferSize(int tcpBufferSize) { - this.tcpBufferSize = tcpBufferSize; - return this; - } - - int tcpBufferSize() { - return tcpBufferSize; - } - - @Override - public ChronicleMap create() throws IOException { - - if (!used.getAndSet(true)) { - return new ClientWiredStatelessChronicleMap( - this, keyClass, valueClass, name, hub); - - } 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/ClientWiredStatelessChronicleMap.java b/src/main/java/net/openhft/chronicle/map/ClientWiredStatelessChronicleMap.java deleted file mode 100644 index 5696ed9e5..000000000 --- a/src/main/java/net/openhft/chronicle/map/ClientWiredStatelessChronicleMap.java +++ /dev/null @@ -1,498 +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.engine.client.ClientWiredStatelessTcpConnectionHub; -import net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub.CoreFields; -import net.openhft.chronicle.hash.function.SerializableFunction; -import net.openhft.chronicle.wire.*; -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.*; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; - -import static java.util.Collections.emptyList; -import static net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub.CoreFields.reply; -import static net.openhft.chronicle.map.ClientWiredStatelessChronicleSet.Params.key; -import static net.openhft.chronicle.map.ClientWiredStatelessChronicleSet.Params.value; -import static net.openhft.chronicle.map.MapWireHandler.EventId; -import static net.openhft.chronicle.map.MapWireHandler.EventId.*; -import static net.openhft.chronicle.map.VanillaChronicleMap.newInstance; - - -/** - * @author Rob Austin. - */ -class ClientWiredStatelessChronicleMap extends MapStatelessClient - implements ChronicleMap, Cloneable, ChannelFactory { - - private static final Logger LOG = - LoggerFactory.getLogger(ClientWiredStatelessChronicleMap.class); - - public static final Consumer VOID_PARAMETERS = out -> out.marshallable(AbstactStatelessClient.EMPTY); - private final Class vClass; - protected Class kClass; - private boolean putReturnsNull; - private boolean removeReturnsNull; - - - public ClientWiredStatelessChronicleMap( - @NotNull final ClientWiredChronicleMapStatelessBuilder config, - @NotNull final Class kClass, - @NotNull final Class vClass, - @NotNull final String channelName, - @NotNull final ClientWiredStatelessTcpConnectionHub hub) { - super(channelName, hub, "MAP", 0); - - this.putReturnsNull = config.putReturnsNull(); - this.removeReturnsNull = config.removeReturnsNull(); - this.kClass = kClass; - this.vClass = vClass; - - } - - - @SuppressWarnings("UnusedDeclaration") - void identifier(int localIdentifier) { - hub.localIdentifier = localIdentifier; - } - - @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 (V) newInstance(vClass, false); - } - - @Override - public K newKeyInstance() { - return newInstance(kClass, true); - } - - @Override - public Class keyClass() { - return kClass; - } - - @Override - public boolean forEachEntryWhile(Predicate> predicate) { - // TODO implement! - throw new UnsupportedOperationException(); - } - - @Override - public void forEachEntry(Consumer> action) { - // TODO implement! - throw new UnsupportedOperationException(); - } - - - public String serverApplicationVersion() { - throw new UnsupportedOperationException(); - } - - @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 (V) proxyReturnTypedObject(putIfAbsent, vClass, key, value); - } - - @SuppressWarnings("NullableProblems") - public boolean remove(Object key, Object value) { - if (key == null) - throw new NullPointerException(); - - return value != null && proxyReturnBooleanWithArgs(removeWithValue, (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 proxyReturnBooleanWithArgs(replaceWithOldAndNewValue, key, oldValue, newValue); - } - - @SuppressWarnings("NullableProblems") - public V replace(K key, V value) { - if (key == null || value == null) - throw new NullPointerException(); - return (V) proxyReturnTypedObject(replace, vClass, key, value); - } - - 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 that = (Map) 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(hashCode); - } - - @NotNull - public String toString() { - final ClientWiredStatelessChronicleSet entrySet = entrySet(); - - - final Iterator> entries = entrySet.iterator(); - if (!entries.hasNext()) - return "{}"; - - StringBuilder sb = new StringBuilder(); - sb.append('{'); - - - while (entries.hasNext()) { - - final Map.Entry e = entries.next(); - final K key = e.getKey(); - final V value = e.getValue(); - sb.append(key == this ? "(this Map)" : key); - sb.append('='); - sb.append(value == this ? "(this Map)" : value); - if (!entries.hasNext()) - return sb.append('}').toString(); - sb.append(',').append(' '); - } - - return sb.toString(); - - } - - - public boolean isEmpty() { - return proxyReturnBoolean(isEmpty, null); - } - - public boolean containsKey(Object key) { - return proxyReturnBoolean(containsKey, out -> out.object(key)); - } - - @NotNull - private NullPointerException keyNotNullNPE() { - return new NullPointerException("key can not be null"); - } - - public boolean containsValue(Object value) { - return proxyReturnBoolean(containsValue, out -> out.object(value)); - } - - public void putAll(@NotNull Map map) { - - proxyReturnVoid(putAll, v -> - map.entrySet().forEach(e -> v.sequence(toParameters(put, e.getKey(), e.getValue()))) - ); - - } - - - public long longSize() { - return proxyReturnLong(longSize); - } - - @Override - public MapKeyContext context(K key) { - throw new UnsupportedOperationException("Contexts are not supported by stateless clients"); - } - - public V get(Object key) { - return (V) this.proxyReturnTypedObject(get, vClass, 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(); - final EventId eventId = removeReturnsNull ? removeWithoutAcc : remove; - return (V) this.proxyReturnTypedObject(eventId, vClass, key); - } - - @Override - public void createChannel(short channelID) { - proxyReturnVoid(createChannel, outValue -> outValue.int16(channelID)); - - } - - - public V put(K key, V value) { - if (key == null || value == null) - throw new NullPointerException(); - return (V) proxyReturnTypedObject(putReturnsNull ? put : getAndPut, - vClass, - key, - value); - } - - - @Nullable - public R getMapped(@Nullable K key, @NotNull SerializableFunction function) { - throw new UnsupportedOperationException(); - } - - @Nullable - @Override - public V putMapped(@Nullable K key, @NotNull UnaryOperator unaryOperator) { - throw new UnsupportedOperationException(); - } - - public void clear() { - proxyReturnVoid(clear); - } - - - @NotNull - @Override - public Collection values() { - return null; - } - - - private final Map cidToCsp = new HashMap<>(); - - @NotNull - public ClientWiredStatelessChronicleSet entrySet() { - - - long cid = proxyReturnWireConsumer(entrySet, (WireIn wireIn) -> { - final long[] cidRef = new long[1]; - final StringBuilder type = Wires.acquireStringBuilder(); - final ValueIn read = wireIn.read(reply); - read.type(type); - read.marshallable(w -> { - - final String csp1 = w.read(CoreFields.csp).text(); - final long cid0 = w.read(CoreFields.cid).int64(); - cidToCsp.put(cid0, csp1); - cidRef[0] = cid0; - - }); - return cidRef[0]; - }); - - - Function> conumer = new Function>() { - Map.Entry e = null; - - @Override - public Map.Entry apply(ValueIn valueIn) { - - valueIn.marshallable(r -> { - final K k = r.read(key).object(kClass); - final V v = r.read(value).object(vClass); - - e = new Map.Entry() { - - @Override - public K getKey() { - return k; - } - - @Override - public V getValue() { - return v; - } - - @Override - public Object setValue(Object value) { - throw new UnsupportedOperationException(); - } - }; - - } - - ); - - return e; - } - }; - - return new ClientWiredStatelessChronicleSet<>(channelName, hub, cid, conumer, "entrySet"); - } - - - @NotNull - public ClientWiredStatelessChronicleSet keySet() { - - throw new UnsupportedOperationException("todo"); - } - - - private int readInt(long tid, long startTime) { - assert !hub.outBytesLock().isHeldByCurrentThread(); - - long timeoutTime = startTime + hub.timeoutMs; - - // receive - hub.inBytesLock().lock(); - try { - final Wire wireIn = hub.proxyReply(timeoutTime, tid); - checkIsData(wireIn); - return wireIn.read(reply).int32(); - } finally { - hub.inBytesLock().unlock(); - } - } - - - @SuppressWarnings("SameParameterValue") - private boolean proxyReturnBoolean(@NotNull final EventId eventId, - @Nullable final Consumer consumer) { - final long startTime = System.currentTimeMillis(); - return readBoolean(sendEvent(startTime, eventId, consumer), startTime); - } - - - @SuppressWarnings("SameParameterValue") - private int proxyReturnInt(@NotNull final EventId eventId) { - final long startTime = System.currentTimeMillis(); - return readInt(sendEvent(startTime, eventId, VOID_PARAMETERS), startTime); - } - - - 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; - ClientWiredStatelessChronicleMap.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/ClientWiredStatelessChronicleSet.java b/src/main/java/net/openhft/chronicle/map/ClientWiredStatelessChronicleSet.java deleted file mode 100644 index ce8aed31e..000000000 --- a/src/main/java/net/openhft/chronicle/map/ClientWiredStatelessChronicleSet.java +++ /dev/null @@ -1,202 +0,0 @@ -package net.openhft.chronicle.map; - -import net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub; -import net.openhft.chronicle.engine.client.ParameterizeWireKey; -import net.openhft.chronicle.wire.ValueIn; -import net.openhft.chronicle.wire.WireKey; -import org.jetbrains.annotations.NotNull; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.function.Function; - -import static net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub.CoreFields.reply; -import static net.openhft.chronicle.map.ClientWiredStatelessChronicleSet.Params.key; -import static net.openhft.chronicle.map.ClientWiredStatelessChronicleSet.Params.segment; -import static net.openhft.chronicle.map.ClientWiredStatelessChronicleSet.SetEventId.*; - - -class ClientWiredStatelessChronicleSet extends MapStatelessClient - implements Set { - - private final Function consumer; - - public ClientWiredStatelessChronicleSet(@NotNull final String channelName, - @NotNull final ClientWiredStatelessTcpConnectionHub hub, - final long cid, - @NotNull final Function wireToSet, - @NotNull final String type) { - - super(channelName, hub, type, cid); - this.consumer = wireToSet; - } - - - @Override - public int size() { - return proxyReturnInt(size); - } - - @Override - public boolean isEmpty() { - return proxyReturnBoolean(isEmpty); - } - - @Override - public boolean contains(Object o) { - return proxyReturnBooleanWithArgs(contains, o); - } - - @NotNull - @Override - public Iterator iterator() { - - // todo improve numberOfSegments - final int numberOfSegments = proxyReturnUint16(SetEventId.numberOfSegments); - - // todo iterate the segments for the moment we just assume one segment - return segmentSet(1).iterator(); - - } - - - /** - * gets the iterator for a given segment - * - * @param segment the maps segment number - * @return and iterator for the {@code segment} - */ - @NotNull - private Set segmentSet(int segment) { - - final Set e = new HashSet(); - - proxyReturnWireConsumerInOut(iterator, - - valueOut -> valueOut.uint16(segment), - - wireIn -> { - - final ValueIn read = wireIn.read(reply); - - while (read.hasNextSequenceItem()) { - read.sequence(v -> e.add(consumer.apply(read))); - } - - return e; - }); - - - return e; - } - - @NotNull - @Override - public Object[] toArray() { - return asSet().toArray(); - } - - @NotNull - private Set asSet() { - - final Set e = new HashSet(); - final int numberOfSegments = proxyReturnUint16(SetEventId.numberOfSegments); - - for (long j = 0; j < numberOfSegments; j++) { - - final long i = j; - proxyReturnWireConsumerInOut(iterator, - - valueOut -> valueOut.uint16(i), - - wireIn -> { - - final ValueIn read = wireIn.read(reply); - - while (read.hasNextSequenceItem()) { - read.sequence(v -> e.add(consumer.apply(read))); - } - - return e; - }); - } - return e; - } - - @NotNull - @Override - public T[] toArray(T[] array) { - return asSet().toArray(array); - } - - @Override - public boolean add(U u) { - return proxyReturnBoolean(add); - } - - - @Override - public boolean remove(Object o) { - return proxyReturnBooleanWithArgs(remove, o); - } - - @Override - public boolean containsAll(Collection c) { - return proxyReturnBooleanWithSequence(containsAll, c); - } - - @Override - public boolean addAll(Collection c) { - return proxyReturnBooleanWithSequence(addAll, c); - } - - - @Override - public boolean retainAll(Collection c) { - return proxyReturnBooleanWithSequence(retainAll, c); - } - - @Override - public boolean removeAll(Collection c) { - return proxyReturnBooleanWithSequence(removeAll, c); - } - - @Override - public void clear() { - proxyReturnVoid(clear); - } - - enum Params implements WireKey { - key, - value, - segment - } - - enum SetEventId implements ParameterizeWireKey { - size, - isEmpty, - add, - addAll, - retainAll, - containsAll, - removeAll, - clear, - remove(key), - numberOfSegments, - contains, - iterator(segment); - - private final WireKey[] params; - -

SetEventId(P... params) { - this.params = params; - } - - public

P[] params() { - return (P[]) this.params; - - } - } -} \ No newline at end of file diff --git a/src/main/java/net/openhft/chronicle/map/EngineMap.java b/src/main/java/net/openhft/chronicle/map/EngineMap.java index 0c82b5070..f2f3978ed 100644 --- a/src/main/java/net/openhft/chronicle/map/EngineMap.java +++ b/src/main/java/net/openhft/chronicle/map/EngineMap.java @@ -43,7 +43,6 @@ public class EngineMap implements ChronicleMap { this.mapWireConnectionHub = mapWireConnectionHub; this.wireType = wireType; - // todo - for the moment we will default to 100 entries per map, but this is for engine to // todo decided later. final ChronicleHashInstanceBuilder instance @@ -89,6 +88,10 @@ public class EngineMap implements ChronicleMap { } private byte[] bytes(Object b) { + + if (b instanceof byte[]) + return (byte[]) b; + if (b == null) return null; final Wire wire = toWire(); @@ -167,7 +170,11 @@ public class EngineMap implements ChronicleMap { } private E toObject(Class eClass, Supplier b) { + final byte[] bytes = b.get(); + if (byte[].class.isAssignableFrom(eClass)) + return (E) bytes; + if (bytes == null) return null; final Wire wire = toWire(bytes); diff --git a/src/main/java/net/openhft/chronicle/map/MapStatelessClient.java b/src/main/java/net/openhft/chronicle/map/MapStatelessClient.java index ea8198266..50f6d296f 100644 --- a/src/main/java/net/openhft/chronicle/map/MapStatelessClient.java +++ b/src/main/java/net/openhft/chronicle/map/MapStatelessClient.java @@ -1,7 +1,8 @@ package net.openhft.chronicle.map; import net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub; -import net.openhft.chronicle.engine.client.ParameterizeWireKey; +import net.openhft.chronicle.wire.CoreFields; +import net.openhft.chronicle.wire.ParameterizeWireKey; import net.openhft.chronicle.wire.WireKey; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -33,7 +34,7 @@ public abstract class MapStatelessClient< E extends ParameterizeWireKey> extends return proxyReturnWireConsumerInOut(eventId, toParameters(eventId, args), - f -> f.read(ClientWiredStatelessTcpConnectionHub.CoreFields.reply) + f -> f.read(CoreFields.reply) .object(resultType)); } @@ -48,14 +49,14 @@ public abstract class MapStatelessClient< E extends ParameterizeWireKey> extends return proxyReturnWireConsumerInOut(eventId, valueOut -> valueOut.object(arg), - f -> f.read(ClientWiredStatelessTcpConnectionHub.CoreFields.reply) + f -> f.read(CoreFields.reply) .object(eClass)); } protected E proxyReturnE(@NotNull final WireKey eventId, @NotNull final Class eClass) { return proxyReturnWireConsumer(eventId, - f -> f.read(ClientWiredStatelessTcpConnectionHub.CoreFields.reply) + f -> f.read(CoreFields.reply) .object(eClass)); } diff --git a/src/main/java/net/openhft/chronicle/map/MapWireConnectionHub.java b/src/main/java/net/openhft/chronicle/map/MapWireConnectionHub.java index 7eb396fff..48a6676f3 100755 --- a/src/main/java/net/openhft/chronicle/map/MapWireConnectionHub.java +++ b/src/main/java/net/openhft/chronicle/map/MapWireConnectionHub.java @@ -23,7 +23,7 @@ import static net.openhft.chronicle.map.ChronicleMapBuilder.of; public class MapWireConnectionHub implements Closeable { public static final int MAP_SERVICE = 3; - private static final Logger LOG = LoggerFactory.getLogger(MapWireHandler.class); + private static final Logger LOG = LoggerFactory.getLogger(MapWireHandlerProcessor.class); private final Map channelMap; private final ReplicationHub hub; private final ArrayList bytesChronicleMaps = new ArrayList<>(); diff --git a/src/main/java/net/openhft/chronicle/map/MapWireHandler.java b/src/main/java/net/openhft/chronicle/map/MapWireHandler.java deleted file mode 100644 index 56644b978..000000000 --- a/src/main/java/net/openhft/chronicle/map/MapWireHandler.java +++ /dev/null @@ -1,705 +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; - -/** - * Created by Rob Austin - */ - -import net.openhft.chronicle.bytes.Bytes; -import net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub; -import net.openhft.chronicle.engine.client.ParameterizeWireKey; -import net.openhft.chronicle.hash.impl.util.BuildVersion; -import net.openhft.chronicle.map.ClientWiredStatelessChronicleSet.SetEventId; -import net.openhft.chronicle.network.WireHandler; -import net.openhft.chronicle.network.event.EventGroup; -import net.openhft.chronicle.network.event.WireHandlers; -import net.openhft.chronicle.wire.*; -import net.openhft.lang.io.DirectStore; -import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.StreamCorruptedException; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Consumer; -import java.util.function.Function; - -import static net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub.CoreFields; -import static net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub.CoreFields.csp; -import static net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub.CoreFields.reply; -import static net.openhft.chronicle.engine.client.StringUtils.endsWith; -import static net.openhft.chronicle.map.ChronicleMapBuilder.*; -import static net.openhft.chronicle.map.MapWireHandler.EventId.*; -import static net.openhft.chronicle.map.MapWireHandler.Params.*; -import static net.openhft.chronicle.wire.Wires.acquireStringBuilder; - -/** - * @author Rob Austin. - */ -public class MapWireHandler implements WireHandler, Consumer { - - private static final Logger LOG = LoggerFactory.getLogger(MapWireHandler.class); - - public static final int SIZE_OF_SIZE = ClientWiredStatelessTcpConnectionHub.SIZE_OF_SIZE; - private final Map incompleteWork = new HashMap<>(); - - private final Map cidToCsp; - @NotNull - private final MapWireConnectionHub mapWireConnectionHub; - private final Map cspToCid = new HashMap<>(); - - - private Wire inWire = null; - private Wire outWire = null; - - private void setCspTextFromCid(long cid) { - cspText.setLength(0); - cspText.append(cidToCsp.get(cid)); - } - - private final Consumer metaDataConsumer = new Consumer() { - - @Override - public void accept(WireIn wireIn) { - - final StringBuilder key = Wires.acquireStringBuilder(); - final ValueIn read = wireIn.read(key); - - if (csp.contentEquals(key)) - read.text(cspText); - else if (CoreFields.cid.contentEquals(key)) - setCspTextFromCid(read.int64()); - - final int slash = cspText.lastIndexOf("/"); - final int hash = cspText.lastIndexOf("#"); - - if (slash != -1 && slash < (cspText.length() - 1) && - hash != -1 && hash < (cspText.length() - 1)) { - final String channelStr = cspText.substring(slash + 1, hash); - try { - - // todo better get the number of entries - bytesChronicleMap = mapWireConnectionHub.acquireMap(channelStr, - of(byte[].class, byte[].class).entries(1000).instance()); - - } catch (IOException e) { - // todo send to user - LOG.error("", e); - } - - } else - bytesChronicleMap = null; - - tid = inWire.read(CoreFields.tid).int64(); - - } - }; - - - private WireHandlers publishLater; - - private BytesChronicleMap bytesChronicleMap; - - - public MapWireHandler( - @NotNull final Map cidToCsp, - @NotNull final MapWireConnectionHub mapWireConnectionHub) throws IOException { - - this.cidToCsp = cidToCsp; - this.mapWireConnectionHub = mapWireConnectionHub; - } - - @Override - public void accept(@NotNull final WireHandlers wireHandlers) { - this.publishLater = wireHandlers; - } - - @Override - public void process(@NotNull final Wire in, @NotNull final Wire out) throws StreamCorruptedException { - try { - this.inWire = in; - this.outWire = out; - inWire.readDocument(metaDataConsumer, dataConsumer); - } catch (Exception e) { - LOG.error("", e); - } - } - - - final StringBuilder cspText = new StringBuilder(); - public long tid; - private final AtomicLong cid = new AtomicLong(); - - /** - * create a new cid if one does not already exist for this csp - * - * @param csp the csp we wish to check for a cid - * @return the cid for this csp - */ - private long createCid(CharSequence csp) { - - final long newCid = cid.incrementAndGet(); - final Long aLong = cspToCid.putIfAbsent(csp, newCid); - - if (aLong != null) - return aLong; - - cidToCsp.put(newCid, csp.toString()); - return newCid; - - } - - - private final Consumer dataConsumer = new Consumer() { - - @Override - public void accept(WireIn wireIn) { - - final StringBuilder eventName = acquireStringBuilder(); - final ValueIn valueIn = inWire.readEventName(eventName); - - if (!incompleteWork.isEmpty()) { - Runnable runnable = incompleteWork.get(CoreFields.tid); - if (runnable != null) { - runnable.run(); - return; - } - } - - final Bytes outBytes = outWire.bytes(); - - outWire.writeDocument(true, wire -> outWire.write(CoreFields.tid).int64(tid)); - - try { - - if (putIfAbsent.contentEquals(eventName)) { - - valueIn.marshallable(wire -> { - - final Params[] params = putIfAbsent.params(); - final byte[] key = wire.read(params[0]).bytes(); - final byte[] value = wire.read(params[1]).bytes(); - - writeValueFromBytes(b -> ((Map) b.delegate).putIfAbsent(key, value)); - - }); - - return; - } - - // -- THESE METHODS ARE USED BOTH MY MAP AND ENTRY-SET - if (size.contentEquals(eventName)) { - write(b -> outWire.write(reply).int32(b.size())); - return; - } - - if (isEmpty.contentEquals(eventName)) { - write(b -> { - final boolean result = b.isEmpty(); - outWire.write(reply).bool(result); - }); - return; - } - - // -- THESE METHODS ARE ONLY ENTRY SET METHODS - if (endsWith(cspText, "#entrySet")) { - - // note : remove on the key-set returns a boolean and on the map returns the - // old value - if (SetEventId.remove.contentEquals(eventName)) { - write(b -> outWire.write(reply).bool( - b.delegate.remove(toByteArray(valueIn)) != null)); - return; - } - - // note : remove on the key-set returns a boolean and on the map returns the - // old value - if (SetEventId.iterator.contentEquals(eventName)) { - write(b -> { - final ValueOut valueOut = outWire.writeEventName(CoreFields.reply); - b.delegate.entrySet().forEach(e -> { - - final Consumer writer = out -> { - - out.marshallable(m -> { - - final byte[] key = (byte[]) e.getKey(); - final byte[] value = (byte[]) e.getValue(); - - m.write(Params.key); - outWire.bytes().write(key); - - m.write(Params.value); - outWire.bytes().write(value); - - }); - - }; - valueOut.sequence(writer); - } - - ); - } - - ); - return; - } - - - if (SetEventId.numberOfSegments.contentEquals(eventName)) { - write(b -> outWire.write(reply).int32(1)); - return; - } - - - - - throw new IllegalStateException("unsupported event=" + eventName); - } - - - // -- THESE METHODS ARE ONLY MAP METHODS - - - if (keySet.contentEquals(eventName)) { - throw new UnsupportedOperationException("todo"); - } - - if (values.contentEquals(eventName)) { - throw new UnsupportedOperationException("todo"); - } - - - if (entrySet.contentEquals(eventName)) { - write(b -> outWire.write(reply).type("set-proxy").writeValue() - - .marshallable(w -> { - CharSequence root = cspText.subSequence(0, cspText - .length() - "#map".length()); - - final StringBuilder csp = acquireStringBuilder() - .append(root) - .append("#entrySet"); - - w.write(CoreFields.csp).text(csp); - w.write(CoreFields.cid).int64(createCid(csp)); - } - - )); - return; - } - - if (longSize.contentEquals(eventName)) { - write(b -> outWire.write(reply).int64(b.longSize())); - return; - } - - - if (containsKey.contentEquals(eventName)) { - // todo remove the toByteArray(..) - write(b -> outWire.write(reply) - .bool(b.delegate.containsKey(toByteArray(valueIn)))); - return; - } - - if (containsValue.contentEquals(eventName)) { - // todo remove the toByteArray(..) - write(b -> outWire.write(reply) - .bool(b.delegate.containsValue(toByteArray(valueIn)))); - return; - } - - if (get.contentEquals(eventName)) { - // todo remove the toByteArray(..) - writeValueUsingDelegate(map -> { - final byte[] key = toByteArray(valueIn); - return map.get(key); - }); - return; - } - - if (getAndPut.contentEquals(eventName)) { - - valueIn.marshallable(wire -> { - - final Params[] params = getAndPut.params(); - - MapWireHandler.this.writeValue(b -> { - byte[] k = wire.read(params[0]).bytes(); - byte[] v = wire.read(params[1]).bytes(); - return b.put(k, v); - }); - - }); - - return; - } - - if (remove.contentEquals(eventName)) { - writeValue(b -> b.remove(toByteArray(valueIn))); - return; - } - - if (clear.contentEquals(eventName)) { - writeVoid(BytesChronicleMap::clear); - return; - } - - if (putAll.contentEquals(eventName)) { - - final Map data = new HashMap(); - - writeVoid(b -> { - while (valueIn.hasNext()) { - valueIn.sequence(v -> valueIn.marshallable(wire -> data.put( - wire.read(put.params()[0]).bytes(), - wire.read(put.params()[1]).bytes()))); - } - b.delegate.putAll(data); - - }); - - return; - } - - - if (replace.contentEquals(eventName)) { - - - // todo fix this this is a hack to get to work for now. - // todo may use something like : - // todo bytesMap.replace(reader, reader, timestamp, identifier()); - - valueIn.marshallable(wire -> { - final Params[] params = replace.params(); - final byte[] key = wire.read(params[0]).bytes(); - final byte[] value = wire.read(params[1]).bytes(); - - writeValueFromBytes(b -> ((Map) b.delegate).replace(key, value)); - - }); - - - return; - } - - if (replaceWithOldAndNewValue.contentEquals(eventName)) { - write(bytesMap -> { - final net.openhft.lang.io.Bytes reader = toReader(valueIn, - replaceWithOldAndNewValue.params()); - boolean result = bytesMap.replace(reader, reader, reader); - outWire.write(reply).bool(result); - }); - - return; - } - - if (putIfAbsent.contentEquals(eventName)) { - valueIn.marshallable(wire -> { - final Params[] params = putIfAbsent.params(); - final byte[] key = wire.read(params[0]).bytes(); - final byte[] value = wire.read(params[1]).bytes(); - - writeValueFromBytes(b -> ((Map) b.delegate).putIfAbsent(key, value)); - - }); - - return; - } - - if (removeWithValue.contentEquals(eventName)) { - write(bytesMap -> { - final net.openhft.lang.io.Bytes reader = toReader(valueIn, removeWithValue.params()); - // todo call outWire.write(result) - // .bool(bytesMap.remove(reader, reader, timestamp, identifier())); - outWire.write(reply).bool(bytesMap.remove(reader, reader)); - }); - return; - } - - - if (getApplicationVersion.contentEquals(eventName)) { - write(b -> outWire.write(reply).text(applicationVersion())); - return; - } - - if (persistedDataVersion.contentEquals(eventName)) { - write(b -> outWire.write(reply).text(persistedDataVersion())); - return; - } - - if (hashCode.contentEquals(eventName)) { - write(b -> outWire.write(reply).int32(b.hashCode())); - return; - } - - throw new IllegalStateException("unsupported event=" + eventName); - - } catch (Exception e) { - LOG.error("", e); - } finally { - - if (EventGroup.IS_DEBUG) { - long len = outBytes.position() - SIZE_OF_SIZE; - if (len == 0) { - System.out.println("--------------------------------------------\n" + - "server writes:\n\n"); - } else { - - - System.out.println("--------------------------------------------\n" + - "server writes:\n\n" + - Wires.fromSizePrefixedBlobs(outBytes, SIZE_OF_SIZE, len)); - - } - } - } - - } - }; - - - @SuppressWarnings("SameReturnValue") - private void writeValueFromBytes(final Function f) { - - write(b -> { - - byte[] fromBytes = f.apply(b); - boolean isNull = fromBytes == null || fromBytes.length == 0; - outWire.write(reply); - - if (isNull) - outWire.writeValue().text(null); - else { - Bytes bytes = outWire.bytes(); - bytes.write(fromBytes); - } - - }); - } - - - @NotNull - private CharSequence persistedDataVersion() { - - if (bytesChronicleMap == null) - return ""; - return bytesChronicleMap.delegate.persistedDataVersion(); - } - - @NotNull - private CharSequence applicationVersion() { - return BuildVersion.version(); - } - - /** - * creates a lang buffer that holds just the payload of the args - * - * @return a new lang buffer containing the bytes of the args - */ - private net.openhft.lang.io.Bytes toReader(ValueIn valueIn, Params... params) { - - // todo this is a bit of a hack - final Bytes bytes1 = valueIn.wireIn().bytes(); - final long inSize = bytes1.remaining(); - - final net.openhft.lang.io.Bytes bytes = DirectStore.allocate(inSize + 1024).bytes(); - - valueIn.marshallable(wire -> { - - for (Params p : params) { - - final ValueIn read = wire.read(p); - - final byte[] data = read.bytes(); - - bytes.writeStopBit(data.length); - bytes.write(data); - } - - }); - - - return bytes.flip(); - } - - - private byte[] toByteArray(ValueIn valueIn) { - final String text = valueIn.text(); - return text.getBytes(); - } - - - @SuppressWarnings("SameReturnValue") - private void writeValue(final Function, byte[]> f) { - writeValueFromBytes(b -> { - final Map delegate = (Map) b.delegate; - return f.apply(delegate); - }); - } - - @SuppressWarnings("SameReturnValue") - private void writeValueUsingDelegate(final Function, byte[]> f) { - - write(b -> { - - byte[] result = f.apply((ChronicleMap) b.delegate); - boolean isNull = result == null || result.length == 0; - - outWire.write(reply); - final Bytes bytes = outWire.bytes(); - - if (isNull) - outWire.writeValue().text(null); - else - bytes.write(result); - - }); - - - } - - - @SuppressWarnings("SameReturnValue") - void write(@NotNull Consumer c) { - - - if (bytesChronicleMap == null) { - LOG.error("no map for channel."); - return; - } - - bytesChronicleMap.output = null; - - outWire.writeDocument(false, out -> { - long position = 0; - try { - position = outWire.bytes().position(); - c.accept(bytesChronicleMap); - } catch (Exception e) { - // bytes.reset(); - // the idea of wire is that is platform independent, - // so we wil have to send the exception as a String - outWire.bytes().position(position); - - final WireOut o = out.write(reply) - .type(e.getClass().getSimpleName()); - - if (e.getMessage() != null) - o.writeValue().text(e.getMessage()); - - LOG.error("", e); - } - }); - - - } - - - @SuppressWarnings("SameReturnValue") - private void writeVoid(@NotNull Consumer process) { - - // skip 4 bytes where we will write the size - - if (bytesChronicleMap == null) { - LOG.error("no map for channelId."); - return; - } - - - try { - outWire.bytes().mark(); - process.accept(bytesChronicleMap); - - } catch (Exception e) { - outWire.writeDocument(false, out -> { - // bytes.reset(); - // the idea of wire is that is platform independent, - // so we wil have to send the exception as a String - outWire.bytes().reset(); - out.write(reply) - .type(e.getClass().getSimpleName()) - .writeValue().text(e.getMessage()); - LOG.error("", e); - }); - } - - - } - - - enum Params implements WireKey { - key, - value, - oldValue, - newValue - } - - enum EventId implements ParameterizeWireKey { - longSize, - size, - isEmpty, - containsKey(key), - containsValue(value), - get(key), - getAndPut(key, value), - put(key, value), - remove(key), - removeWithoutAcc(key), - clear, - keySet, - values, - entrySet, - entrySetRestricted, - replace(key, value), - replaceWithOldAndNewValue(key, oldValue, newValue), - putIfAbsent(key, value), - removeWithValue(key, value), - toString, - getApplicationVersion, - persistedDataVersion, - putAll, - putAllWithoutAcc, - hashCode, - mapForKey, - putMapped, - keyBuilder, - valueBuilder, - createChannel, - remoteIdentifier; - - private final WireKey[] params; - -

EventId(P... params) { - this.params = params; - } - - public

P[] params() { - return (P[]) this.params; - - } - } - - -} - diff --git a/src/main/java/net/openhft/chronicle/map/MapWireHandlerBuilder.java b/src/main/java/net/openhft/chronicle/map/MapWireHandlerBuilder.java deleted file mode 100644 index 90936d365..000000000 --- a/src/main/java/net/openhft/chronicle/map/MapWireHandlerBuilder.java +++ /dev/null @@ -1,37 +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.hash.ChronicleHashInstanceBuilder; -import net.openhft.chronicle.hash.replication.ReplicationHub; -import net.openhft.chronicle.network.WireHandler; -import net.openhft.chronicle.wire.WireKey; -import org.jetbrains.annotations.NotNull; - -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -/** - * Created by Rob Austin - */ -public class MapWireHandlerBuilder { - -} - diff --git a/src/main/java/net/openhft/chronicle/map/MapWireHandlerProcessor.java b/src/main/java/net/openhft/chronicle/map/MapWireHandlerProcessor.java new file mode 100644 index 000000000..f718179a7 --- /dev/null +++ b/src/main/java/net/openhft/chronicle/map/MapWireHandlerProcessor.java @@ -0,0 +1,486 @@ +/* + * 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; + +/** + * Created by Rob Austin + */ + +import net.openhft.chronicle.bytes.Bytes; +import net.openhft.chronicle.engine.client.ClientWiredStatelessTcpConnectionHub; +import net.openhft.chronicle.hash.impl.util.BuildVersion; +import net.openhft.chronicle.network.event.EventGroup; +import net.openhft.chronicle.wire.*; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.StreamCorruptedException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; + +import static net.openhft.chronicle.map.MapWireHandlerProcessor.EventId.*; +import static net.openhft.chronicle.map.MapWireHandlerProcessor.Params.*; +import static net.openhft.chronicle.wire.CoreFields.reply; +import static net.openhft.chronicle.wire.Wires.acquireStringBuilder; + + +/** + * @author Rob Austin. + */ +public class MapWireHandlerProcessor implements MapWireHandler>, Consumer { + + private CharSequence csp; + + @Override + public void process(Wire in, Wire out, ConcurrentMap map, CharSequence csp) throws + StreamCorruptedException { + + try { + this.inWire = in; + this.outWire = out; + this.map = map; + this.csp = csp; + inWire.readDocument(metaDataConsumer, dataConsumer); + } catch (Exception e) { + LOG.error("", e); + } + + } + + enum Params implements WireKey { + key, + value, + oldValue, + newValue + } + + public enum EventId implements ParameterizeWireKey { + longSize, + size, + isEmpty, + containsKey(key), + containsValue(value), + get(key), + getAndPut(key, value), + put(key, value), + remove(key), + removeWithoutAcc(key), + clear, + keySet, + values, + entrySet, + entrySetRestricted, + replace(key, value), + replaceWithOldAndNewValue(key, oldValue, newValue), + putIfAbsent(key, value), + removeWithValue(key, value), + toString, + getApplicationVersion, + persistedDataVersion, + putAll, + putAllWithoutAcc, + hashCode, + mapForKey, + putMapped, + keyBuilder, + valueBuilder, + createChannel, + remoteIdentifier; + + private final WireKey[] params; + +

EventId(P... params) { + this.params = params; + } + + public

P[] params() { + return (P[]) this.params; + } + } + + + private static final Logger LOG = LoggerFactory.getLogger(MapWireHandlerProcessor.class); + + public static final int SIZE_OF_SIZE = ClientWiredStatelessTcpConnectionHub.SIZE_OF_SIZE; + private final Map incompleteWork = new HashMap<>(); + + private final Map cidToCsp; + @NotNull + private final Map cspToCid = new HashMap<>(); + + private Wire inWire = null; + private Wire outWire = null; + + + private final Consumer metaDataConsumer = new Consumer() { + + @Override + public void accept(WireIn wireIn) { + + StringBuilder sb = Wires.acquireStringBuilder(); + + for (; ; ) { + final ValueIn read = inWire.read(sb); + if (CoreFields.tid.contentEquals(sb)) { + tid = read.int64(); + break; + } + } + + + } + }; + + private ConcurrentMap map; + + + private WireHandlers publishLater; + + + public MapWireHandlerProcessor(@NotNull final Map cidToCsp) throws IOException { + this.cidToCsp = cidToCsp; + } + + @Override + public void accept(@NotNull final WireHandlers wireHandlers) { + this.publishLater = wireHandlers; + } + + public long tid; + private final AtomicLong cid = new AtomicLong(); + + /** + * create a new cid if one does not already exist for this csp + * + * @param csp the csp we wish to check for a cid + * @return the cid for this csp + */ + private long createCid(CharSequence csp) { + + final long newCid = cid.incrementAndGet(); + final Long aLong = cspToCid.putIfAbsent(csp, newCid); + + if (aLong != null) + return aLong; + + cidToCsp.put(newCid, csp.toString()); + return newCid; + + } + + final StringBuilder eventName = new StringBuilder(); + + private final Consumer dataConsumer = new Consumer() { + + @Override + public void accept(WireIn wireIn) { + final Bytes outBytes = outWire.bytes(); + try { + + final ValueIn valueIn = inWire.readEventName(eventName); + + if (!incompleteWork.isEmpty()) { + Runnable runnable = incompleteWork.get(CoreFields.tid); + if (runnable != null) { + runnable.run(); + return; + } + } + + outWire.writeDocument(true, wire -> outWire.write(CoreFields.tid).int64(tid)); + + writeData(out -> { + + if (clear.contentEquals(eventName)) { + map.clear(); + return; + } + + if (putAll.contentEquals(eventName)) { + + final Map data = new HashMap(); + while (valueIn.hasNext()) { + valueIn.sequence(v -> valueIn.marshallable(wire -> data.put( + wire.read(put.params()[0]).bytes(), + wire.read(put.params()[1]).bytes()))); + } + + map.putAll(data); + return; + } + + + if (EventId.putIfAbsent.contentEquals(eventName)) { + + valueIn.marshallable(wire -> { + + final Params[] params = putIfAbsent.params(); + final byte[] key = wire.read(params[0]).bytes(); + final byte[] value = wire.read(params[1]).bytes(); + final ValueOut v = outWire.write(reply); + writeValue((map).putIfAbsent(key, value)); + + }); + + return; + } + + + // -- THESE METHODS ARE USED BOTH MY MAP AND ENTRY-SET + if (size.contentEquals(eventName)) { + outWire.write(reply).int32(map.size()); + return; + } + + + if (longSize.contentEquals(eventName)) { + outWire.write(reply).int32(map.size()); + return; + } + + + if (isEmpty.contentEquals(eventName)) { + outWire.write(reply).bool(map.isEmpty()); + return; + } + + if (keySet.contentEquals(eventName)) { + throw new UnsupportedOperationException("todo"); + } + + if (values.contentEquals(eventName)) { + throw new UnsupportedOperationException("todo"); + } + + + if (entrySet.contentEquals(eventName)) { + outWire.write(reply).type("set-proxy").writeValue() + + .marshallable(w -> { + CharSequence root = csp.subSequence(0, csp + .length() - "#map".length()); + + final StringBuilder csp = acquireStringBuilder() + .append(root) + .append("#entrySet"); + + w.write(CoreFields.csp).text(csp); + w.write(CoreFields.cid).int64(createCid(csp)); + }); + + + return; + } + + if (size.contentEquals(eventName)) { + outWire.write(reply).int64(map.size()); + return; + } + + + if (containsKey.contentEquals(eventName)) { + outWire.write(reply) + .bool(map.containsKey(toByteArray(valueIn))); + return; + } + + if (containsValue.contentEquals(eventName)) { + outWire.write(reply).bool(map.containsValue(toByteArray(valueIn))); + return; + } + + if (get.contentEquals(eventName)) { + + outWire.write(reply); + writeValue(map.get(toByteArray(valueIn))); + return; + } + + if (getAndPut.contentEquals(eventName)) { + + valueIn.marshallable(wire -> { + + final Params[] params = getAndPut.params(); + + byte[] k = wire.read(params[0]).bytes(); + byte[] v = wire.read(params[1]).bytes(); + outWire.write(reply); + writeValue(map.put(k, v)); + + }); + + return; + } + + if (remove.contentEquals(eventName)) { + outWire.write(reply); + writeValue(map.remove(toByteArray(valueIn))); + return; + } + + + if (replace.contentEquals(eventName)) { + valueIn.marshallable(wire -> { + final Params[] params = replace.params(); + final byte[] key = wire.read(params[0]).bytes(); + final byte[] value = wire.read(params[1]).bytes(); + outWire.write(reply); + writeValue(map.replace(key, value)); + + }); + + + return; + } + + if (replaceWithOldAndNewValue.contentEquals(eventName)) { + valueIn.marshallable(wire -> { + final Params[] params = replaceWithOldAndNewValue.params(); + final byte[] key = wire.read(params[0]).bytes(); + final byte[] oldValue = wire.read(params[1]).bytes(); + final byte[] newValue = wire.read(params[2]).bytes(); + outWire.write(reply).bool(map.replace(key, oldValue, newValue)); + + }); + return; + } + + if (putIfAbsent.contentEquals(eventName)) { + valueIn.marshallable(wire -> { + final Params[] params = putIfAbsent.params(); + final byte[] key = wire.read(params[0]).bytes(); + final byte[] value = wire.read(params[1]).bytes(); + outWire.write(reply); + writeValue(map.putIfAbsent(key, value)); + + }); + + return; + } + + if (removeWithValue.contentEquals(eventName)) { + throw new UnsupportedOperationException("todo"); + } + + + if (getApplicationVersion.contentEquals(eventName)) { + outWire.write(reply).text(applicationVersion()); + return; + } + + + if (hashCode.contentEquals(eventName)) { + outWire.write(reply).int32(map.hashCode()); + return; + } + + throw new IllegalStateException("unsupported event=" + eventName); + }); + } catch (Exception e) { + LOG.error("", e); + } finally + + { + + if (EventGroup.IS_DEBUG) { + + long len = outBytes.position() - SIZE_OF_SIZE; + if (len == 0) { + System.out.println("--------------------------------------------\n" + + "server writes:\n\n"); + } else { + + + System.out.println("--------------------------------------------\n" + + "server writes:\n\n" + + Wires.fromSizePrefixedBlobs(outBytes, SIZE_OF_SIZE, len)); + + } + } + } + + + } + }; + + + @NotNull + private CharSequence applicationVersion() { + return BuildVersion.version(); + } + + private byte[] toByteArray(ValueIn valueIn) { + final String text = valueIn.text(); + return text.getBytes(); + } + + @SuppressWarnings("SameReturnValue") + private void writeValue(final Object o) { + + if (o instanceof byte[]) + outWire.bytes().write((byte[]) o); + else + outWire.getValueOut().object(o); + + } + + private long start; + + + /** + * write and exceptions and rolls back if no data was written + */ + private void writeData(@NotNull Consumer c) { + + final long position = outWire.bytes().position(); + + outWire.writeDocument(false, out -> { + + start = outWire.bytes().position(); + + try { + c.accept(outWire); + + } catch (Exception e) { + + LOG.error("", e); + out.getValueOut() + .type(e.getClass().getSimpleName()) + .writeValue().text(e.getMessage()); + } + }); + + // rollback if no data was written + if (start == outWire.bytes().position()) { + if (outWire.bytes().position() == start) { + outWire.bytes().position(position); + } + + } + + } + + +} +