repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/NativeTransport.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.concurrent.ExecutorService; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollDatagramChannel; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.channel.socket.nio.NioSocketChannel; // This is a separate class for easier replacement within Quarkus public final class NativeTransport { private static final boolean IS_LINUX = System.getProperty("os.name").toLowerCase().startsWith("linux"); private static final String USE_EPOLL_PROPERTY = "infinispan.server.channel.epoll"; private static final String USE_IOURING_PROPERTY = "infinispan.server.channel.iouring"; private static final boolean EPOLL_DISABLED = System.getProperty(USE_EPOLL_PROPERTY, "true").equalsIgnoreCase("false"); private static final boolean IOURING_DISABLED = System.getProperty(USE_IOURING_PROPERTY, "true").equalsIgnoreCase("false"); // Has to be after other static variables to ensure they are initialized static final boolean USE_NATIVE_EPOLL = useNativeEpoll(); static final boolean USE_NATIVE_IOURING = useNativeIOUring(); private static boolean useNativeEpoll() { try { Class.forName("io.netty.channel.epoll.Epoll", true, NativeTransport.class.getClassLoader()); if (Epoll.isAvailable()) { return !EPOLL_DISABLED && IS_LINUX; } else { if (IS_LINUX) { HOTROD.epollNotAvailable(Epoll.unavailabilityCause().toString()); } } } catch (ClassNotFoundException e) { if (IS_LINUX) { HOTROD.epollNotAvailable(e.getMessage()); } } return false; } private static boolean useNativeIOUring() { try { Class.forName("io.netty.incubator.channel.uring.IOUring", true, NativeTransport.class.getClassLoader()); if (io.netty.incubator.channel.uring.IOUring.isAvailable()) { return !IOURING_DISABLED && IS_LINUX; } else { if (IS_LINUX) { HOTROD.ioUringNotAvailable(io.netty.incubator.channel.uring.IOUring.unavailabilityCause().toString()); } } } catch (ClassNotFoundException e) { if (IS_LINUX) { HOTROD.ioUringNotAvailable(e.getMessage()); } } return false; } public static Class<? extends SocketChannel> socketChannelClass() { if (USE_NATIVE_EPOLL) { return EpollSocketChannel.class; } else if (USE_NATIVE_IOURING) { return IOURingNativeTransport.socketChannelClass(); } else { return NioSocketChannel.class; } } public static Class<? extends DatagramChannel> datagramChannelClass() { if (USE_NATIVE_EPOLL) { return EpollDatagramChannel.class; } else if (USE_NATIVE_IOURING) { return IOURingNativeTransport.datagramChannelClass(); } else { return NioDatagramChannel.class; } } public static EventLoopGroup createEventLoopGroup(int maxExecutors, ExecutorService executorService) { if (USE_NATIVE_EPOLL) { return new EpollEventLoopGroup(maxExecutors, executorService); } else if (USE_NATIVE_IOURING) { return IOURingNativeTransport.createEventLoopGroup(maxExecutors, executorService); } else { return new NioEventLoopGroup(maxExecutors, executorService); } } }
3,781
37.989691
126
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ByteBufUtil.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.commons.io.SignedNumeric.encode; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.transaction.manager.RemoteXid; import org.infinispan.commons.util.Util; import io.netty.buffer.ByteBuf; /** * Helper methods for writing varints, arrays and strings to {@link ByteBuf}. */ public final class ByteBufUtil { private ByteBufUtil() {} public static byte[] readArray(ByteBuf buf) { int length = readVInt(buf); byte[] bytes = new byte[length]; buf.readBytes(bytes, 0, length); return bytes; } public static String readString(ByteBuf buf) { byte[] strContent = readArray(buf); return new String(strContent, HotRodConstants.HOTROD_STRING_CHARSET); } public static void writeString(ByteBuf buf, String string) { if (string != null && !string.isEmpty()) { writeArray(buf, string.getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); } else { writeVInt(buf, 0); } } public static void writeOptionalString(ByteBuf buf, String string) { if (string == null) { writeSignedVInt(buf, -1); } else { writeOptionalArray(buf, string.getBytes(HotRodConstants.HOTROD_STRING_CHARSET)); } } public static void writeArray(ByteBuf buf, byte[] toAppend) { writeVInt(buf, toAppend.length); buf.writeBytes(toAppend); } public static void writeArray(ByteBuf buf, byte[] toAppend, int offset, int count) { writeVInt(buf, count); buf.writeBytes(toAppend, offset, count); } public static int estimateArraySize(byte[] array) { return estimateVIntSize(array.length) + array.length; } public static int estimateVIntSize(int value) { return (32 - Integer.numberOfLeadingZeros(value)) / 7 + 1; } public static void writeOptionalArray(ByteBuf buf, byte[] toAppend) { writeSignedVInt(buf, toAppend.length); buf.writeBytes(toAppend); } public static void writeVInt(ByteBuf buf, int i) { while ((i & ~0x7F) != 0) { buf.writeByte((byte) ((i & 0x7f) | 0x80)); i >>>= 7; } buf.writeByte((byte) i); } public static void writeSignedVInt(ByteBuf buf, int i) { writeVInt(buf, encode(i)); } public static void writeVLong(ByteBuf buf, long i) { while ((i & ~0x7F) != 0) { buf.writeByte((byte) ((i & 0x7f) | 0x80)); i >>>= 7; } buf.writeByte((byte) i); } public static int estimateVLongSize(long value) { return (64 - Long.numberOfLeadingZeros(value)) / 7 + 1; } public static long readVLong(ByteBuf buf) { byte b = buf.readByte(); long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = buf.readByte(); i |= (b & 0x7FL) << shift; } return i; } public static int readVInt(ByteBuf buf) { byte b = buf.readByte(); int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = buf.readByte(); i |= (b & 0x7FL) << shift; } return i; } public static String limitedHexDump(ByteBuf buf) { return Util.hexDump(buf::getByte, buf.readerIndex(), buf.readableBytes()); } /** * Estimates the {@link Xid} encoding size. * <p> * If the instance is a {@link RemoteXid}, the estimation is accurate. Otherwise, the max size is used. * * @param xid the {@link Xid} instance to test. * @return the estimated size. */ public static int estimateXidSize(Xid xid) { if (xid instanceof RemoteXid) { return ((RemoteXid) xid).estimateSize(); } else { // Worst case. // To be more accurate, we need to invoke getGlobalTransactionId and getBranchQualifier that will most likely //create and copy the array return estimateVIntSize(xid.getFormatId()) + Xid.MAXBQUALSIZE + Xid.MAXGTRIDSIZE; } } /** * Writes the {@link Xid} to the {@link ByteBuf}. * * @param buf the buffer to write to. * @param xid the {@link Xid} to encode */ public static void writeXid(ByteBuf buf, Xid xid) { if (xid instanceof RemoteXid) { ((RemoteXid) xid).writeTo(buf); } else { ByteBufUtil.writeSignedVInt(buf, xid.getFormatId()); writeArray(buf, xid.getGlobalTransactionId()); writeArray(buf, xid.getBranchQualifier()); } } }
4,564
28.836601
118
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ActivationHandler.java
package org.infinispan.client.hotrod.impl.transport.netty; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /** * Handler that is added to the end of pipeline during channel creation and handshake. * Its task is to complete {@link ChannelRecord}. */ @Sharable class ActivationHandler extends ChannelInboundHandlerAdapter { static final String NAME = "activation-handler"; private static final Log log = LogFactory.getLog(ActivationHandler.class); static final ActivationHandler INSTANCE = new ActivationHandler(); static final Object ACTIVATION_EVENT = new Object(); @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (log.isTraceEnabled()) { log.tracef("Activating channel %s", ctx.channel()); } ChannelRecord.of(ctx.channel()).complete(ctx.channel()); ctx.pipeline().remove(this); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == ACTIVATION_EVENT) { channelActive(ctx); } else { ctx.fireUserEventTriggered(evt); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Channel channel = ctx.channel(); if (log.isTraceEnabled()) { log.tracef(cause, "Failed to activate channel %s", channel); } try { ctx.close(); } finally { ChannelRecord channelRecord = ChannelRecord.of(channel); // With sync Hot Rod any failure to fetch a transport from pool was wrapped in TransportException channelRecord.completeExceptionally(new TransportException(cause, channelRecord.getUnresolvedAddress())); } } }
2,042
35.482143
114
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelPool.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.SocketAddress; import java.util.Deque; import java.util.NoSuchElementException; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.locks.StampedLock; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.configuration.ExhaustedAction; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.channel.Channel; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.ScheduledFuture; import io.netty.util.internal.PlatformDependent; /** * This is a custom implementation of {@link io.netty.channel.Channel} pooling. * Compared to {@link io.netty.channel.pool.ChannelPool} implementations in Netty it does not enforce context switch before writing to the channel. * **Update**: Netty enforces going through event loop later on by delegating the write through {@link io.netty.channel.AbstractChannelHandlerContext.WriteTask}. * So writing the socket in caller thread is still TODO. * <p> * It should be also more allocation-efficient since it does not create futures and invokes the callback directly if the * channel is available. * <p> * The connections are handled LIFO, pending requests are handled FIFO. */ class ChannelPool { enum ChannelEventType { CONNECTED, CLOSED_IDLE, CLOSED_ACTIVE, CONNECT_FAILED} private static final AtomicIntegerFieldUpdater<TimeoutCallback> invokedUpdater = AtomicIntegerFieldUpdater.newUpdater(TimeoutCallback.class, "invoked"); private static final Log log = LogFactory.getLog(ChannelPool.class); private static final int MAX_FULL_CHANNELS_SEEN = 10; private final Deque<Channel> channels = PlatformDependent.newConcurrentDeque(); private final Deque<ChannelOperation> callbacks = PlatformDependent.newConcurrentDeque(); private final EventExecutor executor; private final SocketAddress address; private final ChannelInitializer newChannelInvoker; private final ExhaustedAction exhaustedAction; private final BiConsumer<ChannelPool, ChannelEventType> connectionFailureListener; private final long maxWait; private final int maxConnections; private final int maxPendingRequests; private final AtomicInteger created = new AtomicInteger(); private final AtomicInteger active = new AtomicInteger(); private final AtomicInteger connected = new AtomicInteger(); private final StampedLock lock = new StampedLock(); private volatile boolean terminated = false; private volatile boolean suspected = false; ChannelPool(EventExecutor executor, SocketAddress address, ChannelInitializer newChannelInvoker, ExhaustedAction exhaustedAction, BiConsumer<ChannelPool, ChannelEventType> connectionFailureListener, long maxWait, int maxConnections, int maxPendingRequests) { this.connectionFailureListener = connectionFailureListener; this.executor = executor; this.address = address; this.newChannelInvoker = newChannelInvoker; this.exhaustedAction = exhaustedAction; this.maxWait = maxWait; this.maxConnections = maxConnections; this.maxPendingRequests = maxPendingRequests; } public void acquire(ChannelOperation callback) { if (terminated) { callback.cancel(address, new RejectedExecutionException("Pool was terminated")); return; } // We could acquire an active channel and submit the callback. if (executeDirectlyIfPossible(callback)) return; // wait action if (maxWait > 0) { TimeoutCallback timeoutCallback = new TimeoutCallback(callback); timeoutCallback.timeoutFuture = executor.schedule(timeoutCallback, maxWait, TimeUnit.MILLISECONDS); callback = timeoutCallback; } // Between the check time and adding the callback to the queue, we could have a channel available. // Let's just try again. if (!executeOrEnqueue(callback)) { boolean remove = false; try { remove = executeDirectlyIfPossible(callback); } finally { if (remove) { callbacks.remove(callback); } } } } boolean executeDirectlyIfPossible(ChannelOperation callback) { Channel channel; int fullChannelsSeen = 0; while ((channel = channels.pollFirst()) != null) { if (!channel.isActive()) { // The channel was closed while idle but not removed - just forget it continue; } if (!channel.isWritable() || channel.pipeline().get(HeaderDecoder.class).registeredOperations() >= maxPendingRequests) { channels.addLast(channel); // prevent looping on non-writable channels if (++fullChannelsSeen < MAX_FULL_CHANNELS_SEEN) { continue; } else { break; } } return activateChannel(channel, callback, false); } int current = created.get(); while (current < maxConnections) { if (created.compareAndSet(current, current + 1)) { int currentActive = active.incrementAndGet(); if (log.isTraceEnabled()) log.tracef("[%s] Creating new channel, created = %d, active = %d", address, current + 1, currentActive); // create new connection and apply callback createAndInvoke(callback); return true; } current = created.get(); } // reached max connections switch (exhaustedAction) { case EXCEPTION: throw new NoSuchElementException("Reached maximum number of connections"); case WAIT: break; case CREATE_NEW: int currentCreated = created.incrementAndGet(); int currentActive = active.incrementAndGet(); if (log.isTraceEnabled()) log.tracef("[%s] Creating new channel, created = %d, active = %d", address, currentCreated, currentActive); createAndInvoke(callback); return true; default: throw new IllegalArgumentException(String.valueOf(exhaustedAction)); } return false; } private boolean executeOrEnqueue(ChannelOperation callback) { Channel channel; // To prevent adding channel and callback concurrently we'll synchronize all additions // TODO: completely lock-free algorithm would be better long stamp = lock.writeLock(); try { for (;;) { // at this point we won't be picky and use non-writable channel anyway channel = channels.pollFirst(); if (channel == null) { if (log.isTraceEnabled()) log.tracef("[%s] No channel available, adding callback to the queue %s", address, callback); callbacks.addLast(callback); return false; } else if (channel.isActive()) { break; } } } finally { lock.unlockWrite(stamp); } return activateChannel(channel, callback, false); } private void createAndInvoke(ChannelOperation callback) { try { newChannelInvoker.createChannel().whenComplete((channel, throwable) -> { if (throwable != null) { int currentActive = active.decrementAndGet(); if (currentActive < 0) { HOTROD.invalidActiveCountAfterClose(channel); } int currentCreated = created.decrementAndGet(); if (currentCreated < 0) { HOTROD.invalidCreatedCountAfterClose(channel); } if (log.isTraceEnabled()) log.tracef(throwable, "[%s] Channel could not be created, created = %d, active = %d, connected = %d", address, currentCreated, currentActive, connected.get()); // Update about a possibly failing server before cancelling the callback. connectionFailureListener.accept(this, ChannelEventType.CONNECT_FAILED); callback.cancel(address, throwable); maybeRejectPendingCallbacks(throwable); } else { suspected = false; int currentConnected = connected.incrementAndGet(); if (log.isTraceEnabled()) log.tracef("[%s] Channel connected, created = %d, active = %d, connected = %d", address, created.get(), active.get(), currentConnected); callback.invoke(channel); connectionFailureListener.accept(this, ChannelEventType.CONNECTED); } }); } catch (Throwable t) { int currentActive = active.decrementAndGet(); int currentCreated = created.decrementAndGet(); if (log.isTraceEnabled()) log.tracef(t, "[%s] Channel could not be created, created = %d, active = %d, connected = %d", address, currentCreated, currentActive, connected.get()); if (currentCreated < 0) { HOTROD.warnf("Invalid created count after channel create failure"); } if (currentActive < 0) { HOTROD.warnf("Invalid active count after channel create failure"); } callback.cancel(address, t); maybeRejectPendingCallbacks(t); } } /** * Release a channel back into the pool after an operation has finished. */ public void release(Channel channel, ChannelRecord record) { // The channel can be closed when it's idle (due to idle timeout or closed connection) if (record.isIdle()) { HOTROD.warnf("Cannot release channel %s because it is idle", channel); return; } if (record.setIdleAndIsClosed()) { if (log.isTraceEnabled()) log.tracef("[%s] Attempt to release already closed channel %s, active = %d", address, channel, active.get()); return; } int currentActive = active.decrementAndGet(); if (log.isTraceEnabled()) log.tracef("[%s] Released channel %s, active = %d", address, channel, currentActive); if (currentActive < 0) { HOTROD.warnf("[%s] Invalid active count after releasing channel %s", address, channel); } ChannelOperation callback; // We're protecting against concurrent acquires, concurrent releases are fine // hopefully the acquire will usually get the channel through the fast (non-locking) path long stamp = lock.readLock(); try { callback = callbacks.pollFirst(); if (callback == null) { channels.addFirst(channel); return; } } finally { lock.unlockRead(stamp); } activateChannel(channel, callback, true); } /** * Update counts after a channel has been closed. */ public void releaseClosedChannel(Channel channel, ChannelRecord channelRecord) { if (channel.isActive()) { HOTROD.warnf("Channel %s cannot be released because it is not closed", channel); return; } boolean idle = channelRecord.closeAndWasIdle(); int currentCreated = created.decrementAndGet(); int currentActive = !idle ? active.decrementAndGet() : active.get(); int currentConnected = connected.decrementAndGet(); if (log.isTraceEnabled()) log.tracef("[%s] Closed channel %s, created = %s, idle = %b, active = %d, connected = %d", address, channel, currentCreated, idle, currentActive, currentConnected); if (currentCreated < 0) { HOTROD.warnf("Invalid created count after closing channel %s", channel); } if (currentActive < 0) { HOTROD.warnf("Invalid active count after closing channel %s", channel); } connectionFailureListener.accept( this, idle ? ChannelEventType.CLOSED_IDLE : ChannelEventType.CLOSED_ACTIVE); } private boolean activateChannel(Channel channel, ChannelOperation callback, boolean useExecutor) { if (!channel.isActive()) return false; int currentActive = active.incrementAndGet(); if (log.isTraceEnabled()) log.tracef("[%s] Activated record %s, created = %d, active = %d", address, channel, created.get(), currentActive); ChannelRecord record = ChannelRecord.of(channel); record.setAcquired(); if (useExecutor) { // Do not execute another operation in releasing thread, we could run out of stack executor.execute(() -> { try { callback.invoke(channel); } catch (Throwable t) { log.tracef(t, "Closing channel %s due to exception", channel); discardChannel(channel); } }); } else { try { callback.invoke(channel); } catch (Throwable t) { log.tracef(t, "Closing channel %s due to exception", channel); discardChannel(channel); throw t; } } return true; } private void discardChannel(Channel channel) { channel.close(); } public SocketAddress getAddress() { return address; } public int getActive() { return active.get(); } public int getIdle() { return Math.max(0, created.get() - active.get()); } public int getConnected() { return connected.get(); } public void close() { terminated = true; long stamp = lock.writeLock(); try { RejectedExecutionException cause = new RejectedExecutionException("Pool was terminated"); callbacks.forEach(callback -> callback.cancel(address, cause)); channels.forEach(channel -> { // We don't want to fail all operations on given channel, // e.g. when moving from unresolved to resolved addresses channel.pipeline().fireUserEventTriggered(ChannelPoolCloseEvent.INSTANCE); }); } finally { lock.unlockWrite(stamp); } } public void inspectPool() { if (terminated || suspected || getConnected() > 0 || getActive() > 0) return; ChannelOperation cb = acquireHead(); if (cb != null) { int currentCreated = created.incrementAndGet(); int currentActive = active.incrementAndGet(); if (log.isTraceEnabled()) log.tracef("[%s] Creating new channel to inspect server, created = %d, active = %d", address, currentCreated, currentActive); suspected = true; createAndInvoke(cb); } } private void maybeRejectPendingCallbacks(Throwable t) { if (terminated || !suspected || getConnected() > 0 || getActive() > 0) return; ChannelOperation cb; while ((cb = acquireHead()) != null) { cb.cancel(address, t); } } private ChannelOperation acquireHead() { long stamp = lock.readLock(); try { return callbacks.pollFirst(); } finally { lock.unlockRead(stamp); } } @Override public String toString() { return "ChannelPool[" + "address=" + address + ", maxWait=" + maxWait + ", maxConnections=" + maxConnections + ", maxPendingRequests=" + maxPendingRequests + ", created=" + created + ", active=" + active + ", connected=" + connected + ", suspected=" + suspected + ", terminated=" + terminated + ']'; } private class TimeoutCallback implements ChannelOperation, Runnable { final ChannelOperation callback; volatile ScheduledFuture<?> timeoutFuture; @SuppressWarnings("unused") volatile int invoked = 0; private TimeoutCallback(ChannelOperation callback) { this.callback = callback; } @Override public void run() { callbacks.remove(this); if (invokedUpdater.compareAndSet(this, 0, 1)) { callback.cancel(address, new TimeoutException("Timed out waiting for connection")); } } @Override public void invoke(Channel channel) { ScheduledFuture<?> timeoutFuture = this.timeoutFuture; if (timeoutFuture != null) { timeoutFuture.cancel(false); } if (invokedUpdater.compareAndSet(this, 0, 1)) { callback.invoke(channel); } } @Override public void cancel(SocketAddress address, Throwable cause) { throw new UnsupportedOperationException(); } } }
16,917
38.807059
161
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelRecord.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.util.AttributeKey; import io.netty.util.concurrent.GenericFutureListener; /** * This class serves multiple purposes: * * 1) Activation: this extends {@link CompletableFuture} which is completed once the connection and initial handshake * are completed. * 2) Storage for unresolved address and pool info. */ public class ChannelRecord extends CompletableFuture<Channel> implements GenericFutureListener<ChannelFuture> { private static final Log log = LogFactory.getLog(ChannelRecord.class); static AttributeKey<ChannelRecord> KEY = AttributeKey.newInstance("activation"); private final SocketAddress unresolvedAddress; private final ChannelPool channelPool; private boolean closed = false; private boolean acquired = true; ChannelRecord(SocketAddress unresolvedAddress, ChannelPool channelPool) { this.unresolvedAddress = unresolvedAddress; this.channelPool = channelPool; } public static ChannelRecord of(Channel channel) { return channel.attr(KEY).get(); } public SocketAddress getUnresolvedAddress() { return unresolvedAddress; } @Override public boolean complete(Channel channel) { // Only add the listener once (or never, if completed exceptionally) boolean complete = super.complete(channel); if (complete) { channel.closeFuture().addListener(this); } return complete; } @Override public void operationComplete(ChannelFuture future) throws Exception { if (log.isTraceEnabled()) { if (!future.isSuccess()) { log.tracef(future.cause(), "Channel %s is closed, see exception for details", get()); } } channelPool.releaseClosedChannel(future.channel(), this); channelPool.inspectPool(); } synchronized void setAcquired() { assert !acquired; acquired = true; } public synchronized boolean isIdle() { return !acquired; } public synchronized boolean setIdleAndIsClosed() { assert acquired; acquired = false; return closed; } public synchronized boolean closeAndWasIdle() { assert !closed; closed = true; return !acquired; } public void release(Channel channel) { channelPool.release(channel, this); } }
2,615
27.434783
117
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelOperation.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.net.SocketAddress; import io.netty.channel.Channel; /** * A callback to be invoked on a channel. */ public interface ChannelOperation { /** * Invoked on an active channel ready to be written */ void invoke(Channel channel); /** * Invoked when the callback cannot be invoked due to timeout or terminated pool. * @param address * @param cause */ void cancel(SocketAddress address, Throwable cause); }
512
21.304348
84
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transport/netty/SaslDecoderEncoder.java
package org.infinispan.client.hotrod.impl.transport.netty; import javax.security.sasl.SaslClient; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; public class SaslDecoderEncoder implements ChannelInboundHandlerDefaults, ChannelOutboundHandlerDefaults { private final SaslClient saslClient; public SaslDecoderEncoder(SaslClient saslClient) { this.saslClient = saslClient; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof ByteBuf)) { throw new IllegalArgumentException(String.valueOf(msg)); } ByteBuf buf = (ByteBuf) msg; // the correct buf size is guaranteed by prepended LengthFieldBaseFrameDecoder byte[] decoded; if (buf.hasArray()) { decoded = saslClient.unwrap(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes()); } else { byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); decoded = saslClient.unwrap(bytes, 0, bytes.length); } buf.release(); ctx.fireChannelRead(Unpooled.wrappedBuffer(decoded)); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof ByteBuf)) { throw new IllegalArgumentException(String.valueOf(msg)); } ByteBuf buf = (ByteBuf) msg; byte[] encoded; if (buf.hasArray()) { encoded = saslClient.wrap(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes()); } else { byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); encoded = saslClient.wrap(bytes, 0, bytes.length); } buf.release(); ctx.write(Unpooled.wrappedBuffer(Unpooled.copyInt(encoded.length), Unpooled.wrappedBuffer(encoded)), promise); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.fireExceptionCaught(cause); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // noop } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // noop } }
2,388
33.128571
116
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/XaModeTransactionTable.java
package org.infinispan.client.hotrod.impl.transaction; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.impl.transaction.recovery.RecoveryIterator; import org.infinispan.client.hotrod.impl.transaction.recovery.RecoveryManager; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.CacheException; /** * A {@link TransactionTable} that registers the {@link RemoteCache} as a {@link XAResource} in the transaction. * <p> * Only a single {@link XAResource} is registered even if multiple {@link RemoteCache}s interact with the same * transaction. * <p> * When more than one {@link RemoteCache} is involved in the {@link Transaction}, the prepare, commit and rollback * requests are sent sequential and they are ordered by the {@link RemoteCache}'s name. * <p> * If a {@link RemoteCache} is read-only, the commit/rollback isn't invoked. * * @author Pedro Ruivo * @since 9.3 */ public class XaModeTransactionTable extends AbstractTransactionTable { private static final Log log = LogFactory.getLog(XaModeTransactionTable.class, Log.class); private final Map<Transaction, XaAdapter> registeredTransactions = new ConcurrentHashMap<>(); private final RecoveryManager recoveryManager = new RecoveryManager(); private final Function<Transaction, XaAdapter> constructor = this::createTransactionData; public XaModeTransactionTable(long timeout) { super(timeout); } @Override public <K, V> TransactionContext<K, V> enlist(TransactionalRemoteCacheImpl<K, V> txRemoteCache, Transaction tx) { XaAdapter xaAdapter = registeredTransactions.computeIfAbsent(tx, constructor); return xaAdapter.registerCache(txRemoteCache); } public XAResource getXaResource() { return new XaAdapter(null, getTimeout()); } private XaAdapter createTransactionData(Transaction transaction) { XaAdapter xaAdapter = new XaAdapter(transaction, getTimeout()); try { transaction.enlistResource(xaAdapter); } catch (RollbackException | SystemException e) { throw new CacheException(e); } return xaAdapter; } private class XaAdapter implements XAResource { private final Transaction transaction; private final Map<String, TransactionContext<?, ?>> registeredCaches; private volatile Xid currentXid; private volatile RecoveryIterator iterator; private long timeoutMs; private boolean needsRecovery = false; private XaAdapter(Transaction transaction, long timeout) { this.transaction = transaction; this.timeoutMs = timeout; this.registeredCaches = transaction == null ? Collections.emptyMap() : new ConcurrentSkipListMap<>(); } @Override public String toString() { return "XaResource{" + "transaction=" + transaction + ", caches=" + registeredCaches.keySet() + '}'; } @Override public void start(Xid xid, int flags) throws XAException { if (log.isTraceEnabled()) { log.tracef("XaResource.start(%s, %s)", xid, flags); } switch (flags) { case TMJOIN: case TMRESUME: // means joining a previously seen transaction. it should exist otherwise throw XAER_NOTA if (currentXid != null && !currentXid.equals(xid)) { //we have a running tx but it isn't the same tx throw new XAException(XAException.XAER_OUTSIDE); } assertStartInvoked(); break; case TMNOFLAGS: //new transaction. if (currentXid != null) { //we have a running transaction already! throw new XAException(XAException.XAER_RMERR); } currentXid = xid; break; default: //no other flag should be used. throw new XAException(XAException.XAER_RMERR); } } @Override public void end(Xid xid, int flags) throws XAException { if (log.isTraceEnabled()) { log.tracef("XaResource.end(%s, %s)", xid, flags); } assertStartInvoked(); assertSameXid(xid, XAException.XAER_OUTSIDE); } @Override public int prepare(Xid xid) throws XAException { if (log.isTraceEnabled()) { log.tracef("XaResource.prepare(%s)", xid); } assertStartInvoked(); assertSameXid(xid, XAException.XAER_INVAL); return internalPrepare(); } @Override public void commit(Xid xid, boolean onePhaseCommit) throws XAException { if (log.isTraceEnabled()) { log.tracef("XaResource.commit(%s, %s)", xid, onePhaseCommit); } if (currentXid == null) { //no transaction running. we are doing some recovery work currentXid = xid; } else { assertSameXid(xid, XAException.XAER_INVAL); } try { if (onePhaseCommit) { onePhaseCommit(); } else { internalCommit(); } } finally { cleanup(); } } @Override public void rollback(Xid xid) throws XAException { if (log.isTraceEnabled()) { log.tracef("XaResource.rollback(%s)", xid); } boolean ignoreNoTx = true; if (currentXid == null) { //no transaction running. we are doing some recovery work currentXid = xid; ignoreNoTx = false; } else { assertSameXid(xid, XAException.XAER_INVAL); } try { internalRollback(ignoreNoTx); } finally { cleanup(); } } @Override public boolean isSameRM(XAResource xaResource) { if (log.isTraceEnabled()) { log.tracef("XaResource.isSameRM(%s)", xaResource); } return xaResource instanceof XaAdapter && Objects.equals(transaction, ((XaAdapter) xaResource).transaction); } @Override public void forget(Xid xid) { if (log.isTraceEnabled()) { log.tracef("XaResource.forget(%s)", xid); } recoveryManager.forgetTransaction(xid); forgetTransaction(xid); } @Override public Xid[] recover(int flags) throws XAException { if (log.isTraceEnabled()) { log.tracef("XaResource.recover(%s)", flags); } RecoveryIterator it = this.iterator; if ((flags & XAResource.TMSTARTRSCAN) != 0) { if (it == null) { it = recoveryManager.startScan(fetchPreparedTransactions()); iterator = it; } else { //we have an iteration in progress. throw new XAException(XAException.XAER_INVAL); } } if ((flags & XAResource.TMENDRSCAN) != 0) { if (it == null) { //we don't have an iteration in progress throw new XAException(XAException.XAER_INVAL); } else { iterator.finish(timeoutMs); iterator = null; } } if (it == null) { //we don't have an iteration in progress throw new XAException(XAException.XAER_INVAL); } return it.next(); } @Override public boolean setTransactionTimeout(int timeoutSeconds) { this.timeoutMs = TimeUnit.SECONDS.toMillis(timeoutSeconds); return true; } @Override public int getTransactionTimeout() { return (int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs); } private void assertStartInvoked() throws XAException { if (currentXid == null) { //we don't have a transaction throw new XAException(XAException.XAER_NOTA); } } private void assertSameXid(Xid otherXid, int xaErrorCode) throws XAException { if (!currentXid.equals(otherXid)) { //we have another tx running throw new XAException(xaErrorCode); } } private void internalRollback(boolean ignoreNoTx) throws XAException { int xa_code = completeTransaction(currentXid, false); switch (xa_code) { case XAResource.XA_OK: //no issues case XAResource.XA_RDONLY: //no issues case XAException.XA_HEURRB: //heuristically rolled back break; case XAException.XAER_NOTA: //no transaction in server. already rolled-back or never reached the server if (ignoreNoTx) { break; } default: throw new XAException(xa_code); } } private void internalCommit() throws XAException { int xa_code = completeTransaction(currentXid, true); switch (xa_code) { case XAResource.XA_OK: //no issues case XAResource.XA_RDONLY: //no issues case XAException.XA_HEURCOM: //heuristically committed break; default: throw new XAException(xa_code); } } private int internalPrepare() throws XAException { boolean readOnly = true; for (TransactionContext<?, ?> ctx : registeredCaches.values()) { switch (ctx.prepareContext(currentXid, false, timeoutMs)) { case XAResource.XA_OK: readOnly = false; break; case XAResource.XA_RDONLY: break; //read only tx. case Integer.MIN_VALUE: //signals a marshaller error of key or value. the server wasn't contacted throw new XAException(XAException.XA_RBROLLBACK); default: //any other code we need to rollback //we may need to send the rollback later throw new XAException(XAException.XA_RBROLLBACK); } } if (needsRecovery) { recoveryManager.addTransaction(currentXid); } return readOnly ? XAResource.XA_RDONLY : XAResource.XA_OK; } private void onePhaseCommit() throws XAException { //check only the write transaction to know who is the last cache to commit List<TransactionContext<?, ?>> txCaches = registeredCaches.values().stream() .filter(TransactionContext::isReadWrite) .collect(Collectors.toList()); int size = txCaches.size(); if (size == 0) { return; } boolean commit = true; outer: for (int i = 0; i < size - 1; ++i) { TransactionContext<?, ?> ctx = txCaches.get(i); switch (ctx.prepareContext(currentXid, false, timeoutMs)) { case XAResource.XA_OK: break; case Integer.MIN_VALUE: //signals a marshaller error of key or value. the server wasn't contacted commit = false; break outer; default: //any other code we need to rollback //we may need to send the rollback later commit = false; break outer; } } //last resource one phase commit! if (commit && txCaches.get(size - 1).prepareContext(currentXid, true, timeoutMs) == XAResource.XA_OK) { internalCommit(); //commit other caches } else { internalRollback(true); throw new XAException(XAException.XA_RBROLLBACK); //tell TM to rollback } } private <K, V> TransactionContext<K, V> registerCache(TransactionalRemoteCacheImpl<K, V> txRemoteCache) { if (currentXid == null) { throw new CacheException("XaResource wasn't invoked!"); } needsRecovery |= txRemoteCache.isRecoveryEnabled(); //noinspection unchecked return (TransactionContext<K, V>) registeredCaches .computeIfAbsent(txRemoteCache.getName(), s -> createTxContext(txRemoteCache)); } private <K, V> TransactionContext<K, V> createTxContext(TransactionalRemoteCacheImpl<K, V> remoteCache) { if (log.isTraceEnabled()) { log.tracef("Registering remote cache '%s' for transaction xid=%s", remoteCache.getName(), currentXid); } return new TransactionContext<>(remoteCache.keyMarshaller(), remoteCache.valueMarshaller(), remoteCache.getOperationsFactory(), remoteCache.getName(), remoteCache.isRecoveryEnabled()); } private void cleanup() { //if null, it was created by RemoteCacheManager.getXaResource() if (transaction != null) { //enlisted with a cache registeredTransactions.remove(transaction); //this instance can be used for recovery. we need at least one cache registered in order to access // the operation factory registeredCaches.values().forEach(TransactionContext::cleanupEntries); } recoveryManager.forgetTransaction(currentXid); //transaction completed, we can remove it from recovery currentXid = null; } } }
14,138
36.207895
117
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/TransactionContext.java
package org.infinispan.client.hotrod.impl.transaction; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import static org.infinispan.commons.util.Util.toStr; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import jakarta.transaction.Transaction; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.transaction.entry.Modification; import org.infinispan.client.hotrod.impl.transaction.entry.TransactionEntry; import org.infinispan.client.hotrod.impl.transaction.operations.PrepareTransactionOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.util.ByRef; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableIteratorSet; /** * A context with the keys involved in a {@link Transaction}. * <p> * There is a single context for each ({@link TransactionalRemoteCacheImpl}, {@link Transaction}) pair. * <p> * It keeps the keys read and written in order to maintain the transactions isolated. * * @author Pedro Ruivo * @since 9.3 */ public class TransactionContext<K, V> { private static final Log log = LogFactory.getLog(TransactionContext.class, Log.class); private final Map<WrappedKey<K>, TransactionEntry<K, V>> entries; private final Function<K, byte[]> keyMarshaller; private final Function<V, byte[]> valueMarshaller; private final OperationsFactory operationsFactory; private final String cacheName; private final boolean recoverable; TransactionContext(Function<K, byte[]> keyMarshaller, Function<V, byte[]> valueMarshaller, OperationsFactory operationsFactory, String cacheName, boolean recoveryEnabled) { this.keyMarshaller = keyMarshaller; this.valueMarshaller = valueMarshaller; this.operationsFactory = operationsFactory; this.cacheName = cacheName; this.recoverable = recoveryEnabled; entries = new ConcurrentHashMap<>(); } @Override public String toString() { return "TransactionContext{" + "cacheName='" + cacheName + '\'' + ", context-size=" + entries.size() + " (entries)" + '}'; } CompletableFuture<Boolean> containsKey(Object key, Function<K, MetadataValue<V>> remoteValueSupplier) { CompletableFuture<Boolean> result = new CompletableFuture<>(); //noinspection unchecked entries.compute(wrap((K) key), (wKey, entry) -> { if (entry == null) { entry = createEntryFromRemote(wKey.key, remoteValueSupplier); } result.complete(!entry.isNonExists()); return entry; }); return result; } boolean containsValue(Object value, Supplier<CloseableIteratorSet<Map.Entry<K, V>>> iteratorSupplier, Function<K, MetadataValue<V>> remoteValueSupplier) { boolean found = entries.values().stream() .map(TransactionEntry::getValue) .filter(Objects::nonNull) .anyMatch(v -> Objects.deepEquals(v, value)); return found || searchValue(value, iteratorSupplier.get(), remoteValueSupplier); } <T> CompletableFuture<T> compute(K key, Function<TransactionEntry<K, V>, T> function) { CompletableFuture<T> future = new CompletableFuture<>(); entries.compute(wrap(key), (wKey, entry) -> { if (entry == null) { entry = TransactionEntry.notReadEntry(wKey.key); } if (log.isTraceEnabled()) { log.tracef("Compute key (%s). Before=%s", wKey, entry); } T result = function.apply(entry); future.complete(result); if (log.isTraceEnabled()) { log.tracef("Compute key (%s). After=%s (result=%s)", wKey, entry, result); } return entry; }); return future; } <T> CompletableFuture<T> compute(K key, Function<TransactionEntry<K, V>, T> function, Function<K, MetadataValue<V>> remoteValueSupplier) { CompletableFuture<T> future = new CompletableFuture<>(); entries.compute(wrap(key), (wKey, entry) -> { if (entry == null) { entry = createEntryFromRemote(wKey.key, remoteValueSupplier); if (log.isTraceEnabled()) { log.tracef("Fetched key (%s) from remote. Entry=%s", wKey, entry); } } if (log.isTraceEnabled()) { log.tracef("Compute key (%s). Before=%s", wKey, entry); } T result = function.apply(entry); future.complete(result); if (log.isTraceEnabled()) { log.tracef("Compute key (%s). After=%s (result=%s)", wKey, entry, result); } return entry; }); return future; } boolean isReadWrite() { return entries.values().stream().anyMatch(TransactionEntry::isModified); } <T> T computeSync(K key, Function<TransactionEntry<K, V>, T> function, Function<K, MetadataValue<V>> remoteValueSupplier) { ByRef<T> ref = new ByRef<>(null); entries.compute(wrap(key), (wKey, entry) -> { if (entry == null) { entry = createEntryFromRemote(wKey.key, remoteValueSupplier); if (log.isTraceEnabled()) { log.tracef("Fetched key (%s) from remote. Entry=%s", wKey, entry); } } if (log.isTraceEnabled()) { log.tracef("Compute key (%s). Before=%s", wKey, entry); } T result = function.apply(entry); ref.set(result); if (log.isTraceEnabled()) { log.tracef("Compute key (%s). After=%s (result=%s)", wKey, entry, result); } return entry; }); return ref.get(); } /** * Prepares the {@link Transaction} in the server and returns the {@link XAResource} code. * <p> * A special value {@link Integer#MIN_VALUE} is used to signal an error before contacting the server (for example, it * wasn't able to marshall the key/value) */ int prepareContext(Xid xid, boolean onePhaseCommit, long timeout) { PrepareTransactionOperation operation; List<Modification> modifications; try { modifications = toModification(); if (log.isTraceEnabled()) { log.tracef("Preparing transaction xid=%s, remote-cache=%s, modification-size=%d", xid, cacheName, modifications.size()); } if (modifications.isEmpty()) { return XAResource.XA_RDONLY; } } catch (Exception e) { return Integer.MIN_VALUE; } try { int xaReturnCode; do { operation = operationsFactory .newPrepareTransactionOperation(xid, onePhaseCommit, modifications, recoverable, timeout); xaReturnCode = operation.execute().get(); } while (operation.shouldRetry()); return xaReturnCode; } catch (Exception e) { HOTROD.exceptionDuringPrepare(xid, e); return XAException.XA_RBROLLBACK; } } void cleanupEntries() { entries.clear(); } private List<Modification> toModification() { return entries.values().stream() .filter(TransactionEntry::isModified) .map(entry -> entry.toModification(keyMarshaller, valueMarshaller)) .collect(Collectors.toList()); } private TransactionEntry<K, V> createEntryFromRemote(K key, Function<K, MetadataValue<V>> remoteValueSupplier) { MetadataValue<V> remoteValue = remoteValueSupplier.apply(key); return remoteValue == null ? TransactionEntry.nonExistingEntry(key) : TransactionEntry.read(key, remoteValue); } private boolean searchValue(Object value, CloseableIteratorSet<Map.Entry<K, V>> iterator, Function<K, MetadataValue<V>> remoteValueSupplier) { try (CloseableIterator<Map.Entry<K, V>> it = iterator.iterator()) { while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); if (!entries.containsKey(wrap(entry.getKey())) && Objects.deepEquals(entry.getValue(), value)) { ByRef.Boolean result = new ByRef.Boolean(false); entries.computeIfAbsent(wrap(entry.getKey()), wrappedKey -> { MetadataValue<V> remoteValue = remoteValueSupplier.apply(wrappedKey.key); if (Objects.deepEquals(remoteValue.getValue(), value)) { //value didn't change. store it locally. result.set(true); return TransactionEntry.read(wrappedKey.key, remoteValue); } else { return null; } }); if (result.get()) { return true; } } } } //we iterated over all keys. return false; } private WrappedKey<K> wrap(K key) { return new WrappedKey<>(key); } private static class WrappedKey<K> { private final K key; private WrappedKey(K key) { this.key = key; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WrappedKey<?> that = (WrappedKey<?>) o; return Objects.deepEquals(key, that.key); } @Override public int hashCode() { if (key instanceof Object[]) { return Arrays.deepHashCode((Object[]) key); } else if (key instanceof byte[]) { return Arrays.hashCode((byte[]) key); } else if (key instanceof short[]) { return Arrays.hashCode((short[]) key); } else if (key instanceof int[]) { return Arrays.hashCode((int[]) key); } else if (key instanceof long[]) { return Arrays.hashCode((long[]) key); } else if (key instanceof char[]) { return Arrays.hashCode((char[]) key); } else if (key instanceof float[]) { return Arrays.hashCode((float[]) key); } else if (key instanceof double[]) { return Arrays.hashCode((double[]) key); } else if (key instanceof boolean[]) { return Arrays.hashCode((boolean[]) key); } else { return Objects.hashCode(key); } } @Override public String toString() { return "WrappedKey{" + "key=" + toStr(key) + '}'; } } }
11,005
35.809365
120
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/TransactionalRemoteCacheImpl.java
package org.infinispan.client.hotrod.impl.transaction; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Function; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.RemoteCacheImpl; import org.infinispan.client.hotrod.impl.Util; import org.infinispan.client.hotrod.impl.transaction.entry.TransactionEntry; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.time.TimeService; /** * A {@link RemoteCache} implementation that handles {@link Transaction}. * <p> * All streaming operation (example {@link TransactionalRemoteCacheImpl#retrieveEntries(String, int)}) and {@link * TransactionalRemoteCacheImpl#size()} aren't transactional in a way they don't interact with the transaction's data * (keys, values). * <p> * {@link TransactionalRemoteCacheImpl#containsValue(Object)} is a special case where a key with the specific value is * marked as read for the transaction. * * @author Pedro Ruivo * @since 9.3 */ public class TransactionalRemoteCacheImpl<K, V> extends RemoteCacheImpl<K, V> { private static final Log log = LogFactory.getLog(TransactionalRemoteCacheImpl.class, Log.class); private final boolean forceReturnValue; private final boolean recoveryEnabled; private final TransactionManager transactionManager; private final TransactionTable transactionTable; // TODO: the remote get is force to be sync and is blocking! // https://issues.redhat.com/browse/ISPN-11633 private final Function<K, MetadataValue<V>> remoteGet = this::getWithMetadataNotTracked; private final Function<K, byte[]> keyMarshaller = this::keyToBytes; private final Function<V, byte[]> valueMarshaller = this::valueToBytes; public TransactionalRemoteCacheImpl(RemoteCacheManager rcm, String name, boolean forceReturnValue, boolean recoveryEnabled, TransactionManager transactionManager, TransactionTable transactionTable, TimeService timeService) { super(rcm, name, timeService); this.forceReturnValue = forceReturnValue; this.recoveryEnabled = recoveryEnabled; this.transactionManager = transactionManager; this.transactionTable = transactionTable; } @Override public CompletableFuture<Boolean> removeWithVersionAsync(K key, long version) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.removeWithVersionAsync(key, version) : txContext.compute(key, entry -> removeEntryIfSameVersion(entry, version), remoteGet); } @Override public CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.replaceWithVersionAsync(key, newValue, version, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit) : txContext.compute(key, entry -> replaceEntryIfSameVersion(entry, newValue, version, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit), remoteGet); } @Override public CompletableFuture<MetadataValue<V>> getWithMetadataAsync(K key) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.getWithMetadataAsync(key) : txContext.compute(key, TransactionEntry::toMetadataValue, remoteGet); } private MetadataValue<V> getWithMetadataNotTracked(K key) { return Util.await(super.getWithMetadataAsync(key)); } @Override public CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { TransactionContext<K, V> txContext = getTransactionContext(); if (txContext == null) { return super.putAllAsync(map, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } else { //this is local only map.forEach((key, value) -> txContext.compute(key, entry -> getAndSetEntry(entry, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit))); return CompletableFuture.completedFuture(null); } } @Override public CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { TransactionContext<K, V> txContext = getTransactionContext(); if (txContext == null) { return super.putAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } if (forceReturnValue) { return txContext.compute(key, entry -> getAndSetEntry(entry, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit), remoteGet); } else { return txContext.compute(key, entry -> getAndSetEntry(entry, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } } @Override public CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.putIfAbsentAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit) : txContext.compute(key, entry -> putEntryIfAbsent(entry, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit), remoteGet); } @Override public CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.replaceAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit) : txContext.compute(key, entry -> replaceEntry(entry, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit), remoteGet); } @Override public CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.replaceAsync(key, oldValue, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit) : txContext.compute(key, entry -> replaceEntryIfEquals(entry, oldValue, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit), remoteGet); } @Override public CompletableFuture<Boolean> containsKeyAsync(K key) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.containsKeyAsync(key) : txContext.containsKey(key, remoteGet); } @Override public boolean containsValue(Object value) { TransactionContext<K, V> txContext = getTransactionContext(); return txContext == null ? super.containsValue(value) : txContext.containsValue(value, super::entrySet, remoteGet); } @Override public CompletableFuture<V> getAsync(Object key) { TransactionContext<K, V> txContext = getTransactionContext(); //noinspection unchecked return txContext == null ? super.getAsync(key) : txContext.compute((K) key, TransactionEntry::getValue, remoteGet); } @Override public CompletableFuture<V> removeAsync(Object key) { TransactionContext<K, V> txContext = getTransactionContext(); if (txContext == null) { return super.removeAsync(key); } if (forceReturnValue) { //noinspection unchecked return txContext.compute((K) key, this::removeEntry, remoteGet); } else { //noinspection unchecked return txContext.compute((K) key, this::removeEntry); } } @Override public CompletableFuture<Boolean> removeAsync(Object key, Object value) { TransactionContext<K, V> txContext = getTransactionContext(); //noinspection unchecked return txContext == null ? super.removeAsync(key, value) : txContext.compute((K) key, entry -> removeEntryIfEquals(entry, value), remoteGet); } @Override public CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { throw new UnsupportedOperationException(); } @Override public CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { throw new UnsupportedOperationException(); } @Override public TransactionManager getTransactionManager() { return transactionManager; } @Override public boolean isTransactional() { return true; } boolean isRecoveryEnabled() { return recoveryEnabled; } Function<K, byte[]> keyMarshaller() { return keyMarshaller; } Function<V, byte[]> valueMarshaller() { return valueMarshaller; } private boolean removeEntryIfSameVersion(TransactionEntry<K, V> entry, long version) { if (entry.exists() && entry.getVersion() == version) { entry.remove(); return true; } else { return false; } } private boolean replaceEntryIfSameVersion(TransactionEntry<K, V> entry, V newValue, long version, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { if (entry.exists() && entry.getVersion() == version) { entry.set(newValue, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); return true; } else { return false; } } private V putEntryIfAbsent(TransactionEntry<K, V> entry, V value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { V currentValue = entry.getValue(); if (currentValue == null) { entry.set(value, lifespan, lifespanTimeUnit, maxIdleTime, maxIdleTimeUnit); } return currentValue; } private V replaceEntry(TransactionEntry<K, V> entry, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { V currentValue = entry.getValue(); if (currentValue != null) { entry.set(value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } return currentValue; } private boolean replaceEntryIfEquals(TransactionEntry<K, V> entry, V oldValue, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { V currentValue = entry.getValue(); if (currentValue != null && Objects.deepEquals(currentValue, oldValue)) { entry.set(value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); return true; } else { return false; } } private V removeEntry(TransactionEntry<K, V> entry) { V oldValue = entry.getValue(); entry.remove(); return oldValue; } private boolean removeEntryIfEquals(TransactionEntry<K, V> entry, Object value) { V oldValue = entry.getValue(); if (oldValue != null && Objects.deepEquals(oldValue, value)) { entry.remove(); return true; } return false; } private V getAndSetEntry(TransactionEntry<K, V> entry, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { V oldValue = entry.getValue(); entry.set(value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); return oldValue; } private TransactionContext<K, V> getTransactionContext() { assertRemoteCacheManagerIsStarted(); Transaction tx = getRunningTransaction(); if (tx != null) { return transactionTable.enlist(this, tx); } return null; } private Transaction getRunningTransaction() { try { return transactionManager.getTransaction(); } catch (SystemException e) { log.debug("Exception in getRunningTransaction().", e); return null; } } }
13,026
38.237952
200
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/TransactionOperationFactory.java
package org.infinispan.client.hotrod.impl.transaction; import java.util.concurrent.atomic.AtomicReference; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transaction.operations.CompleteTransactionOperation; import org.infinispan.client.hotrod.impl.transaction.operations.ForgetTransactionOperation; import org.infinispan.client.hotrod.impl.transaction.operations.RecoveryOperation; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; /** * An operation factory that builds operations independent from the cache used. * <p> * This operations are the commit/rollback request, forget request and in-doubt transactions request. * <p> * This operation aren't associated to any cache, but they use the default cache topology to pick the server to * contact. * * @author Pedro Ruivo * @since 10.0 */ public class TransactionOperationFactory { private final Configuration configuration; private final ChannelFactory channelFactory; private final AtomicReference<ClientTopology> clientTopology; public TransactionOperationFactory(Configuration configuration, ChannelFactory channelFactory) { this.configuration = configuration; this.channelFactory = channelFactory; clientTopology = channelFactory.createTopologyId(HotRodConstants.DEFAULT_CACHE_NAME_BYTES); } CompleteTransactionOperation newCompleteTransactionOperation(Xid xid, boolean commit) { return new CompleteTransactionOperation(channelFactory.getNegotiatedCodec(), channelFactory, clientTopology, configuration, xid, commit); } ForgetTransactionOperation newForgetTransactionOperation(Xid xid) { return new ForgetTransactionOperation(channelFactory.getNegotiatedCodec(), channelFactory, clientTopology, configuration, xid); } RecoveryOperation newRecoveryOperation() { return new RecoveryOperation(channelFactory.getNegotiatedCodec(), channelFactory, clientTopology, configuration); } }
2,164
41.45098
143
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/TransactionTable.java
package org.infinispan.client.hotrod.impl.transaction; import jakarta.transaction.Transaction; /** * A {@link Transaction} table that knows how to interact with the {@link Transaction} and how the {@link * TransactionalRemoteCacheImpl} is enlisted. * * @author Pedro Ruivo * @since 9.3 */ public interface TransactionTable { <K, V> TransactionContext<K, V> enlist(TransactionalRemoteCacheImpl<K, V> txRemoteCache, Transaction tx); /** * It initializes the {@link TransactionTable} with the {@link TransactionOperationFactory} to use. * * @param operationFactory The {@link TransactionOperationFactory} to use. */ void start(TransactionOperationFactory operationFactory); }
708
29.826087
108
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/AbstractTransactionTable.java
package org.infinispan.client.hotrod.impl.transaction; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CompletableFuture; import javax.transaction.xa.XAException; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.impl.transaction.operations.CompleteTransactionOperation; import org.infinispan.client.hotrod.impl.transaction.operations.ForgetTransactionOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; /** * A Base {@link TransactionTable} with common logic. * <p> * It contains the functions to handle server requests that don't depend of the cache. Such operations are the commit, * rollback and forget request and the recovery process. * * @author Pedro Ruivo * @since 10.0 */ abstract class AbstractTransactionTable implements TransactionTable { private static final Log log = LogFactory.getLog(AbstractTransactionTable.class, Log.class); private final long timeout; private volatile TransactionOperationFactory operationFactory; AbstractTransactionTable(long timeout) { this.timeout = timeout; } @Override public final void start(TransactionOperationFactory operationFactory) { this.operationFactory = operationFactory; } /** * Check this component has started (i.e. {@link TransactionOperationFactory} isn't null) * * @return the {@link TransactionOperationFactory} to use. */ TransactionOperationFactory assertStartedAndReturnFactory() { TransactionOperationFactory tmp = operationFactory; if (tmp == null) { throw log.transactionTableNotStarted(); } return tmp; } final long getTimeout() { return timeout; } /** * It completes the transaction with the commit or rollback request. * <p> * It can be a commit or rollback request. * * @param xid The transaction {@link Xid}. * @param commit {@code True} to commit the transaction, {@link false} to rollback. * @return The server's return code. */ int completeTransaction(Xid xid, boolean commit) { try { TransactionOperationFactory factory = assertStartedAndReturnFactory(); CompleteTransactionOperation operation = factory.newCompleteTransactionOperation(xid, commit); return operation.execute().get(); } catch (Exception e) { log.debug("Exception while commit/rollback.", e); return XAException.XA_HEURRB; //heuristically rolled-back } } /** * Tells the server to forget this transaction. * * @param xid The transaction {@link Xid}. */ void forgetTransaction(Xid xid) { try { TransactionOperationFactory factory = assertStartedAndReturnFactory(); ForgetTransactionOperation operation = factory.newForgetTransactionOperation(xid); //async. //we don't need the reply from server. If we can't forget for some reason (timeouts or other exception), // the server reaper will cleanup the completed transactions after a while. (default 1 min) operation.execute(); } catch (Exception e) { if (log.isTraceEnabled()) { log.tracef(e, "Exception in forget transaction xid=%s", xid); } } } /** * It requests the server for all in-doubt prepared transactions, to be handled by the recovery process. * * @return A {@link CompletableFuture} which is completed with a collections of transaction {@link Xid}. */ CompletableFuture<Collection<Xid>> fetchPreparedTransactions() { try { TransactionOperationFactory factory = assertStartedAndReturnFactory(); return factory.newRecoveryOperation().execute(); } catch (Exception e) { if (log.isTraceEnabled()) { log.trace("Exception while fetching prepared transactions", e); } return CompletableFuture.completedFuture(Collections.emptyList()); } } }
4,018
34.254386
118
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/SyncModeTransactionTable.java
package org.infinispan.client.hotrod.impl.transaction; import static org.infinispan.commons.tx.Util.transactionStatusToString; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Consumer; import java.util.function.Function; import jakarta.transaction.RollbackException; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import javax.transaction.xa.XAResource; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.transaction.manager.RemoteXid; import org.infinispan.commons.CacheException; import org.infinispan.commons.util.Util; /** * A {@link TransactionTable} that registers the {@link RemoteCache} as a {@link Synchronization} in the transaction. * <p> * Only a single {@link Synchronization} is registered even if multiple {@link RemoteCache}s interact with the same * transaction. * <p> * When more than one {@link RemoteCache} is involved in the {@link Transaction}, the prepare, commit and rollback * requests are sent sequential and they are ordered by the {@link RemoteCache}'s name. * <p> * If a {@link RemoteCache} is read-only, the commit/rollback isn't invoked. * * @author Pedro Ruivo * @since 9.3 */ public class SyncModeTransactionTable extends AbstractTransactionTable { private static final Log log = LogFactory.getLog(SyncModeTransactionTable.class, Log.class); private final Map<Transaction, SynchronizationAdapter> registeredTransactions = new ConcurrentHashMap<>(); private final UUID uuid = Util.threadLocalRandomUUID(); private final Consumer<Transaction> cleanup = registeredTransactions::remove; private final Function<Transaction, SynchronizationAdapter> constructor = this::createSynchronizationAdapter; public SyncModeTransactionTable(long timeout) { super(timeout); } @Override public <K, V> TransactionContext<K, V> enlist(TransactionalRemoteCacheImpl<K, V> txRemoteCache, Transaction tx) { assertStartedAndReturnFactory(); //registers a synchronization if it isn't done yet. SynchronizationAdapter adapter = registeredTransactions.computeIfAbsent(tx, constructor); //registers the cache. TransactionContext<K, V> context = adapter.registerCache(txRemoteCache); if (log.isTraceEnabled()) { log.tracef("Xid=%s retrieving context: %s", adapter.xid, context); } return context; } /** * Creates and registers the {@link SynchronizationAdapter} in the {@link Transaction}. */ private SynchronizationAdapter createSynchronizationAdapter(Transaction transaction) { SynchronizationAdapter adapter = new SynchronizationAdapter(transaction, RemoteXid.create(uuid)); try { transaction.registerSynchronization(adapter); } catch (RollbackException | SystemException e) { throw new CacheException(e); } if (log.isTraceEnabled()) { log.tracef("Registered synchronization for transaction %s. Sync=%s", transaction, adapter); } return adapter; } private class SynchronizationAdapter implements Synchronization { private final Map<String, TransactionContext<?, ?>> registeredCaches = new ConcurrentSkipListMap<>(); private final Transaction transaction; private final RemoteXid xid; private SynchronizationAdapter(Transaction transaction, RemoteXid xid) { this.transaction = transaction; this.xid = xid; } @Override public String toString() { return "SynchronizationAdapter{" + "registeredCaches=" + registeredCaches.keySet() + ", transaction=" + transaction + ", xid=" + xid + '}'; } @Override public void beforeCompletion() { if (log.isTraceEnabled()) { log.tracef("BeforeCompletion(xid=%s, remote-caches=%s)", xid, registeredCaches.keySet()); } if (isMarkedRollback()) { return; } for (TransactionContext<?, ?> txContext : registeredCaches.values()) { switch (txContext.prepareContext(xid, false, getTimeout())) { case XAResource.XA_OK: case XAResource.XA_RDONLY: break; //read only tx. case Integer.MIN_VALUE: //signals a marshaller error of key or value. the server wasn't contacted markAsRollback(); return; default: markAsRollback(); return; } } } @Override public void afterCompletion(int status) { if (log.isTraceEnabled()) { log.tracef("AfterCompletion(xid=%s, status=%s, remote-caches=%s)", xid, transactionStatusToString(status), registeredCaches.keySet()); } //the server commits everything when the first request arrives. try { boolean commit = status == Status.STATUS_COMMITTED; completeTransaction(xid, commit); } finally { forgetTransaction(xid); cleanup.accept(transaction); } } private void markAsRollback() { try { transaction.setRollbackOnly(); } catch (SystemException e) { log.debug("Exception in markAsRollback", e); } } private boolean isMarkedRollback() { try { return transaction.getStatus() == Status.STATUS_MARKED_ROLLBACK; } catch (SystemException e) { log.debug("Exception in isMarkedRollback", e); //lets assume not. return false; } } private <K, V> TransactionContext<K, V> registerCache(TransactionalRemoteCacheImpl<K, V> txRemoteCache) { //noinspection unchecked return (TransactionContext<K, V>) registeredCaches .computeIfAbsent(txRemoteCache.getName(), s -> createTxContext(txRemoteCache)); } private <K, V> TransactionContext<K, V> createTxContext(TransactionalRemoteCacheImpl<K, V> remoteCache) { if (log.isTraceEnabled()) { log.tracef("Registering remote cache '%s' for transaction xid=%s", remoteCache.getName(), xid); } return new TransactionContext<>(remoteCache.keyMarshaller(), remoteCache.valueMarshaller(), remoteCache.getOperationsFactory(), remoteCache.getName(), false); } } }
6,766
37.890805
118
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/entry/Modification.java
package org.infinispan.client.hotrod.impl.transaction.entry; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.writeArray; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.impl.protocol.Codec; import io.netty.buffer.ByteBuf; /** * The final modification of a specific key. * * @author Pedro Ruivo * @since 9.3 */ public class Modification { private final byte[] key; private final byte[] value; private final long versionRead; private final long lifespan; private final long maxIdle; private final TimeUnit lifespanTimeUnit; private final TimeUnit maxIdleTimeUnit; private final byte control; Modification(byte[] key, byte[] value, long versionRead, long lifespan, long maxIdle, TimeUnit lifespanTimeUnit, TimeUnit maxIdleTimeUnit, byte control) { this.key = key; this.value = value; this.versionRead = versionRead; this.lifespan = lifespan; this.maxIdle = maxIdle; this.lifespanTimeUnit = lifespanTimeUnit; this.maxIdleTimeUnit = maxIdleTimeUnit; this.control = control; } /** * Writes this modification to the {@link ByteBuf}. * * @param byteBuf the {@link ByteBuf} to write to. * @param codec the {@link Codec} to use. */ public void writeTo(ByteBuf byteBuf, Codec codec) { writeArray(byteBuf, key); byteBuf.writeByte(control); if (!ControlByte.NON_EXISTING.hasFlag(control) && !ControlByte.NOT_READ.hasFlag(control)) { byteBuf.writeLong(versionRead); } if (ControlByte.REMOVE_OP.hasFlag(control)) { return; } codec.writeExpirationParams(byteBuf, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); writeArray(byteBuf, value); } /** * The estimated size. * * @param codec the {@link Codec} to use for the size estimation. * @return the estimated size. */ public int estimateSize(Codec codec) { int size = key.length + 1; //key + control if (!ControlByte.NON_EXISTING.hasFlag(control) && !ControlByte.NOT_READ.hasFlag(control)) { size += 8; //long } if (!ControlByte.REMOVE_OP.hasFlag(control)) { size += value.length; size += codec.estimateExpirationSize(lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); } return size; } /** * @return The key changed by this modification. */ public byte[] getKey() { return key; } }
2,496
28.034884
115
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/entry/ControlByte.java
package org.infinispan.client.hotrod.impl.transaction.entry; /** * A control byte used by each write operation to flag if the key was read or not, or if the write operation is a remove * operation * * @author Pedro Ruivo * @since 9.3 */ public enum ControlByte { NOT_READ(0x1), NON_EXISTING(0x2), REMOVE_OP(0x4); private final byte bitSet; ControlByte(int bitSet) { this.bitSet = (byte) bitSet; } public static String prettyPrint(byte bitSet) { StringBuilder builder = new StringBuilder("["); if (NOT_READ.hasFlag(bitSet)) { builder.append("NOT_READ"); } else if (NON_EXISTING.hasFlag(bitSet)) { builder.append("NON_EXISTING"); } else { builder.append("READ"); } if (REMOVE_OP.hasFlag(bitSet)) { builder.append(", REMOVED"); } return builder.append("]").toString(); } /** * Sets {@code this} flag to the {@code bitSet}. * * @return The new bit set. */ public byte set(byte bitSet) { return (byte) (bitSet | this.bitSet); } /** * @return {@code true} if {@code this} flag is set in the {@code bitSet}, {@code false} otherwise. */ public boolean hasFlag(byte bitSet) { return (bitSet & this.bitSet) == this.bitSet; } /** * @return The bit corresponding to {@code this} flag. */ public byte bit() { return bitSet; } }
1,419
23.067797
120
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/entry/TransactionEntry.java
package org.infinispan.client.hotrod.impl.transaction.entry; import static org.infinispan.commons.util.Util.toStr; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.client.hotrod.impl.MetadataValueImpl; import org.infinispan.client.hotrod.impl.VersionedValueImpl; import org.infinispan.client.hotrod.impl.transaction.TransactionContext; /** * An entry in the {@link TransactionContext}. * <p> * It represents a single key and contains its initial version (if it was read) and the most up-to-date value (can be * null if the key was removed). * * @author Pedro Ruivo * @since 9.3 */ public class TransactionEntry<K, V> { private final K key; private final long version; //version read. never changes during the transaction private final byte readControl; private V value; //null == removed private long created = -1; private long lastUsed = -1; private long lifespan = -1; private TimeUnit lifespanTimeUnit; private long maxIdle = -1; private TimeUnit maxIdleTimeUnit; private boolean modified; private TransactionEntry(K key, long version, byte readControl) { this.key = key; this.version = version; this.readControl = readControl; this.modified = false; } public static <K, V> TransactionEntry<K, V> nonExistingEntry(K key) { return new TransactionEntry<>(key, 0, ControlByte.NON_EXISTING.bit()); } public static <K, V> TransactionEntry<K, V> notReadEntry(K key) { return new TransactionEntry<>(key, 0, ControlByte.NOT_READ.bit()); } public static <K, V> TransactionEntry<K, V> read(K key, MetadataValue<V> value) { TransactionEntry<K, V> entry = new TransactionEntry<>(key, value.getVersion(), (byte) 0); entry.init(value); return entry; } public long getVersion() { return version; } public V getValue() { return value; } public VersionedValue<V> toVersionValue() { return isNonExists() ? null : new VersionedValueImpl<>(version, value); } public MetadataValue<V> toMetadataValue() { return isNonExists() ? null : new MetadataValueImpl<>(created, getLifespan(), lastUsed, getMaxIdle(), version, value); } public boolean isModified() { return modified; } public boolean isNonExists() { return value == null; } public boolean exists() { return value != null; } public void set(V value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { this.value = value; this.lifespan = lifespan; this.maxIdle = maxIdle; this.lifespanTimeUnit = lifespanTimeUnit; this.maxIdleTimeUnit = maxIdleTimeUnit; this.modified = true; } public void remove() { this.value = null; this.modified = true; } public Modification toModification(Function<K, byte[]> keyMarshaller, Function<V, byte[]> valueMarshaller) { if (value == null) { //remove operation return new Modification(keyMarshaller.apply(key), null, version, 0, 0, null, null, ControlByte.REMOVE_OP.set(readControl)); } else { return new Modification(keyMarshaller.apply(key), valueMarshaller.apply(value), version, lifespan, maxIdle, lifespanTimeUnit, maxIdleTimeUnit, readControl); } } @Override public String toString() { return "TransactionEntry{" + "key=" + toStr(key) + ", version=" + version + ", readControl=" + ControlByte.prettyPrint(readControl) + ", value=" + toStr(value) + ", created=" + created + ", lifespan=" + lifespan + ", lifespanTimeUnit=" + lifespanTimeUnit + ", maxIdle=" + maxIdle + ", maxIdleTimeUnit=" + maxIdleTimeUnit + ", modified=" + modified + '}'; } private int getLifespan() { return lifespan < 0 ? -1 : (int) lifespanTimeUnit.toSeconds(lifespan); } private int getMaxIdle() { return maxIdle < 0 ? -1 : (int) maxIdleTimeUnit.toSeconds(maxIdle); } private void init(MetadataValue<V> metadataValue) { this.value = metadataValue.getValue(); this.created = metadataValue.getCreated(); this.lastUsed = metadataValue.getLastUsed(); this.lifespan = metadataValue.getLifespan(); this.lifespanTimeUnit = TimeUnit.SECONDS; this.maxIdle = metadataValue.getMaxIdle(); this.maxIdleTimeUnit = TimeUnit.SECONDS; } }
4,684
30.655405
117
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/recovery/RecoveryIterator.java
package org.infinispan.client.hotrod.impl.transaction.recovery; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; /** * The iterator return when {@link XAResource#recover(int)} is invoked with {@link XAResource#TMSTARTRSCAN}. * <p> * Initially, it returns the in-doubt transaction stored locally while it sends the request to the server. When {@link * XAResource#recover(int)} is invoked with {@link XAResource#TMENDRSCAN}, it waits for the server reply and return the * remaining in-doubt transactions. * * @author Pedro Ruivo * @since 9.4 */ public class RecoveryIterator { private static final Log log = LogFactory.getLog(RecoveryIterator.class, Log.class); private static final Xid[] NOTHING = new Xid[0]; private final Set<Xid> uniqueFilter = Collections.synchronizedSet(new HashSet<>()); private final BlockingDeque<Xid> inDoubtTransactions = new LinkedBlockingDeque<>(); private final CompletableFuture<Void> remoteRequest; RecoveryIterator(Collection<Xid> localTransactions, CompletableFuture<Collection<Xid>> remoteRequest) { add(localTransactions); this.remoteRequest = remoteRequest.thenAccept(this::add); } public Xid[] next() { if (inDoubtTransactions.isEmpty()) { if (log.isTraceEnabled()) { log.trace("RecoveryIterator.next() = []"); } return NOTHING; } Collection<Xid> txs = new ArrayList<>(inDoubtTransactions.size()); inDoubtTransactions.drainTo(txs); if (log.isTraceEnabled()) { log.tracef("RecoveryIterator.next() = %s", txs); } return txs.toArray(NOTHING); } public void finish(long timeout) { try { remoteRequest.get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { if (log.isTraceEnabled()) { log.trace("Exception while waiting for prepared transaction from server.", e); } } } private void add(Collection<Xid> transactions) { for (Xid xid : transactions) { if (uniqueFilter.add(xid)) { if (log.isTraceEnabled()) { log.tracef("RecoveryIterator new xid=%s", xid); } inDoubtTransactions.add(xid); } } } }
2,819
33.390244
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/recovery/RecoveryManager.java
package org.infinispan.client.hotrod.impl.transaction.recovery; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import javax.transaction.xa.Xid; /** * It keeps the local in-doubt transactions. * * @author Pedro Ruivo * @since 9.4 */ //TODO merge with org.infinispan.client.hotrod.impl.transaction.XaModeTransactionTable ? public class RecoveryManager { private final Collection<Xid> preparedTransactions = ConcurrentHashMap.newKeySet(); public void addTransaction(Xid xid) { preparedTransactions.add(xid); } public void forgetTransaction(Xid xid) { preparedTransactions.remove(xid); } public RecoveryIterator startScan(CompletableFuture<Collection<Xid>> requestFuture) { return new RecoveryIterator(preparedTransactions, requestFuture); } }
867
26.125
88
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/operations/CompleteTransactionOperation.java
package org.infinispan.client.hotrod.impl.transaction.operations; import java.util.concurrent.atomic.AtomicReference; import jakarta.transaction.TransactionManager; import javax.transaction.xa.XAException; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * Represents a commit or rollback request from the {@link TransactionManager}. * * @author Pedro Ruivo * @since 9.3 */ public class CompleteTransactionOperation extends RetryOnFailureOperation<Integer> { private final Xid xid; public CompleteTransactionOperation(Codec codec, ChannelFactory channelFactory, AtomicReference<ClientTopology> clientTopology, Configuration cfg, Xid xid, boolean commit) { super(commit ? COMMIT_REQUEST : ROLLBACK_REQUEST, commit ? COMMIT_RESPONSE : ROLLBACK_RESPONSE, codec, channelFactory, DEFAULT_CACHE_NAME_BYTES, clientTopology, 0, cfg, null, null); this.xid = xid; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(estimateSize()); codec.writeHeader(buf, header); ByteBufUtil.writeXid(buf, xid); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status == NO_ERROR_STATUS) { complete(buf.readInt()); } else { complete(XAException.XA_HEURRB); } } private int estimateSize() { return codec.estimateHeaderSize(header) + ByteBufUtil.estimateXidSize(xid); } }
2,068
33.483333
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/operations/ForgetTransactionOperation.java
package org.infinispan.client.hotrod.impl.transaction.operations; import java.util.concurrent.atomic.AtomicReference; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * It forgets the transaction identified by {@link Xid} in the server. * <p> * It affects all caches involved in the transaction. It is requested from {@link XAResource#forget(Xid)}. * * @author Pedro Ruivo * @since 9.4 */ public class ForgetTransactionOperation extends RetryOnFailureOperation<Void> { private final Xid xid; public ForgetTransactionOperation(Codec codec, ChannelFactory channelFactory, AtomicReference<ClientTopology> clientTopology, Configuration cfg, Xid xid) { super(FORGET_TX_REQUEST, FORGET_TX_RESPONSE, codec, channelFactory, DEFAULT_CACHE_NAME_BYTES, clientTopology, 0, cfg, null, null); this.xid = xid; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(null); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(estimateSize()); codec.writeHeader(buf, header); ByteBufUtil.writeXid(buf, xid); channel.writeAndFlush(buf); } private int estimateSize() { return codec.estimateHeaderSize(header) + ByteBufUtil.estimateXidSize(xid); } }
1,934
33.553571
128
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/operations/RecoveryOperation.java
package org.infinispan.client.hotrod.impl.transaction.operations; import static java.util.Collections.emptyList; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; import jakarta.transaction.TransactionManager; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.transaction.manager.RemoteXid; import org.infinispan.commons.io.SignedNumeric; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * A recovery request from the {@link TransactionManager}. * <p> * It returns all in-doubt transactions seen by the server. * * @author Pedro Ruivo * @since 9.4 */ public class RecoveryOperation extends RetryOnFailureOperation<Collection<Xid>> { public RecoveryOperation(Codec codec, ChannelFactory channelFactory, AtomicReference<ClientTopology> clientTopology, Configuration cfg) { super(FETCH_TX_RECOVERY_REQUEST, FETCH_TX_RECOVERY_RESPONSE, codec, channelFactory, DEFAULT_CACHE_NAME_BYTES, clientTopology, 0, cfg, null, null); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status != NO_ERROR_STATUS) { complete(emptyList()); return; } int size = ByteBufUtil.readVInt(buf); if (size == 0) { complete(emptyList()); return; } Collection<Xid> xids = new ArrayList<>(size); for (int i = 0; i < size; ++i) { int formatId = SignedNumeric.decode(ByteBufUtil.readVInt(buf)); byte[] globalId = ByteBufUtil.readArray(buf); byte[] branchId = ByteBufUtil.readArray(buf); //the Xid class does't matter since it only compares the format-id, global-id and branch-id xids.add(RemoteXid.create(formatId, globalId, branchId)); } complete(xids); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(estimateSize()); codec.writeHeader(buf, header); channel.writeAndFlush(buf); } private int estimateSize() { return codec.estimateHeaderSize(header); } }
2,642
34.24
140
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/operations/PrepareTransactionOperation.java
package org.infinispan.client.hotrod.impl.transaction.operations; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.estimateVIntSize; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.estimateXidSize; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.writeVInt; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.writeXid; import java.net.SocketAddress; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import jakarta.transaction.TransactionManager; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.impl.protocol.Codec; import org.infinispan.client.hotrod.impl.transaction.entry.Modification; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * A prepare request from the {@link TransactionManager}. * <p> * It contains all the transaction modification to perform the validation. * * @author Pedro Ruivo * @since 9.3 */ public class PrepareTransactionOperation extends RetryOnFailureOperation<Integer> { private final Xid xid; private final boolean onePhaseCommit; private final List<Modification> modifications; private final boolean recoverable; private final long timeoutMs; private boolean retry; public PrepareTransactionOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, Configuration cfg, Xid xid, boolean onePhaseCommit, List<Modification> modifications, boolean recoverable, long timeoutMs) { super(PREPARE_TX_2_REQUEST, PREPARE_TX_2_RESPONSE, codec, channelFactory, cacheName, clientTopology, 0, cfg, null, null); this.xid = xid; this.onePhaseCommit = onePhaseCommit; this.modifications = modifications; this.recoverable = recoverable; this.timeoutMs = timeoutMs; } public boolean shouldRetry() { return retry; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status == NO_ERROR_STATUS) { complete(buf.readInt()); } else { retry = status == NOT_PUT_REMOVED_REPLACED_STATUS; complete(0); } } @Override protected void executeOperation(Channel channel) { retry = false; scheduleRead(channel); ByteBuf buf = channel.alloc().buffer(estimateSize()); codec.writeHeader(buf, header); writeXid(buf, xid); buf.writeBoolean(onePhaseCommit); buf.writeBoolean(recoverable); buf.writeLong(timeoutMs); writeVInt(buf, modifications.size()); for (Modification m : modifications) { m.writeTo(buf, codec); } channel.writeAndFlush(buf); } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (modifications.isEmpty()) { super.fetchChannelAndInvoke(retryCount, failedServers); } else { channelFactory.fetchChannelAndInvoke(modifications.get(0).getKey(), failedServers, cacheName(), this); } } private int estimateSize() { int size = codec.estimateHeaderSize(header) + estimateXidSize(xid) + 1 + estimateVIntSize(modifications.size()); for (Modification modification : modifications) { size += modification.estimateSize(codec); } return size; } }
3,771
35.621359
127
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/marshall/ProtoStreamMarshaller.java
package org.infinispan.client.hotrod.marshall; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.protostream.SerializationContext; /** * A client-side marshaller that uses Protocol Buffers. * * @author anistor@redhat.com * @since 6.0 * @deprecated since 10.0, will be removed in the future. org.infinispan.commons.marshall.ProtoStreamMarshaller * should be used instead. */ @Deprecated public class ProtoStreamMarshaller extends org.infinispan.commons.marshall.ProtoStreamMarshaller { /** * Obtains the {@link SerializationContext} associated with the given remote cache manager. * * @param remoteCacheManager the remote cache manager (must not be {@code null}) * @return the associated {@link SerializationContext} * @throws HotRodClientException if the cache manager is not configured to use a {@link org.infinispan.commons.marshall.ProtoStreamMarshaller} * @deprecated since 10.0 and will be removed in the future. Use {@link MarshallerUtil#getSerializationContext(RemoteCacheManager)} * instead. */ @Deprecated public static SerializationContext getSerializationContext(RemoteCacheManager remoteCacheManager) { return MarshallerUtil.getSerializationContext(remoteCacheManager); } }
1,344
41.03125
145
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/marshall/BytesOnlyMarshaller.java
package org.infinispan.client.hotrod.marshall; import java.util.Arrays; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.Marshaller; /** * Marshaller that only supports byte[] instances writing them as is * * @author Tristan Tarrant * @author wburns * @since 10.0 */ public class BytesOnlyMarshaller implements Marshaller { private BytesOnlyMarshaller() { } public static final BytesOnlyMarshaller INSTANCE = new BytesOnlyMarshaller(); private static final BufferSizePredictor predictor = new IdentityBufferSizePredictor(); private void checkByteArray(Object o) { if (!(o instanceof byte[])) { throw new IllegalArgumentException("Only byte[] instances are supported currently!"); } } @Override public byte[] objectToByteBuffer(Object obj, int estimatedSize) { checkByteArray(obj); return (byte[]) obj; } @Override public byte[] objectToByteBuffer(Object obj) { checkByteArray(obj); return (byte[]) obj; } @Override public Object objectFromByteBuffer(byte[] buf) { return buf; } @Override public Object objectFromByteBuffer(byte[] buf, int offset, int length) { if (offset == 0 && length == buf.length) { return buf; } return Arrays.copyOfRange(buf, offset, offset + length); } @Override public ByteBuffer objectToBuffer(Object o) { checkByteArray(o); return ByteBufferImpl.create((byte[]) o); } @Override public boolean isMarshallable(Object o) { return o instanceof byte[]; } @Override public BufferSizePredictor getBufferSizePredictor(Object o) { return predictor; } @Override public MediaType mediaType() { return MediaType.APPLICATION_OCTET_STREAM; } private static final class IdentityBufferSizePredictor implements BufferSizePredictor { @Override public int nextSize(Object obj) { return ((byte[]) obj).length; } @Override public void recordSize(int previousSize) { // NOOP } } }
2,265
23.901099
94
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/marshall/MarshallerUtil.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectStreamConstants; import org.infinispan.client.hotrod.RemoteCacheContainer; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.CacheException; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.CheckedInputStream; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.util.Util; import org.infinispan.protostream.SerializationContext; /** * @author Galder Zamarreño */ public final class MarshallerUtil { private static final Log log = LogFactory.getLog(MarshallerUtil.class, Log.class); private MarshallerUtil() { } /** * A convenience method to return the {@link SerializationContext} associated with the {@link ProtoStreamMarshaller} * configured on the provided {@link RemoteCacheManager}. * * @return the associated {@link SerializationContext} * @throws HotRodClientException if the cache manager is not started or is not configured to use a {@link ProtoStreamMarshaller} */ public static SerializationContext getSerializationContext(RemoteCacheContainer remoteCacheManager) { Marshaller marshaller = remoteCacheManager.getMarshaller(); if (marshaller instanceof ProtoStreamMarshaller) { return ((ProtoStreamMarshaller) marshaller).getSerializationContext(); } if (marshaller == null) { throw new HotRodClientException("The cache manager must be configured with a ProtoStreamMarshaller and must be started before attempting to retrieve the ProtoStream SerializationContext"); } throw new HotRodClientException("The cache manager is not configured with a ProtoStreamMarshaller"); } @SuppressWarnings("unchecked") public static <T> T bytes2obj(Marshaller marshaller, byte[] bytes, boolean objectStorage, ClassAllowList allowList) { if (bytes == null || bytes.length == 0) return null; try { Object ret = marshaller.objectFromByteBuffer(bytes); if (objectStorage) { // Server stores objects // No extra configuration is required for client in this scenario, // and no different marshaller should be required to deal with standard serialization. // So, if the unmarshalled object is still a byte[], it could be a standard // serialized object, so check for stream magic if (ret instanceof byte[] && isJavaSerialized((byte[]) ret)) { T ois = tryJavaDeserialize(bytes, (byte[]) ret, allowList); if (ois != null) return ois; } } return (T) ret; } catch (Exception e) { throw HOTROD.unableToUnmarshallBytes(Util.toHexString(bytes), e); } } public static <T> T tryJavaDeserialize(byte[] bytes, byte[] ret, ClassAllowList allowList) { try (ObjectInputStream ois = new CheckedInputStream(new ByteArrayInputStream(ret), allowList)) { return (T) ois.readObject(); } catch (CacheException ce) { throw ce; } catch (Exception ee) { if (log.isDebugEnabled()) log.debugf("Standard deserialization not in use for %s", Util.printArray(bytes)); } return null; } private static boolean isJavaSerialized(byte[] bytes) { if (bytes.length > 2) { short magic = (short) ((bytes[1] & 0xFF) + (bytes[0] << 8)); return magic == ObjectStreamConstants.STREAM_MAGIC; } return false; } /** * @deprecated Since 12.0, will be removed in 15.0 */ @Deprecated public static byte[] obj2bytes(Marshaller marshaller, Object o, boolean isKey, int estimateKeySize, int estimateValueSize) { try { return marshaller.objectToByteBuffer(o, isKey ? estimateKeySize : estimateValueSize); } catch (IOException ioe) { throw new HotRodClientException( "Unable to marshall object of type [" + o.getClass().getName() + "]", ioe); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return null; } } public static byte[] obj2bytes(Marshaller marshaller, Object o, BufferSizePredictor sizePredictor) { try { byte[] bytes = marshaller.objectToByteBuffer(o, sizePredictor.nextSize(o)); sizePredictor.recordSize(bytes.length); return bytes; } catch (IOException ioe) { throw new HotRodClientException( "Unable to marshall object of type [" + o.getClass().getName() + "]", ioe); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return null; } } }
5,207
39.061538
197
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/annotation/package-info.java
/** * Hot Rod client annotations. * * @api.public */ package org.infinispan.client.hotrod.annotation;
106
14.285714
48
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/annotation/ClientCacheEntryModified.java
package org.infinispan.client.hotrod.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Galder Zamarreño */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ClientCacheEntryModified { }
359
23
48
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/annotation/ClientListener.java
package org.infinispan.client.hotrod.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation that marks a class to receive remote events from Hot Rod caches. * Classes with this annotation are expected to have at least one callback * annotated with one of the events it can receive: * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated}, * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryModified}, * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved}, * {@link org.infinispan.client.hotrod.annotation.ClientCacheFailover} * * @author Galder Zamarreño */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ClientListener { /** * Defines the key/value filter factory for this client listener. Filter * factories create filters that help decide which events should be sent * to this client listener. This helps with reducing traffic from server * to client. By default, no filtering is applied. */ String filterFactoryName() default ""; /** * Defines the converter factory for this client listener. Converter * factories create event converters that customize the contents of the * events sent to this listener. When event customization is enabled, * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated}, * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryModified}, * and {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved} * callbacks receive {@link org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent} * instances as parameters instead of their corresponding create/modified/removed * event. Event customization helps reduce the payload of events, or * increase to send even more information back to the client listener. * By default, no event customization is applied. */ String converterFactoryName() default ""; /** * This option affects the type of the parameters received by a configured * filter and/or converter. If using raw data, filter and/or converter * classes receive raw binary arrays as parameters instead of unmarshalled * instances, which is the default. On top of that, when raw data is * enabled, custom events produced by the converters are expected to be * byte arrays. This option is useful when trying to avoid marshalling * costs involved in unmarshalling data to pass to filter/converter * callbacks or costs involved in marshalling custom event POJOs. * Using raw data also helps with potential classloading issues related to * loading callback parameter classes or custom event POJOs. By using raw * data, there's no need for class sharing between the server and client. * By default, using raw binary data for filter/converter callbacks is * disabled. */ boolean useRawData() default false; /** * This flag enables cached state to be sent back to remote clients when * either adding a cache listener for the first time, or when the node where * a remote listener is registered changes. When enabled, state is sent * back as cache entry created events to the clients. In the special case * that the node where the remote listener is registered changes, before * sending any cache entry created events, the client receives a failover * event so that it's aware of the change of node. This is useful in order * to do local clean up before receiving the state again. For example, a * client building a local near cache and keeping it up to date with remote * events might decide to clear in when the failover event is received and * before the state is received. * * If disabled, no state is sent back to the client when adding a listener, * nor it gets state when the node where the listener is registered changes. * * By default, including state is disabled in order to provide best * performance. If clients must receive all events, enable including state. */ boolean includeCurrentState() default false; }
4,255
49.070588
94
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/annotation/ClientCacheEntryCreated.java
package org.infinispan.client.hotrod.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Galder Zamarreño */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ClientCacheEntryCreated { }
358
22.933333
48
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/annotation/ClientCacheFailover.java
package org.infinispan.client.hotrod.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ClientCacheFailover { }
319
23.615385
48
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/annotation/ClientCacheEntryRemoved.java
package org.infinispan.client.hotrod.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Galder Zamarreño */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ClientCacheEntryRemoved { }
358
22.933333
48
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/annotation/ClientCacheEntryExpired.java
package org.infinispan.client.hotrod.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author William Burns */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ClientCacheEntryExpired { }
355
22.733333
48
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/NotificationManager.java
package org.infinispan.client.hotrod.counter.impl; import static org.infinispan.client.hotrod.impl.Util.await; import java.net.SocketAddress; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.function.Consumer; import org.infinispan.client.hotrod.counter.operation.AddListenerOperation; import org.infinispan.client.hotrod.counter.operation.RemoveListenerOperation; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.event.impl.CounterEventDispatcher; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.util.concurrent.NonReentrantLock; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.Handle; /** * A Hot Rod client notification manager for a single {@link CounterManager}. * <p> * This handles all the users listeners. * * @author Pedro Ruivo * @since 9.2 */ public class NotificationManager { private static final Log log = LogFactory.getLog(NotificationManager.class, Log.class); private static final CompletableFuture<Short> NO_ERROR_FUTURE = CompletableFuture.completedFuture((short) HotRodConstants.NO_ERROR_STATUS); private final byte[] listenerId; private final ClientListenerNotifier notifier; private final CounterOperationFactory factory; private final ConcurrentMap<String, List<Consumer<HotRodCounterEvent>>> clientListeners = new ConcurrentHashMap<>(); private final Lock lock = new NonReentrantLock(); private volatile CounterEventDispatcher dispatcher; NotificationManager(ClientListenerNotifier notifier, CounterOperationFactory factory) { this.notifier = notifier; this.factory = factory; this.listenerId = new byte[16]; ThreadLocalRandom.current().nextBytes(listenerId); } public <T extends CounterListener> Handle<T> addListener(String counterName, T listener) { if (log.isTraceEnabled()) { log.tracef("Add listener for counter '%s'", counterName); } CounterEventDispatcher dispatcher = this.dispatcher; if (dispatcher != null) { return registerListener(counterName, listener, dispatcher.address()); } log.debugf("ALock %s", lock); lock.lock(); try { dispatcher = this.dispatcher; return registerListener(counterName, listener, dispatcher == null ? null : dispatcher.address()); } finally { lock.unlock(); log.debugf("AUnLock %s", lock); } } private <T extends CounterListener> Handle<T> registerListener(String counterName, T listener, SocketAddress address) { HandleImpl<T> handle = new HandleImpl<>(counterName, listener); clientListeners.computeIfAbsent(counterName, name -> { AddListenerOperation op = factory.newAddListenerOperation(counterName, listenerId, address); if (await(op.execute())) { if (address == null) { this.dispatcher = new CounterEventDispatcher(listenerId, clientListeners, op.getChannel().remoteAddress(), this::failover, op::cleanup); notifier.addDispatcher(dispatcher); notifier.startClientListener(listenerId); } } return new CopyOnWriteArrayList<>(); }).add(handle); return handle; } private void removeListener(String counterName, HandleImpl<?> handle) { if (log.isTraceEnabled()) { log.tracef("Remove listener for counter '%s'", counterName); } clientListeners.computeIfPresent(counterName, (name, list) -> { list.remove(handle); if (list.isEmpty()) { if (dispatcher != null) { RemoveListenerOperation op = factory.newRemoveListenerOperation(counterName, listenerId, dispatcher.address()); if (!await(op.execute())) { log.debugf("Failed to remove counter listener %s on server side", counterName); } } return null; } return list; }); } private CompletableFuture<Void> failover() { dispatcher = null; Iterator<String> iterator = clientListeners.keySet().iterator(); if (!iterator.hasNext()) { return null; } CompletableFuture<Void> cf = new CompletableFuture<>(); String firstCounterName = iterator.next(); AddListenerOperation op = factory.newAddListenerOperation(firstCounterName, listenerId, null); log.debugf("Lock %s", lock); lock.lock(); if (dispatcher == null) { op.execute().whenComplete((useChannel, throwable) -> { if (throwable != null) { lock.unlock(); log.debugf(throwable, "Failed to failover counter listener %s", firstCounterName); cf.completeExceptionally(throwable); } else { AtomicInteger counter = new AtomicInteger(1); SocketAddress address; try { if (useChannel) { log.debugf("Creating new counter event dispatcher on %s", op.getChannel()); dispatcher = new CounterEventDispatcher(listenerId, clientListeners, op.getChannel().remoteAddress(), this::failover, op::cleanup); notifier.addDispatcher(dispatcher); notifier.startClientListener(listenerId); } address = dispatcher.address(); } catch (Throwable t) { cf.completeExceptionally(t); return; } finally { lock.unlock(); log.debugf("UnLock %s", lock); } while (iterator.hasNext()) { String counterName = iterator.next(); factory.newAddListenerOperation(counterName, listenerId, address).execute() .whenComplete((useChannel2, throwable2) -> { if (throwable2 != null) { log.debugf(throwable2, "Failed to failover counter listener %s", counterName); cf.completeExceptionally(throwable2); } else { if (useChannel2) { cf.completeExceptionally(new IllegalStateException("Unexpected to use another channel for the same counter")); } if (counter.decrementAndGet() == 0) { cf.complete(null); } } }); } if (counter.decrementAndGet() == 0) { cf.complete(null); } } }); return cf; } else { lock.unlock(); log.debugf("UnLock %s", lock); return null; } } public void stop() { log.debugf("Stopping %s (%s)", this, lock); lock.lock(); try { CompletableFuture[] futures = clientListeners.keySet().stream().map(counterName -> factory.newRemoveListenerOperation(counterName, listenerId, dispatcher.address()).execute()) .toArray(CompletableFuture[]::new); await(CompletableFuture.allOf(futures)); clientListeners.clear(); } finally { lock.unlock(); } } private class HandleImpl<T extends CounterListener> implements Handle<T>, Consumer<HotRodCounterEvent> { private final T listener; private final String counterName; private HandleImpl(String counterName, T listener) { this.counterName = counterName; this.listener = listener; } @Override public T getCounterListener() { return listener; } @Override public void remove() { removeListener(counterName, this); } @Override public void accept(HotRodCounterEvent event) { try { listener.onUpdate(event); } catch (Throwable t) { log.debug("Exception in user listener", t); } } } }
8,659
38.543379
152
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/RemoteCounterManager.java
package org.infinispan.client.hotrod.counter.impl; import static org.infinispan.client.hotrod.impl.Util.await; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.logging.Log; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; import org.infinispan.counter.exception.CounterException; /** * A {@link CounterManager} implementation for Hot Rod clients. * * @author Pedro Ruivo * @since 9.2 */ public class RemoteCounterManager implements CounterManager { private static final Log commonsLog = LogFactory.getLog(RemoteCounterManager.class, Log.class); private final Map<String, Object> counters; private CounterOperationFactory factory; private NotificationManager notificationManager; public RemoteCounterManager() { counters = new ConcurrentHashMap<>(); } public void start(ChannelFactory channelFactory, Configuration configuration, ClientListenerNotifier listenerNotifier) { this.factory = new CounterOperationFactory(configuration, channelFactory); this.notificationManager = new NotificationManager(listenerNotifier, factory); } @Override public StrongCounter getStrongCounter(String name) { return getOrCreateCounter(name, StrongCounter.class, this::createStrongCounter, () -> commonsLog.invalidCounterType("Strong", "Weak")); } @Override public WeakCounter getWeakCounter(String name) { return getOrCreateCounter(name, WeakCounter.class, this::createWeakCounter, () -> commonsLog.invalidCounterType("Weak", "Strong")); } @Override public boolean defineCounter(String name, CounterConfiguration configuration) { return await(factory.newDefineCounterOperation(name, configuration).execute()); } @Override public void undefineCounter(String name) { } @Override public boolean isDefined(String name) { return await(factory.newIsDefinedOperation(name).execute()); } @Override public CounterConfiguration getConfiguration(String counterName) { return await(factory.newGetConfigurationOperation(counterName).execute()); } @Override public void remove(String counterName) { await(factory.newRemoveOperation(counterName, true).execute()); } @Override public Collection<String> getCounterNames() { return await(factory.newGetCounterNamesOperation().execute()); } public void stop() { if (notificationManager != null) { notificationManager.stop(); } } private <T> T getOrCreateCounter(String name, Class<T> tClass, Function<String, T> createFunction, Supplier<CounterException> invalidCounter) { Object counter = counters.computeIfAbsent(name, createFunction); if (!tClass.isInstance(counter)) { throw invalidCounter.get(); } return tClass.cast(counter); } private void assertWeakCounter(CounterConfiguration configuration) { if (configuration.type() != CounterType.WEAK) { throw commonsLog.invalidCounterType("Weak", "Strong"); } } private WeakCounter createWeakCounter(String counterName) { CounterConfiguration configuration = getConfiguration(counterName); if (configuration == null) { throw commonsLog.undefinedCounter(counterName); } assertWeakCounter(configuration); return new WeakCounterImpl(counterName, configuration, factory, notificationManager); } private StrongCounter createStrongCounter(String counterName) { CounterConfiguration configuration = getConfiguration(counterName); if (configuration == null) { throw commonsLog.undefinedCounter(counterName); } assertStrongCounter(configuration); return new StrongCounterImpl(counterName, configuration, factory, notificationManager); } private void assertStrongCounter(CounterConfiguration configuration) { if (configuration.type() == CounterType.WEAK) { throw commonsLog.invalidCounterType("Strong", "Weak"); } } }
4,610
34.198473
123
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/BaseCounter.java
package org.infinispan.client.hotrod.counter.impl; import java.util.concurrent.CompletableFuture; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.Handle; public class BaseCounter { protected final String name; protected final CounterConfiguration configuration; protected final CounterOperationFactory factory; private final NotificationManager notificationManager; BaseCounter(CounterConfiguration configuration, String name, CounterOperationFactory factory, NotificationManager notificationManager) { this.configuration = configuration; this.name = name; this.factory = factory; this.notificationManager = notificationManager; } public String getName() { return name; } public CompletableFuture<Void> reset() { return factory.newResetOperation(name, useConsistentHash()).execute(); } public CompletableFuture<Void> remove() { return factory.newRemoveOperation(name, useConsistentHash()).execute(); } public CounterConfiguration getConfiguration() { return configuration; } public <T extends CounterListener> Handle<T> addListener(T listener) { return notificationManager.addListener(name, listener); } boolean useConsistentHash() { return false; } }
1,378
28.340426
96
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/HotRodCounterEvent.java
package org.infinispan.client.hotrod.counter.impl; import org.infinispan.counter.api.CounterEvent; import org.infinispan.counter.api.CounterState; /** * A {@link CounterEvent} implementation for the Hot Rod client. * * @author Pedro Ruivo * @since 9.2 */ public class HotRodCounterEvent implements CounterEvent { private final byte[] listenerId; private final String counterName; private final long oldValue; private final CounterState oldState; private final long newValue; private final CounterState newState; public HotRodCounterEvent(byte[] listenerId, String counterName, long oldValue, CounterState oldState, long newValue, CounterState newState) { this.listenerId = listenerId; this.counterName = counterName; this.oldValue = oldValue; this.oldState = oldState; this.newValue = newValue; this.newState = newState; } public byte[] getListenerId() { return listenerId; } public String getCounterName() { return counterName; } @Override public long getOldValue() { return oldValue; } @Override public CounterState getOldState() { return oldState; } @Override public long getNewValue() { return newValue; } @Override public CounterState getNewState() { return newState; } @Override public String toString() { return "HotRodCounterEvent{" + "counterName='" + counterName + '\'' + ", oldValue=" + oldValue + ", oldState=" + oldState + ", newValue=" + newValue + ", newState=" + newState + '}'; } }
1,681
23.028571
120
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/StrongCounterImpl.java
package org.infinispan.client.hotrod.counter.impl; import static org.infinispan.client.hotrod.impl.Util.await; import java.util.concurrent.CompletableFuture; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.SyncStrongCounter; /** * A {@link StrongCounter} implementation for Hot Rod clients. * * @author Pedro Ruivo * @since 9.2 */ class StrongCounterImpl extends BaseCounter implements StrongCounter { private final SyncStrongCounter syncCounter; StrongCounterImpl(String name, CounterConfiguration configuration, CounterOperationFactory operationFactory, NotificationManager notificationManager) { super(configuration, name, operationFactory, notificationManager); this.syncCounter = new Sync(); } public CompletableFuture<Long> getValue() { return factory.newGetValueOperation(name, useConsistentHash()).execute(); } public CompletableFuture<Long> addAndGet(long delta) { return factory.newAddOperation(name, delta, useConsistentHash()).execute(); } @Override public CompletableFuture<Long> compareAndSwap(long expect, long update) { return factory.newCompareAndSwapOperation(name, expect, update, super.getConfiguration()).execute(); } @Override public SyncStrongCounter sync() { return syncCounter; } @Override public CompletableFuture<Long> getAndSet(long value) { return factory.newSetOperation(name, value, useConsistentHash()).execute(); } @Override boolean useConsistentHash() { return true; } private class Sync implements SyncStrongCounter { @Override public long addAndGet(long delta) { return await(StrongCounterImpl.this.addAndGet(delta)); } @Override public void reset() { await(StrongCounterImpl.this.reset()); } @Override public long getValue() { return await(StrongCounterImpl.this.getValue()); } @Override public long compareAndSwap(long expect, long update) { return await(StrongCounterImpl.this.compareAndSwap(expect, update)); } @Override public String getName() { return name; } @Override public CounterConfiguration getConfiguration() { return configuration; } @Override public void remove() { await(StrongCounterImpl.this.remove()); } @Override public long getAndSet(long value) { return await(StrongCounterImpl.this.getAndSet(value)); } } }
2,631
26.134021
111
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/CounterOperationFactory.java
package org.infinispan.client.hotrod.counter.impl; import java.net.SocketAddress; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.counter.operation.AddListenerOperation; import org.infinispan.client.hotrod.counter.operation.AddOperation; import org.infinispan.client.hotrod.counter.operation.CompareAndSwapOperation; import org.infinispan.client.hotrod.counter.operation.DefineCounterOperation; import org.infinispan.client.hotrod.counter.operation.GetConfigurationOperation; import org.infinispan.client.hotrod.counter.operation.GetCounterNamesOperation; import org.infinispan.client.hotrod.counter.operation.GetValueOperation; import org.infinispan.client.hotrod.counter.operation.IsDefinedOperation; import org.infinispan.client.hotrod.counter.operation.RemoveListenerOperation; import org.infinispan.client.hotrod.counter.operation.RemoveOperation; import org.infinispan.client.hotrod.counter.operation.ResetOperation; import org.infinispan.client.hotrod.counter.operation.SetOperation; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.counter.api.CounterConfiguration; /** * A operation factory that builds counter operations. * * @author Pedro Ruivo * @since 9.2 */ public class CounterOperationFactory { public static final byte[] COUNTER_CACHE_NAME = RemoteCacheManager.cacheNameBytes("org.infinispan.COUNTER"); private final Configuration configuration; private final ChannelFactory channelFactory; private final AtomicReference<ClientTopology> clientTopologyRef; CounterOperationFactory(Configuration configuration, ChannelFactory channelFactory) { this.configuration = configuration; this.channelFactory = channelFactory; clientTopologyRef = channelFactory.createTopologyId(COUNTER_CACHE_NAME); } IsDefinedOperation newIsDefinedOperation(String counterName) { return new IsDefinedOperation(channelFactory, clientTopologyRef, configuration, counterName); } GetConfigurationOperation newGetConfigurationOperation(String counterName) { return new GetConfigurationOperation(channelFactory, clientTopologyRef, configuration, counterName); } DefineCounterOperation newDefineCounterOperation(String counterName, CounterConfiguration cfg) { return new DefineCounterOperation(channelFactory, clientTopologyRef, configuration, counterName, cfg); } RemoveOperation newRemoveOperation(String counterName, boolean useConsistentHash) { return new RemoveOperation(channelFactory, clientTopologyRef, configuration, counterName, useConsistentHash); } AddOperation newAddOperation(String counterName, long delta, boolean useConsistentHash) { return new AddOperation(channelFactory, clientTopologyRef, configuration, counterName, delta, useConsistentHash); } GetValueOperation newGetValueOperation(String counterName, boolean useConsistentHash) { return new GetValueOperation(channelFactory, clientTopologyRef, configuration, counterName, useConsistentHash); } ResetOperation newResetOperation(String counterName, boolean useConsistentHash) { return new ResetOperation(channelFactory, clientTopologyRef, configuration, counterName, useConsistentHash); } CompareAndSwapOperation newCompareAndSwapOperation(String counterName, long expect, long update, CounterConfiguration counterConfiguration) { return new CompareAndSwapOperation(channelFactory, clientTopologyRef, configuration, counterName, expect, update, counterConfiguration); } SetOperation newSetOperation(String counterName, long value, boolean useConsistentHash) { return new SetOperation(channelFactory, clientTopologyRef, configuration, counterName, value, useConsistentHash); } GetCounterNamesOperation newGetCounterNamesOperation() { return new GetCounterNamesOperation(channelFactory, clientTopologyRef, configuration); } AddListenerOperation newAddListenerOperation(String counterName, byte[] listenerId, SocketAddress server) { return new AddListenerOperation(channelFactory, clientTopologyRef, configuration, counterName, listenerId, server); } RemoveListenerOperation newRemoveListenerOperation(String counterName, byte[] listenerId, SocketAddress server) { return new RemoveListenerOperation(channelFactory, clientTopologyRef, configuration, counterName, listenerId, server); } }
4,699
47.958333
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/CounterHelper.java
package org.infinispan.client.hotrod.counter.impl; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; /** * A helper class for {@link StrongCounter} and {@link WeakCounter}. * * @author Pedro Ruivo * @since 9.2 */ class CounterHelper { private final CounterOperationFactory factory; CounterHelper(CounterOperationFactory factory) { this.factory = factory; } }
431
18.636364
68
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/impl/WeakCounterImpl.java
package org.infinispan.client.hotrod.counter.impl; import static org.infinispan.client.hotrod.impl.Util.await; import java.util.concurrent.CompletableFuture; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.SyncWeakCounter; import org.infinispan.counter.api.WeakCounter; /** * A {@link WeakCounter} implementation for Hot Rod client. * * @author Pedro Ruivo * @since 9.2 */ class WeakCounterImpl extends BaseCounter implements WeakCounter { private final SyncWeakCounter syncCounter; WeakCounterImpl(String name, CounterConfiguration configuration, CounterOperationFactory operationFactory, NotificationManager notificationManager) { super(configuration, name, operationFactory, notificationManager); syncCounter = new Sync(); } @Override public long getValue() { return await(factory.newGetValueOperation(name, useConsistentHash()).execute()); } @Override public CompletableFuture<Void> add(long delta) { return factory.newAddOperation(name, delta, useConsistentHash()).execute().thenRun(() -> {}); } @Override public SyncWeakCounter sync() { return syncCounter; } private class Sync implements SyncWeakCounter { @Override public String getName() { return name; } @Override public long getValue() { return WeakCounterImpl.this.getValue(); } @Override public void add(long delta) { await(WeakCounterImpl.this.add(delta)); } @Override public void reset() { await(WeakCounterImpl.this.reset()); } @Override public CounterConfiguration getConfiguration() { return configuration; } @Override public void remove() { await(WeakCounterImpl.this.remove()); } } }
1,869
24.27027
109
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/AddOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.counter.exception.CounterOutOfBoundsException; /** * Add operation. * <p> * Adds the {@code delta} to the counter's value and returns the result. * <p> * It can throw a {@link CounterOutOfBoundsException} if the counter is bounded and the it has been reached. * * @author Pedro Ruivo * @since 9.2 */ public class AddOperation extends BaseCounterOperation<Long> { private static final Log commonsLog = LogFactory.getLog(AddOperation.class, Log.class); private final long delta; public AddOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, long delta, boolean useConsistentHash) { super(COUNTER_ADD_AND_GET_REQUEST, COUNTER_ADD_AND_GET_RESPONSE, channelFactory, topologyId, cfg, counterName, useConsistentHash); this.delta = delta; } @Override protected void executeOperation(Channel channel) { ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, 8); buf.writeLong(delta); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); assertBoundaries(status); assert status == NO_ERROR_STATUS; complete(buf.readLong()); } private void assertBoundaries(short status) { if (status == NOT_EXECUTED_WITH_PREVIOUS) { if (delta > 0) { throw commonsLog.counterOurOfBounds(CounterOutOfBoundsException.UPPER_BOUND); } else { throw commonsLog.counterOurOfBounds(CounterOutOfBoundsException.LOWER_BOUND); } } } }
2,195
34.419355
136
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/AddListenerOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.net.SocketAddress; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; /** * An add listener operation for {@link StrongCounter#addListener(CounterListener)} and {@link * WeakCounter#addListener(CounterListener)} * * @author Pedro Ruivo * @since 9.2 */ public class AddListenerOperation extends BaseCounterOperation<Boolean> { private final byte[] listenerId; private final SocketAddress server; private Channel channel; public AddListenerOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, byte[] listenerId, SocketAddress server) { super(COUNTER_ADD_LISTENER_REQUEST, COUNTER_ADD_LISTENER_RESPONSE, channelFactory, topologyId, cfg, counterName, false); this.listenerId = listenerId; this.server = server; } public Channel getChannel() { return channel; } @Override protected void executeOperation(Channel channel) { this.channel = channel; ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, ByteBufUtil.estimateArraySize(listenerId)); ByteBufUtil.writeArray(buf, listenerId); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); if (status != NO_ERROR_STATUS) { complete(false); } else { decoder.addListener(listenerId); complete(true); } } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (server == null) { super.fetchChannelAndInvoke(retryCount, failedServers); } else { channelFactory.fetchChannelAndInvoke(server, this); } } @Override public void releaseChannel(Channel channel) { if (codec.allowOperationsAndEvents()) { //we aren't using this channel. we can release it super.releaseChannel(channel); } } public void cleanup() { // To prevent releasing concurrently from the channel and closing it channel.eventLoop().execute(() -> { if (log.isTraceEnabled()) { log.tracef("Cleanup for %s on %s", this, channel); } if (!codec.allowOperationsAndEvents()) { if (channel.isOpen()) { super.releaseChannel(channel); } } HeaderDecoder decoder = channel.pipeline().get(HeaderDecoder.class); if (decoder != null) { decoder.removeListener(listenerId); } }); } }
3,241
32.770833
126
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/GetCounterNamesOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.CounterManager; /** * A counter operation for {@link CounterManager#getCounterNames()}. * * @author Pedro Ruivo * @since 9.2 */ public class GetCounterNamesOperation extends BaseCounterOperation<Collection<String>> { private int size; private Collection<String> names; public GetCounterNamesOperation(ChannelFactory transportFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg) { super(COUNTER_GET_NAMES_REQUEST, COUNTER_GET_NAMES_RESPONSE, transportFactory, topologyId, cfg, "", false); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendHeader(channel); setCacheName(); } @Override protected void reset() { super.reset(); names = null; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { assert status == NO_ERROR_STATUS; if (names == null) { size = ByteBufUtil.readVInt(buf); names = new ArrayList<>(size); decoder.checkpoint(); } while (names.size() < size) { names.add(ByteBufUtil.readString(buf)); decoder.checkpoint(); } complete(names); } }
1,850
30.372881
113
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/ResetOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; /** * A counter operation for {@link StrongCounter#reset()} and {@link WeakCounter#reset()}. * * @author Pedro Ruivo * @since 9.2 */ public class ResetOperation extends BaseCounterOperation<Void> { public ResetOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, boolean useConsistentHash) { super(COUNTER_RESET_REQUEST, COUNTER_RESET_RESPONSE, channelFactory, topologyId, cfg, counterName, useConsistentHash); } @Override protected void executeOperation(Channel channel) { sendHeaderAndCounterNameAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); complete(null); } }
1,323
33.842105
124
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/RemoveOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; /** * A counter operation for {@link CounterManager#remove(String)}, {@link StrongCounter#remove()} and {@link * WeakCounter#remove()}. * * @author Pedro Ruivo * @since 9.2 */ public class RemoveOperation extends BaseCounterOperation<Void> { public RemoveOperation(ChannelFactory transportFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, boolean useConsistentHash) { super(COUNTER_REMOVE_REQUEST, COUNTER_REMOVE_RESPONSE, transportFactory, topologyId, cfg, counterName, useConsistentHash); } @Override protected void executeOperation(Channel channel) { sendHeaderAndCounterNameAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); complete(null); } }
1,441
35.974359
128
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/IsDefinedOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.CounterManager; /** * A counter operation for {@link CounterManager#isDefined(String)}. * * @author Pedro Ruivo * @since 9.2 */ public class IsDefinedOperation extends BaseCounterOperation<Boolean> { public IsDefinedOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> clientTopology, Configuration cfg, String counterName) { super(COUNTER_IS_DEFINED_REQUEST, COUNTER_IS_DEFINED_RESPONSE, channelFactory, clientTopology, cfg, counterName, false); } @Override protected void executeOperation(Channel channel) { sendHeaderAndCounterNameAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(status == NO_ERROR_STATUS); } }
1,260
34.027778
126
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/CompareAndSwapOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.exception.CounterOutOfBoundsException; /** * A compare-and-set operation for {@link StrongCounter#compareAndSwap(long, long)} and {@link * StrongCounter#compareAndSet(long, long)}. * * @author Pedro Ruivo * @since 9.2 */ public class CompareAndSwapOperation extends BaseCounterOperation<Long> { private static final Log commonsLog = LogFactory.getLog(CompareAndSwapOperation.class, Log.class); private final long expect; private final long update; private final CounterConfiguration counterConfiguration; public CompareAndSwapOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, long expect, long update, CounterConfiguration counterConfiguration) { super(COUNTER_CAS_REQUEST, COUNTER_CAS_RESPONSE, channelFactory, topologyId, cfg, counterName, true); this.expect = expect; this.update = update; this.counterConfiguration = counterConfiguration; } @Override protected void executeOperation(Channel channel) { ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, 16); buf.writeLong(expect); buf.writeLong(update); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); assertBoundaries(status); assert status == NO_ERROR_STATUS; complete(buf.readLong()); } private void assertBoundaries(short status) { if (status == NOT_EXECUTED_WITH_PREVIOUS) { if (update >= counterConfiguration.upperBound()) { throw commonsLog.counterOurOfBounds(CounterOutOfBoundsException.UPPER_BOUND); } else { throw commonsLog.counterOurOfBounds(CounterOutOfBoundsException.LOWER_BOUND); } } } }
2,527
37.30303
143
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/SetOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.exception.CounterOutOfBoundsException; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; /** * A set operation for {@link StrongCounter#getAndSet(long)} * * @author Dipanshu Gupta * @since 15 */ public class SetOperation extends BaseCounterOperation<Long> { private static final Log commonsLog = LogFactory.getLog(SetOperation.class, Log.class); private final long value; public SetOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, long value, boolean useConsistentHash) { super(COUNTER_GET_AND_SET_REQUEST, COUNTER_GET_AND_SET_RESPONSE, channelFactory, topologyId, cfg, counterName, useConsistentHash); this.value = value; } @Override protected void executeOperation(Channel channel) { ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, 8); buf.writeLong(value); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); assertBoundaries(status); assert status == NO_ERROR_STATUS; complete(buf.readLong()); } private void assertBoundaries(short status) { if (status == NOT_EXECUTED_WITH_PREVIOUS) { if (value > 0) { throw commonsLog.counterOurOfBounds(CounterOutOfBoundsException.UPPER_BOUND); } else { throw commonsLog.counterOurOfBounds(CounterOutOfBoundsException.LOWER_BOUND); } } } }
2,107
34.728814
136
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/BaseCounterOperation.java
package org.infinispan.client.hotrod.counter.operation; import static org.infinispan.client.hotrod.counter.impl.CounterOperationFactory.COUNTER_CACHE_NAME; import java.net.SocketAddress; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.logging.Log; import org.infinispan.commons.util.Util; import org.infinispan.counter.exception.CounterException; /** * A base operation class for the counter's operation. * * @author Pedro Ruivo * @since 9.2 */ abstract class BaseCounterOperation<T> extends RetryOnFailureOperation<T> { private static final Log commonsLog = LogFactory.getLog(BaseCounterOperation.class, Log.class); private static final Charset CHARSET = StandardCharsets.UTF_8; private static final byte[] EMPTY_CACHE_NAME = Util.EMPTY_BYTE_ARRAY; private final String counterName; private final boolean useConsistentHash; BaseCounterOperation(short requestCode, short responseCode, ChannelFactory channelFactory, AtomicReference<ClientTopology> clientTopology, Configuration cfg, String counterName, boolean useConsistentHash) { super(requestCode, responseCode, channelFactory.getNegotiatedCodec(), channelFactory, EMPTY_CACHE_NAME, clientTopology, 0, cfg, null, null); this.counterName = counterName; this.useConsistentHash = useConsistentHash; } /** * Writes the operation header followed by the counter's name. */ void sendHeaderAndCounterNameAndRead(Channel channel) { ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, 0); channel.writeAndFlush(buf); } ByteBuf getHeaderAndCounterNameBufferAndRead(Channel channel, int extraBytes) { scheduleRead(channel); // counterName should never be null/empty byte[] counterBytes = counterName.getBytes(HotRodConstants.HOTROD_STRING_CHARSET); ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(counterBytes) + extraBytes); codec.writeHeader(buf, header); ByteBufUtil.writeString(buf, counterName); setCacheName(); return buf; } /** * If the status is {@link #KEY_DOES_NOT_EXIST_STATUS}, the counter is undefined and a {@link CounterException} is * thrown. */ void checkStatus(short status) { if (status == KEY_DOES_NOT_EXIST_STATUS) { throw commonsLog.undefinedCounter(counterName); } } void setCacheName() { header.cacheName(COUNTER_CACHE_NAME); } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (retryCount == 0 && useConsistentHash) { channelFactory.fetchChannelAndInvoke(new ByteString(counterName), failedServers, COUNTER_CACHE_NAME, this); } else { channelFactory.fetchChannelAndInvoke(failedServers, COUNTER_CACHE_NAME, this); } } @Override protected Throwable handleException(Throwable cause, Channel channel, SocketAddress address) { cause = super.handleException(cause, channel, address); if (cause instanceof CounterException) { completeExceptionally(cause); return null; } return cause; } @Override protected void addParams(StringBuilder sb) { sb.append("counter=").append(counterName); } private static class ByteString { private final int hash; private final byte[] b; private ByteString(String s) { //copied from ByteString in core this.b = s.getBytes(CHARSET); this.hash = Arrays.hashCode(b); } @Override public int hashCode() { return hash; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ByteString that = (ByteString) o; return Arrays.equals(b, that.b); } @Override public String toString() { return new String(b, CHARSET); } } }
4,695
33.529412
160
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/GetValueOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; /** * A counter operation that returns the counter's value. * * @author Pedro Ruivo * @since 9.2 */ public class GetValueOperation extends BaseCounterOperation<Long> { public GetValueOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, boolean useConsistentHash) { super(COUNTER_GET_REQUEST, COUNTER_GET_RESPONSE, channelFactory, topologyId, cfg, counterName, useConsistentHash); } @Override protected void executeOperation(Channel channel) { sendHeaderAndCounterNameAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); assert status == NO_ERROR_STATUS; complete(buf.readLong()); } }
1,246
32.702703
120
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/GetConfigurationOperation.java
package org.infinispan.client.hotrod.counter.operation; import static org.infinispan.counter.util.EncodeUtil.decodeConfiguration; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; /** * A counter configuration for {@link CounterManager#getConfiguration(String)}. * * @author Pedro Ruivo * @since 9.2 */ public class GetConfigurationOperation extends BaseCounterOperation<CounterConfiguration> { public GetConfigurationOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName) { super(COUNTER_GET_CONFIGURATION_REQUEST, COUNTER_GET_CONFIGURATION_RESPONSE, channelFactory, topologyId, cfg, counterName, false); } @Override protected void executeOperation(Channel channel) { sendHeaderAndCounterNameAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status != NO_ERROR_STATUS) { complete(null); return; } complete(decodeConfiguration(buf::readByte, buf::readLong, () -> ByteBufUtil.readVInt(buf))); } }
1,659
35.888889
136
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/DefineCounterOperation.java
package org.infinispan.client.hotrod.counter.operation; import static org.infinispan.counter.util.EncodeUtil.encodeConfiguration; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; /** * A counter define operation for {@link CounterManager#defineCounter(String, CounterConfiguration)}. * * @author Pedro Ruivo * @since 9.2 */ public class DefineCounterOperation extends BaseCounterOperation<Boolean> { private final CounterConfiguration configuration; public DefineCounterOperation(ChannelFactory channelFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, CounterConfiguration configuration) { super(COUNTER_CREATE_REQUEST, COUNTER_CREATE_RESPONSE, channelFactory, topologyId, cfg, counterName, false); this.configuration = configuration; } @Override protected void executeOperation(Channel channel) { ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, 28); encodeConfiguration(configuration, buf::writeByte, buf::writeLong, i -> ByteBufUtil.writeVInt(buf, i)); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); complete(status == NO_ERROR_STATUS); } }
1,816
38.5
114
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/counter/operation/RemoveListenerOperation.java
package org.infinispan.client.hotrod.counter.operation; import java.net.SocketAddress; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; import org.infinispan.counter.api.Handle; /** * A remove listener operation for {@link Handle#remove()}. * * @author Pedro Ruivo * @since 9.2 */ public class RemoveListenerOperation extends BaseCounterOperation<Boolean> { private final byte[] listenerId; private final SocketAddress server; public RemoveListenerOperation(ChannelFactory transportFactory, AtomicReference<ClientTopology> topologyId, Configuration cfg, String counterName, byte[] listenerId, SocketAddress server) { super(COUNTER_REMOVE_LISTENER_REQUEST, COUNTER_REMOVE_LISTENER_RESPONSE, transportFactory, topologyId, cfg, counterName, false); this.listenerId = listenerId; this.server = server; } @Override protected void executeOperation(Channel channel) { ByteBuf buf = getHeaderAndCounterNameBufferAndRead(channel, ByteBufUtil.estimateArraySize(listenerId)); ByteBufUtil.writeArray(buf, listenerId); channel.writeAndFlush(buf); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { checkStatus(status); if (status == NO_ERROR_STATUS) { decoder.removeListener(listenerId); } complete(status == NO_ERROR_STATUS); } @Override protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (server == null) { super.fetchChannelAndInvoke(retryCount, failedServers); } else { channelFactory.fetchChannelAndInvoke(server, this); } } }
2,119
34.333333
134
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/transaction/manager/RemoteTransactionManager.java
package org.infinispan.client.hotrod.transaction.manager; import java.util.UUID; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.commons.tx.TransactionManagerImpl; /** * A simple {@link TransactionManager} implementation. * <p> * It provides the basic to handle {@link Transaction}s and supports any {@link javax.transaction.xa.XAResource}. * <p> * Implementation notes: <ul> <li>The state is kept in memory only.</li> <li>Does not support recover.</li> <li>Does not * support multi-thread transactions. Although it is possible to execute the transactions in multiple threads, this * transaction manager does not wait for them to complete. It is the application responsibility to wait before invoking * {@link #commit()} or {@link #rollback()}</li> <li>The transaction should not block. It is no possible to {@link * #setTransactionTimeout(int)} and this transaction manager won't rollback the transaction if it takes too long.</li> * </ul> * <p> * If you need any of the requirements above, please consider use another implementation. * <p> * Also, it does not implement any 1-phase-commit optimization. * * @author Pedro Ruivo * @since 9.3 */ public final class RemoteTransactionManager extends TransactionManagerImpl { private RemoteTransactionManager() { super(); } public static RemoteTransactionManager getInstance() { return LazyInitializeHolder.INSTANCE; } @Override protected Transaction createTransaction() { return new RemoteTransaction(this); } UUID getTransactionManagerId() { return transactionManagerId; } private static class LazyInitializeHolder { static final RemoteTransactionManager INSTANCE = new RemoteTransactionManager(); } }
1,801
33.653846
120
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/transaction/manager/RemoteXid.java
package org.infinispan.client.hotrod.transaction.manager; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.estimateVIntSize; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.writeArray; import static org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil.writeSignedVInt; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import javax.transaction.xa.Xid; import org.infinispan.commons.tx.XidImpl; import io.netty.buffer.ByteBuf; /** * Implementation of {@link Xid} used by {@link RemoteTransactionManager}. * * @author Pedro Ruivo * @since 9.3 */ public final class RemoteXid extends XidImpl { //HRTX in hex private static final int FORMAT_ID = 0x48525458; private static final AtomicLong GLOBAL_ID_GENERATOR = new AtomicLong(1); private static final AtomicLong BRANCH_QUALIFIER_GENERATOR = new AtomicLong(1); private RemoteXid(int formatId, byte[] globalTransactionId, byte[] branchQualifier) { super(formatId, globalTransactionId, branchQualifier); } public static RemoteXid create(UUID tmId) { long creationTime = System.currentTimeMillis(); byte[] gid = create(tmId, creationTime, GLOBAL_ID_GENERATOR); byte[] bid = create(tmId, creationTime, BRANCH_QUALIFIER_GENERATOR); return new RemoteXid(FORMAT_ID, gid, bid); } private static void longToBytes(long val, byte[] array, int offset) { for (int i = 7; i > 0; i--) { array[offset + i] = (byte) val; val >>>= 8; } array[offset] = (byte) val; } private static byte[] create(UUID transactionManagerId, long creatingTime, AtomicLong generator) { byte[] field = new byte[32]; //size of 4 longs longToBytes(transactionManagerId.getLeastSignificantBits(), field, 0); longToBytes(transactionManagerId.getMostSignificantBits(), field, 8); longToBytes(creatingTime, field, 16); longToBytes(generator.getAndIncrement(), field, 24); return field; } public void writeTo(ByteBuf byteBuf) { writeSignedVInt(byteBuf, FORMAT_ID); byte[] rawData = rawData(); writeArray(byteBuf, rawData, globalIdOffset(), globalIdLength()); writeArray(byteBuf, rawData, branchQualifierOffset(), branchQualifierLength()); } public int estimateSize() { return estimateVIntSize(FORMAT_ID) + globalIdLength() + branchQualifierLength(); } }
2,436
34.318841
101
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/transaction/manager/RemoteTransaction.java
package org.infinispan.client.hotrod.transaction.manager; import jakarta.transaction.Transaction; import org.infinispan.commons.tx.TransactionImpl; /** * A {@link Transaction} implementation used by {@link RemoteTransactionManager}. * * @author Pedro Ruivo * @since 9.3 * @see RemoteTransactionManager */ final class RemoteTransaction extends TransactionImpl { RemoteTransaction(RemoteTransactionManager transactionManager) { super(); setXid(RemoteXid.create(transactionManager.getTransactionManagerId())); } }
540
23.590909
81
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/transaction/lookup/GenericTransactionManagerLookup.java
package org.infinispan.client.hotrod.transaction.lookup; import java.util.Optional; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.TransactionManager; import org.infinispan.client.hotrod.transaction.manager.RemoteTransactionManager; import org.infinispan.commons.util.Util; import org.infinispan.commons.tx.lookup.LookupNames; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import net.jcip.annotations.GuardedBy; /** * A {@link TransactionManagerLookup} implementation that attempts to locate a {@link TransactionManager}. * <p> * A variety of different classes and JNDI locations are tried, for servers such as: <ul> <li> JBoss <li> JRun4 <li> * Resin <li> Orion <li> JOnAS <li> BEA Weblogic <li> Websphere 4.0, 5.0, 5.1, 6.0 <li> Sun, Glassfish </ul>. * <p> * If a transaction manager is not found, returns an {@link RemoteTransactionManager}. * * @author Pedro Ruivo * @since 9.3 */ public class GenericTransactionManagerLookup implements TransactionManagerLookup { private static final GenericTransactionManagerLookup INSTANCE = new GenericTransactionManagerLookup(); @GuardedBy("this") private TransactionManager transactionManager = null; private GenericTransactionManagerLookup() { } public static GenericTransactionManagerLookup getInstance() { return INSTANCE; } @Override public synchronized TransactionManager getTransactionManager() { if (transactionManager != null) { return transactionManager; } transactionManager = tryTmFactoryLookup().orElseGet(RemoteTransactionManager::getInstance); transactionManager = tryJndiLookup().orElseGet( () -> tryTmFactoryLookup().orElseGet(RemoteTransactionManager::getInstance)); return transactionManager; } private Optional<TransactionManager> tryJndiLookup() { InitialContext ctx; try { ctx = new InitialContext(); } catch (NamingException e) { return Optional.empty(); } try { //probe jndi lookups first for (LookupNames.JndiTransactionManager knownJNDIManager : LookupNames.JndiTransactionManager.values()) { Object jndiObject; try { jndiObject = ctx.lookup(knownJNDIManager.getJndiLookup()); } catch (NamingException e) { continue; } if (jndiObject instanceof TransactionManager) { return Optional.of((TransactionManager) jndiObject); } } } finally { Util.close(ctx); } return Optional.empty(); } private Optional<TransactionManager> tryTmFactoryLookup() { for (LookupNames.TransactionManagerFactory transactionManagerFactory : LookupNames.TransactionManagerFactory .values()) { TransactionManager transactionManager = transactionManagerFactory .tryLookup(GenericTransactionManagerLookup.class.getClassLoader()); if (transactionManager != null) { return Optional.of(transactionManager); } } return Optional.empty(); } }
3,171
33.857143
116
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/transaction/lookup/RemoteTransactionManagerLookup.java
package org.infinispan.client.hotrod.transaction.lookup; import jakarta.transaction.TransactionManager; import org.infinispan.client.hotrod.transaction.manager.RemoteTransactionManager; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; /** * Returns an instance of {@link RemoteTransactionManager}. * * @author Pedro Ruivo * @since 9.3 */ public class RemoteTransactionManagerLookup implements TransactionManagerLookup { private static final RemoteTransactionManagerLookup INSTANCE = new RemoteTransactionManagerLookup(); private RemoteTransactionManagerLookup() { } public static TransactionManagerLookup getInstance() { return INSTANCE; } @Override public TransactionManager getTransactionManager() { return RemoteTransactionManager.getInstance(); } @Override public String toString() { return "RemoteTransactionManagerLookup"; } }
914
25.142857
103
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/HotRodMutinyCacheTest.java
package org.infinispan.hotrod; import static org.infinispan.hotrod.AwaitAssertions.assertAwaitEquals; import static org.infinispan.hotrod.AwaitAssertions.await; import static org.infinispan.hotrod.CacheEntryAssertions.assertEntry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.time.Duration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import io.smallrye.mutiny.Multi; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryMetadata; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.cache.CacheEntryImpl; import org.infinispan.hotrod.impl.cache.CacheEntryMetadataImpl; import org.infinispan.hotrod.impl.cache.CacheEntryVersionImpl; import org.infinispan.hotrod.test.AbstractMutinyCacheSingleServerTest; import org.infinispan.hotrod.test.KeyValueGenerator; import org.infinispan.hotrod.util.FlowUtils; import org.infinispan.hotrod.util.MapKVHelper; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * @since 14.0 **/ public class HotRodMutinyCacheTest<K, V> extends AbstractMutinyCacheSingleServerTest<K, V> { @MethodSource("parameterized") @ParameterizedTest(name = "getPut[{0}]") public void testPut(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V v1 = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion version1 = new CacheEntryVersionImpl(1); assertEntry(key, null, kvGenerator, await(cache.put(key, v1, options))); kvGenerator.assertValueEquals(v1, await(cache.get(key))); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); CacheWriteOptions optionsV1 = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(20)) .lifespanAndMaxIdle(Duration.ofSeconds(25), Duration.ofSeconds(30)) .build(); final CacheEntryVersion version2 = new CacheEntryVersionImpl(2); final V v2 = kvGenerator.generateValue(cacheName, 1); assertEntry(key, v1, kvGenerator, await(cache.put(key, v2, optionsV1)), options, version1); assertEntry(key, v2, kvGenerator, await(cache.getEntry(key)), optionsV1, version2); } @MethodSource("parameterized") @ParameterizedTest(name = "testPutIfAbsent[{0}]") public void testPutIfAbsent(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V v1 = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion version1 = new CacheEntryVersionImpl(1); assertAwaitEquals(null, cache.putIfAbsent(key, v1, options)); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); final V other = kvGenerator.generateValue(cacheName, 1); CacheEntry<K, V> previousEntry = await(cache.putIfAbsent(key, other)); kvGenerator.assertKeyEquals(key, previousEntry.key()); kvGenerator.assertValueEquals(v1, previousEntry.value()); kvGenerator.assertValueEquals(v1, await(cache.get(key))); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); } @MethodSource("parameterized") @ParameterizedTest(name = "testSetIfAbsent[{0}]") public void testSetIfAbsent(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V value = kvGenerator.generateValue(cacheName, 0); CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); assertAwaitEquals(true, cache.setIfAbsent(key, value, options)); assertEntry(key, value, kvGenerator, await(cache.getEntry(key)), options, new CacheEntryVersionImpl(1)); final V other = kvGenerator.generateValue(cacheName, 1); assertAwaitEquals(false, cache.setIfAbsent(key, other)); final V actual = await(cache.get(key)); kvGenerator.assertValueEquals(value, actual); assertEntry(key, value, kvGenerator, await(cache.getEntry(key)), options, new CacheEntryVersionImpl(1)); } @MethodSource("parameterized") @ParameterizedTest(name = "testSet[{0}]") public void testSet(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V v1 = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion version1 = new CacheEntryVersionImpl(1); await(cache.set(key, v1, options)); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); final CacheWriteOptions optionsV2 = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(20)) .lifespanAndMaxIdle(Duration.ofSeconds(25), Duration.ofSeconds(30)) .build(); final CacheEntryVersion version2 = new CacheEntryVersionImpl(2); final V v2 = kvGenerator.generateValue(cacheName, 1); await(cache.set(key, v2, optionsV2)); V actual = await(cache.get(key)); kvGenerator.assertValueEquals(v2, actual); assertEntry(key, v2, kvGenerator, await(cache.getEntry(key)), optionsV2, version2); } @MethodSource("parameterized") @ParameterizedTest(name = "testGetAndRemove[{0}]") public void testGetAndRemove(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V value = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion cev = new CacheEntryVersionImpl(1); assertEntry(key, null, kvGenerator, await(cache.put(key, value, options))); assertEntry(key, value, kvGenerator, await(cache.getEntry(key)), options, cev); assertEntry(key, value, kvGenerator, await(cache.getAndRemove(key)), options, cev); assertAwaitEquals(null, cache.get(key)); } @MethodSource("parameterized") @ParameterizedTest(name = "testPutAllAndClear[{0}]") public void testPutAllAndClear(KeyValueGenerator<K, V> kvGenerator) { Map<K, V> entries = new HashMap<>(); for (int i = 0; i < 10; i++) { final K key = kvGenerator.generateKey(cacheName, i); final V value = kvGenerator.generateValue(cacheName, i); entries.put(key, value); } final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); await(cache.putAll(entries, options)); final CacheEntryVersion cve = new CacheEntryVersionImpl(1); for (Map.Entry<K, V> entry : entries.entrySet()) { assertEntry(entry.getKey(), entry.getValue(), kvGenerator, await(cache.getEntry(entry.getKey())), options, cve); } await(cache.clear()); for (Map.Entry<K, V> entry : entries.entrySet()) { assertAwaitEquals(null, cache.get(entry.getKey())); } } @MethodSource("parameterized") @ParameterizedTest(name = "testPutAllGetAll[{0}]") public void testPutAllGetAll(KeyValueGenerator<K, V> kvGenerator) { Map<K, V> entries = new HashMap<>(); for (int i = 0; i < 10; i++) { final K key = kvGenerator.generateKey(cacheName, i); final V value = kvGenerator.generateValue(cacheName, i); entries.put(key, value); } final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); await(cache.putAll(entries, options)); Multi<CacheEntry<K, V>> multi = cache.getAndRemoveAll(Multi.createFrom().iterable(entries.keySet())); Map<K, CacheEntry<K, V>> retrieved = FlowUtils.blockingCollect(multi) .stream().collect(Collectors.toMap(CacheEntry::key, e -> e)); assertEquals(entries.size(), retrieved.size()); MapKVHelper<K, V> helper = new MapKVHelper<>(entries, kvGenerator); for (Map.Entry<K, CacheEntry<K, V>> entry : retrieved.entrySet()) { V expected = helper.get(entry.getKey()); assertNotNull(expected); // TODO: once handling metadata on remote cache verify that too assertEntry(entry.getKey(), expected, kvGenerator, entry.getValue()); } } @MethodSource("parameterized") @ParameterizedTest(name = "testPutAllGetAndRemoveAll[{0}]") public void testPutAllGetAndRemoveAll(KeyValueGenerator<K, V> kvGenerator) { Map<K, V> entries = new HashMap<>(); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); for (int i = 0; i < 10; i++) { final K key = kvGenerator.generateKey(cacheName, i); final V value = kvGenerator.generateValue(cacheName, i); entries.put(key, value); } CacheEntryMetadata metadata = new CacheEntryMetadataImpl(); List<CacheEntry<K, V>> allEntries = entries.entrySet().stream() .map(e -> new CacheEntryImpl<>(e.getKey(), e.getValue(), metadata)) .collect(Collectors.toList()); await(cache.putAll(Multi.createFrom().iterable(allEntries), options)); Multi<CacheEntry<K, V>> multi = cache.getAndRemoveAll(Multi.createFrom().iterable(entries.keySet())); Map<K, CacheEntry<K, V>> retrieved = FlowUtils.blockingCollect(multi) .stream().collect(Collectors.toMap(CacheEntry::key, e -> e)); assertEquals(entries.size(), retrieved.size()); final CacheEntryVersion cve = new CacheEntryVersionImpl(1); MapKVHelper<K, V> helper = new MapKVHelper<>(entries, kvGenerator); for (Map.Entry<K, CacheEntry<K, V>> entry : retrieved.entrySet()) { V expected = helper.get(entry.getKey()); assertNotNull(expected); assertEntry(entry.getKey(), expected, kvGenerator, entry.getValue(), options, cve); } for (Map.Entry<K, V> entry : entries.entrySet()) { assertAwaitEquals(null, cache.get(entry.getKey())); } } @MethodSource("parameterized") @ParameterizedTest(name = "testReplace[{0}]") public void testReplace(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V initialValue = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); // Returns false for an unexistent entry. final CacheEntryVersion cve0 = new CacheEntryVersionImpl(0); assertAwaitEquals(false, cache.replace(key, initialValue, cve0)); assertEntry(key, null, kvGenerator, await(cache.put(key, initialValue, options))); assertEntry(key, initialValue, kvGenerator, await(cache.getEntry(key))); final V replaceValue = kvGenerator.generateValue(cacheName, 1); final CacheEntryVersion cve2 = new CacheEntryVersionImpl(2); assertAwaitEquals(true, cache.replace(key, replaceValue, cve2)); // Returns false for the wrong version. final V anyValue = kvGenerator.generateValue(cacheName, 1); assertAwaitEquals(false, cache.replace(key, anyValue, cve0)); } public final Stream<Arguments> parameterized() { return Stream.of( Arguments.of(KeyValueGenerator.BYTE_ARRAY_GENERATOR), Arguments.of(KeyValueGenerator.STRING_GENERATOR), Arguments.of(KeyValueGenerator.GENERIC_ARRAY_GENERATOR) ); } }
12,923
44.992883
121
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/AwaitAssertions.java
package org.infinispan.hotrod; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import io.smallrye.mutiny.Uni; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.junit.jupiter.api.Assertions; /** * @since 14.0 **/ public class AwaitAssertions { public static <T> void assertAwaitEquals(T expected, CompletionStage<T> actualFuture) { T actual = await(actualFuture); Assertions.assertEquals(expected, actual); } public static <T> void assertAwaitEquals(T expected, Uni<T> uni) { assertAwaitEquals(expected, uni.convert().toCompletionStage()); } public static <T> T await(CompletionStage<T> actual) { CompletableFuture<T> future = actual.toCompletableFuture(); boolean completed = CompletableFutures.uncheckedAwait(future, 30, TimeUnit.SECONDS); if (!completed) { Assertions.fail("Timeout obtaining responses"); } return future.getNow(null); } public static <T> T await(Uni<T> actual) { return actual.await().atMost(Duration.ofSeconds(10)); } }
1,171
29.842105
90
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/HotRodFactoryTest.java
package org.infinispan.hotrod; import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.URI; import org.infinispan.api.Infinispan; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.hotrod.configuration.HotRodConfigurationBuilder; import org.junit.jupiter.api.Test; /** * @since 14.0 **/ public class HotRodFactoryTest { @Test public void testHotRodInstantiationByURI() { try (Infinispan infinispan = Infinispan.create(URI.create("hotrod://127.0.0.1:11222"))) { assertTrue(infinispan instanceof HotRod); } } @Test public void testHotRodInstantiationByURIasString() { try (Infinispan infinispan = Infinispan.create("hotrod://127.0.0.1:11222")) { assertTrue(infinispan instanceof HotRod); } } @Test public void testHotRodInstantiationByConfiguration() { HotRodConfiguration configuration = new HotRodConfigurationBuilder().build(); try (Infinispan infinispan = Infinispan.create(configuration)) { assertTrue(infinispan instanceof HotRod); } } }
1,101
27.25641
95
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/HotRodAsyncCacheTest.java
package org.infinispan.hotrod; import static org.infinispan.hotrod.AwaitAssertions.assertAwaitEquals; import static org.infinispan.hotrod.AwaitAssertions.await; import static org.infinispan.hotrod.CacheEntryAssertions.assertEntry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import java.util.concurrent.SubmissionPublisher; import java.util.stream.Collectors; import java.util.stream.Stream; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.cache.CacheEntryImpl; import org.infinispan.hotrod.impl.cache.CacheEntryVersionImpl; import org.infinispan.hotrod.test.AbstractAsyncCacheSingleServerTest; import org.infinispan.hotrod.test.KeyValueGenerator; import org.infinispan.hotrod.util.FlowUtils; import org.infinispan.hotrod.util.MapKVHelper; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * @since 14.0 **/ public class HotRodAsyncCacheTest<K, V> extends AbstractAsyncCacheSingleServerTest<K, V> { @MethodSource("parameterized") @ParameterizedTest(name = "getPut[{0}]") public void testPut(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V v1 = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion version1 = new CacheEntryVersionImpl(1); assertEntry(key, null, kvGenerator, await(cache.put(key, v1, options))); kvGenerator.assertValueEquals(v1, await(cache.get(key))); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); CacheWriteOptions optionsV1 = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(20)) .lifespanAndMaxIdle(Duration.ofSeconds(25), Duration.ofSeconds(30)) .build(); final CacheEntryVersion version2 = new CacheEntryVersionImpl(2); final V v2 = kvGenerator.generateValue(cacheName, 1); assertEntry(key, v1, kvGenerator, await(cache.put(key, v2, optionsV1)), options, version1); assertEntry(key, v2, kvGenerator, await(cache.getEntry(key)), optionsV1, version2); } @MethodSource("parameterized") @ParameterizedTest(name = "testPutIfAbsent[{0}]") public void testPutIfAbsent(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V v1 = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion version1 = new CacheEntryVersionImpl(1); assertAwaitEquals(null, cache.putIfAbsent(key, v1, options)); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); final V other = kvGenerator.generateValue(cacheName, 1); CacheEntry<K, V> previousEntry = await(cache.putIfAbsent(key, other)); kvGenerator.assertKeyEquals(key, previousEntry.key()); kvGenerator.assertValueEquals(v1, previousEntry.value()); kvGenerator.assertValueEquals(v1, await(cache.get(key))); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); } @MethodSource("parameterized") @ParameterizedTest(name = "testSetIfAbsent[{0}]") public void testSetIfAbsent(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V value = kvGenerator.generateValue(cacheName, 0); CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); assertAwaitEquals(true, cache.setIfAbsent(key, value, options)); assertEntry(key, value, kvGenerator, await(cache.getEntry(key)), options, new CacheEntryVersionImpl(1)); final V other = kvGenerator.generateValue(cacheName, 1); assertAwaitEquals(false, cache.setIfAbsent(key, other)); final V actual = await(cache.get(key)); kvGenerator.assertValueEquals(value, actual); assertEntry(key, value, kvGenerator, await(cache.getEntry(key)), options, new CacheEntryVersionImpl(1)); } @MethodSource("parameterized") @ParameterizedTest(name = "testSet[{0}]") public void testSet(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V v1 = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion version1 = new CacheEntryVersionImpl(1); await(cache.set(key, v1, options)); assertEntry(key, v1, kvGenerator, await(cache.getEntry(key)), options, version1); final CacheWriteOptions optionsV2 = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(20)) .lifespanAndMaxIdle(Duration.ofSeconds(25), Duration.ofSeconds(30)) .build(); final CacheEntryVersion version2 = new CacheEntryVersionImpl(2); final V v2 = kvGenerator.generateValue(cacheName, 1); await(cache.set(key, v2, optionsV2)); V actual = await(cache.get(key)); kvGenerator.assertValueEquals(v2, actual); assertEntry(key, v2, kvGenerator, await(cache.getEntry(key)), optionsV2, version2); } @MethodSource("parameterized") @ParameterizedTest(name = "testGetAndRemove[{0}]") public void testGetAndRemove(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V value = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); final CacheEntryVersion cev = new CacheEntryVersionImpl(1); assertEntry(key, null, kvGenerator, await(cache.put(key, value, options))); assertEntry(key, value, kvGenerator, await(cache.getEntry(key)), options, cev); assertEntry(key, value, kvGenerator, await(cache.getAndRemove(key)), options, cev); assertAwaitEquals(null, cache.get(key)); } @MethodSource("parameterized") @ParameterizedTest(name = "testPutAllAndClear[{0}]") public void testPutAllAndClear(KeyValueGenerator<K, V> kvGenerator) { Map<K, V> entries = new HashMap<>(); for (int i = 0; i < 10; i++) { final K key = kvGenerator.generateKey(cacheName, i); final V value = kvGenerator.generateValue(cacheName, i); entries.put(key, value); } final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); await(cache.putAll(entries, options)); final CacheEntryVersion cve = new CacheEntryVersionImpl(1); for (Map.Entry<K, V> entry : entries.entrySet()) { assertEntry(entry.getKey(), entry.getValue(), kvGenerator, await(cache.getEntry(entry.getKey())), options, cve); } await(cache.clear()); for (Map.Entry<K, V> entry : entries.entrySet()) { assertAwaitEquals(null, cache.get(entry.getKey())); } } @MethodSource("parameterized") @ParameterizedTest(name = "testPutAllGetAll[{0}]") public void testPutAllGetAll(KeyValueGenerator<K, V> kvGenerator) { Map<K, V> entries = new HashMap<>(); for (int i = 0; i < 10; i++) { final K key = kvGenerator.generateKey(cacheName, i); final V value = kvGenerator.generateValue(cacheName, i); entries.put(key, value); } final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); await(cache.putAll(entries, options)); Flow.Publisher<CacheEntry<K, V>> publisher = cache.getAll(entries.keySet()); Map<K, CacheEntry<K, V>> retrieved = FlowUtils.blockingCollect(publisher) .stream().collect(Collectors.toMap(CacheEntry::key, e -> e)); assertEquals(entries.size(), retrieved.size()); MapKVHelper<K, V> helper = new MapKVHelper<>(entries, kvGenerator); for (Map.Entry<K, CacheEntry<K, V>> entry : retrieved.entrySet()) { V expected = helper.get(entry.getKey()); assertNotNull(expected); // TODO: once handling metadata on remote cache verify that too assertEntry(entry.getKey(), expected, kvGenerator, entry.getValue()); } } @MethodSource("parameterized") @ParameterizedTest(name = "testPutAllGetAndRemoveAll[{0}]") public void testPutAllGetAndRemoveAll(KeyValueGenerator<K, V> kvGenerator) { Map<K, V> entries = new HashMap<>(); SubmissionPublisher<CacheEntry<K, V>> entriesPublisher = new SubmissionPublisher<>(); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); CompletionStage<Void> putAll = cache.putAll(entriesPublisher, options); for (int i = 0; i < 10; i++) { final K key = kvGenerator.generateKey(cacheName, i); final V value = kvGenerator.generateValue(cacheName, i); entries.put(key, value); entriesPublisher.submit(new CacheEntryImpl<>(key, value, null)); } entriesPublisher.close(); await(putAll); Flow.Publisher<CacheEntry<K, V>> publisher = cache.getAndRemoveAll(entries.keySet()); Map<K, CacheEntry<K, V>> retrieved = FlowUtils.blockingCollect(publisher) .stream().collect(Collectors.toMap(CacheEntry::key, e -> e)); assertEquals(entries.size(), retrieved.size()); final CacheEntryVersion cve = new CacheEntryVersionImpl(1); MapKVHelper<K, V> helper = new MapKVHelper<>(entries, kvGenerator); for (Map.Entry<K, CacheEntry<K, V>> entry : retrieved.entrySet()) { V expected = helper.get(entry.getKey()); assertNotNull(expected); assertEntry(entry.getKey(), expected, kvGenerator, entry.getValue(), options, cve); } for (Map.Entry<K, V> entry : entries.entrySet()) { assertAwaitEquals(null, cache.get(entry.getKey())); } // Removing keys that dont exists returns nothing. retrieved = FlowUtils.blockingCollect(cache.getAndRemoveAll(entries.keySet())) .stream().collect(Collectors.toMap(CacheEntry::key, e -> e)); assertTrue(retrieved.isEmpty()); } @MethodSource("parameterized") @ParameterizedTest(name = "testReplace[{0}]") public void testReplace(KeyValueGenerator<K, V> kvGenerator) { final K key = kvGenerator.generateKey(cacheName, 0); final V initialValue = kvGenerator.generateValue(cacheName, 0); final CacheWriteOptions options = CacheWriteOptions.writeOptions() .timeout(Duration.ofSeconds(15)) .lifespanAndMaxIdle(Duration.ofSeconds(20), Duration.ofSeconds(25)) .build(); // Returns false for an unexistent entry. final CacheEntryVersion cve0 = new CacheEntryVersionImpl(0); assertAwaitEquals(false, cache.replace(key, initialValue, cve0)); assertEntry(key, null, kvGenerator, await(cache.put(key, initialValue, options))); assertEntry(key, initialValue, kvGenerator, await(cache.getEntry(key))); final V replaceValue = kvGenerator.generateValue(cacheName, 1); final CacheEntryVersion cve2 = new CacheEntryVersionImpl(2); assertAwaitEquals(true, cache.replace(key, replaceValue, cve2)); // Returns false for the wrong version. final V anyValue = kvGenerator.generateValue(cacheName, 1); assertAwaitEquals(false, cache.replace(key, anyValue, cve0)); } public Stream<Arguments> parameterized() { return Stream.of( Arguments.of(KeyValueGenerator.BYTE_ARRAY_GENERATOR), Arguments.of(KeyValueGenerator.STRING_GENERATOR), Arguments.of(KeyValueGenerator.GENERIC_ARRAY_GENERATOR) ); } }
13,114
44.696864
121
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/CacheEntryAssertions.java
package org.infinispan.hotrod; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryMetadata; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.test.KeyValueGenerator; public final class CacheEntryAssertions { private CacheEntryAssertions() { } public static <K, V> void assertEntry(K key, V value, KeyValueGenerator<K, V> kv, CacheEntry<K, V> entry) { kv.assertKeyEquals(key, entry.key()); kv.assertValueEquals(value, entry.value()); } public static <K, V> void assertEntry(K key, V value, KeyValueGenerator<K, V> kv, CacheEntry<K, V> entry, CacheWriteOptions writeOptions) { assertEntry(key, value, kv, entry); CacheEntryMetadata metadata = entry.metadata(); assertEquals(writeOptions.expiration(), metadata.expiration()); } public static <K, V> void assertEntry(K key, V value, KeyValueGenerator<K, V> kv, CacheEntry<K, V> entry, CacheWriteOptions writeOptions, CacheEntryVersion version) { assertEntry(key, value, kv, entry, writeOptions); assertEquals(version, entry.metadata().version()); } }
1,335
39.484848
111
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/HotRodServerExtension.java
package org.infinispan.hotrod; import java.lang.reflect.Method; import java.net.URI; import org.infinispan.api.Infinispan; import org.infinispan.api.configuration.Configuration; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.hotrod.configuration.HotRodConfigurationBuilder; import org.infinispan.hotrod.impl.HotRodURI; import org.infinispan.hotrod.impl.transport.netty.HotRodTestTransport; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; /** * @since 14.0 **/ public class HotRodServerExtension implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback { private HotRodServer hotRodServer; private String cacheName; @Override public void afterAll(ExtensionContext extensionContext) throws Exception { stop(); } @Override public void beforeAll(ExtensionContext extensionContext) throws Exception { start(); } @Override public void beforeEach(ExtensionContext extensionContext) throws Exception { Method method = extensionContext.getTestMethod().orElseThrow(); cacheName = method.getName(); ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); builder .clustering() .cacheMode(CacheMode.DIST_SYNC) .transaction().cacheStopTimeout(0L); hotRodServer.getCacheManager().createCache(cacheName, builder.build()); } public void start() { if (hotRodServer == null) { TestResourceTracker.setThreadTestName("InfinispanServer"); GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); gcb.transport().defaultTransport(); gcb.defaultCacheName("default"); EmbeddedCacheManager ecm = TestCacheManagerFactory.createClusteredCacheManager( gcb, new ConfigurationBuilder(), new TransportFlags()); ecm.administration().createTemplate("test", new ConfigurationBuilder().template(true).build()); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); hotRodServer = HotRodTestingUtil.startHotRodServer(ecm, serverBuilder); } } public void stop() { if (hotRodServer != null) { EmbeddedCacheManager cacheManager = hotRodServer.getCacheManager(); hotRodServer.stop(); cacheManager.stop(); hotRodServer = null; } } public String cacheName() { return cacheName; } public Infinispan getClient() { HotRodConfigurationBuilder builder = new HotRodConfigurationBuilder(); builder.addServer().host(hotRodServer.getHost()).port(hotRodServer.getPort()); return Infinispan.create(builder.build(), new Infinispan.Factory() { @Override public Infinispan create(URI uri) { try { return create(HotRodURI.create(uri).toConfigurationBuilder().build()); } catch (Throwable t) { // Not a Hot Rod URI return null; } } @Override public Infinispan create(Configuration configuration) { assert configuration instanceof HotRodConfiguration; HotRodConfiguration hrc = (HotRodConfiguration) configuration; return new HotRod(hrc, HotRodTestTransport.createTestTransport(hrc)); } }); } public static Builder builder() { return new Builder(); } public static class Builder { public HotRodServerExtension build() { return new HotRodServerExtension(); } } }
4,723
36.792
104
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/util/MapKVHelper.java
package org.infinispan.hotrod.util; import java.util.Collections; import java.util.Map; import org.infinispan.hotrod.test.KeyValueGenerator; /** * Small helper that wraps a view of the entries in the cache with the {@link KeyValueGenerator}. * This is necessary to correctly find the keys within the map for different types of keys. * <p/> * Most operations need to iterate over the entry set and check using the {@link KeyValueGenerator} * to check for equality. * * @param <K>: The type of keys. * @param <V>: The type of values. */ public class MapKVHelper<K, V> { private final Map<K, V> entries; private final KeyValueGenerator<K, V> kvGenerator; public MapKVHelper(Map<K, V> entries, KeyValueGenerator<K, V> kvGenerator) { this.entries = Collections.unmodifiableMap(entries); this.kvGenerator = kvGenerator; } public V get(K key) { for (Map.Entry<K, V> entry: entries.entrySet()) { if (kvGenerator.equalKeys(entry.getKey(), key)) { return entry.getValue(); } } return null; } public boolean contains(K key) { return get(key) != null; } }
1,149
27.75
99
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/util/FlowUtils.java
package org.infinispan.hotrod.util; import java.time.Duration; import java.util.List; import java.util.concurrent.Flow; import java.util.concurrent.TimeUnit; import java.util.stream.Collector; import java.util.stream.Collectors; import io.reactivex.rxjava3.core.Flowable; import io.smallrye.mutiny.Multi; import org.reactivestreams.FlowAdapters; public final class FlowUtils { private FlowUtils() { } public static <T> Flowable<T> toFlowable(Flow.Publisher<T> publisher) { return Flowable.fromPublisher(FlowAdapters.toPublisher(publisher)); } public static <T, R, A> R blockingCollect(Flowable<T> flowable, Collector<? super T, A, R> collector) { return flowable.collect(collector) .timeout(10, TimeUnit.SECONDS) .blockingGet(); } /** * Collect all values in the {@link Flow.Publisher} using the given {@link Collector}. * This is a blocking method. * * @param publisher: Source of the values. * @param collector: Collect the values. * @return The collected values. */ public static <T, R, A> R blockingCollect(Flow.Publisher<T> publisher, Collector<? super T, A, R> collector) { return blockingCollect(toFlowable(publisher), collector); } /** * Collect all values in the {@link Flow.Publisher} into a list. * This is a blocking method. * * @param publisher: Source of the values. * @return A list with the elements from {@link Flow.Publisher}. * @param <T>: Type of the elements. */ public static <T> List<T> blockingCollect(Flow.Publisher<T> publisher) { return blockingCollect(publisher, Collectors.toList()); } public static <T> List<T> blockingCollect(Multi<T> multi) { return multi.collect().asList().await().atMost(Duration.ofSeconds(30)); } }
1,809
31.321429
113
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/test/AbstractAsyncCacheSingleServerTest.java
package org.infinispan.hotrod.test; import static org.infinispan.hotrod.AwaitAssertions.await; import org.infinispan.api.Infinispan; import org.infinispan.api.async.AsyncCache; import org.infinispan.api.async.AsyncContainer; /** * @since 14.0 */ public abstract class AbstractAsyncCacheSingleServerTest<K, V> extends AbstractSingleHotRodServerTest<AsyncCache<K, V>> { public void teardown() { assert container instanceof AsyncContainer : "Could not destroy AsyncCache"; await(((AsyncContainer) container).caches().remove(cacheName)); } @Override Infinispan container() { if (container != null) return container; return server.getClient().async(); } @Override AsyncCache<K, V> cache() { if (cache != null) { return cache; } assert container instanceof AsyncContainer : "Could not create AsyncCache"; return await(((AsyncContainer) container).caches().create(cacheName, "template")); } }
985
26.388889
121
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/test/AbstractSingleHotRodServerTest.java
package org.infinispan.hotrod.test; import static org.infinispan.hotrod.HotRodServerExtension.builder; import org.infinispan.api.Infinispan; import org.infinispan.hotrod.HotRodServerExtension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.RegisterExtension; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class AbstractSingleHotRodServerTest<C> { protected C cache; protected Infinispan container; protected String cacheName; @RegisterExtension static HotRodServerExtension server = builder() .build(); @BeforeEach public void setup() { container = container(); cacheName = server.cacheName(); cache = cache(); } @AfterEach public void internalTeardown() { assert container != null : "Container is null"; teardown(); container.close(); container = null; cache = null; } protected abstract void teardown(); abstract Infinispan container(); abstract C cache(); }
1,104
23.555556
66
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/test/AbstractMutinyCacheSingleServerTest.java
package org.infinispan.hotrod.test; import static org.infinispan.hotrod.AwaitAssertions.await; import org.infinispan.api.Infinispan; import org.infinispan.api.mutiny.MutinyCache; import org.infinispan.api.mutiny.MutinyContainer; /** * @since 14.0 * @param <K>: Cache key type. * @param <V>: Cache value type. */ public abstract class AbstractMutinyCacheSingleServerTest<K, V> extends AbstractSingleHotRodServerTest<MutinyCache<K, V>> { @Override protected void teardown() { assert container instanceof MutinyContainer : "Could not destroy MutinyCache"; await(((MutinyContainer) container).caches().remove(cacheName).convert().toCompletionStage()); } @Override Infinispan container() { if (container != null) return container; return server.getClient().mutiny(); } @Override MutinyCache<K, V> cache() { if (cache != null) { return cache; } assert container instanceof MutinyContainer : "Could not create MutinyCache"; return await(((MutinyContainer) container).caches().create(cacheName, "template")); } }
1,109
27.461538
123
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/test/KeyValueGenerator.java
package org.infinispan.hotrod.test; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import org.opentest4j.AssertionFailedError; /** * A key and value generator for Hot Rod testing. * * @author Pedro Ruivo * @since 9.3 */ public interface KeyValueGenerator<K, V> { KeyValueGenerator<String, String> STRING_GENERATOR = new KeyValueGenerator<>() { @Override public String generateKey(String method, int index) { return k(method, index); } @Override public String generateValue(String method, int index) { return v(method, index); } @Override public void assertValueEquals(String expected, String actual) { assertEquals(expected, actual); } @Override public void assertKeyEquals(String expected, String actual) { assertEquals(expected, actual); } @Override public String toString() { return "STRING"; } }; KeyValueGenerator<byte[], byte[]> BYTE_ARRAY_GENERATOR = new KeyValueGenerator<>() { @Override public byte[] generateKey(String method, int index) { return k(method, index).getBytes(); } @Override public byte[] generateValue(String method, int index) { return v(method, index).getBytes(); } @Override public void assertValueEquals(byte[] expected, byte[] actual) { assertArrayEquals(expected, actual); } @Override public void assertKeyEquals(byte[] expected, byte[] actual) { assertArrayEquals(expected, actual); } @Override public String toString() { return "BYTE_ARRAY"; } }; KeyValueGenerator<Object[], Object[]> GENERIC_ARRAY_GENERATOR = new KeyValueGenerator<>() { @Override public Object[] generateKey(String method, int index) { return new Object[] { method, "key", index }; } @Override public Object[] generateValue(String method, int index) { return new Object[] { method, "value", index }; } @Override public void assertValueEquals(Object[] expected, Object[] actual) { assertArrayEquals(expected, actual); } @Override public void assertKeyEquals(Object[] expected, Object[] actual) { assertArrayEquals(expected, actual); } @Override public String toString() { return "GENERIC_ARRAY"; } }; K generateKey(String method, int index); V generateValue(String method, int index); void assertValueEquals(V expected, V actual); void assertKeyEquals(K expected, K actual); default boolean equalKeys(K expected, K actual) { try { assertKeyEquals(expected, actual); return true; } catch (AssertionFailedError ignore) { return false; } } default void assertValueNotEquals(V expected, V actual) { try { assertValueEquals(expected, actual); } catch (AssertionFailedError ignore) { return; } fail("Value should be different"); } }
3,322
25.165354
94
java
null
infinispan-main/client/hotrod/src/test/java/org/infinispan/hotrod/impl/transport/netty/HotRodTestTransport.java
package org.infinispan.hotrod.impl.transport.netty; import java.net.SocketAddress; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.hotrod.impl.HotRodTransport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.handler.codec.FixedLengthFrameDecoder; public class HotRodTestTransport { public static HotRodTransport createTestTransport(HotRodConfiguration configuration) { return new HotRodTransport(configuration) { @Override protected ChannelFactory createChannelFactory() { return new ChannelFactory() { @Override protected ChannelInitializer createChannelInitializer(SocketAddress address, Bootstrap bootstrap) { return new ChannelInitializer(bootstrap, address, getCacheOperationsFactory(), getConfiguration(), this) { @Override protected void initChannel(Channel channel) throws Exception { super.initChannel(channel); channel.pipeline().addFirst("1frame", new FixedLengthFrameDecoder(1)); } }; } }; } }; } }
1,322
36.8
124
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncCache.java
package org.infinispan.hotrod; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import org.infinispan.api.async.AsyncCache; import org.infinispan.api.async.AsyncCacheEntryProcessor; import org.infinispan.api.async.AsyncContainer; import org.infinispan.api.async.AsyncQuery; import org.infinispan.api.async.AsyncStreamingCache; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.common.events.cache.CacheEntryEvent; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.api.common.events.cache.CacheListenerOptions; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.common.process.CacheProcessorOptions; import org.infinispan.api.configuration.CacheConfiguration; import org.infinispan.hotrod.impl.cache.RemoteCache; /** * @since 14.0 **/ public class HotRodAsyncCache<K, V> implements AsyncCache<K, V> { private final HotRod hotrod; private final RemoteCache<K, V> remoteCache; HotRodAsyncCache(HotRod hotrod, RemoteCache<K, V> remoteCache) { this.hotrod = hotrod; this.remoteCache = remoteCache; } @Override public String name() { return remoteCache.getName(); } @Override public CompletionStage<CacheConfiguration> configuration() { return remoteCache.configuration(); } @Override public AsyncContainer container() { return hotrod.async(); } @Override public CompletionStage<V> get(K key, CacheOptions options) { return remoteCache.get(key, options); } @Override public CompletionStage<CacheEntry<K, V>> getEntry(K key, CacheOptions options) { return remoteCache.getEntry(key, options); } @Override public CompletionStage<CacheEntry<K, V>> putIfAbsent(K key, V value, CacheWriteOptions options) { return remoteCache.putIfAbsent(key, value, options); } @Override public CompletionStage<Boolean> setIfAbsent(K key, V value, CacheWriteOptions options) { return remoteCache.setIfAbsent(key, value, options); } @Override public CompletionStage<CacheEntry<K, V>> put(K key, V value, CacheWriteOptions options) { return remoteCache.put(key, value, options); } @Override public CompletionStage<Void> set(K key, V value, CacheWriteOptions options) { return remoteCache.set(key, value, options); } @Override public CompletionStage<Boolean> replace(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return remoteCache.replace(key, value, version, options); } @Override public CompletionStage<CacheEntry<K, V>> getOrReplaceEntry(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return remoteCache.getOrReplaceEntry(key, value, version, options); } @Override public CompletionStage<Boolean> remove(K key, CacheOptions options) { return remoteCache.remove(key, options); } @Override public CompletionStage<Boolean> remove(K key, CacheEntryVersion version, CacheOptions options) { return remoteCache.remove(key, version, options); } @Override public CompletionStage<CacheEntry<K, V>> getAndRemove(K key, CacheOptions options) { return remoteCache.getAndRemove(key, options); } @Override public Flow.Publisher<K> keys(CacheOptions options) { return remoteCache.keys(options); } @Override public Flow.Publisher<CacheEntry<K, V>> entries(CacheOptions options) { return remoteCache.entries(options); } @Override public CompletionStage<Void> putAll(Map<K, V> entries, CacheWriteOptions options) { return remoteCache.putAll(entries, options); } @Override public CompletionStage<Void> putAll(Flow.Publisher<CacheEntry<K, V>> entries, CacheWriteOptions options) { return remoteCache.putAll(entries, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAll(Set<K> keys, CacheOptions options) { return remoteCache.getAll(keys, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAll(CacheOptions options, K... keys) { return remoteCache.getAll(options, keys); } @Override public Flow.Publisher<K> removeAll(Set<K> keys, CacheWriteOptions options) { return remoteCache.removeAll(keys, options); } @Override public Flow.Publisher<K> removeAll(Flow.Publisher<K> keys, CacheWriteOptions options) { return remoteCache.removeAll(keys, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Set<K> keys, CacheWriteOptions options) { return remoteCache.getAndRemoveAll(keys, options); } @Override public Flow.Publisher<CacheEntry<K, V>> getAndRemoveAll(Flow.Publisher<K> keys, CacheWriteOptions options) { return remoteCache.getAndRemoveAll(keys, options); } @Override public CompletionStage<Long> estimateSize(CacheOptions options) { return remoteCache.estimateSize(options); } @Override public CompletionStage<Void> clear(CacheOptions options) { return remoteCache.clear(options); } @Override public <R> AsyncQuery<K, V, R> query(String query, CacheOptions options) { return new HotRodAsyncQuery(query, options); } @Override public Flow.Publisher<CacheEntryEvent<K, V>> listen(CacheListenerOptions options, CacheEntryEventType... types) { return remoteCache.listen(options, types); } @Override public <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> process(Set<K> keys, AsyncCacheEntryProcessor<K, V, T> processor, CacheOptions options) { return remoteCache.process(keys, processor, options); } @Override public <T> Flow.Publisher<CacheEntryProcessorResult<K, T>> processAll(AsyncCacheEntryProcessor<K, V, T> processor, CacheProcessorOptions options) { return remoteCache.processAll(processor, options); } @Override public AsyncStreamingCache<K> streaming() { return new HotRodAsyncStreamingCache(hotrod, remoteCache); } }
6,241
31.510417
151
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodSyncStreamingCache.java
package org.infinispan.hotrod; import java.io.InputStream; import java.io.OutputStream; import org.infinispan.api.common.CacheEntryMetadata; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.sync.SyncStreamingCache; import org.infinispan.hotrod.impl.cache.RemoteCache; /** * @since 14.0 **/ public class HotRodSyncStreamingCache<K> implements SyncStreamingCache<K> { private final HotRod hotrod; private final RemoteCache<K, ?> remoteCache; HotRodSyncStreamingCache(HotRod hotrod, RemoteCache<K, ?> remoteCache) { this.hotrod = hotrod; this.remoteCache = remoteCache; } @Override public <T extends InputStream & CacheEntryMetadata> T get(K key) { throw new UnsupportedOperationException(); } @Override public <T extends InputStream & CacheEntryMetadata> T get(K key, CacheOptions options) { throw new UnsupportedOperationException(); } @Override public OutputStream put(K key, CacheOptions options) { throw new UnsupportedOperationException(); } @Override public OutputStream putIfAbsent(K key, CacheWriteOptions options) { throw new UnsupportedOperationException(); } }
1,240
27.204545
91
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyCache.java
package org.infinispan.hotrod; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.common.events.cache.CacheEntryEvent; import org.infinispan.api.common.events.cache.CacheEntryEventType; import org.infinispan.api.common.events.cache.CacheListenerOptions; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.configuration.CacheConfiguration; import org.infinispan.api.mutiny.MutinyCache; import org.infinispan.api.mutiny.MutinyCacheEntryProcessor; import org.infinispan.api.mutiny.MutinyQuery; import org.infinispan.api.mutiny.MutinyStreamingCache; import org.infinispan.hotrod.impl.cache.RemoteCache; import java.util.Map; import java.util.Set; /** * @since 14.0 **/ public class HotRodMutinyCache<K, V> implements MutinyCache<K, V> { private final HotRod hotrod; private final RemoteCache<K, V> remoteCache; HotRodMutinyCache(HotRod hotrod, RemoteCache<K, V> remoteCache) { this.hotrod = hotrod; this.remoteCache = remoteCache; } @Override public String name() { return remoteCache.getName(); } @Override public Uni<CacheConfiguration> configuration() { return Uni.createFrom().completionStage(remoteCache.configuration()); } @Override public HotRodMutinyContainer container() { return hotrod.mutiny(); } @Override public Uni<V> get(K key, CacheOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.get(key, options)); } @Override public Uni<CacheEntry<K, V>> getEntry(K key, CacheOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.getEntry(key, options)); } @Override public Uni<CacheEntry<K, V>> putIfAbsent(K key, V value, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.putIfAbsent(key, value, options)); } @Override public Uni<Boolean> setIfAbsent(K key, V value, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.setIfAbsent(key, value, options)); } @Override public Uni<CacheEntry<K, V>> put(K key, V value, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.put(key, value, options)); } @Override public Uni<Void> set(K key, V value, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.set(key, value, options)); } @Override public Uni<Boolean> remove(K key, CacheOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.remove(key, options)); } @Override public Uni<CacheEntry<K, V>> getAndRemove(K key, CacheOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.getAndRemove(key, options)); } @Override public Multi<K> keys(CacheOptions options) { return Multi.createFrom().publisher(remoteCache.keys(options)); } @Override public Multi<CacheEntry<K, V>> entries(CacheOptions options) { return Multi.createFrom().publisher(remoteCache.entries(options)); } @Override public Multi<CacheEntry<K, V>> getAll(Set<K> keys, CacheOptions options) { return Multi.createFrom().publisher(remoteCache.getAll(keys, options)); } @Override public Multi<CacheEntry<K, V>> getAll(CacheOptions options, K... keys) { return Multi.createFrom().publisher(remoteCache.getAll(options, keys)); } @Override public Uni<Void> putAll(Multi<CacheEntry<K, V>> entries, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.putAll(entries.convert().toPublisher(), options)); } @Override public Uni<Void> putAll(Map<K, V> map, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.putAll(map, options)); } @Override public Uni<Boolean> replace(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.replace(key, value, version, options)); } @Override public Uni<CacheEntry<K, V>> getOrReplaceEntry(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.getOrReplaceEntry(key, value, version, options)); } @Override public Multi<K> removeAll(Set<K> keys, CacheWriteOptions options) { return Multi.createFrom().publisher(remoteCache.removeAll(keys, options)); } @Override public Multi<K> removeAll(Multi<K> keys, CacheWriteOptions options) { return Multi.createFrom().publisher(remoteCache.removeAll(keys.convert().toPublisher(), options)); } @Override public Multi<CacheEntry<K, V>> getAndRemoveAll(Multi<K> keys, CacheWriteOptions options) { return Multi.createFrom().publisher(remoteCache.getAndRemoveAll(keys.convert().toPublisher(), options)); } @Override public Uni<Long> estimateSize(CacheOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.estimateSize(options)); } @Override public Uni<Void> clear(CacheOptions options) { return Uni.createFrom().completionStage(() -> remoteCache.clear(options)); } @Override public <R> MutinyQuery<K, V, R> query(String query, CacheOptions options) { return new HotRodMutinyQuery(query, options); } @Override public Multi<CacheEntryEvent<K, V>> listen(CacheListenerOptions options, CacheEntryEventType... types) { return Multi.createFrom().publisher(remoteCache.listen(options, types)); } @Override public <T> Multi<CacheEntryProcessorResult<K, T>> process(Set<K> keys, MutinyCacheEntryProcessor<K, V, T> processor, CacheOptions options) { return Multi.createFrom().publisher(remoteCache.process(keys, new MutinyToAsyncCacheEntryProcessor<>(processor), options)); } @Override public MutinyStreamingCache<K> streaming() { return new HotRodMutinyStreamingCache<>(hotrod, remoteCache); } }
6,241
34.668571
143
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/package-info.java
/** * Hot Rod client API. * * @api.public */ package org.infinispan.hotrod;
80
10.571429
30
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodSyncLock.java
package org.infinispan.hotrod; import java.util.concurrent.TimeUnit; import org.infinispan.api.sync.SyncLock; /** * @since 14.0 **/ public class HotRodSyncLock implements SyncLock { private final HotRod hotrod; private final String name; HotRodSyncLock(HotRod hotrod, String name) { this.hotrod = hotrod; this.name = name; } @Override public String name() { return name; } @Override public HotRodSyncContainer container() { return hotrod.sync(); } @Override public void lock() { } @Override public boolean tryLock() { return false; } @Override public boolean tryLock(long time, TimeUnit unit) { return false; } @Override public void unlock() { } @Override public boolean isLocked() { return false; } @Override public boolean isLockedByMe() { return false; } }
908
14.40678
53
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncMultimaps.java
package org.infinispan.hotrod; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import org.infinispan.api.async.AsyncMultimap; import org.infinispan.api.async.AsyncMultimaps; import org.infinispan.api.configuration.MultimapConfiguration; /** * @since 14.0 **/ public class HotRodAsyncMultimaps implements AsyncMultimaps { private final HotRod hotrod; HotRodAsyncMultimaps(HotRod hotrod) { this.hotrod = hotrod; } @Override public <K, V> CompletionStage<AsyncMultimap<K, V>> create(String name, MultimapConfiguration cacheConfiguration) { return CompletableFuture.completedFuture(new HotRodAsyncMultimap<>(hotrod, name)); // PLACEHOLDER } @Override public <K, V> CompletionStage<AsyncMultimap<K, V>> create(String name, String template) { return CompletableFuture.completedFuture(new HotRodAsyncMultimap<>(hotrod, name)); // PLACEHOLDER } @Override public <K, V> CompletionStage<AsyncMultimap<K, V>> get(String name) { return CompletableFuture.completedFuture(new HotRodAsyncMultimap<>(hotrod, name)); // PLACEHOLDER } @Override public CompletionStage<Void> remove(String name) { return null; } @Override public Flow.Publisher<String> names() { return null; } @Override public CompletionStage<Void> createTemplate(String name, MultimapConfiguration cacheConfiguration) { return null; } @Override public CompletionStage<Void> removeTemplate(String name) { return null; } @Override public Flow.Publisher<String> templateNames() { return null; } }
1,670
26.393443
117
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncStreamingCache.java
package org.infinispan.hotrod; import org.infinispan.api.async.AsyncStreamingCache; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.hotrod.impl.cache.RemoteCache; /** * @since 14.0 **/ public class HotRodAsyncStreamingCache<K> implements AsyncStreamingCache<K> { private final HotRod hotrod; private final RemoteCache<K, ?> remoteCache; HotRodAsyncStreamingCache(HotRod hotrod, RemoteCache<K, ?> remoteCache) { this.hotrod = hotrod; this.remoteCache = remoteCache; } @Override public CacheEntrySubscriber get(K key, CacheOptions metadata) { throw new UnsupportedOperationException(); } @Override public CacheEntryPublisher put(K key, CacheWriteOptions metadata) { throw new UnsupportedOperationException(); } @Override public CacheEntryPublisher putIfAbsent(K key, CacheWriteOptions metadata) { throw new UnsupportedOperationException(); } }
992
27.371429
78
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodSyncStrongCounters.java
package org.infinispan.hotrod; import org.infinispan.api.configuration.CounterConfiguration; import org.infinispan.api.sync.SyncStrongCounters; /** * @since 14.0 **/ public class HotRodSyncStrongCounters implements SyncStrongCounters { private final HotRod hotrod; public HotRodSyncStrongCounters(HotRod hotrod) { this.hotrod = hotrod; } @Override public HotRodSyncStrongCounter get(String name) { return new HotRodSyncStrongCounter(hotrod, name); // PLACEHOLDER } @Override public HotRodSyncStrongCounter create(String name, CounterConfiguration counterConfiguration) { return new HotRodSyncStrongCounter(hotrod, name); // PLACEHOLDER } @Override public void remove(String name) { } @Override public Iterable<String> names() { return null; } }
824
21.916667
98
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyLocks.java
package org.infinispan.hotrod; import org.infinispan.api.configuration.LockConfiguration; import org.infinispan.api.mutiny.MutinyLock; import org.infinispan.api.mutiny.MutinyLocks; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * @since 14.0 **/ public class HotRodMutinyLocks implements MutinyLocks { private final HotRod hotrod; HotRodMutinyLocks(HotRod hotrod) { this.hotrod = hotrod; } @Override public Uni<MutinyLock> lock(String name) { return Uni.createFrom().item(new HotRodMutinyLock(hotrod, name)); } @Override public Uni<MutinyLock> create(String name, LockConfiguration configuration) { return Uni.createFrom().item(new HotRodMutinyLock(hotrod, name)); } @Override public Uni<Void> remove(String name) { return null; } @Override public Multi<String> names() { return null; } }
895
21.4
80
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncMultimap.java
package org.infinispan.hotrod; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import org.infinispan.api.async.AsyncMultimap; import org.infinispan.api.configuration.MultimapConfiguration; /** * @since 14.0 **/ public class HotRodAsyncMultimap<K, V> implements AsyncMultimap<K, V> { private final HotRod hotrod; private final String name; HotRodAsyncMultimap(HotRod hotrod, String name) { this.hotrod = hotrod; this.name = name; } @Override public String name() { return name; } @Override public CompletionStage<MultimapConfiguration> configuration() { return null; } @Override public HotRodAsyncContainer container() { return hotrod.async(); } @Override public CompletionStage<Void> add(K key, V value) { return null; } @Override public Flow.Publisher<V> get(K key) { return null; } @Override public CompletionStage<Boolean> remove(K key) { return null; } @Override public CompletionStage<Boolean> remove(K key, V value) { return null; } @Override public CompletionStage<Boolean> containsKey(K key) { return null; } @Override public CompletionStage<Boolean> containsEntry(K key, V value) { return null; } @Override public CompletionStage<Long> estimateSize() { return null; } }
1,400
18.732394
71
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncStrongCounter.java
package org.infinispan.hotrod; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; import org.infinispan.api.async.AsyncStrongCounter; import org.infinispan.api.common.events.counter.CounterEvent; import org.infinispan.api.configuration.CounterConfiguration; /** * @since 14.0 **/ public class HotRodAsyncStrongCounter implements AsyncStrongCounter { private final HotRod hotrod; private final String name; HotRodAsyncStrongCounter(HotRod hotrod, String name) { this.hotrod = hotrod; this.name = name; } @Override public String name() { return name; } @Override public CompletionStage<CounterConfiguration> configuration() { return null; } @Override public HotRodAsyncContainer container() { return hotrod.async(); } @Override public CompletionStage<Long> value() { return null; } @Override public CompletionStage<Long> addAndGet(long delta) { return null; } @Override public CompletionStage<Void> reset() { return null; } @Override public CompletionStage<AutoCloseable> listen(Consumer<CounterEvent> listener) { return null; } @Override public CompletionStage<Long> compareAndSwap(long expect, long update) { return null; } @Override public CompletionStage<Long> getAndSet(long value) { return null; } }
1,408
20.029851
82
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncWeakCounters.java
package org.infinispan.hotrod; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import org.infinispan.api.async.AsyncWeakCounter; import org.infinispan.api.async.AsyncWeakCounters; import org.infinispan.api.configuration.CounterConfiguration; /** * @since 14.0 **/ public class HotRodAsyncWeakCounters implements AsyncWeakCounters { private final HotRod hotrod; HotRodAsyncWeakCounters(HotRod hotrod) { this.hotrod = hotrod; } @Override public CompletionStage<AsyncWeakCounter> get(String name) { return CompletableFuture.completedFuture(new HotRodAsyncWeakCounter(hotrod, name)); // PLACEHOLDER } @Override public CompletionStage<AsyncWeakCounter> create(String name, CounterConfiguration configuration) { return CompletableFuture.completedFuture(new HotRodAsyncWeakCounter(hotrod, name)); // PLACEHOLDER } @Override public CompletionStage<Void> remove(String name) { return null; } @Override public Flow.Publisher<String> names() { return null; } }
1,113
26.170732
104
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodSyncWeakCounters.java
package org.infinispan.hotrod; import org.infinispan.api.configuration.CounterConfiguration; import org.infinispan.api.sync.SyncWeakCounter; import org.infinispan.api.sync.SyncWeakCounters; /** * @since 14.0 **/ public class HotRodSyncWeakCounters implements SyncWeakCounters { private final HotRod hotrod; public HotRodSyncWeakCounters(HotRod hotrod) { this.hotrod = hotrod; } @Override public SyncWeakCounter get(String name) { return new HotRodSyncWeakCounter(hotrod, name); // PLACEHOLDER } @Override public SyncWeakCounter create(String name, CounterConfiguration counterConfiguration) { return new HotRodSyncWeakCounter(hotrod, name); // PLACEHOLDER } @Override public void remove(String name) { } @Override public Iterable<String> names() { return null; } }
844
21.837838
90
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyMultimap.java
package org.infinispan.hotrod; import org.infinispan.api.configuration.MultimapConfiguration; import org.infinispan.api.mutiny.MutinyMultimap; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * @since 14.0 **/ public class HotRodMutinyMultimap<K, V> implements MutinyMultimap<K, V> { private final HotRod hotrod; private final String name; HotRodMutinyMultimap(HotRod hotrod, String name) { this.hotrod = hotrod; this.name = name; } @Override public String name() { return name; } @Override public Uni<MultimapConfiguration> configuration() { return null; } @Override public HotRodMutinyContainer container() { return hotrod.mutiny(); } @Override public Uni<Void> add(K key, V value) { return null; } @Override public Multi<V> get(K key) { return null; } @Override public Uni<Boolean> remove(K key) { return null; } @Override public Uni<Boolean> remove(K key, V value) { return null; } @Override public Uni<Boolean> containsKey(K key) { return null; } @Override public Uni<Boolean> containsEntry(K key, V value) { return null; } @Override public Uni<Long> estimateSize() { return null; } }
1,299
17.309859
73
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyWeakCounters.java
package org.infinispan.hotrod; import org.infinispan.api.configuration.CounterConfiguration; import org.infinispan.api.mutiny.MutinyWeakCounter; import org.infinispan.api.mutiny.MutinyWeakCounters; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * @since 14.0 **/ public class HotRodMutinyWeakCounters implements MutinyWeakCounters { private final HotRod hotrod; HotRodMutinyWeakCounters(HotRod hotrod) { this.hotrod = hotrod; } @Override public Uni<MutinyWeakCounter> get(String name) { return Uni.createFrom().item(new HotRodMutinyWeakCounter(hotrod, name)); // PLACEHOLDER } @Override public Uni<MutinyWeakCounter> create(String name, CounterConfiguration configuration) { return Uni.createFrom().item(new HotRodMutinyWeakCounter(hotrod, name)); // PLACEHOLDER } @Override public Uni<Void> remove(String name) { return null; } @Override public Multi<String> names() { return null; } }
993
23.85
93
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodSyncContainer.java
package org.infinispan.hotrod; import java.util.function.Function; import org.infinispan.api.common.events.container.ContainerListenerEventType; import org.infinispan.api.sync.SyncContainer; import org.infinispan.api.sync.events.container.SyncContainerListener; /** * @since 14.0 **/ public class HotRodSyncContainer implements SyncContainer { private final HotRod hotrod; public HotRodSyncContainer(HotRod hotrod) { this.hotrod = hotrod; } @Override public HotRodSyncContainer sync() { return this; } @Override public HotRodAsyncContainer async() { return hotrod.async(); } @Override public HotRodMutinyContainer mutiny() { return hotrod.mutiny(); } @Override public void close() { hotrod.close(); } @Override public HotRodSyncCaches caches() { return new HotRodSyncCaches(hotrod); } @Override public HotRodSyncMultimaps multimaps() { return new HotRodSyncMultimaps(hotrod); } @Override public HotRodSyncStrongCounters strongCounters() { return new HotRodSyncStrongCounters(hotrod); } @Override public HotRodSyncWeakCounters weakCounters() { return new HotRodSyncWeakCounters(hotrod); } @Override public HotRodSyncLocks locks() { return new HotRodSyncLocks(hotrod); } @Override public void listen(SyncContainerListener listener, ContainerListenerEventType... types) { } @Override public <T> T batch(Function<SyncContainer, T> function) { return null; } }
1,548
19.932432
92
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodSyncWeakCounter.java
package org.infinispan.hotrod; import org.infinispan.api.sync.SyncWeakCounter; /** * @since 14.0 **/ public class HotRodSyncWeakCounter implements SyncWeakCounter { private final HotRod hotrod; private final String name; HotRodSyncWeakCounter(HotRod hotrod, String name) { this.hotrod = hotrod; this.name = name; } @Override public String name() { return null; } @Override public HotRodSyncContainer container() { return hotrod.sync(); } @Override public long value() { return 0; } @Override public void add(long delta) { } }
614
15.621622
63
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyMultimaps.java
package org.infinispan.hotrod; import org.infinispan.api.configuration.MultimapConfiguration; import org.infinispan.api.mutiny.MutinyMultimap; import org.infinispan.api.mutiny.MutinyMultimaps; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * @since 14.0 **/ public class HotRodMutinyMultimaps implements MutinyMultimaps { private final HotRod hotrod; HotRodMutinyMultimaps(HotRod hotrod) { this.hotrod = hotrod; } @Override public <K, V> Uni<MutinyMultimap<K, V>> create(String name, MultimapConfiguration cacheConfiguration) { return Uni.createFrom().item(new HotRodMutinyMultimap(hotrod, name)); // PLACEHOLDER } @Override public <K, V> Uni<MutinyMultimap<K, V>> create(String name, String template) { return Uni.createFrom().item(new HotRodMutinyMultimap(hotrod, name)); // PLACEHOLDER } @Override public <K, V> Uni<MutinyMultimap<K, V>> get(String name) { return Uni.createFrom().item(new HotRodMutinyMultimap(hotrod, name)); // PLACEHOLDER } @Override public Uni<Void> remove(String name) { return null; } @Override public Multi<String> names() { return null; } @Override public Uni<Void> createTemplate(String name, MultimapConfiguration cacheConfiguration) { return null; } @Override public Uni<Void> removeTemplate(String name) { return null; } @Override public Multi<String> templateNames() { return null; } }
1,489
23.833333
106
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyWeakCounter.java
package org.infinispan.hotrod; import org.infinispan.api.mutiny.MutinyWeakCounter; import io.smallrye.mutiny.Uni; /** * @since 14.0 **/ public class HotRodMutinyWeakCounter implements MutinyWeakCounter { private final HotRod hotrod; private final String name; HotRodMutinyWeakCounter(HotRod hotrod, String name) { this.hotrod = hotrod; this.name = name; } @Override public String name() { return name; } @Override public HotRodMutinyContainer container() { return hotrod.mutiny(); } @Override public Uni<Long> value() { return null; } @Override public Uni<Void> add(long delta) { return null; } }
691
16.74359
67
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/MutinyToAsyncCacheEntryProcessor.java
package org.infinispan.hotrod; import io.smallrye.mutiny.Multi; import org.infinispan.api.async.AsyncCacheEntryProcessor; import org.infinispan.api.common.MutableCacheEntry; import org.infinispan.api.common.process.CacheEntryProcessorContext; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.mutiny.MutinyCacheEntryProcessor; import java.util.concurrent.Flow; public class MutinyToAsyncCacheEntryProcessor<K, V, T> implements AsyncCacheEntryProcessor<K, V, T> { private final MutinyCacheEntryProcessor<K, V, T> mutinyCacheEntryProcessor; public MutinyToAsyncCacheEntryProcessor(MutinyCacheEntryProcessor<K, V, T> mutinyCacheEntryProcessor) { this.mutinyCacheEntryProcessor = mutinyCacheEntryProcessor; } @Override public Flow.Publisher<CacheEntryProcessorResult<K, T>> process(Flow.Publisher<MutableCacheEntry<K, V>> entries, CacheEntryProcessorContext context) { return mutinyCacheEntryProcessor.process(Multi.createFrom().publisher(entries), context).convert().toPublisher(); } }
1,062
43.291667
152
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodSyncCache.java
package org.infinispan.hotrod; import static org.infinispan.hotrod.impl.Util.await; import java.util.Map; import java.util.Set; import java.util.concurrent.Flow; import java.util.stream.Collectors; import org.infinispan.api.common.CacheEntry; import org.infinispan.api.common.CacheEntryVersion; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.common.CloseableIterable; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.common.process.CacheProcessorOptions; import org.infinispan.api.configuration.CacheConfiguration; import org.infinispan.api.sync.SyncCache; import org.infinispan.api.sync.SyncCacheEntryProcessor; import org.infinispan.api.sync.SyncQuery; import org.infinispan.api.sync.SyncStreamingCache; import org.infinispan.api.sync.events.cache.SyncCacheEntryListener; import org.infinispan.hotrod.impl.cache.RemoteCache; import org.reactivestreams.FlowAdapters; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; /** * @since 14.0 **/ public class HotRodSyncCache<K, V> implements SyncCache<K, V> { private final HotRod hotrod; private final RemoteCache<K, V> remoteCache; HotRodSyncCache(HotRod hotrod, RemoteCache<K, V> remoteCache) { this.hotrod = hotrod; this.remoteCache = remoteCache; } // This method is blocking - but only invoked by user code @SuppressWarnings("checkstyle:ForbiddenMethod") private <E> E blockingGet(Single<E> single) { return single.blockingGet(); } @Override public String name() { return remoteCache.getName(); } @Override public CacheConfiguration configuration() { return await(remoteCache.configuration()); } @Override public HotRodSyncContainer container() { return hotrod.sync(); } @Override public CacheEntry<K, V> getEntry(K key, CacheOptions options) { return await(remoteCache.getEntry(key, options)); } @Override public CacheEntry<K, V> put(K key, V value, CacheWriteOptions options) { return await(remoteCache.put(key, value, options)); } @Override public void set(K key, V value, CacheWriteOptions options) { await(remoteCache.set(key, value, options)); } @Override public CacheEntry<K, V> putIfAbsent(K key, V value, CacheWriteOptions options) { return await(remoteCache.putIfAbsent(key, value, options)); } @Override public boolean setIfAbsent(K key, V value, CacheWriteOptions options) { return await(remoteCache.setIfAbsent(key, value, options)); } @Override public boolean replace(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return await(remoteCache.replace(key, value, version, options)); } @Override public CacheEntry<K, V> getOrReplaceEntry(K key, V value, CacheEntryVersion version, CacheWriteOptions options) { return await(remoteCache.getOrReplaceEntry(key, value, version, options)); } @Override public boolean remove(K key, CacheOptions options) { return await(remoteCache.remove(key, options)); } @Override public boolean remove(K key, CacheEntryVersion version, CacheOptions options) { return await(remoteCache.remove(key, version, options)); } @Override public CacheEntry<K, V> getAndRemove(K key, CacheOptions options) { return await(remoteCache.getAndRemove(key, options)); } @Override public CloseableIterable<K> keys(CacheOptions options) { throw new UnsupportedOperationException(); } @Override public CloseableIterable<CacheEntry<K, V>> entries(CacheOptions options) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<K, V> entries, CacheWriteOptions options) { await(remoteCache.putAll(entries, options)); } @Override public Map<K, V> getAll(Set<K> keys, CacheOptions options) { return blockingGet(Flowable.fromPublisher(FlowAdapters.toPublisher(remoteCache.getAll(keys, options))) .collect(Collectors.toMap(CacheEntry::key, CacheEntry::value))); } @Override public Map<K, V> getAll(CacheOptions options, K... keys) { return blockingGet(Flowable.fromPublisher(FlowAdapters.toPublisher(remoteCache.getAll(options, keys))) .collect(Collectors.toMap(CacheEntry::key, CacheEntry::value))); } @Override public Set<K> removeAll(Set<K> keys, CacheWriteOptions options) { return blockingGet(Flowable.fromPublisher(FlowAdapters.toPublisher(remoteCache.removeAll(keys, options))) .collect(Collectors.toSet())); } @Override public Map<K, CacheEntry<K, V>> getAndRemoveAll(Set<K> keys, CacheWriteOptions options) { return blockingGet(Flowable.fromPublisher(FlowAdapters.toPublisher(remoteCache.getAndRemoveAll(keys, options))) .collect(Collectors.toMap(CacheEntry::key, ce -> ce))); } @Override public long estimateSize(CacheOptions options) { return await(remoteCache.estimateSize(options)); } @Override public void clear(CacheOptions options) { await(remoteCache.clear(options)); } @Override public <R> SyncQuery<K, V, R> query(String query, CacheOptions options) { return new HotRodSyncQuery(query, options); } @Override public AutoCloseable listen(SyncCacheEntryListener<K, V> listener) { throw new UnsupportedOperationException(); } @Override public <T> Set<CacheEntryProcessorResult<K, T>> process(Set<K> keys, SyncCacheEntryProcessor<K, V, T> processor, CacheProcessorOptions options) { Flow.Publisher<CacheEntryProcessorResult<K, T>> flowPublisher = remoteCache.process(keys, // TODO: do we worry about the sync processor here? Guessing we need to offload it to another thread ? new SyncToAsyncEntryProcessor<>(processor), options); return blockingGet(Flowable.fromPublisher(FlowAdapters.toPublisher(flowPublisher)) .collect(Collectors.toSet())); } @Override public <T> Set<CacheEntryProcessorResult<K, T>> processAll(SyncCacheEntryProcessor<K, V, T> processor, CacheProcessorOptions options) { Flow.Publisher<CacheEntryProcessorResult<K, T>> flowPublisher = remoteCache.processAll( // TODO: do we worry about the sync processor here? Guessing we need to offload it to another thread ? new SyncToAsyncEntryProcessor<>(processor), options); return blockingGet(Flowable.fromPublisher(FlowAdapters.toPublisher(flowPublisher)) .collect(Collectors.toSet())); } @Override public SyncStreamingCache<K> streaming() { return new HotRodSyncStreamingCache(hotrod, remoteCache); } }
6,765
33.876289
148
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyCaches.java
package org.infinispan.hotrod; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.function.Function; import org.infinispan.api.configuration.CacheConfiguration; import org.infinispan.api.mutiny.MutinyCache; import org.infinispan.api.mutiny.MutinyCaches; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * @since 14.0 **/ public class HotRodMutinyCaches implements MutinyCaches { private final HotRod hotrod; HotRodMutinyCaches(HotRod hotrod) { this.hotrod = hotrod; } @Override public <K, V> Uni<MutinyCache<K, V>> create(String name, CacheConfiguration cacheConfiguration) { return Uni.createFrom().completionStage(() -> hotrod.transport.<K, V>getRemoteCache(name)) .map(r -> new HotRodMutinyCache<>(hotrod, r)); } @Override public <K, V> Uni<MutinyCache<K, V>> create(String name, String template) { return Uni.createFrom().completionStage(() -> hotrod.transport.<K, V>getRemoteCache(name)) .map(r -> new HotRodMutinyCache<>(hotrod, r)); } @Override public <K, V> Uni<MutinyCache<K, V>> get(String name) { return Uni.createFrom().completionStage(() -> hotrod.transport.<K, V>getRemoteCache(name)) .map(r -> new HotRodMutinyCache<>(hotrod, r)); } @Override public Uni<Void> remove(String name) { return Uni.createFrom().completionStage(() -> hotrod.transport.removeCache(name)); } @Override public Multi<String> names() { return Multi.createFrom().deferred(() -> toMulti(hotrod.transport.getCacheNames())); } @Override public Uni<Void> createTemplate(String name, CacheConfiguration cacheConfiguration) { return null; } @Override public Uni<Void> removeTemplate(String name) { return null; } @Override public Multi<String> templateNames() { return Multi.createFrom().deferred(() -> toMulti(hotrod.transport.getTemplateNames())); } private Multi<String> toMulti(CompletionStage<Set<String>> cs) { return Multi.createFrom().completionStage(cs).onItem().transformToIterable(Function.identity()); } }
2,149
29.28169
102
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodFactory.java
package org.infinispan.hotrod; import java.net.URI; import org.infinispan.api.Infinispan; import org.infinispan.api.configuration.Configuration; import org.infinispan.hotrod.configuration.HotRodConfiguration; import org.infinispan.hotrod.impl.HotRodURI; import org.kohsuke.MetaInfServices; /** * @since 14.0 **/ @MetaInfServices(Infinispan.Factory.class) public class HotRodFactory implements Infinispan.Factory { @Override public Infinispan create(URI uri) { try { return new HotRod(HotRodURI.create(uri).toConfigurationBuilder().build()); } catch (Throwable t) { // Not a Hot Rod URI return null; } } @Override public Infinispan create(Configuration configuration) { assert configuration instanceof HotRodConfiguration; return new HotRod((HotRodConfiguration) configuration); } }
863
26
83
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyStreamingCache.java
package org.infinispan.hotrod; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.CacheWriteOptions; import org.infinispan.api.mutiny.MutinyStreamingCache; import org.infinispan.hotrod.impl.cache.RemoteCache; import io.smallrye.mutiny.subscription.BackPressureStrategy; /** * @since 14.0 **/ public class HotRodMutinyStreamingCache<K> implements MutinyStreamingCache<K> { private final HotRod hotrod; private final RemoteCache<K, ?> remoteCache; HotRodMutinyStreamingCache(HotRod hotrod, RemoteCache<K, ?> remoteCache) { this.hotrod = hotrod; this.remoteCache = remoteCache; } @Override public CacheEntrySubscriber get(K key, BackPressureStrategy backPressureStrategy, CacheOptions options) { throw new UnsupportedOperationException(); } @Override public CacheEntryPublisher put(K key, CacheWriteOptions options, BackPressureStrategy backPressureStrategy) { throw new UnsupportedOperationException(); } @Override public CacheEntryPublisher putIfAbsent(K key, CacheWriteOptions options, BackPressureStrategy backPressureStrategy) { throw new UnsupportedOperationException(); } }
1,185
31.054054
120
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncStrongCounters.java
package org.infinispan.hotrod; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import org.infinispan.api.async.AsyncStrongCounter; import org.infinispan.api.async.AsyncStrongCounters; import org.infinispan.api.configuration.CounterConfiguration; /** * @since 14.0 **/ public class HotRodAsyncStrongCounters implements AsyncStrongCounters { private final HotRod hotrod; HotRodAsyncStrongCounters(HotRod hotrod) { this.hotrod = hotrod; } @Override public CompletionStage<AsyncStrongCounter> get(String name) { return CompletableFuture.completedFuture(new HotRodAsyncStrongCounter(hotrod, name)); // PLACEHOLDER } @Override public CompletionStage<AsyncStrongCounter> create(String name, CounterConfiguration configuration) { return CompletableFuture.completedFuture(new HotRodAsyncStrongCounter(hotrod, name)); // PLACEHOLDER } @Override public CompletionStage<Void> remove(String name) { return null; } @Override public Flow.Publisher<String> names() { return null; } }
1,131
26.609756
106
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodAsyncContainer.java
package org.infinispan.hotrod; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import java.util.function.Function; import org.infinispan.api.async.AsyncContainer; import org.infinispan.api.async.AsyncStrongCounters; import org.infinispan.api.common.events.container.ContainerEvent; import org.infinispan.api.common.events.container.ContainerListenerEventType; /** * @since 14.0 **/ public class HotRodAsyncContainer implements AsyncContainer { private final HotRod hotrod; HotRodAsyncContainer(HotRod hotrod) { this.hotrod = hotrod; } @Override public HotRodSyncContainer sync() { return hotrod.sync(); } @Override public HotRodAsyncContainer async() { return this; } @Override public HotRodMutinyContainer mutiny() { return hotrod.mutiny(); } @Override public void close() { hotrod.close(); } @Override public HotRodAsyncCaches caches() { return new HotRodAsyncCaches(hotrod); } @Override public HotRodAsyncMultimaps multimaps() { return new HotRodAsyncMultimaps(hotrod); } @Override public AsyncStrongCounters strongCounters() { return new HotRodAsyncStrongCounters(hotrod); } @Override public HotRodAsyncWeakCounters weakCounters() { return new HotRodAsyncWeakCounters(hotrod); } @Override public HotRodAsyncLocks locks() { return new HotRodAsyncLocks(hotrod); } @Override public Flow.Publisher<ContainerEvent> listen(ContainerListenerEventType... types) { return null; } @Override public <T> CompletionStage<T> batch(Function<AsyncContainer, CompletionStage<T>> function) { return null; } }
1,723
21.38961
95
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/HotRodMutinyQuery.java
package org.infinispan.hotrod; import org.infinispan.api.common.CacheOptions; import org.infinispan.api.common.events.cache.CacheContinuousQueryEvent; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.common.process.CacheProcessor; import org.infinispan.api.common.process.CacheProcessorOptions; import org.infinispan.api.mutiny.MutinyCacheEntryProcessor; import org.infinispan.api.mutiny.MutinyQuery; import org.infinispan.api.mutiny.MutinyQueryResult; import org.infinispan.hotrod.impl.cache.RemoteQuery; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * @since 14.0 **/ public class HotRodMutinyQuery<K, V, R> implements MutinyQuery<K, V, R> { private final RemoteQuery query; HotRodMutinyQuery(String query, CacheOptions options) { this.query = new RemoteQuery(query, options); } @Override public MutinyQuery<K, V, R> param(String name, Object value) { query.param(name, value); return this; } @Override public MutinyQuery<K, V, R> skip(long skip) { query.skip(skip); return this; } @Override public MutinyQuery<K, V, R> limit(int limit) { query.limit(limit); return this; } @Override public Uni<MutinyQueryResult<R>> find() { throw new UnsupportedOperationException(); } @Override public <R1> Multi<CacheContinuousQueryEvent<K, R1>> findContinuously() { throw new UnsupportedOperationException(); } @Override public Uni<Long> execute() { throw new UnsupportedOperationException(); } @Override public <T> Multi<CacheEntryProcessorResult<K, T>> process(MutinyCacheEntryProcessor<K, V, T> processor, CacheProcessorOptions options) { throw new UnsupportedOperationException(); } @Override public <T> Multi<CacheEntryProcessorResult<K, T>> process(CacheProcessor processor, CacheProcessorOptions options) { throw new UnsupportedOperationException(); } }
1,986
27.385714
139
java
null
infinispan-main/client/hotrod/src/main/java/org/infinispan/hotrod/SyncToAsyncEntryProcessor.java
package org.infinispan.hotrod; import java.util.concurrent.Flow; import org.infinispan.api.async.AsyncCacheEntryProcessor; import org.infinispan.api.common.MutableCacheEntry; import org.infinispan.api.common.process.CacheEntryProcessorContext; import org.infinispan.api.common.process.CacheEntryProcessorResult; import org.infinispan.api.sync.SyncCacheEntryProcessor; import org.reactivestreams.FlowAdapters; import io.reactivex.rxjava3.core.Flowable; public class SyncToAsyncEntryProcessor<K, V, T> implements AsyncCacheEntryProcessor<K, V, T> { private final SyncCacheEntryProcessor<K, V, T> syncCacheEntryProcessor; public SyncToAsyncEntryProcessor(SyncCacheEntryProcessor<K, V, T> syncCacheEntryProcessor) { this.syncCacheEntryProcessor = syncCacheEntryProcessor; } @Override public Flow.Publisher<CacheEntryProcessorResult<K, T>> process(Flow.Publisher<MutableCacheEntry<K, V>> entries, CacheEntryProcessorContext context) { Flowable<CacheEntryProcessorResult<K, T>> flowable = Flowable.fromPublisher(FlowAdapters.toPublisher(entries)) .map(e -> { try { return CacheEntryProcessorResult.onResult(e.key(), syncCacheEntryProcessor.process(e, context)); } catch (Throwable t) { return CacheEntryProcessorResult.onError(e.key(), t); } }); return FlowAdapters.toFlowPublisher(flowable); } }
1,438
41.323529
152
java