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/configuration/ExecutorFactoryConfigurationBuilder.java
package org.infinispan.client.hotrod.configuration; import java.util.Properties; import org.infinispan.client.hotrod.impl.async.DefaultAsyncExecutorFactory; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.util.TypedProperties; import org.infinispan.commons.util.Util; /** * Configures executor factory. * * @author Tristan Tarrant * @since 5.3 */ public class ExecutorFactoryConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<ExecutorFactoryConfiguration> { private Class<? extends ExecutorFactory> factoryClass = DefaultAsyncExecutorFactory.class; private ExecutorFactory factory; private Properties properties; private final ConfigurationBuilder builder; ExecutorFactoryConfigurationBuilder(ConfigurationBuilder builder) { super(builder); this.builder = builder; this.properties = new Properties(); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Specify factory class for executor * * @param factoryClass * clazz * @return this ExecutorFactoryConfig */ public ExecutorFactoryConfigurationBuilder factoryClass(Class<? extends ExecutorFactory> factoryClass) { this.factoryClass = factoryClass; return this; } public ExecutorFactoryConfigurationBuilder factoryClass(String factoryClass) { this.factoryClass = Util.loadClass(factoryClass, builder.classLoader()); return this; } /** * Specify factory class for executor * * @param factory * clazz * @return this ExecutorFactoryConfig */ public ExecutorFactoryConfigurationBuilder factory(ExecutorFactory factory) { this.factory = factory; return this; } /** * Add key/value property pair to this executor factory configuration * * @param key * property key * @param value * property value * @return previous value if exists, null otherwise */ public ExecutorFactoryConfigurationBuilder addExecutorProperty(String key, String value) { this.properties.put(key, value); return this; } /** * Set key/value properties to this executor factory configuration * * @param props * Properties * @return this ExecutorFactoryConfig */ public ExecutorFactoryConfigurationBuilder withExecutorProperties(Properties props) { this.properties = props; return this; } @Override public ExecutorFactoryConfiguration create() { if (factory != null) return new ExecutorFactoryConfiguration(factory, TypedProperties.toTypedProperties(properties)); else return new ExecutorFactoryConfiguration(factoryClass, TypedProperties.toTypedProperties(properties)); } @Override public ExecutorFactoryConfigurationBuilder read(ExecutorFactoryConfiguration template, Combine combine) { this.factory = template.factory(); this.factoryClass = template.factoryClass(); this.properties = template.properties(); return this; } @Override public String toString() { return "ExecutorFactoryConfigurationBuilder [factoryClass=" + factoryClass + ", factory=" + factory + ", properties=" + properties + "]"; } }
3,504
29.745614
143
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ExecutorFactoryConfiguration.java
package org.infinispan.client.hotrod.configuration; import org.infinispan.commons.configuration.AbstractTypedPropertiesConfiguration; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.util.TypedProperties; /** * ExecutorFactoryConfiguration. * * @author Tristan Tarrant * @since 5.3 */ public class ExecutorFactoryConfiguration extends AbstractTypedPropertiesConfiguration { private final Class<? extends ExecutorFactory> factoryClass; private final ExecutorFactory factory; ExecutorFactoryConfiguration(Class<? extends ExecutorFactory> factoryClass, TypedProperties properties) { super(properties); this.factoryClass = factoryClass; this.factory = null; } ExecutorFactoryConfiguration(ExecutorFactory factory, TypedProperties properties) { super(properties); this.factory = factory; this.factoryClass = null; } public Class<? extends ExecutorFactory> factoryClass() { return factoryClass; } public ExecutorFactory factory() { return factory; } @Override public String toString() { return "ExecutorFactoryConfiguration [factoryClass=" + factoryClass + ", factory=" + factory + ", properties()=" + properties() + "]"; } }
1,265
27.772727
140
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/configuration/ServerConfiguration.java
package org.infinispan.client.hotrod.configuration; /** * ServerConfiguration. * * @author Tristan Tarrant * @since 5.3 */ public class ServerConfiguration { private final String host; private final int port; ServerConfiguration(String host, int port) { this.host = host; this.port = port; } public String host() { return host; } public int port() { return port; } @Override public String toString() { return "ServerConfiguration[" + "host='" + host + '\'' + ", port=" + port + ']'; } }
596
16.558824
51
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/security/BasicCallbackHandler.java
package org.infinispan.client.hotrod.security; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.RealmCallback; /** * A basic {@link CallbackHandler}. This can be used for PLAIN and CRAM-MD mechanisms * * @author Tristan Tarrant * @since 9.0 */ public class BasicCallbackHandler implements CallbackHandler { private final String username; private final String realm; private final char[] password; public BasicCallbackHandler() { this(null, null, null); } public BasicCallbackHandler(String username, char[] password) { this(username, null, password); } public BasicCallbackHandler(String username, String realm, char[] password) { this.username = username; this.password = password; this.realm = realm; } public String getUsername() { return username; } public String getRealm() { return realm; } public char[] getPassword() { return password; } @Override public void handle(Callback[] callbacks) throws UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { NameCallback nameCallback = (NameCallback) callback; nameCallback.setName(username); } else if (callback instanceof PasswordCallback) { PasswordCallback passwordCallback = (PasswordCallback) callback; passwordCallback.setPassword(password); } else if (callback instanceof AuthorizeCallback) { AuthorizeCallback authorizeCallback = (AuthorizeCallback) callback; authorizeCallback.setAuthorized(authorizeCallback.getAuthenticationID().equals( authorizeCallback.getAuthorizationID())); } else if (callback instanceof RealmCallback) { if (realm == null) throw new UnsupportedCallbackException(callback, "The mech requests a realm, but none has been supplied"); RealmCallback realmCallback = (RealmCallback) callback; realmCallback.setText(realm); } else { throw new UnsupportedCallbackException(callback); } } } }
2,556
34.513889
126
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/security/TokenCallbackHandler.java
package org.infinispan.client.hotrod.security; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import org.wildfly.security.auth.callback.CredentialCallback; import org.wildfly.security.credential.BearerTokenCredential; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.1 **/ public class TokenCallbackHandler implements CallbackHandler { private volatile String token; public TokenCallbackHandler(String token) { this.token = token; } @Override public void handle(Callback[] callbacks) { for (Callback callback : callbacks) { if (callback instanceof CredentialCallback) { CredentialCallback cc = (CredentialCallback) callback; cc.setCredential(new BearerTokenCredential(token)); } } } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
975
24.684211
66
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/security/VoidCallbackHandler.java
package org.infinispan.client.hotrod.security; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; /** * * No-op {@link javax.security.auth.callback.CallbackHandler}. Convenient CallbackHandler which comes handy when * no auth. callback is needed. This applies namely to SASL EXTERNAL auth. mechanism when auth. information is obtained * from external channel, like TLS certificate. * * @author vjuranek * @since 9.0 */ public class VoidCallbackHandler implements CallbackHandler { @Override public void handle(Callback[] callbacks) { // NO-OP } }
625
28.809524
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/telemetry/impl/TelemetryServiceImpl.java
package org.infinispan.client.hotrod.telemetry.impl; import java.nio.charset.StandardCharsets; import org.infinispan.client.hotrod.impl.protocol.HeaderParams; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.Context; public class TelemetryServiceImpl implements TelemetryService { private final W3CTraceContextPropagator propagator; public TelemetryServiceImpl() { propagator = W3CTraceContextPropagator.getInstance(); } public void injectSpanContext(HeaderParams header) { // Inject the request with the *current* Context, which contains client current Span if exists. propagator.inject(Context.current(), header, (carrier, paramKey, paramValue) -> carrier.otherParam(paramKey, paramValue.getBytes(StandardCharsets.UTF_8)) ); } }
863
32.230769
101
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/telemetry/impl/TelemetryService.java
package org.infinispan.client.hotrod.telemetry.impl; import org.infinispan.client.hotrod.impl.protocol.HeaderParams; public interface TelemetryService { /** * Try to create a {@link TelemetryService} instance. * * @throws ClassCastException if the OpenTelemetry API module is not in the classpath * @return a {@link TelemetryService} instance */ static TelemetryService create() { return new TelemetryServiceImpl(); } void injectSpanContext(HeaderParams header); }
508
24.45
88
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/near/NearCache.java
package org.infinispan.client.hotrod.near; import java.util.Map; import org.infinispan.client.hotrod.MetadataValue; /** * Near cache contract. * * @since 7.1 */ public interface NearCache<K, V> extends Iterable<Map.Entry<K, MetadataValue<V>>> { void put(K key, MetadataValue<V> value); void putIfAbsent(K key, MetadataValue<V> value); boolean remove(K key); MetadataValue<V> get(K key); void clear(); int size(); }
440
21.05
83
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/near/NearCacheFactory.java
package org.infinispan.client.hotrod.near; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.configuration.NearCacheConfiguration; /** * @since 14.0 **/ public interface NearCacheFactory { <K,V> NearCache<K, V> createNearCache(NearCacheConfiguration config, BiConsumer<K, MetadataValue<V>> removedConsumer); }
393
27.142857
121
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/near/NearCacheService.java
package org.infinispan.client.hotrod.near; import java.net.SocketAddress; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientCacheFailover; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.configuration.NearCacheConfiguration; import org.infinispan.client.hotrod.event.ClientCacheEntryExpiredEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; import org.infinispan.client.hotrod.event.ClientCacheFailoverEvent; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.util.BloomFilter; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.MurmurHash3BloomFilter; import org.infinispan.commons.util.Util; /** * Near cache service, manages the lifecycle of the near cache. * * @since 7.1 */ public class NearCacheService<K, V> implements NearCache<K, V> { private static final Log log = LogFactory.getLog(NearCacheService.class); private final NearCacheConfiguration config; private final ClientListenerNotifier listenerNotifier; private final AtomicInteger nearCacheRemovals = new AtomicInteger(); private Object listener; private byte[] listenerId; private NearCache<K, V> cache; private Runnable invalidationCallback; private int bloomFilterBits = -1; private int bloomFilterUpdateThreshold; private InternalRemoteCache<K, V> remote; private SocketAddress listenerAddress; protected NearCacheService(NearCacheConfiguration config, ClientListenerNotifier listenerNotifier) { this.config = config; this.listenerNotifier = listenerNotifier; } public SocketAddress start(InternalRemoteCache<K, V> remote) { if (cache == null) { // Create near cache cache = createNearCache(config, this::entryRemovedFromNearCache); // Add a listener that updates the near cache listener = new InvalidatedNearCacheListener<>(this); int maxEntries = config.maxEntries(); if (maxEntries > 0 && config.bloomFilter()) { bloomFilterBits = determineBloomFilterBits(maxEntries); // We want to scale the update frequency of the bloom filter to be based on the number of max entries // This number along with default values of 3 hash algorithms and 4x bit size we end up with // between 14.689 and 16.573 percent hits per entry. bloomFilterUpdateThreshold = maxEntries / 16 + 3; listenerAddress = remote.addNearCacheListener(listener, bloomFilterBits); } else { remote.addClientListener(listener); } // Get the listener ID for faster listener connected lookups listenerId = listenerNotifier.findListenerId(listener); } this.remote = remote; return listenerAddress; } private static int determineBloomFilterBits(int maxEntries) { int bloomFilterBitScaler = Integer.parseInt(System.getProperty("infinispan.bloom-filter.bit-multiplier", "4")); return maxEntries * bloomFilterBitScaler; } void entryRemovedFromNearCache(K key, MetadataValue<V> value) { while (true) { int removals = nearCacheRemovals.get(); if (removals >= bloomFilterUpdateThreshold) { if (nearCacheRemovals.compareAndSet(removals, 0)) { remote.updateBloomFilter(); break; } } else if (nearCacheRemovals.compareAndSet(removals, removals + 1)) { break; } } } public void stop(RemoteCache<K, V> remote) { if (log.isTraceEnabled()) log.tracef("Stop near cache, remove underlying listener id %s", Util.printArray(listenerId)); // Remove listener remote.removeClientListener(listener); // Empty cache cache.clear(); } protected NearCache<K, V> createNearCache(NearCacheConfiguration config, BiConsumer<K, MetadataValue<V>> removedConsumer) { return config.nearCacheFactory().createNearCache(config, removedConsumer); } public static <K, V> NearCacheService<K, V> create( NearCacheConfiguration config, ClientListenerNotifier listenerNotifier) { return new NearCacheService<>(config, listenerNotifier); } @Override public void put(K key, MetadataValue<V> value) { cache.put(key, value); if (log.isTraceEnabled()) log.tracef("Put key=%s and value=%s in near cache (listenerId=%s)", key, value, Util.printArray(listenerId)); } @Override public void putIfAbsent(K key, MetadataValue<V> value) { cache.putIfAbsent(key, value); if (log.isTraceEnabled()) log.tracef("Conditionally put key=%s and value=%s if absent in near cache (listenerId=%s)", key, value, Util.printArray(listenerId)); } @Override public boolean remove(K key) { boolean removed = cache.remove(key); if (removed) { if (invalidationCallback != null) { invalidationCallback.run(); } if (log.isTraceEnabled()) log.tracef("Removed key=%s from near cache (listenedId=%s)", key, Util.printArray(listenerId)); } else { log.tracef("Received false positive remove for key=%s from near cache (listenedId=%s)", key, Util.printArray(listenerId)); // There was a false positive, add that to the removal entryRemovedFromNearCache(key, null); } return removed; } @Override public MetadataValue<V> get(K key) { boolean listenerConnected = isConnected(); if (listenerConnected) { MetadataValue<V> value = cache.get(key); if (log.isTraceEnabled()) log.tracef("Get key=%s returns value=%s (listenerId=%s)", key, value, Util.printArray(listenerId)); return value; } if (log.isTraceEnabled()) log.tracef("Near cache disconnected from server, returning null for key=%s (listenedId=%s)", key, Util.printArray(listenerId)); return null; } @Override public void clear() { cache.clear(); if (log.isTraceEnabled()) log.tracef("Cleared near cache (listenerId=%s)", Util.printArray(listenerId)); } @Override public int size() { return cache.size(); } @Override public Iterator<Map.Entry<K, MetadataValue<V>>> iterator() { return cache.iterator(); } boolean isConnected() { return listenerNotifier.isListenerConnected(listenerId); } public void setInvalidationCallback(Runnable r) { this.invalidationCallback = r; } public int getBloomFilterBits() { return bloomFilterBits; } public byte[] getListenerId() { return listenerId; } public byte[] calculateBloomBits() { if (bloomFilterBits <= 0) { return null; } BloomFilter<byte[]> bloomFilter = MurmurHash3BloomFilter.createFilter(bloomFilterBits); for (Map.Entry<K, MetadataValue<V>> entry : cache) { bloomFilter.addToFilter(remote.keyToBytes(entry.getKey())); } IntSet intSet = bloomFilter.getIntSet(); return intSet.toBitSet(); } @ClientListener private static class InvalidatedNearCacheListener<K, V> { private static final Log log = LogFactory.getLog(InvalidatedNearCacheListener.class); private final NearCache<K, V> cache; private InvalidatedNearCacheListener(NearCache<K, V> cache) { this.cache = cache; } @ClientCacheEntryModified @SuppressWarnings("unused") public void handleModifiedEvent(ClientCacheEntryModifiedEvent<K> event) { invalidate(event.getKey()); } @ClientCacheEntryRemoved @SuppressWarnings("unused") public void handleRemovedEvent(ClientCacheEntryRemovedEvent<K> event) { invalidate(event.getKey()); } @ClientCacheEntryExpired @SuppressWarnings("unused") public void handleExpiredEvent(ClientCacheEntryExpiredEvent<K> event) { invalidate(event.getKey()); } @ClientCacheFailover @SuppressWarnings("unused") public void handleFailover(ClientCacheFailoverEvent e) { if (log.isTraceEnabled()) log.trace("Clear near cache after fail-over of server"); cache.clear(); } private void invalidate(K key) { cache.remove(key); } } }
9,098
34.404669
131
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/near/DefaultNearCacheFactory.java
package org.infinispan.client.hotrod.near; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.configuration.NearCacheConfiguration; /** * @since 14.0 **/ public class DefaultNearCacheFactory implements NearCacheFactory { public static final DefaultNearCacheFactory INSTANCE = new DefaultNearCacheFactory(); @Override public <K, V> NearCache<K, V> createNearCache(NearCacheConfiguration config, BiConsumer<K, MetadataValue<V>> removedConsumer) { return config.maxEntries() > 0 ? BoundedConcurrentMapNearCache.create(config, removedConsumer) : ConcurrentMapNearCache.create(); } @Override public String toString() { return "DefaultNearCacheFactory{}"; } }
792
29.5
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/near/BoundedConcurrentMapNearCache.java
package org.infinispan.client.hotrod.near; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.configuration.NearCacheConfiguration; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; /** * Near cache based on {@link BoundedConcurrentMapNearCache} * * @since 7.2 */ final class BoundedConcurrentMapNearCache<K, V> implements NearCache<K, V> { private final ConcurrentMap<K, MetadataValue<V>> map; private final Cache<K, MetadataValue<V>> cache; private BoundedConcurrentMapNearCache(Cache<K, MetadataValue<V>> cache) { this.cache = cache; this.map = cache.asMap(); } public static <K, V> NearCache<K, V> create(final NearCacheConfiguration config, BiConsumer<? super K, ? super MetadataValue<V>> removedConsumer) { Cache<K, MetadataValue<V>> cache = Caffeine.newBuilder() .maximumSize(config.maxEntries()) .<K, MetadataValue<V>>removalListener((key, value, cause) -> removedConsumer.accept(key, value)) .build(); return new BoundedConcurrentMapNearCache<>(cache); } @Override public void put(K key, MetadataValue<V> value) { cache.put(key, value); } @Override public void putIfAbsent(K key, MetadataValue<V> value) { map.putIfAbsent(key, value); } @Override public boolean remove(K key) { return map.remove(key) != null; } @Override public MetadataValue<V> get(K key) { return map.get(key); } @Override public void clear() { map.clear(); } @Override public int size() { // Make sure to clean up any evicted entries so the returned size is correct cache.cleanUp(); return map.size(); } @Override public Iterator<Map.Entry<K, MetadataValue<V>>> iterator() { return map.entrySet().iterator(); } }
2,069
26.6
113
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/near/ConcurrentMapNearCache.java
package org.infinispan.client.hotrod.near; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.infinispan.client.hotrod.MetadataValue; /** * A concurrent-map-based near cache implementation. * It does not provide eviction capabilities. * * @since 7.1 */ final class ConcurrentMapNearCache<K, V> implements NearCache<K, V> { private final ConcurrentMap<K, MetadataValue<V>> cache = new ConcurrentHashMap<>(); @Override public void put(K key, MetadataValue<V> value) { cache.put(key, value); } @Override public void putIfAbsent(K key, MetadataValue<V> value) { cache.putIfAbsent(key, value); } @Override public boolean remove(K key) { return cache.remove(key) != null; } @Override public MetadataValue<V> get(Object key) { return cache.get(key); } @Override public void clear() { cache.clear(); } @Override public int size() { return cache.size(); } public static <K, V> NearCache<K, V> create() { return new ConcurrentMapNearCache<K, V>(); } @Override public Iterator<Map.Entry<K, MetadataValue<V>>> iterator() { return cache.entrySet().iterator(); } }
1,288
20.483333
86
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/logging/Log.java
package org.infinispan.client.hotrod.logging; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; import java.lang.reflect.Method; import java.net.SocketAddress; import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.configuration.ExhaustedAction; import org.infinispan.client.hotrod.event.IncorrectClientListenerException; import org.infinispan.client.hotrod.exceptions.CacheNotTransactionalException; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.CacheListenerException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Param; import io.netty.channel.Channel; /** * Log abstraction for the hot rod client. For this module, message ids * ranging from 4001 to 5000 inclusively have been reserved. * * @author Galder Zamarreño * @since 5.0 */ @MessageLogger(projectCode = "ISPN") public interface Log extends BasicLogger { String LOG_ROOT = "org.infinispan."; Log HOTROD = Logger.getMessageLogger(Log.class, LOG_ROOT + "HOTROD"); @LogMessage(level = WARN) @Message(value = "Could not find '%s' file in classpath, using defaults.", id = 4001) void couldNotFindPropertiesFile(String propertiesFile); @LogMessage(level = INFO) @Message(value = "Cannot perform operations on a cache associated with an unstarted RemoteCacheManager. Use RemoteCacheManager.start before using the remote cache.", id = 4002) void unstartedRemoteCacheManager(); @Message(value = "Invalid magic number. Expected %#x and received %#x", id = 4003) InvalidResponseException invalidMagicNumber(short expectedMagicNumber, short receivedMagic); // @LogMessage(level = ERROR) // @Message(value = "Invalid message id. Expected %d and received %d", id = 4004) // void invalidMessageId(long expectedMsgId, long receivedMsgId); @LogMessage(level = WARN) @Message(value = "Error received from the server: %s", id = 4005) void errorFromServer(String message); @LogMessage(level = INFO) @Message(value = "Server sent new topology view (id=%d, age=%d) containing %d addresses: %s", id = 4006) void newTopology(int viewId, int age, int topologySize, Collection<? extends SocketAddress> addresses); @LogMessage(level = ERROR) @Message(value = "Exception encountered. Retry %d out of %d", id = 4007) void exceptionAndNoRetriesLeft(int retry, int maxRetries, @Cause Throwable te); // id = 4008 is now logged to TRACE(ISPN-1794) // id = 4009 removed: errorClosingSocket @LogMessage(level = WARN) @Message(value = "No hash function configured for version: %d", id = 4011) void noHasHFunctionConfigured(int hashFunctionVersion); // id = 4012 removed: couldNoInvalidateConnection // id = 4013 removed: couldNotReleaseConnection @LogMessage(level = INFO) @Message(value = "New server added(%s), adding to the pool.", id = 4014) void newServerAdded(SocketAddress server); @LogMessage(level = WARN) @Message(value = "Failed adding new server %s", id = 4015) void failedAddingNewServer(SocketAddress server, @Cause Throwable e); @LogMessage(level = INFO) @Message(value = "Server not in cluster anymore(%s), removing from the pool.", id = 4016) void removingServer(SocketAddress server); // @LogMessage(level = WARN) // @Message(value = "Unable to convert string property [%s] to an int! Using default value of %d", id = 4018) // void unableToConvertStringPropertyToInt(String value, int defaultValue); // // @LogMessage(level = WARN) // @Message(value = "Unable to convert string property [%s] to a long! Using default value of %d", id = 4019) // void unableToConvertStringPropertyToLong(String value, long defaultValue); // // @LogMessage(level = WARN) // @Message(value = "Unable to convert string property [%s] to a boolean! Using default value of %b", id = 4020) // void unableToConvertStringPropertyToBoolean(String value, boolean defaultValue); @LogMessage(level = INFO) @Message(value = "Infinispan version: %s", id = 4021) void version(String version); @Message(value = "SSL Enabled but no TrustStore specified", id = 4024) CacheConfigurationException noSSLTrustManagerConfiguration(); @Message(value = "A password is required to open the KeyStore '%s'", id = 4025) CacheConfigurationException missingKeyStorePassword(String keyStore); @Message(value = "A password is required to open the TrustStore '%s'", id = 4026) CacheConfigurationException missingTrustStorePassword(String trustStore); @Message(value = "Cannot configure custom KeyStore and/or TrustStore when specifying a SSLContext", id = 4027) CacheConfigurationException xorSSLContext(); @Message(value = "Unable to parse server IP address %s", id = 4028) CacheConfigurationException parseErrorServerAddress(String server); @Message(value = "Invalid max_retries (value=%s). Value should be greater or equal than zero.", id = 4029) CacheConfigurationException invalidMaxRetries(int retriesPerServer); @Message(value = "Cannot enable authentication without specifying either a username, a token, a client Subject or a CallbackHandler", id = 4030) CacheConfigurationException invalidAuthenticationConfiguration(); @Message(value = "The selected authentication mechanism '%s' is not among the supported server mechanisms: %s", id = 4031) SecurityException unsupportedMech(String authMech, List<String> serverMechs); // @Message(value = "'%s' is an invalid SASL mechanism", id = 4032) // CacheConfigurationException invalidSaslMechanism(String saslMechanism); // // @Message(value = "Connection dedicated to listener with id=%s but received event for listener with id=%s", id = 4033) // IllegalStateException unexpectedListenerId(String expectedListenerId, String receivedListenerId); @Message(value = "Unable to unmarshall bytes %s", id = 4034) HotRodClientException unableToUnmarshallBytes(String bytes, @Cause Exception e); @Message(value = "Caught exception [%s] while invoking method [%s] on listener instance: %s", id = 4035) CacheListenerException exceptionInvokingListener(String name, Method m, Object target, @Cause Throwable cause); @Message(value = "Methods annotated with %s must accept exactly one parameter, of assignable from type %s", id = 4036) IncorrectClientListenerException incorrectClientListener(String annotationName, Collection<?> allowedParameters); @Message(value = "Methods annotated with %s should have a return type of void.", id = 4037) IncorrectClientListenerException incorrectClientListener(String annotationName); @LogMessage(level = ERROR) @Message(value = "Unexpected error consuming event %s", id = 4038) void unexpectedErrorConsumingEvent(Object event, @Cause Throwable t); @LogMessage(level = WARN) @Message(value = "Unable to complete reading event from server %s", id = 4039) void unableToReadEventFromServer(@Cause Throwable t, SocketAddress server); @Message(value = "Cache listener class %s must be annotated with org.infinispan.client.hotrod.annotation.ClientListener", id = 4040) IncorrectClientListenerException missingClientListenerAnnotation(String className); @Message(value = "Unknown event type %s received", id = 4041) HotRodClientException unknownEvent(short eventTypeId); @LogMessage(level = ERROR) @Message(value = "Unable to set method %s accessible", id = 4042) void unableToSetAccesible(Method m, @Cause Exception e); // @LogMessage(level = ERROR) // @Message(value = "Unrecoverable error reading event from server %s, exiting listener %s", id = 4043) // void unrecoverableErrorReadingEvent(@Cause Throwable t, SocketAddress server, String listenerId); // // @LogMessage(level = ERROR) // @Message(value = "Unable to read %s bytes %s", id = 4044) // void unableToUnmarshallBytesError(String element, String bytes, @Cause Exception e); @Message(value = "When enabling near caching, number of max entries must be configured", id = 4045) CacheConfigurationException nearCacheMaxEntriesUndefined(); @LogMessage(level = DEBUG) @Message(value = "Successfully closed remote iterator '%s'", id = 4046) void iterationClosed(String iterationId); @Message(value = "Invalid iteration id '%s'", id = 4047) IllegalStateException errorClosingIteration(String iterationId); @Message(value = "Invalid iteration id '%s'", id = 4048) NoSuchElementException errorRetrievingNext(String iterationId); @LogMessage(level = INFO) @Message(value = "Switched to cluster '%s'", id = 4050) void switchedToCluster(String clusterName); @LogMessage(level = INFO) @Message(value = "Switched back to main cluster", id = 4051) void switchedBackToMainCluster(); @LogMessage(level = INFO) @Message(value = "Manually switched to cluster '%s'", id = 4052) void manuallySwitchedToCluster(String clusterName); @LogMessage(level = INFO) @Message(value = "Manually switched back to main cluster", id = 4053) void manuallySwitchedBackToMainCluster(); @Message(value = "Name of the failover cluster needs to be specified", id = 4054) CacheConfigurationException missingClusterNameDefinition(); @Message(value = "Host needs to be specified in server definition of failover cluster", id = 4055) CacheConfigurationException missingHostDefinition(); @Message(value = "At least one server address needs to be specified for failover cluster %s", id = 4056) CacheConfigurationException missingClusterServersDefinition(String siteName); @Message(value = "Duplicate failover cluster %s has been specified", id = 4057) CacheConfigurationException duplicateClusterDefinition(String siteName); @Message(value = "The client listener must use raw data when it uses a query as a filter: %s", id = 4058) IncorrectClientListenerException clientListenerMustUseRawData(String className); @Message(value = "The client listener must use the '%s' filter/converter factory", id = 4059) IncorrectClientListenerException clientListenerMustUseDesignatedFilterConverterFactory(String filterConverterFactoryName); @LogMessage(level = WARN) @Message(value = "Ignoring error when closing iteration '%s'", id = 4061) void ignoringErrorDuringIterationClose(String iterationId, @Cause Throwable e); @LogMessage(level = DEBUG) @Message(value = "Started iteration '%s'", id = 4062) void startedIteration(String iterationId); @LogMessage(level = DEBUG) @Message(value = "Channel to %s obtained for iteration '%s'", id = 4063) void iterationTransportObtained(SocketAddress address, String iterationId); @LogMessage(level = TRACE) @Message(value = "Tracking key %s belonging to segment %d, already tracked? = %b", id = 4064) void trackingSegmentKey(String key, int segment, boolean isTracked); // @LogMessage(level = WARN) // @Message(value = "Classpath does not look correct. Make sure you are not mixing uber and jars", id = 4065) // void warnAboutUberJarDuplicates(); // @LogMessage(level = WARN) // @Message(value = "Unable to convert property [%s] to an enum! Using default value of %d", id = 4066) // void unableToConvertStringPropertyToEnum(String value, String defaultValue); @Message(value = "Cannot specify both a callback handler and a username/token for authentication", id = 4067) CacheConfigurationException callbackHandlerAndUsernameMutuallyExclusive(); // @Message(value = "Class '%s' blocked by Java standard deserialization white list. Adjust the client configuration java serialization white list regular expression to include this class.", id = 4068) // CacheException classNotInWhitelist(String className); @Message(value = "Connection to %s is not active.", id = 4069) TransportException channelInactive(@Param SocketAddress address1, SocketAddress address2); @Message(value = "Failed to add client listener %s, server responded with status %d", id = 4070) HotRodClientException failedToAddListener(Object listener, short status); @Message(value = "Connection to %s was closed while waiting for response.", id = 4071) TransportException connectionClosed(@Param SocketAddress address1, SocketAddress address2); @LogMessage(level = ERROR) @Message(value = "Cannot create another async thread. Please increase 'infinispan.client.hotrod.default_executor_factory.pool_size' (current value is %d).", id = 4072) void cannotCreateAsyncThread(int maxPoolSize); // @LogMessage(level = WARN) // @Message(value = "TransportFactory is deprecated, this setting is not used anymore.", id = 4073) // void transportFactoryDeprecated(); @LogMessage(level = INFO) @Message(value = "Native Epoll transport not available, using NIO instead: %s", id = 4074) void epollNotAvailable(String cause); @Message(value = "TrustStoreFileName and TrustStorePath are mutually exclusive", id = 4075) CacheConfigurationException trustStoreFileAndPathExclusive(); @Message(value = "Unknown message id %d; cannot find matching request", id = 4076) IllegalStateException unknownMessageId(long messageId); @Message(value = "Closing channel %s due to error in unknown operation.", id = 4077) TransportException errorFromUnknownOperation(Channel channel, @Cause Throwable cause, @Param SocketAddress address); @Message(value = "This channel is about to be closed and does not accept any further operations.", id = 4078) HotRodClientException noMoreOperationsAllowed(); @Message(value = "Unexpected listenerId %s", id = 4079) IllegalStateException unexpectedListenerId(String listenerId); @Message(value = "Event should use messageId of previous Add Client Listener operation but id is %d and operation is %s", id = 4080) IllegalStateException operationIsNotAddClientListener(long messageId, String operation); @Message(value = "TransactionMode must be non-null.", id = 4082) CacheConfigurationException invalidTransactionMode(); @Message(value = "TransactionManagerLookup must be non-null", id = 4083) CacheConfigurationException invalidTransactionManagerLookup(); @Message(value = "Cache %s doesn't support transactions. Please check the documentation how to configure it properly.", id = 4084) CacheNotTransactionalException cacheDoesNotSupportTransactions(String name); @LogMessage(level = ERROR) @Message(value = "Error checking server configuration for transactional cache %s", id = 4085) void invalidTxServerConfig(String name, @Cause Throwable throwable); @LogMessage(level = WARN) @Message(value = "Exception caught while preparing transaction %s", id = 4086) void exceptionDuringPrepare(Xid xid, @Cause Exception e); @LogMessage(level = WARN) @Message(value = "Use of maxIdle expiration with a near cache is unsupported.", id = 4087) void nearCacheMaxIdleUnsupported(); @Message(value = "Transactions timeout must be positive", id = 4088) HotRodClientException invalidTransactionTimeout(); @Message(value = "TransactionTable is not started!", id = 4089) HotRodClientException transactionTableNotStarted(); @Message(value = "[%s] Invalid response operation. Expected %#x and received %#x", id = 4090) InvalidResponseException invalidResponse(String cacheName, short opRespCode, double receivedOpCode); @Message(value = "MBean registration failed", id = 4091) HotRodClientException jmxRegistrationFailure(@Cause Throwable cause); @Message(value = "MBean unregistration failed", id = 4092) HotRodClientException jmxUnregistrationFailure(@Cause Throwable cause); @Message(value = "OAUTHBEARER mechanism selected without providing a token", id = 4093) CacheConfigurationException oauthBearerWithoutToken(); @Message(value = "Cannot specify both template name and configuration for '%s'", id = 4094) CacheConfigurationException remoteCacheTemplateNameXorConfiguration(String name); @Message(value = "Not a Hot Rod URI: %s", id = 4095) IllegalArgumentException notaHotRodURI(String uri); @Message(value = "Invalid property format in URI: %s", id = 4096) IllegalArgumentException invalidPropertyFormat(String part); @Message(value = "Illegal attempt to redefine an already existing cache configuration: %s", id = 4097) IllegalArgumentException duplicateCacheConfiguration(String name); @LogMessage(level = WARN) @Message(value = "Closing connection %s due to transport error", id = 4098) void closingChannelAfterError(Channel channel, @Cause Throwable t); @LogMessage(level = WARN) @Message(value = "Remote iteration over the entire result set of query '%s' without using pagination options is inefficient for large result sets. Please consider using 'startOffset' and 'maxResults' options.", id = 4099) void warnPerfRemoteIterationWithoutPagination(String query); @LogMessage(level = WARN) @Message(value = "Error reaching the server during iteration", id = 4100) void throwableDuringPublisher(@Cause Throwable t); @LogMessage(level = WARN) @Message(value = "Configuration property '%s' has been deprecated", id = 4101) void deprecatedConfigurationProperty(String property); @Message(value = "Near cache number of max entries must be a positive number when using bloom filter optimization, it was %d", id = 4102) CacheConfigurationException nearCacheMaxEntriesPositiveWithBloom(int maxEntries); @Message(value = "Near cache with bloom filter requires pool max active to be 1, was %s, and exhausted action to be WAIT, was %s", id = 4103) CacheConfigurationException bloomFilterRequiresMaxActiveOneAndWait(int maxActive, ExhaustedAction action); @LogMessage(level = WARN) @Message(value = "Failed to load and create an optional ProtoStream serialization context initializer: %s", id = 4104) void failedToCreatePredefinedSerializationContextInitializer(String className, @Cause Throwable throwable); @LogMessage(level = WARN) @Message(value = "Reverting to the initial server list for caches %s", id = 4105) void revertCacheToInitialServerList(Collection<String> cacheName); @LogMessage(level = WARN) @Message(value = "Invalid active count after closing channel %s", id = 4106) void invalidActiveCountAfterClose(Channel channel); @LogMessage(level = WARN) @Message(value = "Invalid created count after closing channel %s", id = 4107) void invalidCreatedCountAfterClose(Channel channel); @LogMessage(level = INFO) @Message(value = "Native IOUring transport not available, using NIO instead: %s", id = 4108) void ioUringNotAvailable(String cause); @LogMessage(level = DEBUG) @Message(value = "OpenTelemetry API is not present in the classpath. Client context tracing will not be propagated.", id = 4109) void noOpenTelemetryAPI(@Cause Throwable throwable); @LogMessage(level = DEBUG) @Message(value = "OpenTelemetry API is present in the classpath and the tracing propagation is enabled. Client context tracing will be propagated.", id = 4110) void openTelemetryPropagationEnabled(); @LogMessage(level = DEBUG) @Message(value = "OpenTelemetry API is present in the classpath, but the tracing propagation is not enabled. Client context tracing will not be propagated.", id = 4111) void openTelemetryPropagationDisabled(); }
20,047
48.746898
224
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/logging/LogFactory.java
package org.infinispan.client.hotrod.logging; import org.jboss.logging.Logger; /** * Factory that creates {@link Log} instances. * * @author Manik Surtani * @since 4.0 */ public class LogFactory { public static Log getLog(Class<?> clazz) { return Logger.getMessageLogger(Log.class, clazz.getName()); } public static <T> T getLog(Class<?> clazz, Class<T> logClass) { return Logger.getMessageLogger(logClass, clazz.getName()); } }
463
20.090909
66
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/filter/Filters.java
package org.infinispan.client.hotrod.filter; import java.util.Map; import org.infinispan.query.dsl.Query; /** * @author gustavonalle * @since 8.1 */ public final class Filters { /** * The name of the factory used for query DSL based filters and converters. This factory is provided internally by * the server. */ public static final String QUERY_DSL_FILTER_FACTORY_NAME = "query-dsl-filter-converter-factory"; public static final String ITERATION_QUERY_FILTER_CONVERTER_FACTORY_NAME = "iteration-filter-converter-factory"; public static final String CONTINUOUS_QUERY_FILTER_FACTORY_NAME = "continuous-query-filter-converter-factory"; private Filters() { } public static Object[] makeFactoryParams(String queryString, Map<String, Object> namedParameters) { if (namedParameters == null) { return new Object[]{queryString}; } Object[] factoryParams = new Object[1 + namedParameters.size() * 2]; factoryParams[0] = queryString; int i = 1; for (Map.Entry<String, Object> e : namedParameters.entrySet()) { factoryParams[i++] = e.getKey(); factoryParams[i++] = e.getValue(); } return factoryParams; } public static Object[] makeFactoryParams(Query<?> query) { return makeFactoryParams(query.getQueryString(), query.getParameters()); } }
1,365
30.045455
117
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/jmx/RemoteCacheClientStatisticsMXBean.java
package org.infinispan.client.hotrod.jmx; /** * RemoteCache client-side statistics (such as number of connections) */ public interface RemoteCacheClientStatisticsMXBean { /** * Returns the number of hits for a remote cache. */ long getRemoteHits(); /** * Returns the number of misses for a remote cache. */ long getRemoteMisses(); /** * Returns the average read time, in milliseconds, for a remote cache. */ long getAverageRemoteReadTime(); /** * Returns the number of remote cache stores (put, replace) that the client applied. * Failed conditional operations do not increase the count of entries in the remote cache. Put operations always increase the count even if an operation replaces an equal value. */ long getRemoteStores(); /** * Returns the average store time, in milliseconds, for a remote cache. */ long getAverageRemoteStoreTime(); /** * Returns the number of removes for a remote cache. */ long getRemoteRemoves(); /** * Returns the average time, in milliseconds, for remove operations in a remote cache. */ long getAverageRemoteRemovesTime(); /** * Returns the number of near-cache hits. Returns a value of 0 if near-caching is disabled. */ long getNearCacheHits(); /** * Returns the number of near-cache misses. Returns a value of 0 if near-caching is disabled. */ long getNearCacheMisses(); /** * Returns the number of near-cache invalidations. Returns a value of 0 if near-caching is disabled. */ long getNearCacheInvalidations(); /** * Returns the number of entries currently stored in the near-cache. Returns a value of 0 if near-caching is disabled. */ long getNearCacheSize(); /** * Resets statistics. */ void resetStatistics(); /** * Returns the time, in seconds, since the last reset. See {@link #resetStatistics()} */ long getTimeSinceReset(); }
1,973
25.675676
180
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/jmx/RemoteCacheManagerMXBean.java
package org.infinispan.client.hotrod.jmx; /** * RemoteCacheManager client-side statistics and operations */ public interface RemoteCacheManagerMXBean { /** * Returns a list of servers to which the client is currently connected in the format of ip_address:port_number. */ String[] getServers(); /** * Returns the number of active connections */ int getActiveConnectionCount(); /** * Returns the total number of connections */ int getConnectionCount(); /** * Returns the number of idle connections */ int getIdleConnectionCount(); /** * Returns the total number of retries that have been executed */ long getRetries(); /** * Switch remote cache manager to a different cluster, previously * declared via configuration. If the switch was completed successfully, * this method returns {@code true}, otherwise it returns {@code false}. * * @param clusterName name of the cluster to which to switch to * @return {@code true} if the cluster was switched, {@code false} otherwise */ boolean switchToCluster(String clusterName); /** * Switch remote cache manager to a the default cluster, previously * declared via configuration. If the switch was completed successfully, * this method returns {@code true}, otherwise it returns {@code false}. * * @return {@code true} if the cluster was switched, {@code false} otherwise */ boolean switchToDefaultCluster(); }
1,494
28.313725
115
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/multimap/MultimapCacheManager.java
package org.infinispan.client.hotrod.multimap; import org.infinispan.commons.util.Experimental; @Experimental public interface MultimapCacheManager<K, V> { /** * Retrieves a named multimap cache from the system. * * @param name, name of multimap cache to retrieve * @return null if no configuration exists as per rules set above, otherwise returns a multimap cache instance * identified by cacheName and doesn't support duplicates */ default RemoteMultimapCache<K, V> get(String name) { return get(name, false); } /** * Retrieves a named multimap cache from the system. * * @param name, name of multimap cache to retrieve * @param supportsDuplicates, boolean check for identifying whether it supports duplicates or not. * @return null if no configuration exists as per rules set above, otherwise returns a multimap cache instance * identified by cacheName */ RemoteMultimapCache<K, V> get(String name, boolean supportsDuplicates); }
1,010
33.862069
113
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/multimap/RemoteMultimapCacheManager.java
package org.infinispan.client.hotrod.multimap; import java.util.Collection; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.multimap.RemoteMultimapCacheImpl; /** * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class RemoteMultimapCacheManager<K, V> implements MultimapCacheManager<K, V> { private final RemoteCacheManager remoteCacheManager; public RemoteMultimapCacheManager(RemoteCacheManager remoteCacheManager) { this.remoteCacheManager = remoteCacheManager; } @Override public RemoteMultimapCache<K, V> get(String cacheName, boolean supportsDuplicates) { RemoteCache<K, Collection<V>> cache = remoteCacheManager.getCache(cacheName); RemoteMultimapCacheImpl<K, V> multimapCache = new RemoteMultimapCacheImpl<>(remoteCacheManager, cache, supportsDuplicates); multimapCache.init(); return multimapCache; } }
983
32.931034
129
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/multimap/RemoteMultimapCache.java
package org.infinispan.client.hotrod.multimap; import java.util.concurrent.CompletableFuture; import org.infinispan.multimap.api.BasicMultimapCache; /** * {@inheritDoc} * <p> * Remote MultimapCache interface used for server mode. * * @author Katia Aresti, karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Infinispan documentation</a> * @since 9.2 */ public interface RemoteMultimapCache<K, V> extends BasicMultimapCache<K, V> { /** * Returns a {@link MetadataCollection<V>} of the values associated with key in this multimap cache, * if any. Any changes to the retrieved collection won't change the values in this multimap cache. * <b>When this method returns an empty metadata collection, it means the key was not found.</b> * * @param key to be retrieved * @return the collection with the metadata of the given key */ CompletableFuture<MetadataCollection<V>> getWithMetadata(K key); }
958
32.068966
103
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/multimap/RemoteMultimapCacheManagerFactory.java
package org.infinispan.client.hotrod.multimap; import org.infinispan.client.hotrod.RemoteCacheManager; /** * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public final class RemoteMultimapCacheManagerFactory { private RemoteMultimapCacheManagerFactory() { } public static <K, V> MultimapCacheManager<K, V> from(RemoteCacheManager remoteCacheManager) { return new RemoteMultimapCacheManager<>(remoteCacheManager); } }
453
24.222222
96
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/multimap/MetadataCollection.java
package org.infinispan.client.hotrod.multimap; import java.util.Collection; import org.infinispan.client.hotrod.Metadata; import org.infinispan.client.hotrod.Versioned; /** * Metadata and collection, used for Multimap * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public interface MetadataCollection<V> extends Versioned, Metadata { /** * Collection of values with metadata * @return the collection */ Collection<V> getCollection(); }
477
20.727273
68
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/package-info.java
/** * Hot Rod client exceptions. * * @api.public */ package org.infinispan.client.hotrod.exceptions;
105
14.142857
48
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/RemoteNodeSuspectException.java
package org.infinispan.client.hotrod.exceptions; /** * When a remote node is suspected and evicted from the cluster while an * operation is ongoing, the Hot Rod client emits this exception. * * @author Galder Zamarreño * @since 4.2 */ public class RemoteNodeSuspectException extends HotRodClientException { public RemoteNodeSuspectException(String msgFromServer, long messageId, short status) { super(msgFromServer, messageId, status); } }
461
26.176471
90
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/RemoteIllegalLifecycleStateException.java
package org.infinispan.client.hotrod.exceptions; import java.net.SocketAddress; /** * This exception is thrown when the remote cache or cache manager does not * have the right lifecycle state for operations to be called on it. Situations * like this include when the cache is stopping or is stopped, when the cache * manager is stopped...etc. * * @since 7.0 */ public class RemoteIllegalLifecycleStateException extends HotRodClientException { private final SocketAddress serverAddress; @Deprecated public RemoteIllegalLifecycleStateException(String msgFromServer, long messageId, short status) { super(msgFromServer, messageId, status); this.serverAddress = null; } public RemoteIllegalLifecycleStateException(String msgFromServer, long messageId, short status, SocketAddress serverAddress) { super(msgFromServer, messageId, status); this.serverAddress = serverAddress; } public SocketAddress getServerAddress() { return serverAddress; } }
1,008
29.575758
129
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/HotRodTimeoutException.java
package org.infinispan.client.hotrod.exceptions; /** * Signals an remote timeout(due to locking) in the infinispan server. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class HotRodTimeoutException extends HotRodClientException { public HotRodTimeoutException() { } public HotRodTimeoutException(String message) { super(message); } public HotRodTimeoutException(Throwable cause) { super(cause); } public HotRodTimeoutException(String message, Throwable cause) { super(message, cause); } public HotRodTimeoutException(String remoteMessage, long messageId, int errorStatusCode) { super(remoteMessage, messageId, errorStatusCode); } }
709
23.482759
93
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/ParallelOperationException.java
package org.infinispan.client.hotrod.exceptions; /** * @author Guillaume Darmont / guillaume@dropinocean.com */ public class ParallelOperationException extends HotRodClientException { public ParallelOperationException(String message) { super(message); } public ParallelOperationException(Throwable cause) { super(cause); } public ParallelOperationException(String message, Throwable cause) { super(message, cause); } }
461
22.1
71
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/RemoteCacheManagerNotStartedException.java
package org.infinispan.client.hotrod.exceptions; /** * Thrown when trying to use an {@link org.infinispan.client.hotrod.RemoteCache} that is associated to an * {@link org.infinispan.client.hotrod.RemoteCacheManager} that was not started. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class RemoteCacheManagerNotStartedException extends HotRodClientException { public RemoteCacheManagerNotStartedException(String message) { super(message); } }
476
28.8125
105
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/InvalidResponseException.java
package org.infinispan.client.hotrod.exceptions; /** * Signals an internal protocol error. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class InvalidResponseException extends HotRodClientException { public InvalidResponseException() { } public InvalidResponseException(String message) { super(message); } public InvalidResponseException(String message, Throwable cause) { super(message, cause); } public InvalidResponseException(Throwable cause) { super(cause); } }
531
20.28
69
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/CacheNotTransactionalException.java
package org.infinispan.client.hotrod.exceptions; /** * When try to create a transactional {@code org.infinispan.client.hotrod.RemoteCache} but the cache in the Hot Rod * server isn't transactional, this exception is thrown. * * Check if the cache is properly configured in the server configuration. * * @author Pedro Ruivo * @since 10.0 */ public class CacheNotTransactionalException extends HotRodClientException { public CacheNotTransactionalException() { } public CacheNotTransactionalException(String message) { super(message); } public CacheNotTransactionalException(Throwable cause) { super(cause); } public CacheNotTransactionalException(String message, Throwable cause) { super(message, cause); } public CacheNotTransactionalException(String remoteMessage, long messageId, int errorStatusCode) { super(remoteMessage, messageId, errorStatusCode); } }
925
27.9375
115
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/HotRodClientException.java
package org.infinispan.client.hotrod.exceptions; /** * Base class for exceptions reported by the hot rod client. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class HotRodClientException extends RuntimeException { private long messageId = -1; private int errorStatusCode = -1; public HotRodClientException() { } public HotRodClientException(String message) { super(message); } public HotRodClientException(Throwable cause) { super(cause); } public HotRodClientException(String message, Throwable cause) { super(message, cause); } public HotRodClientException(String remoteMessage, long messageId, int errorStatusCode) { super(remoteMessage); this.messageId = messageId; this.errorStatusCode = errorStatusCode; } @Override public String toString() { StringBuilder sb = new StringBuilder(getClass().getName()); sb.append(":"); if (messageId != -1) sb.append("Request for messageId=").append(messageId); if (errorStatusCode != -1) sb.append(" returned ").append(toErrorMsg(errorStatusCode)); String message = getLocalizedMessage(); if (message != null) sb.append(": ").append(message); return sb.toString(); } private String toErrorMsg(int errorStatusCode) { return String.format("server error (status=0x%x)", errorStatusCode); } public boolean isServerError() { return errorStatusCode != -1; } }
1,468
26.716981
93
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/exceptions/TransportException.java
package org.infinispan.client.hotrod.exceptions; import java.net.SocketAddress; /** * Indicates a communication exception with the Hot Rod server: e.g. TCP connection is broken while reading a response * from the server. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class TransportException extends HotRodClientException { private final SocketAddress serverAddress; public TransportException(String message, SocketAddress serverAddress) { super(message); this.serverAddress = serverAddress; } public TransportException(String message, Throwable cause, SocketAddress serverAddress) { super(message, cause); this.serverAddress = serverAddress; } public TransportException(Throwable cause, SocketAddress serverAddress) { super(cause); this.serverAddress = serverAddress; } public SocketAddress getServerAddress() { return serverAddress; } }
935
25
118
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/package-info.java
/** * Hot Rod client remote event API. * * @api.public */ package org.infinispan.client.hotrod.event;
106
14.285714
43
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientCacheEntryCreatedEvent.java
package org.infinispan.client.hotrod.event; /** * Client side cache entry created events provide information on the created * key, and the version of the entry. This version can be used to invoke conditional * operations on the server, such as * {@link org.infinispan.client.hotrod.RemoteCache#replaceWithVersion(Object, Object, long)} * or {@link org.infinispan.client.hotrod.RemoteCache#removeWithVersion(Object, long)} * * @param <K> type of key created. */ public interface ClientCacheEntryCreatedEvent<K> extends ClientEvent { /** * Created cache entry's key. * @return an instance of the key with which a cache entry has been * created in the remote server(s). */ K getKey(); /** * Provides access to the version of the created cache entry. This version * can be used to invoke conditional operations on the server, such as * {@link org.infinispan.client.hotrod.RemoteCache#replaceWithVersion(Object, Object, long)} * or {@link org.infinispan.client.hotrod.RemoteCache#removeWithVersion(Object, long)} * * @return a long containing the version of the created cache entry. */ long getVersion(); /** * This will be true if the write command that caused this had to be retried * again due to a topology change. This could be a sign that this event * has been duplicated or another event was dropped and replaced * (eg: ModifiedEvent replaced CreateEvent) * * @return Whether the command that caused this event was retried */ boolean isCommandRetried(); }
1,562
36.214286
95
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientCacheFailoverEvent.java
package org.infinispan.client.hotrod.event; /** * Event received when the registered listener fails over to a different node. * Receiving this event indicates that a failure happened in the node where * the listener was registered in and another server has been selected for * installing the listener in. As a result of this failover, some events might * have been missed, hence, this event can be used to clear locally cached * data. After this failover event is received, the entire cache contents will * be iterated over and the client receives events on these contents, which * can be used to rebuild any locally built cache. * * @author Galder Zamarreño * @since 7.0 */ public interface ClientCacheFailoverEvent extends ClientEvent { }
755
38.789474
78
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientCacheEntryModifiedEvent.java
package org.infinispan.client.hotrod.event; /** * Client side cache entry modified events provide information on the modified * key, and the version of the entry after the modification. This version can * be used to invoke conditional operations on the server, such as * {@link org.infinispan.client.hotrod.RemoteCache#replaceWithVersion(Object, Object, long)} * or {@link org.infinispan.client.hotrod.RemoteCache#removeWithVersion(Object, long)} * * @param <K> type of key created. */ public interface ClientCacheEntryModifiedEvent<K> extends ClientEvent { /** * Modifiedcache entry's key. * @return an instance of the key with which a cache entry has been * modified in the remote server(s). */ K getKey(); /** * Provides access to the version of the modified cache entry. This version * can be used to invoke conditional operations on the server, such as * {@link org.infinispan.client.hotrod.RemoteCache#replaceWithVersion(Object, Object, long)} * or {@link org.infinispan.client.hotrod.RemoteCache#removeWithVersion(Object, long)} * * @return a long containing the version of the modified cache entry. */ long getVersion(); /** * This will be true if the write command that caused this had to be retried * again due to a topology change. This could be a sign that this event * has been duplicated or another event was dropped and replaced * (eg: ModifiedEvent replaced CreateEvent) * * @return Whether the command that caused this event was retried */ boolean isCommandRetried(); }
1,591
36.904762
95
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientEvent.java
package org.infinispan.client.hotrod.event; /** * @author Galder Zamarreño */ public interface ClientEvent { enum Type { CLIENT_CACHE_ENTRY_CREATED, CLIENT_CACHE_ENTRY_MODIFIED, CLIENT_CACHE_ENTRY_REMOVED, CLIENT_CACHE_ENTRY_EXPIRED, CLIENT_CACHE_FAILOVER } Type getType(); }
320
16.833333
43
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientCacheEntryRemovedEvent.java
package org.infinispan.client.hotrod.event; /** * Client side cache entry removed events provide information on the removed key. * * @param <K> type of key created. */ public interface ClientCacheEntryRemovedEvent<K> extends ClientEvent { /** * Created cache entry's key. * @return an instance of the key with which a cache entry has been * created in remote server. */ K getKey(); /** * This will be true if the write command that caused this had to be retried * again due to a topology change. This could be a sign that this event * has been duplicated or another event was dropped and replaced * (eg: ModifiedEvent replaced CreateEvent) * * @return Whether the command that caused this event was retried */ boolean isCommandRetried(); }
805
27.785714
81
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientEvents.java
package org.infinispan.client.hotrod.event; import static org.infinispan.client.hotrod.filter.Filters.makeFactoryParams; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.impl.ClientEventDispatcher; import org.infinispan.client.hotrod.filter.Filters; import org.infinispan.commons.util.ReflectionUtil; import org.infinispan.query.dsl.Query; public class ClientEvents { private ClientEvents() { // Static helper class, cannot be constructed } /** * @deprecated since 10.1.2. Will be removed in 11 without replacement. */ @Deprecated public static ClientCacheFailoverEvent mkCachefailoverEvent() { //todo make ClientEventDispatcher.FAILOVER_EVENT_SINGLETON private after removing this deprecated method in 11 return ClientEventDispatcher.FAILOVER_EVENT_SINGLETON; } /** * Register a client listener that uses a query DSL based filter. The listener is expected to be annotated such that * {@link org.infinispan.client.hotrod.annotation.ClientListener#useRawData} = true and {@link * org.infinispan.client.hotrod.annotation.ClientListener#filterFactoryName} and {@link * org.infinispan.client.hotrod.annotation.ClientListener#converterFactoryName} are equal to {@link * Filters#QUERY_DSL_FILTER_FACTORY_NAME} * * @param remoteCache the remote cache to attach the listener * @param listener the listener instance * @param query the query to be used for filtering and conversion (if projections are used) */ public static void addClientQueryListener(RemoteCache<?, ?> remoteCache, Object listener, Query<?> query) { ClientListener l = ReflectionUtil.getAnnotation(listener.getClass(), ClientListener.class); if (l == null) { throw HOTROD.missingClientListenerAnnotation(listener.getClass().getName()); } if (!l.useRawData()) { throw HOTROD.clientListenerMustUseRawData(listener.getClass().getName()); } if (!l.filterFactoryName().equals(Filters.QUERY_DSL_FILTER_FACTORY_NAME)) { throw HOTROD.clientListenerMustUseDesignatedFilterConverterFactory(Filters.QUERY_DSL_FILTER_FACTORY_NAME); } if (!l.converterFactoryName().equals(Filters.QUERY_DSL_FILTER_FACTORY_NAME)) { throw HOTROD.clientListenerMustUseDesignatedFilterConverterFactory(Filters.QUERY_DSL_FILTER_FACTORY_NAME); } Object[] factoryParams = makeFactoryParams(query); remoteCache.addClientListener(listener, factoryParams, null); } }
2,664
45.754386
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/IncorrectClientListenerException.java
package org.infinispan.client.hotrod.event; import org.infinispan.client.hotrod.exceptions.HotRodClientException; /** * @author Galder Zamarreño */ public class IncorrectClientListenerException extends HotRodClientException { public IncorrectClientListenerException(String message) { super(message); } }
320
23.692308
77
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientCacheEntryExpiredEvent.java
package org.infinispan.client.hotrod.event; /** * Client side cache entry expired events provide information on the expired key. * * @param <K> type of key expired. */ public interface ClientCacheEntryExpiredEvent<K> extends ClientEvent { /** * Created cache entry's key. * @return an instance of the key with which a cache entry has been * created in remote server. */ K getKey(); }
412
23.294118
81
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/ClientCacheEntryCustomEvent.java
package org.infinispan.client.hotrod.event; /** * The events generated by default contain just enough information to make the * event relevant but they avoid cramming too much information in order to reduce * the cost of sending them. Optionally, the information shipped in the events * can be customised in order to contain more information, such as values, or to * contain even less information. This customization is done with {@link org.infinispan.filter.Converter} * instances generated by a {@link org.infinispan.filter.ConverterFactory}. * * As a result of this conversion, custom events are reprenseted by this class, * and are expected in methods annotation with either * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated}, * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryModified} or, * {@link org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved}. * The event parameter for any of these callbacks is always a {@link ClientCacheEntryCustomEvent}, * and if needed, the event's {@link org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent#getType()} * can be queried to find out whether the originating event was the result of create, * modified or removed. * * @param <T> Type of customized event data. It needs to be marshallable. */ public interface ClientCacheEntryCustomEvent<T> extends ClientEvent { /** * Customized event data. It can be any type as long as it can be converted * to binary format for shipping between the server and client. * * @return an instance of the customised event data. */ T getEventData(); /** * This will be true if the write command that caused this had to be retried * again due to a topology change. This could be a sign that this event * has been duplicated or another event was dropped and replaced * (eg: ModifiedEvent replaced CreateEvent) * * @return Whether the command that caused this event was retried */ boolean isCommandRetried(); }
2,031
45.181818
110
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/ExpiredEventImpl.java
package org.infinispan.client.hotrod.event.impl; import org.infinispan.client.hotrod.event.ClientCacheEntryExpiredEvent; public class ExpiredEventImpl<K> extends AbstractClientEvent implements ClientCacheEntryExpiredEvent<K> { private final K key; public ExpiredEventImpl(byte[] listenerId, K key) { super(listenerId); this.key = key; } @Override public K getKey() { return key; } @Override public Type getType() { return Type.CLIENT_CACHE_ENTRY_EXPIRED; } @Override public String toString() { return "ExpiredEventImpl(" + "key=" + key + ")"; } }
619
21.142857
105
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/RemovedEventImpl.java
package org.infinispan.client.hotrod.event.impl; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; public class RemovedEventImpl<K> extends AbstractClientEvent implements ClientCacheEntryRemovedEvent<K> { private final K key; private final boolean retried; public RemovedEventImpl(byte[] listenerId, K key, boolean retried) { super(listenerId); this.key = key; this.retried = retried; } @Override public K getKey() { return key; } @Override public boolean isCommandRetried() { return retried; } @Override public Type getType() { return Type.CLIENT_CACHE_ENTRY_REMOVED; } @Override public String toString() { return "RemovedEventImpl(" + "key=" + key + ")"; } }
780
21.314286
105
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/ClientEventDispatcher.java
package org.infinispan.client.hotrod.event.impl; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientCacheFailover; import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryExpiredEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; import org.infinispan.client.hotrod.event.ClientCacheFailoverEvent; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.InvalidatedNearRemoteCache; import org.infinispan.client.hotrod.impl.operations.ClientListenerOperation; import org.infinispan.commons.util.ReflectionUtil; import org.infinispan.commons.util.Util; public final class ClientEventDispatcher extends EventDispatcher<ClientEvent> { public static final ClientCacheFailoverEvent FAILOVER_EVENT_SINGLETON = () -> ClientEvent.Type.CLIENT_CACHE_FAILOVER; private static final Map<Class<? extends Annotation>, Class<?>[]> allowedListeners = new HashMap<>(5); static { allowedListeners.put(ClientCacheEntryCreated.class, new Class[]{ClientCacheEntryCreatedEvent.class, ClientCacheEntryCustomEvent.class}); allowedListeners.put(ClientCacheEntryModified.class, new Class[]{ClientCacheEntryModifiedEvent.class, ClientCacheEntryCustomEvent.class}); allowedListeners.put(ClientCacheEntryRemoved.class, new Class[]{ClientCacheEntryRemovedEvent.class, ClientCacheEntryCustomEvent.class}); allowedListeners.put(ClientCacheEntryExpired.class, new Class[]{ClientCacheEntryExpiredEvent.class, ClientCacheEntryCustomEvent.class}); allowedListeners.put(ClientCacheFailover.class, new Class[]{ClientCacheFailoverEvent.class}); } private final Map<Class<? extends Annotation>, List<ClientListenerInvocation>> invocables; private final ClientListenerOperation op; private final InternalRemoteCache<?, ?> remoteCache; ClientEventDispatcher(ClientListenerOperation op, SocketAddress address, Map<Class<? extends Annotation>, List<ClientListenerInvocation>> invocables, String cacheName, Runnable cleanup, InternalRemoteCache<?, ?> remoteCache) { super(cacheName, op.listener, op.listenerId, address, cleanup); this.op = op; this.invocables = invocables; this.remoteCache = remoteCache; } public static ClientEventDispatcher create(ClientListenerOperation op, SocketAddress address, Runnable cleanup, InternalRemoteCache<?, ?> remoteCache) { Map<Class<? extends Annotation>, List<ClientEventDispatcher.ClientListenerInvocation>> invocables = findMethods(op.listener); return new ClientEventDispatcher(op, address, invocables, op.getCacheName(), cleanup, remoteCache); } public static Map<Class<? extends Annotation>, List<ClientEventDispatcher.ClientListenerInvocation>> findMethods(Object listener) { Map<Class<? extends Annotation>, List<ClientEventDispatcher.ClientListenerInvocation>> listenerMethodMap = new HashMap<>(4, 0.99f); for (Method m : listener.getClass().getMethods()) { // loop through all valid method annotations for (Map.Entry<Class<? extends Annotation>, Class<?>[]> entry : allowedListeners.entrySet()) { Class<? extends Annotation> annotationType = entry.getKey(); Class<?>[] eventTypes = entry.getValue(); if (m.isAnnotationPresent(annotationType)) { testListenerMethodValidity(m, eventTypes, annotationType.getName()); ReflectionUtil.setAccessible(m); ClientEventDispatcher.ClientListenerInvocation invocation = new ClientEventDispatcher.ClientListenerInvocation(listener, m); listenerMethodMap.computeIfAbsent(annotationType, a -> new ArrayList<>()).add(invocation); } } } return listenerMethodMap; } static void testListenerMethodValidity(Method m, Class<?>[] allowedParameters, String annotationName) { boolean isAllowed = false; for (Class<?> allowedParameter : allowedParameters) { if (m.getParameterCount() == 1 && m.getParameterTypes()[0].isAssignableFrom(allowedParameter)) { isAllowed = true; break; } } if (!isAllowed) throw HOTROD.incorrectClientListener(annotationName, Arrays.asList(allowedParameters)); if (!m.getReturnType().equals(void.class)) throw HOTROD.incorrectClientListener(annotationName); } @Override public void invokeEvent(ClientEvent clientEvent) { if (log.isTraceEnabled()) log.tracef("Event %s received for listener with id=%s", clientEvent, Util.printArray(listenerId)); switch (clientEvent.getType()) { case CLIENT_CACHE_ENTRY_CREATED: invokeCallbacks(clientEvent, ClientCacheEntryCreated.class); break; case CLIENT_CACHE_ENTRY_MODIFIED: invokeCallbacks(clientEvent, ClientCacheEntryModified.class); break; case CLIENT_CACHE_ENTRY_REMOVED: invokeCallbacks(clientEvent, ClientCacheEntryRemoved.class); break; case CLIENT_CACHE_ENTRY_EXPIRED: invokeCallbacks(clientEvent, ClientCacheEntryExpired.class); break; } } private void invokeCallbacks(ClientEvent event, Class<? extends Annotation> type) { List<ClientListenerInvocation> callbacks = invocables.get(type); if (callbacks != null) { for (ClientListenerInvocation callback : callbacks) callback.invoke(event); } } @Override public CompletableFuture<Void> executeFailover() { CompletableFuture<SocketAddress> future = op.copy().execute(); if (remoteCache instanceof InvalidatedNearRemoteCache) { future = future.thenApply(socketAddress -> { ((InvalidatedNearRemoteCache<?, ?>) remoteCache).setBloomListenerAddress(socketAddress); return socketAddress; }); } return future.thenApply(ignore -> null); } @Override protected void invokeFailoverEvent() { List<ClientListenerInvocation> callbacks = invocables.get(ClientCacheFailover.class); if (callbacks != null) { for (ClientListenerInvocation callback : callbacks) { callback.invoke(FAILOVER_EVENT_SINGLETON); } } } DataFormat getDataFormat() { return op.dataFormat(); } static final class ClientListenerInvocation { final Object listener; final Method method; private ClientListenerInvocation(Object listener, Method method) { this.listener = listener; this.method = method; } public void invoke(ClientEvent event) { try { method.invoke(listener, event); } catch (Exception e) { throw HOTROD.exceptionInvokingListener( e.getClass().getName(), method, listener, e); } } } }
7,853
43.625
144
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/EventDispatcher.java
package org.infinispan.client.hotrod.event.impl; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; public abstract class EventDispatcher<T> { static final Log log = LogFactory.getLog(EventDispatcher.class); private static final AtomicReferenceFieldUpdater<EventDispatcher, DispatcherStatus> statusUpdater = AtomicReferenceFieldUpdater.newUpdater(EventDispatcher.class, DispatcherStatus.class, "status"); final Object listener; final byte[] listenerId; final SocketAddress address; final String cacheName; final Runnable cleanup; private volatile DispatcherStatus status = DispatcherStatus.STOPPED; EventDispatcher(String cacheName, Object listener, byte[] listenerId, SocketAddress address, Runnable cleanup) { this.listener = listener; this.listenerId = listenerId; this.address = address; this.cacheName = cacheName; this.cleanup = cleanup; } public boolean start() { return statusUpdater.compareAndSet(this, EventDispatcher.DispatcherStatus.STOPPED, EventDispatcher.DispatcherStatus.RUNNING); } public boolean stop() { boolean stopped = statusUpdater.compareAndSet(this, DispatcherStatus.RUNNING, DispatcherStatus.STOPPED); if (stopped && cleanup != null) { cleanup.run(); } return stopped; } public boolean isRunning() { return status == DispatcherStatus.RUNNING; } public abstract CompletableFuture<Void> executeFailover(); protected abstract void invokeEvent(T event); protected void invokeFailoverEvent() {} public SocketAddress address() { return address; } enum DispatcherStatus { STOPPED, RUNNING } }
1,892
30.032787
131
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/CounterEventDispatcher.java
package org.infinispan.client.hotrod.event.impl; import java.net.SocketAddress; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; import java.util.function.Supplier; import org.infinispan.client.hotrod.counter.impl.HotRodCounterEvent; public class CounterEventDispatcher extends EventDispatcher<HotRodCounterEvent> { private final ConcurrentMap<String, List<Consumer<HotRodCounterEvent>>> clientListeners; private final Supplier<CompletableFuture<Void>> failover; public CounterEventDispatcher(byte[] listenerId, ConcurrentMap<String, List<Consumer<HotRodCounterEvent>>> clientListeners, SocketAddress address, Supplier<CompletableFuture<Void>> failover, Runnable cleanup) { super("", null, listenerId, address, cleanup); this.clientListeners = clientListeners; this.failover = failover; } @Override public CompletableFuture<Void> executeFailover() { return failover.get(); } @Override protected void invokeEvent(HotRodCounterEvent event) { if (log.isTraceEnabled()) { log.tracef("Received counter event %s", event); } clientListeners.getOrDefault(event.getCounterName(), Collections.emptyList()) .parallelStream() .forEach(handle -> handle.accept(event)); } }
1,467
35.7
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/ReconnectTask.java
package org.infinispan.client.hotrod.event.impl; import java.util.concurrent.ScheduledFuture; import java.util.function.Consumer; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.util.Util; public class ReconnectTask implements Runnable, Consumer<Void> { private static final Log log = LogFactory.getLog(ReconnectTask.class); private final EventDispatcher<?> dispatcher; private ScheduledFuture<?> cancellationFuture; private boolean completed = false; public ReconnectTask(EventDispatcher<?> dispatcher) { this.dispatcher = dispatcher; } @Override public void run() { if (log.isTraceEnabled()) { log.tracef("Reconnecting client listener with id %s", Util.printArray(dispatcher.listenerId)); } dispatcher.executeFailover().thenAccept(this); } public synchronized void setCancellationFuture(ScheduledFuture<?> cancellationFuture) { this.cancellationFuture = cancellationFuture; if (completed) { cancellationFuture.cancel(false); } } @Override public synchronized void accept(Void address) { ScheduledFuture<?> cancellationFuture = this.cancellationFuture; completed = true; if (cancellationFuture != null) { cancellationFuture.cancel(false); } } }
1,376
29.6
103
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/CreatedEventImpl.java
package org.infinispan.client.hotrod.event.impl; import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; public class CreatedEventImpl<K> extends AbstractClientEvent implements ClientCacheEntryCreatedEvent<K> { final K key; final long version; final boolean retried; public CreatedEventImpl(byte[] listenerId, K key, long version, boolean retried) { super(listenerId); this.key = key; this.version = version; this.retried = retried; } @Override public K getKey() { return key; } @Override public long getVersion() { return version; } @Override public boolean isCommandRetried() { return retried; } @Override public Type getType() { return Type.CLIENT_CACHE_ENTRY_CREATED; } @Override public String toString() { return "CreatedEventImpl(" + "key=" + key + ", dataVersion=" + version + ")"; } }
943
20.953488
105
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/ContinuousQueryImpl.java
package org.infinispan.client.hotrod.event.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.client.hotrod.filter.Filters; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.api.continuous.ContinuousQueryListener; import org.infinispan.query.dsl.Query; import org.infinispan.query.remote.client.impl.ContinuousQueryResult; /** * A container of continuous query listeners for a remote cache. * <p>This class is not threadsafe. * * @author anistor@redhat.com * @since 8.2 */ public final class ContinuousQueryImpl<K, V> implements ContinuousQuery<K, V> { private final RemoteCache<K, V> cache; private final SerializationContext serializationContext; private final List<ClientEntryListener<K, ?>> listeners = new ArrayList<>(); public ContinuousQueryImpl(RemoteCache<K, V> cache) { if (cache == null) { throw new IllegalArgumentException("cache parameter cannot be null"); } this.cache = cache; serializationContext = MarshallerUtil.getSerializationContext(cache.getRemoteCacheContainer()); } @Override public <C> void addContinuousQueryListener(String queryString, ContinuousQueryListener<K, C> listener) { addContinuousQueryListener(queryString, null, listener); } @Override public <C> void addContinuousQueryListener(String queryString, Map<String, Object> namedParameters, ContinuousQueryListener<K, C> listener) { ClientEntryListener<K, ?> eventListener = new ClientEntryListener<>(serializationContext, listener); Object[] factoryParams = Filters.makeFactoryParams(queryString, namedParameters); cache.addClientListener(eventListener, factoryParams, null); listeners.add(eventListener); } /** * Registers a continuous query listener that uses a query DSL based filter. The listener will receive notifications * when a cache entry joins or leaves the matching set defined by the query. * * @param listener the continuous query listener instance * @param query the query to be used for determining the matching set */ public <C> void addContinuousQueryListener(Query<?> query, ContinuousQueryListener<K, C> listener) { addContinuousQueryListener(query.getQueryString(), query.getParameters(), listener); } public void removeContinuousQueryListener(ContinuousQueryListener<K, ?> listener) { for (Iterator<ClientEntryListener<K, ?>> it = listeners.iterator(); it.hasNext(); ) { ClientEntryListener<?, ?> l = it.next(); if (l.listener == listener) { cache.removeClientListener(l); it.remove(); break; } } } public List<ContinuousQueryListener<K, ?>> getListeners() { List<ContinuousQueryListener<K, ?>> queryListeners = new ArrayList<>(listeners.size()); for (ClientEntryListener<K, ?> l : listeners) { queryListeners.add(l.listener); } return queryListeners; } public void removeAllListeners() { for (ClientEntryListener<?, ?> l : listeners) { cache.removeClientListener(l); } listeners.clear(); } @ClientListener(filterFactoryName = Filters.CONTINUOUS_QUERY_FILTER_FACTORY_NAME, converterFactoryName = Filters.CONTINUOUS_QUERY_FILTER_FACTORY_NAME, useRawData = true, includeCurrentState = true) private static final class ClientEntryListener<K, C> { private final SerializationContext serializationContext; private final ContinuousQueryListener<K, C> listener; ClientEntryListener(SerializationContext serializationContext, ContinuousQueryListener<K, C> listener) { this.serializationContext = serializationContext; this.listener = listener; } @ClientCacheEntryCreated @ClientCacheEntryModified @ClientCacheEntryRemoved @ClientCacheEntryExpired public void handleEvent(ClientCacheEntryCustomEvent<byte[]> event) throws IOException { byte[] eventData = event.getEventData(); ContinuousQueryResult cqr = ProtobufUtil.fromWrappedByteArray(serializationContext, eventData); Object key = ProtobufUtil.fromWrappedByteArray(serializationContext, cqr.getKey()); Object value = cqr.getValue() != null ? ProtobufUtil.fromWrappedByteArray(serializationContext, cqr.getValue()) : cqr.getProjection(); switch (cqr.getResultType()) { case JOINING: listener.resultJoining((K) key, (C) value); break; case UPDATED: listener.resultUpdated((K) key, (C) value); break; case LEAVING: listener.resultLeaving((K) key); break; default: throw new IllegalStateException("Unexpected result type : " + cqr.getResultType()); } } } }
5,614
39.688406
144
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/CustomEventImpl.java
package org.infinispan.client.hotrod.event.impl; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.commons.util.Util; public class CustomEventImpl<T> extends AbstractClientEvent implements ClientCacheEntryCustomEvent<T> { private final T data; private final boolean retried; private final Type type; public CustomEventImpl(byte[] listenerId, T data, boolean retried, Type type) { super(listenerId); this.data = data; this.retried = retried; this.type = type; } @Override public T getEventData() { return data; } @Override public boolean isCommandRetried() { return retried; } @Override public Type getType() { return type; } @Override public String toString() { return "CustomEventImpl(" + "eventData=" + Util.toStr(data) + ", eventType=" + type + ")"; } }
906
22.868421
103
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/ModifiedEventImpl.java
package org.infinispan.client.hotrod.event.impl; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; public class ModifiedEventImpl<K> extends AbstractClientEvent implements ClientCacheEntryModifiedEvent<K> { private final K key; private final long version; private final boolean retried; public ModifiedEventImpl(byte[] listenerId, K key, long version, boolean retried) { super(listenerId); this.key = key; this.version = version; this.retried = retried; } @Override public K getKey() { return key; } @Override public long getVersion() { return version; } @Override public boolean isCommandRetried() { return retried; } @Override public Type getType() { return Type.CLIENT_CACHE_ENTRY_MODIFIED; } @Override public String toString() { return "ModifiedEventImpl(" + "key=" + key + ", dataVersion=" + version + ")"; } }
973
21.651163
107
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/ClientListenerNotifier.java
package org.infinispan.client.hotrod.event.impl; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.SocketAddress; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.util.TypedProperties; import org.infinispan.commons.util.Util; /** * @author Galder Zamarreño */ // Note: this class was moved to impl package as it was not meant to be public public class ClientListenerNotifier { private static final Log log = LogFactory.getLog(ClientListenerNotifier.class, Log.class); public static final AtomicInteger counter = new AtomicInteger(0); // Time for trying to reconnect listeners when all connections are down. public static final int RECONNECT_PERIOD = 5000; private final ConcurrentMap<WrappedByteArray, EventDispatcher<?>> dispatchers = new ConcurrentHashMap<>(); private final ScheduledThreadPoolExecutor reconnectExecutor; private final Marshaller marshaller; private final ChannelFactory channelFactory; private final ClassAllowList allowList; public ClientListenerNotifier(Marshaller marshaller, ChannelFactory channelFactory, Configuration configuration) { this.marshaller = marshaller; this.channelFactory = channelFactory; this.allowList = configuration.getClassAllowList(); TypedProperties defaultAsyncExecutorProperties = configuration.asyncExecutorFactory().properties(); ConfigurationProperties cp = new ConfigurationProperties(defaultAsyncExecutorProperties); final String threadNamePrefix = cp.getDefaultExecutorFactoryThreadNamePrefix(); final String threadNameSuffix = cp.getDefaultExecutorFactoryThreadNameSuffix(); reconnectExecutor = new ScheduledThreadPoolExecutor(1, r -> { // Reuse the DefaultAsyncExecutorFactory thread name settings Thread th = new Thread(r, threadNamePrefix + "-" + counter.getAndIncrement() + threadNameSuffix); th.setDaemon(true); return th; }); reconnectExecutor.setKeepAliveTime(2 * RECONNECT_PERIOD, TimeUnit.MILLISECONDS); reconnectExecutor.allowCoreThreadTimeOut(true); } public Marshaller marshaller() { return marshaller; } public void addDispatcher(EventDispatcher<?> dispatcher) { dispatchers.put(new WrappedByteArray(dispatcher.listenerId), dispatcher); if (log.isTraceEnabled()) log.tracef("Add dispatcher %s for client listener with id %s, for listener %s", dispatcher, Util.printArray(dispatcher.listenerId), dispatcher.listener); } public void failoverListeners(Set<SocketAddress> failedServers) { // Compile all listener ids that need failing over List<WrappedByteArray> failoverListenerIds = new ArrayList<>(); for (Map.Entry<WrappedByteArray, EventDispatcher<?>> entry : dispatchers.entrySet()) { EventDispatcher<?> dispatcher = entry.getValue(); if (failedServers.contains(dispatcher.address())) failoverListenerIds.add(entry.getKey()); } if (log.isTraceEnabled() && failoverListenerIds.isEmpty()) log.tracef("No event listeners registered in failed servers: %s", failedServers); // Remove tracking listeners and read to the fallback transport failoverListenerIds.forEach(wrapped -> failoverClientListener(wrapped.getBytes())); } public void failoverClientListener(byte[] listenerId) { EventDispatcher<?> dispatcher = removeClientListener(listenerId); if (dispatcher == null) { return; } // Invoke failover event callback, if presents dispatcher.invokeFailoverEvent(); // Re-execute adding client listener in one of the remaining nodes dispatcher.executeFailover().whenComplete((ignore, throwable) -> { if (throwable != null) { if (throwable instanceof RejectedExecutionException) { log.debug("Client listener failover rejected, not retrying", throwable); } else { log.debug("Unable to failover client listener, so ignore connection reset", throwable); ReconnectTask reconnectTask = new ReconnectTask(dispatcher); ScheduledFuture<?> scheduledFuture = reconnectExecutor.scheduleAtFixedRate(reconnectTask, RECONNECT_PERIOD, RECONNECT_PERIOD, TimeUnit.MILLISECONDS); reconnectTask.setCancellationFuture(scheduledFuture); } } else { if (log.isTraceEnabled()) { log.tracef("Fallback listener id %s from a failed server %s", Util.printArray(listenerId), dispatcher.address()); } } }); } public void startClientListener(byte[] listenerId) { EventDispatcher<?> eventDispatcher = dispatchers.get(new WrappedByteArray(listenerId)); eventDispatcher.start(); } public EventDispatcher<?> removeClientListener(byte[] listenerId) { return removeClientListener(new WrappedByteArray(listenerId)); } private EventDispatcher<?> removeClientListener(WrappedByteArray listenerId) { EventDispatcher<?> dispatcher = dispatchers.remove(listenerId); if (dispatcher == null) { if (log.isTraceEnabled()) { log.tracef("Client listener %s not present (removed concurrently?)", Util.printArray(listenerId.getBytes())); } } else { dispatcher.stop(); } if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId.getBytes())); return dispatcher; } public byte[] findListenerId(Object listener) { for (EventDispatcher<?> dispatcher : dispatchers.values()) { if (dispatcher.listener.equals(listener)) return dispatcher.listenerId; } return null; } public boolean isListenerConnected(byte[] listenerId) { EventDispatcher<?> dispatcher = dispatchers.get(new WrappedByteArray(listenerId)); // If listener not present, is not active return dispatcher != null && dispatcher.isRunning(); } public SocketAddress findAddress(byte[] listenerId) { EventDispatcher<?> dispatcher = dispatchers.get(new WrappedByteArray(listenerId)); if (dispatcher != null) return dispatcher.address(); return null; } public Set<Object> getListeners(String cacheName) { Set<Object> ret = new HashSet<>(dispatchers.size()); for (EventDispatcher<?> dispatcher : dispatchers.values()) { if (dispatcher.cacheName.equals(cacheName)) ret.add(dispatcher.listener); } return ret; } public void stop() { for (WrappedByteArray listenerId : dispatchers.keySet()) { if (log.isTraceEnabled()) log.tracef("Remote cache manager stopping, remove client listener id %s", Util.printArray(listenerId.getBytes())); removeClientListener(listenerId); } reconnectExecutor.shutdownNow(); } public <T> void invokeEvent(byte[] listenerId, T event) { EventDispatcher<T> eventDispatcher = (EventDispatcher<T>) dispatchers.get(new WrappedByteArray(listenerId)); if (eventDispatcher == null) { throw HOTROD.unexpectedListenerId(Util.printArray(listenerId)); } eventDispatcher.invokeEvent(event); } public DataFormat getCacheDataFormat(byte[] listenerId) { ClientEventDispatcher clientEventDispatcher = (ClientEventDispatcher) dispatchers.get(new WrappedByteArray(listenerId)); if (clientEventDispatcher == null) { throw HOTROD.unexpectedListenerId(Util.printArray(listenerId)); } return clientEventDispatcher.getDataFormat(); } public ClassAllowList allowList() { return allowList; } /** * @deprecated Use {@link #allowList()} instead. To be removed in 14.0. */ @Deprecated public ClassAllowList whitelist() { return allowList(); } public ChannelFactory channelFactory() { return channelFactory; } }
8,958
39.722727
164
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/event/impl/AbstractClientEvent.java
package org.infinispan.client.hotrod.event.impl; import org.infinispan.client.hotrod.event.ClientEvent; public abstract class AbstractClientEvent implements ClientEvent { private final byte[] listenerId; protected AbstractClientEvent(byte[] listenerId) { this.listenerId = listenerId; } public byte[] getListenerId() { return listenerId; } }
373
22.375
66
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/TopologyInfo.java
package org.infinispan.client.hotrod.impl; import static org.infinispan.client.hotrod.impl.Util.wrapBytes; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.client.hotrod.CacheTopologyInfo; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashFactory; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.topology.CacheInfo; import org.infinispan.client.hotrod.impl.topology.ClusterInfo; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import net.jcip.annotations.NotThreadSafe; /** * Maintains topology information about caches. * * @author gustavonalle * @author Dan Berindei */ @NotThreadSafe public final class TopologyInfo { private static final Log log = LogFactory.getLog(TopologyInfo.class, Log.class); private final Supplier<FailoverRequestBalancingStrategy> balancerFactory; private final ConsistentHashFactory hashFactory = new ConsistentHashFactory(); private final ConcurrentMap<WrappedBytes, CacheInfo> caches = new ConcurrentHashMap<>(); private volatile ClusterInfo cluster; public TopologyInfo(Configuration configuration, ClusterInfo clusterInfo) { this.balancerFactory = configuration.balancingStrategyFactory(); this.hashFactory.init(configuration); this.cluster = clusterInfo.withTopologyAge(0); } public Map<SocketAddress, Set<Integer>> getPrimarySegmentsByServer(byte[] cacheName) { WrappedByteArray key = wrapBytes(cacheName); CacheInfo cacheInfo = caches.get(key); if (cacheInfo != null) { return cacheInfo.getPrimarySegments(); } else { return Collections.emptyMap(); } } public List<InetSocketAddress> getServers(WrappedBytes cacheName) { return getCacheInfo(cacheName).getServers(); } public Collection<InetSocketAddress> getAllServers() { return caches.values().stream().flatMap(ct -> ct.getServers().stream()).collect(Collectors.toSet()); } public SegmentConsistentHash createConsistentHash(int numSegments, short hashFunctionVersion, SocketAddress[][] segmentOwners) { SegmentConsistentHash hash = null; if (hashFunctionVersion > 0) { hash = hashFactory.newConsistentHash(hashFunctionVersion); if (hash == null) { HOTROD.noHasHFunctionConfigured(hashFunctionVersion); } else { hash.init(segmentOwners, numSegments); } } return hash; } public ConsistentHashFactory getConsistentHashFactory() { return hashFactory; } public CacheTopologyInfo getCacheTopologyInfo(byte[] cacheName) { WrappedByteArray key = wrapBytes(cacheName); return caches.get(key).getCacheTopologyInfo(); } public CacheInfo getCacheInfo(WrappedBytes cacheName) { return caches.get(cacheName); } public CacheInfo getOrCreateCacheInfo(WrappedBytes cacheName) { return caches.computeIfAbsent(cacheName, cn -> { // TODO Do we still need locking, in case the cluster switch iteration misses this cache? ClusterInfo cluster = this.cluster; CacheInfo cacheInfo = new CacheInfo(cn, balancerFactory.get(), cluster.getTopologyAge(), cluster.getInitialServers(), cluster.getIntelligence()); cacheInfo.updateBalancerServers(); if (log.isTraceEnabled()) log.tracef("Creating cache info %s with topology age %d", cacheInfo.getCacheName(), cluster.getTopologyAge()); return cacheInfo; }); } /** * Switch to another cluster and update the topologies of all caches with its initial server list. */ public void switchCluster(ClusterInfo newCluster) { ClusterInfo oldCluster = this.cluster; int newTopologyAge = oldCluster.getTopologyAge() + 1; if (log.isTraceEnabled()) { log.tracef("Switching cluster: %s -> %s with servers %s", oldCluster.getName(), newCluster.getName(), newCluster.getInitialServers()); } // Stop accepting topology updates from old requests caches.forEach((name, oldCacheInfo) -> { CacheInfo newCacheInfo = oldCacheInfo.withNewServers(newTopologyAge, HotRodConstants.SWITCH_CLUSTER_TOPOLOGY, newCluster.getInitialServers(), newCluster.getIntelligence()); updateCacheInfo(name, oldCacheInfo, newCacheInfo); }); // Update the topology age for new requests so that the topology updates from their responses are accepted this.cluster = newCluster.withTopologyAge(newTopologyAge); } /** * Reset a single ache to the initial server list. * * <p>Useful if there are still live servers in the cluster, but all the server in this cache's * current topology are unreachable.</p> */ public void reset(WrappedBytes cacheName) { if (log.isTraceEnabled()) log.tracef("Switching to initial server list for cache %s, cluster %s", cacheName, cluster.getName()); CacheInfo oldCacheInfo = caches.get(cacheName); CacheInfo newCacheInfo = oldCacheInfo.withNewServers(cluster.getTopologyAge(), HotRodConstants.DEFAULT_CACHE_TOPOLOGY, cluster.getInitialServers(), cluster.getIntelligence()); updateCacheInfo(cacheName, oldCacheInfo, newCacheInfo); } public ClusterInfo getCluster() { return cluster; } public int getTopologyAge() { return cluster.getTopologyAge(); } public void updateCacheInfo(WrappedBytes cacheName, CacheInfo oldCacheInfo, CacheInfo newCacheInfo) { if (log.isTraceEnabled()) log.tracef("Updating topology for %s: %s -> %s", newCacheInfo.getCacheName(), oldCacheInfo.getTopologyId(), newCacheInfo.getTopologyId()); CacheInfo existing = caches.put(cacheName, newCacheInfo); assert existing == oldCacheInfo : "Locking should have prevented concurrent updates"; // The new CacheInfo doesn't have a new balancer instance, so the server update affects both newCacheInfo.updateBalancerServers(); // Update the topology id for new requests newCacheInfo.updateClientTopologyRef(); } public void forEachCache(BiConsumer<WrappedBytes, CacheInfo> action) { caches.forEach(action); } }
7,326
40.162921
154
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/VersionedValueImpl.java
package org.infinispan.client.hotrod.impl; import org.infinispan.client.hotrod.VersionedValue; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ public class VersionedValueImpl<V> implements VersionedValue<V> { private long version; private V value; public VersionedValueImpl(long version, V value) { this.version = version; this.value = value; } @Override public long getVersion() { return version; } @Override public V getValue() { return value; } @Override public String toString() { return "VersionedValueImpl{" + "version=" + version + ", value=" + value + '}'; } }
691
17.210526
65
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/RemoteCacheImpl.java
package org.infinispan.client.hotrod.impl; import static org.infinispan.client.hotrod.filter.Filters.makeFactoryParams; import static org.infinispan.client.hotrod.impl.Util.await; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.SocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Function; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.client.hotrod.CacheTopologyInfo; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.RemoteCacheContainer; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.ServerStatistics; import org.infinispan.client.hotrod.StreamingRemoteCache; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.StatisticsConfiguration; import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier; import org.infinispan.client.hotrod.exceptions.RemoteCacheManagerNotStartedException; import org.infinispan.client.hotrod.filter.Filters; import org.infinispan.client.hotrod.impl.iteration.RemotePublisher; import org.infinispan.client.hotrod.impl.operations.AddClientListenerOperation; import org.infinispan.client.hotrod.impl.operations.ClearOperation; import org.infinispan.client.hotrod.impl.operations.ContainsKeyOperation; import org.infinispan.client.hotrod.impl.operations.ExecuteOperation; import org.infinispan.client.hotrod.impl.operations.GetAllParallelOperation; import org.infinispan.client.hotrod.impl.operations.GetOperation; import org.infinispan.client.hotrod.impl.operations.GetWithMetadataOperation; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.client.hotrod.impl.operations.PutAllParallelOperation; import org.infinispan.client.hotrod.impl.operations.PutIfAbsentOperation; import org.infinispan.client.hotrod.impl.operations.PutOperation; import org.infinispan.client.hotrod.impl.operations.RemoveClientListenerOperation; import org.infinispan.client.hotrod.impl.operations.RemoveIfUnmodifiedOperation; import org.infinispan.client.hotrod.impl.operations.RemoveOperation; import org.infinispan.client.hotrod.impl.operations.ReplaceIfUnmodifiedOperation; import org.infinispan.client.hotrod.impl.operations.ReplaceOperation; import org.infinispan.client.hotrod.impl.operations.RetryAwareCompletionStage; import org.infinispan.client.hotrod.impl.operations.SizeOperation; import org.infinispan.client.hotrod.impl.operations.StatsOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.near.NearCacheService; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableIteratorCollection; import org.infinispan.commons.util.CloseableIteratorSet; import org.infinispan.commons.util.Closeables; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.query.dsl.Query; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ public class RemoteCacheImpl<K, V> extends RemoteCacheSupport<K, V> implements InternalRemoteCache<K, V> { private static final Log log = LogFactory.getLog(RemoteCacheImpl.class, Log.class); private final String name; private final RemoteCacheManager remoteCacheManager; protected OperationsFactory operationsFactory; private int batchSize; private volatile boolean isObjectStorage; private DataFormat dataFormat; protected ClientStatistics clientStatistics; private ObjectName mbeanObjectName; public RemoteCacheImpl(RemoteCacheManager rcm, String name, TimeService timeService) { this(rcm, name, timeService, null); } public RemoteCacheImpl(RemoteCacheManager rcm, String name, TimeService timeService, NearCacheService<K, V> nearCacheService) { if (log.isTraceEnabled()) { log.tracef("Creating remote cache: %s", name); } this.name = name; this.remoteCacheManager = rcm; this.dataFormat = DataFormat.builder().build(); this.clientStatistics = new ClientStatistics(rcm.getConfiguration().statistics().enabled(), timeService, nearCacheService); } protected RemoteCacheImpl(RemoteCacheManager rcm, String name, ClientStatistics clientStatistics) { if (log.isTraceEnabled()) { log.tracef("Creating remote cache: %s", name); } this.name = name; this.remoteCacheManager = rcm; this.dataFormat = DataFormat.builder().build(); this.clientStatistics = clientStatistics; } @Override public void init(OperationsFactory operationsFactory, Configuration configuration, ObjectName jmxParent) { init(operationsFactory, configuration); registerMBean(jmxParent); } /** * Inititalize without mbeans */ @Override public void init(OperationsFactory operationsFactory, Configuration configuration) { init(operationsFactory, configuration.batchSize()); } private void init(OperationsFactory operationsFactory, int batchSize) { this.operationsFactory = operationsFactory; this.batchSize = batchSize; } private void registerMBean(ObjectName jmxParent) { StatisticsConfiguration configuration = getRemoteCacheContainer().getConfiguration().statistics(); if (configuration.jmxEnabled()) { try { MBeanServer mbeanServer = configuration.mbeanServerLookup().getMBeanServer(); String cacheName = name.isEmpty() ? "org.infinispan.default" : name; mbeanObjectName = new ObjectName(String.format("%s:type=HotRodClient,name=%s,cache=%s", jmxParent.getDomain(), configuration.jmxName(), cacheName)); mbeanServer.registerMBean(clientStatistics, mbeanObjectName); } catch (Exception e) { throw HOTROD.jmxRegistrationFailure(e); } } } private void unregisterMBean() { if (mbeanObjectName != null) { try { MBeanServer mBeanServer = getRemoteCacheContainer().getConfiguration().statistics() .mbeanServerLookup().getMBeanServer(); if (mBeanServer.isRegistered(mbeanObjectName)) { mBeanServer.unregisterMBean(mbeanObjectName); } else { HOTROD.debugf("MBean not registered: %s", mbeanObjectName); } } catch (Exception e) { throw HOTROD.jmxUnregistrationFailure(e); } } } @Override public OperationsFactory getOperationsFactory() { return operationsFactory; } @Override public RemoteCacheContainer getRemoteCacheContainer() { return remoteCacheManager; } @Override public CompletableFuture<Boolean> removeWithVersionAsync(final K key, final long version) { assertRemoteCacheManagerIsStarted(); RemoveIfUnmodifiedOperation<V> op = operationsFactory.newRemoveIfUnmodifiedOperation( keyAsObjectIfNeeded(key), keyToBytes(key), version, dataFormat); return op.execute().thenApply(response -> response.getCode().isUpdated()); } @Override public CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { throw new UnsupportedOperationException(); } public CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { assertRemoteCacheManagerIsStarted(); ReplaceIfUnmodifiedOperation op = operationsFactory.newReplaceIfUnmodifiedOperation( keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(newValue), lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, version, dataFormat); return op.execute().thenApply(response -> response.getCode().isUpdated()); } @Override public CloseableIterator<Entry<Object, Object>> retrieveEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { Publisher<Entry<K, Object>> remotePublisher = publishEntries(filterConverterFactory, filterConverterParams, segments, batchSize); //noinspection unchecked return Closeables.iterator((Publisher) remotePublisher, batchSize); } @Override public <E> Publisher<Entry<K, E>> publishEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { assertRemoteCacheManagerIsStarted(); if (segments != null && segments.isEmpty()) { return Flowable.empty(); } byte[][] params = marshallParams(filterConverterParams); return new RemotePublisher<>(operationsFactory, filterConverterFactory, params, segments, batchSize, false, dataFormat); } @Override public CloseableIterator<Entry<Object, Object>> retrieveEntriesByQuery(Query<?> filterQuery, Set<Integer> segments, int batchSize) { Publisher<Entry<K, Object>> remotePublisher = publishEntriesByQuery(filterQuery, segments, batchSize); //noinspection unchecked return Closeables.iterator((Publisher) remotePublisher, batchSize); } @Override public <E> Publisher<Entry<K, E>> publishEntriesByQuery(Query<?> filterQuery, Set<Integer> segments, int batchSize) { Object[] factoryParams = makeFactoryParams(filterQuery); return publishEntries(Filters.ITERATION_QUERY_FILTER_CONVERTER_FACTORY_NAME, factoryParams, segments, batchSize); } @Override public CloseableIterator<Entry<Object, MetadataValue<Object>>> retrieveEntriesWithMetadata(Set<Integer> segments, int batchSize) { Publisher<Entry<K, MetadataValue<V>>> remotePublisher = publishEntriesWithMetadata(segments, batchSize); //noinspection unchecked return Closeables.iterator((Publisher) remotePublisher, batchSize); } @Override public Publisher<Entry<K, MetadataValue<V>>> publishEntriesWithMetadata(Set<Integer> segments, int batchSize) { return new RemotePublisher<>(operationsFactory, null, null, segments, batchSize, true, dataFormat); } @Override public CompletableFuture<MetadataValue<V>> getWithMetadataAsync(K key) { assertRemoteCacheManagerIsStarted(); GetWithMetadataOperation<V> op = operationsFactory.newGetWithMetadataOperation( keyAsObjectIfNeeded(key), keyToBytes(key), dataFormat); return op.execute(); } @Override public RetryAwareCompletionStage<MetadataValue<V>> getWithMetadataAsync(K key, SocketAddress preferredAddres) { assertRemoteCacheManagerIsStarted(); GetWithMetadataOperation<V> op = operationsFactory.newGetWithMetadataOperation( keyAsObjectIfNeeded(key), keyToBytes(key), dataFormat, preferredAddres); return op.internalExecute(); } @Override public CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { assertRemoteCacheManagerIsStarted(); if (log.isTraceEnabled()) { log.tracef("About to putAll entries (%s) lifespan:%d (%s), maxIdle:%d (%s)", map, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } Map<byte[], byte[]> byteMap = new HashMap<>(); for (Entry<? extends K, ? extends V> entry : map.entrySet()) { byteMap.put(keyToBytes(entry.getKey()), valueToBytes(entry.getValue())); } PutAllParallelOperation op = operationsFactory.newPutAllOperation(byteMap, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit, dataFormat); return op.execute(); } @Override public CompletableFuture<Long> sizeAsync() { assertRemoteCacheManagerIsStarted(); SizeOperation op = operationsFactory.newSizeOperation(); return op.execute().thenApply(Integer::longValue); } @Override public boolean isEmpty() { return size() == 0; } @Override public ClientStatistics clientStatistics() { return clientStatistics; } @Override public ServerStatistics serverStatistics() { return await(serverStatisticsAsync()); } @Override public CompletionStage<ServerStatistics> serverStatisticsAsync() { assertRemoteCacheManagerIsStarted(); StatsOperation op = operationsFactory.newStatsOperation(); return op.execute(); } @Override public K keyAsObjectIfNeeded(Object key) { return isObjectStorage ? (K) key : null; } @Override public CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { assertRemoteCacheManagerIsStarted(); if (log.isTraceEnabled()) { log.tracef("About to add (K,V): (%s, %s) lifespan:%d, maxIdle:%d", key, value, lifespan, maxIdleTime); } PutOperation<V> op = operationsFactory.newPutKeyValueOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit, dataFormat); return op.execute(); } @Override public CompletableFuture<Void> clearAsync() { assertRemoteCacheManagerIsStarted(); ClearOperation op = operationsFactory.newClearOperation(); return op.execute(); } @Override public CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { CompletableFuture<MetadataValue<V>> cf = getWithMetadataAsync(key); return cf.thenCompose(metadataValue -> { V newValue; V oldValue; long version; if (metadataValue != null) { oldValue = metadataValue.getValue(); version = metadataValue.getVersion(); } else { oldValue = null; version = -1; } newValue = remappingFunction.apply(key, oldValue); CompletionStage<Boolean> doneStage; if (newValue != null) { if (oldValue != null) { doneStage = replaceWithVersionAsync(key, newValue, version, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } else { doneStage = putIfAbsentAsync(key, newValue, lifespan, lifespanUnit, maxIdle, maxIdleUnit) .thenApply(Objects::isNull); } } else { if (oldValue != null) { doneStage = removeWithVersionAsync(key, version); } else { // Nothing to remove doneStage = CompletableFuture.completedFuture(Boolean.TRUE); } } return doneStage.thenCompose(done -> { if (done) { return CompletableFuture.completedFuture(newValue); } // Retry if one of the operations failed return computeAsync(key, remappingFunction, lifespan, lifespanUnit, maxIdle, maxIdleUnit); }); }); } @Override public CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { CompletableFuture<V> cf = getAsync(key); return cf.thenCompose(oldValue -> { if (oldValue != null) return CompletableFuture.completedFuture(oldValue); V newValue = mappingFunction.apply(key); if (newValue == null) return CompletableFutures.completedNull(); return putIfAbsentAsync(key, newValue, lifespan, lifespanUnit, maxIdle, maxIdleUnit) .thenApply(v -> v == null ? newValue : v); }); } @Override public CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { CompletableFuture<MetadataValue<V>> cf = getWithMetadataAsync(key); return cf.thenCompose(metadata -> { if (metadata == null || metadata.getValue() == null) return CompletableFutures.completedNull(); V newValue = remappingFunction.apply(key, metadata.getValue()); CompletableFuture<Boolean> done; if (newValue == null) { done = removeWithVersionAsync(key, metadata.getVersion()); } else { done = replaceWithVersionAsync(key, newValue, metadata.getVersion(), lifespan, lifespanUnit, maxIdle, maxIdleUnit); } return done.thenCompose(success -> { if (success) { return CompletableFuture.completedFuture(newValue); } return computeIfPresentAsync(key, remappingFunction, lifespan, lifespanUnit, maxIdle, maxIdleUnit); }); }); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } @Override public CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { assertRemoteCacheManagerIsStarted(); PutIfAbsentOperation<V> op = operationsFactory.newPutIfAbsentOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit, dataFormat); return op.execute(); } @Override public CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { Objects.requireNonNull(oldValue); Objects.requireNonNull(newValue); CompletionStage<MetadataValue<V>> stage = getWithMetadataAsync(key); return stage.thenCompose(metadataValue -> { if (metadataValue != null) { V prevValue = metadataValue.getValue(); if (oldValue.equals(prevValue)) { return replaceWithVersionAsync(key, newValue, metadataValue.getVersion(), lifespan, lifespanUnit, maxIdle, maxIdleUnit) .thenCompose(replaced -> { if (replaced) { return CompletableFuture.completedFuture(replaced); } // Concurrent modification - the value could still equal - we need to retry return replaceAsync(key, oldValue, newValue, lifespan, lifespanUnit, maxIdle, maxIdleUnit); }); } } return CompletableFuture.completedFuture(Boolean.FALSE); }).toCompletableFuture(); } @Override public CompletableFuture<V> removeAsync(Object key) { assertRemoteCacheManagerIsStarted(); RemoveOperation<V> removeOperation = operationsFactory.newRemoveOperation(keyAsObjectIfNeeded(key), keyToBytes(key), dataFormat); // TODO: It sucks that you need the prev value to see if it works... // We need to find a better API for RemoteCache... return removeOperation.execute(); } @Override public CompletableFuture<Boolean> removeAsync(Object key, Object value) { Objects.requireNonNull(value); CompletionStage<MetadataValue<V>> stage = getWithMetadataAsync((K) key); return stage.thenCompose(metadataValue -> { if (metadataValue == null || !value.equals(metadataValue.getValue())) { return CompletableFuture.completedFuture(Boolean.FALSE); } return removeWithVersionAsync((K) key, metadataValue.getVersion()) .thenCompose(removed -> { if (removed) { return CompletableFuture.completedFuture(Boolean.TRUE); } // Concurrent operation - need to retry return removeAsync(key, value); }); }).toCompletableFuture(); } @Override public CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { assertRemoteCacheManagerIsStarted(); ReplaceOperation<V> op = operationsFactory.newReplaceOperation(keyAsObjectIfNeeded(key), keyToBytes(key), valueToBytes(value), lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit, dataFormat); return op.execute(); } @Override public CompletableFuture<Boolean> containsKeyAsync(K key) { assertRemoteCacheManagerIsStarted(); ContainsKeyOperation op = operationsFactory.newContainsKeyOperation( keyAsObjectIfNeeded(key), keyToBytes(key), dataFormat); return op.execute(); } @Override public boolean containsValue(Object value) { Objects.requireNonNull(value); return values().contains(value); } @Override public CompletableFuture<Map<K, V>> getAllAsync(Set<?> keys) { assertRemoteCacheManagerIsStarted(); if (log.isTraceEnabled()) { log.tracef("About to getAll entries (%s)", keys); } Set<byte[]> byteKeys = new HashSet<>(keys.size()); for (Object key : keys) { byteKeys.add(keyToBytes(key)); } GetAllParallelOperation<K, V> op = operationsFactory.newGetAllOperation(byteKeys, dataFormat); return op.execute().thenApply(Collections::unmodifiableMap); } @Override public void start() { if (log.isDebugEnabled()) { log.debugf("Start called, nothing to do here(%s)", getName()); } } @Override public void stop() { unregisterMBean(); } @Override public String getName() { return name; } @Override public String getVersion() { return RemoteCacheImpl.class.getPackage().getImplementationVersion(); } @Override public String getProtocolVersion() { return "HotRod client, protocol version: " + ProtocolVersion.DEFAULT_PROTOCOL_VERSION; } @Override public void addClientListener(Object listener) { assertRemoteCacheManagerIsStarted(); AddClientListenerOperation op = operationsFactory.newAddClientListenerOperation(listener, dataFormat); // no timeout, see below await(op.execute()); } @Override public void addClientListener(Object listener, Object[] filterFactoryParams, Object[] converterFactoryParams) { assertRemoteCacheManagerIsStarted(); byte[][] marshalledFilterParams = marshallParams(filterFactoryParams); byte[][] marshalledConverterParams = marshallParams(converterFactoryParams); AddClientListenerOperation op = operationsFactory.newAddClientListenerOperation( listener, marshalledFilterParams, marshalledConverterParams, dataFormat); // No timeout: transferring initial state can take a while, socket timeout setting is not applicable here await(op.execute()); } @Override public SocketAddress addNearCacheListener(Object listener, int bloomBits) { throw new UnsupportedOperationException("Adding a near cache listener to a RemoteCache is not supported!"); } private byte[][] marshallParams(Object[] params) { if (params == null) return org.infinispan.commons.util.Util.EMPTY_BYTE_ARRAY_ARRAY; byte[][] marshalledParams = new byte[params.length][]; for (int i = 0; i < marshalledParams.length; i++) { byte[] bytes = keyToBytes(params[i]);// should be small marshalledParams[i] = bytes; } return marshalledParams; } @Override public void removeClientListener(Object listener) { assertRemoteCacheManagerIsStarted(); RemoveClientListenerOperation op = operationsFactory.newRemoveClientListenerOperation(listener); await(op.execute()); } @Deprecated @Override public Set<Object> getListeners() { ClientListenerNotifier listenerNotifier = operationsFactory.getListenerNotifier(); return listenerNotifier.getListeners(operationsFactory.getCacheName()); } @Override public InternalRemoteCache<K, V> withFlags(Flag... flags) { operationsFactory.setFlags(flags); return this; } @Override public CompletableFuture<V> getAsync(Object key) { assertRemoteCacheManagerIsStarted(); byte[] keyBytes = keyToBytes(key); GetOperation<V> gco = operationsFactory.newGetKeyOperation(keyAsObjectIfNeeded(key), keyBytes, dataFormat); CompletableFuture<V> result = gco.execute(); if (log.isTraceEnabled()) { result.thenAccept(value -> log.tracef("For key(%s) returning %s", key, value)); } return result; } public CompletionStage<PingResponse> ping() { return operationsFactory.newFaultTolerantPingOperation().execute(); } @Override public byte[] keyToBytes(Object o) { return dataFormat.keyToBytes(o); } protected byte[] valueToBytes(Object o) { return dataFormat.valueToBytes(o); } protected void assertRemoteCacheManagerIsStarted() { if (!remoteCacheManager.isStarted()) { String message = "Cannot perform operations on a cache associated with an unstarted RemoteCacheManager. Use RemoteCacheManager.start before using the remote cache."; HOTROD.unstartedRemoteCacheManager(); throw new RemoteCacheManagerNotStartedException(message); } } @Override public CloseableIteratorSet<K> keySet(IntSet segments) { return new RemoteCacheKeySet<>(this, segments); } @Override public CloseableIterator<K> keyIterator(IntSet segments) { return operationsFactory.getCodec().keyIterator(this, operationsFactory, segments, batchSize); } @Override public CloseableIteratorSet<Entry<K, V>> entrySet(IntSet segments) { return new RemoteCacheEntrySet<>(this, segments); } @Override public CloseableIterator<Entry<K, V>> entryIterator(IntSet segments) { return operationsFactory.getCodec().entryIterator(this, segments, batchSize); } @Override public CloseableIteratorCollection<V> values(IntSet segments) { return new RemoteCacheValuesCollection<>(this, segments); } @Override public <T> T execute(String taskName, Map<String, ?> params) { return execute(taskName, params, null); } @Override public <T> T execute(String taskName, Map<String, ?> params, Object key) { assertRemoteCacheManagerIsStarted(); Map<String, byte[]> marshalledParams = new HashMap<>(); if (params != null) { for (java.util.Map.Entry<String, ?> entry : params.entrySet()) { marshalledParams.put(entry.getKey(), keyToBytes(entry.getValue())); } } Object keyHint = null; if (key != null) { keyHint = isObjectStorage ? key : keyToBytes(key); } ExecuteOperation<T> op = operationsFactory.newExecuteOperation(taskName, marshalledParams, keyHint, dataFormat); return await(op.execute()); } @Override public CacheTopologyInfo getCacheTopologyInfo() { return operationsFactory.getCacheTopologyInfo(); } @Override public StreamingRemoteCache<K> streaming() { assertRemoteCacheManagerIsStarted(); return new StreamingRemoteCacheImpl<>(this); } @Override public <T, U> InternalRemoteCache<T, U> withDataFormat(DataFormat newDataFormat) { Objects.requireNonNull(newDataFormat, "Data Format must not be null") .initialize(remoteCacheManager, name, isObjectStorage); RemoteCacheImpl<T, U> instance = newInstance(); instance.dataFormat = newDataFormat; return instance; } private <T, U> RemoteCacheImpl<T, U> newInstance() { RemoteCacheImpl<T, U> copy = new RemoteCacheImpl<>(this.remoteCacheManager, name, clientStatistics); copy.init(this.operationsFactory, this.batchSize); return copy; } public void resolveStorage(boolean objectStorage) { this.isObjectStorage = objectStorage; this.dataFormat.initialize(remoteCacheManager, name, isObjectStorage); } @Override public DataFormat getDataFormat() { return dataFormat; } @Override public boolean isTransactional() { return false; } public boolean isObjectStorage() { return isObjectStorage; } @Override public boolean hasForceReturnFlag() { return operationsFactory.hasFlag(Flag.FORCE_RETURN_VALUE); } @Override public CompletionStage<Void> updateBloomFilter() { return CompletableFuture.completedFuture(null); } @Override public String toString() { return "RemoteCache " + name; } }
29,276
39.270977
206
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/ConfigurationProperties.java
package org.infinispan.client.hotrod.impl; import java.util.Objects; import java.util.Properties; import java.util.regex.Pattern; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.TransportFactory; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.ExhaustedAction; import org.infinispan.client.hotrod.configuration.NearCacheMode; import org.infinispan.client.hotrod.configuration.StatisticsConfiguration; import org.infinispan.client.hotrod.configuration.TransactionConfigurationBuilder; import org.infinispan.client.hotrod.impl.async.DefaultAsyncExecutorFactory; import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy; import org.infinispan.commons.util.TypedProperties; /** * Encapsulate all config properties here * * @author Manik Surtani * @version 4.1 */ public class ConfigurationProperties { static final String ICH = "infinispan.client.hotrod."; public static final String URI = ICH + "uri"; public static final String SERVER_LIST = ICH + "server_list"; public static final String MARSHALLER = ICH + "marshaller"; public static final String CONTEXT_INITIALIZERS = ICH + "context-initializers"; public static final String ASYNC_EXECUTOR_FACTORY = ICH + "async_executor_factory"; public static final String CLIENT_INTELLIGENCE = ICH + "client_intelligence"; public static final String DEFAULT_EXECUTOR_FACTORY_POOL_SIZE = ICH + "default_executor_factory.pool_size"; public static final String DEFAULT_EXECUTOR_FACTORY_THREADNAME_PREFIX = ICH + "default_executor_factory.threadname_prefix"; public static final String DEFAULT_EXECUTOR_FACTORY_THREADNAME_SUFFIX = ICH + "default_executor_factory.threadname_suffix"; public static final String TCP_NO_DELAY = ICH + "tcp_no_delay"; public static final String TCP_KEEP_ALIVE = ICH + "tcp_keep_alive"; public static final String REQUEST_BALANCING_STRATEGY = ICH + "request_balancing_strategy"; /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public static final String KEY_SIZE_ESTIMATE = ICH + "key_size_estimate"; /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public static final String VALUE_SIZE_ESTIMATE = ICH + "value_size_estimate"; public static final String FORCE_RETURN_VALUES = ICH + "force_return_values"; public static final String HASH_FUNCTION_PREFIX = ICH + "hash_function_impl"; // Connection properties public static final String SO_TIMEOUT = ICH + "socket_timeout"; public static final String CONNECT_TIMEOUT = ICH + "connect_timeout"; public static final String PROTOCOL_VERSION = ICH + "protocol_version"; public static final String TRANSPORT_FACTORY = ICH + "transport_factory"; // Encryption properties public static final String USE_SSL = ICH + "use_ssl"; public static final String KEY_STORE_FILE_NAME = ICH + "key_store_file_name"; public static final String KEY_STORE_TYPE = ICH + "key_store_type"; public static final String KEY_STORE_PASSWORD = ICH + "key_store_password"; public static final String SNI_HOST_NAME = ICH + "sni_host_name"; public static final String KEY_ALIAS = ICH + "key_alias"; public static final String KEY_STORE_CERTIFICATE_PASSWORD = ICH + "key_store_certificate_password"; public static final String TRUST_STORE_FILE_NAME = ICH + "trust_store_file_name"; public static final String TRUST_STORE_PATH = ICH + "trust_store_path"; public static final String TRUST_STORE_TYPE = ICH + "trust_store_type"; public static final String TRUST_STORE_PASSWORD = ICH + "trust_store_password"; public static final String SSL_PROVIDER = ICH + "ssl_provider"; public static final String SSL_PROTOCOL = ICH + "ssl_protocol"; public static final String SSL_CIPHERS = ICH + "ssl_ciphers"; public static final String SSL_CONTEXT = ICH + "ssl_context"; public static final String MAX_RETRIES = ICH + "max_retries"; // Authentication properties public static final String USE_AUTH = ICH + "use_auth"; public static final String SASL_MECHANISM = ICH + "sasl_mechanism"; public static final String AUTH_CALLBACK_HANDLER = ICH + "auth_callback_handler"; public static final String AUTH_SERVER_NAME = ICH + "auth_server_name"; public static final String AUTH_USERNAME = ICH + "auth_username"; public static final String AUTH_PASSWORD = ICH + "auth_password"; public static final String AUTH_TOKEN = ICH + "auth_token"; public static final String AUTH_REALM = ICH + "auth_realm"; public static final String AUTH_CLIENT_SUBJECT = ICH + "auth_client_subject"; public static final String SASL_PROPERTIES_PREFIX = ICH + "sasl_properties"; public static final Pattern SASL_PROPERTIES_PREFIX_REGEX = Pattern.compile('^' + ConfigurationProperties.SASL_PROPERTIES_PREFIX + '.'); public static final String JAVA_SERIAL_ALLOWLIST = ICH + "java_serial_allowlist"; @Deprecated public static final String JAVA_SERIAL_WHITELIST = ICH + "java_serial_whitelist"; public static final String BATCH_SIZE = ICH + "batch_size"; // Statistics properties public static final String STATISTICS = ICH + "statistics"; public static final String JMX = ICH + "jmx"; public static final String JMX_NAME = ICH + "jmx_name"; public static final String JMX_DOMAIN = ICH + "jmx_domain"; // Transaction properties public static final String TRANSACTION_MANAGER_LOOKUP = ICH + "transaction.transaction_manager_lookup"; public static final String TRANSACTION_MODE = ICH + "transaction.transaction_mode"; public static final String TRANSACTION_TIMEOUT = ICH + "transaction.timeout"; // Near cache properties public static final String NEAR_CACHE_MAX_ENTRIES = ICH + "near_cache.max_entries"; public static final String NEAR_CACHE_MODE = ICH + "near_cache.mode"; public static final String NEAR_CACHE_BLOOM_FILTER = ICH + "near_cache.bloom_filter"; public static final String NEAR_CACHE_NAME_PATTERN = ICH + "near_cache.name_pattern"; // Pool properties public static final String CONNECTION_POOL_MAX_ACTIVE = ICH + "connection_pool.max_active"; public static final String CONNECTION_POOL_MAX_WAIT = ICH + "connection_pool.max_wait"; public static final String CONNECTION_POOL_MIN_IDLE = ICH + "connection_pool.min_idle"; public static final String CONNECTION_POOL_MAX_PENDING_REQUESTS = ICH + "connection_pool.max_pending_requests"; public static final String CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME = ICH + "connection_pool.min_evictable_idle_time"; public static final String CONNECTION_POOL_EXHAUSTED_ACTION = ICH + "connection_pool.exhausted_action"; // XSite properties public static final String CLUSTER_PROPERTIES_PREFIX = ICH + "cluster"; public static final Pattern CLUSTER_PROPERTIES_PREFIX_REGEX = Pattern.compile('^' + ConfigurationProperties.CLUSTER_PROPERTIES_PREFIX + '.'); public static final Pattern CLUSTER_PROPERTIES_PREFIX_INTELLIGENCE_REGEX = Pattern.compile('^' + ConfigurationProperties.CLUSTER_PROPERTIES_PREFIX + '.' + "intelligence."); // Tracing properties public static final String TRACING_PROPAGATION_ENABLED = ICH + "tracing.propagation_enabled"; // Cache properties public static final String CACHE_PREFIX= ICH + "cache."; public static final String CACHE_CONFIGURATION_SUFFIX = ".configuration"; public static final String CACHE_CONFIGURATION_URI_SUFFIX = ".configuration_uri"; public static final String CACHE_FORCE_RETURN_VALUES_SUFFIX = ".force_return_values"; public static final String CACHE_MARSHALLER = ".marshaller"; public static final String CACHE_NEAR_CACHE_MODE_SUFFIX = ".near_cache.mode"; public static final String CACHE_NEAR_CACHE_MAX_ENTRIES_SUFFIX = ".near_cache.max_entries"; public static final String CACHE_NEAR_CACHE_FACTORY_SUFFIX = ".near_cache.factory"; public static final String CACHE_NEAR_CACHE_BLOOM_FILTER_SUFFIX = ".near_cache.bloom_filter"; public static final String CACHE_TEMPLATE_NAME_SUFFIX = ".template_name"; public static final String CACHE_TRANSACTION_MODE_SUFFIX = ".transaction.transaction_mode"; public static final String CACHE_TRANSACTION_MANAGER_LOOKUP_SUFFIX = ".transaction.transaction_manager_lookup"; public static final String DNS_RESOLVER_MIN_TTL = ".dns_resolver_min_ttl"; public static final String DNS_RESOLVER_MAX_TTL = ".dns_resolver_max_ttl"; public static final String DNS_RESOLVER_NEGATIVE_TTL = ".dns_resolver_negative_ttl"; // defaults /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public static final int DEFAULT_KEY_SIZE = 64; /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public static final int DEFAULT_VALUE_SIZE = 512; public static final int DEFAULT_HOTROD_PORT = 11222; public static final int DEFAULT_SO_TIMEOUT = 2_000; public static final int DEFAULT_CONNECT_TIMEOUT = 2_000; public static final int DEFAULT_MAX_RETRIES = 3; public static final int DEFAULT_BATCH_SIZE = 10_000; public static final int DEFAULT_MAX_PENDING_REQUESTS = 5; public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME = 180000L; public static final int DEFAULT_MAX_ACTIVE = -1; public static final int DEFAULT_MAX_WAIT = -1; public static final int DEFAULT_MIN_IDLE = -1; public static final boolean DEFAULT_TRACING_PROPAGATION_ENABLED = true; private final TypedProperties props; public ConfigurationProperties() { this.props = new TypedProperties(); } public ConfigurationProperties(String serverList) { this(); setServerList(serverList); } public ConfigurationProperties(Properties props) { this.props = props == null ? new TypedProperties() : TypedProperties.toTypedProperties(props); } public void setURI(String uri) { props.setProperty(URI, uri); } public String getURI() { return props.getProperty(URI); } public void setServerList(String serverList) { props.setProperty(SERVER_LIST, serverList); } public String getMarshaller() { return props.getProperty(MARSHALLER); } public void setMarshaller(String marshaller) { props.setProperty(MARSHALLER, marshaller); } public String getContextInitializers() { return props.getProperty(CONTEXT_INITIALIZERS); } public void setContextInitializers(String contextInitializers) { props.setProperty(CONTEXT_INITIALIZERS, contextInitializers); } public String getAsyncExecutorFactory() { return props.getProperty(ASYNC_EXECUTOR_FACTORY, DefaultAsyncExecutorFactory.class.getName()); } public int getDefaultExecutorFactoryPoolSize() { return props.getIntProperty(DEFAULT_EXECUTOR_FACTORY_POOL_SIZE, 99); } public void setDefaultExecutorFactoryPoolSize(int poolSize) { props.setProperty(DEFAULT_EXECUTOR_FACTORY_POOL_SIZE, poolSize); } public String getDefaultExecutorFactoryThreadNamePrefix() { return props.getProperty(DEFAULT_EXECUTOR_FACTORY_THREADNAME_PREFIX, DefaultAsyncExecutorFactory.THREAD_NAME); } public void setDefaultExecutorFactoryThreadNamePrefix(String threadNamePrefix) { props.setProperty(DEFAULT_EXECUTOR_FACTORY_THREADNAME_PREFIX, threadNamePrefix); } public String getDefaultExecutorFactoryThreadNameSuffix() { return props.getProperty(DEFAULT_EXECUTOR_FACTORY_THREADNAME_SUFFIX, ""); } public void setDefaultExecutorFactoryThreadNameSuffix(String threadNameSuffix) { props.setProperty(DEFAULT_EXECUTOR_FACTORY_THREADNAME_SUFFIX, threadNameSuffix); } public void setTransportFactory(String transportFactoryClass) { props.setProperty(TRANSPORT_FACTORY, transportFactoryClass); } public void setTransportFactory(Class<TransportFactory> transportFactory) { setTransportFactory(transportFactory.getName()); } public String getTransportFactory() { return props.getProperty(TRANSPORT_FACTORY, TransportFactory.DEFAULT.getClass().getName()); } public boolean getTcpNoDelay() { return props.getBooleanProperty(TCP_NO_DELAY, true); } public void setTcpNoDelay(boolean tcpNoDelay) { props.setProperty(TCP_NO_DELAY, tcpNoDelay); } public boolean getTcpKeepAlive() { return props.getBooleanProperty(TCP_KEEP_ALIVE, false); } public void setTcpKeepAlive(boolean tcpKeepAlive) { props.setProperty(TCP_KEEP_ALIVE, tcpKeepAlive); } public String getRequestBalancingStrategy() { return props.getProperty(REQUEST_BALANCING_STRATEGY, RoundRobinBalancingStrategy.class.getName()); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public int getKeySizeEstimate() { return props.getIntProperty(KEY_SIZE_ESTIMATE, DEFAULT_KEY_SIZE); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public void setKeySizeEstimate(int keySizeEstimate) { props.setProperty(KEY_SIZE_ESTIMATE, keySizeEstimate); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public int getValueSizeEstimate() { return props.getIntProperty(VALUE_SIZE_ESTIMATE, DEFAULT_VALUE_SIZE); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public void setValueSizeEstimate(int valueSizeEstimate) { props.setProperty(VALUE_SIZE_ESTIMATE, valueSizeEstimate); } public boolean getForceReturnValues() { return props.getBooleanProperty(FORCE_RETURN_VALUES, false); } public void setForceReturnValues(boolean forceReturnValues) { props.setProperty(FORCE_RETURN_VALUES, forceReturnValues); } public Properties getProperties() { return props; } public int getSoTimeout() { return props.getIntProperty(SO_TIMEOUT, DEFAULT_SO_TIMEOUT); } public void setSocketTimeout(int socketTimeout) { props.setProperty(SO_TIMEOUT, socketTimeout); } public String getProtocolVersion() { return props.getProperty(PROTOCOL_VERSION, ProtocolVersion.DEFAULT_PROTOCOL_VERSION.toString()); } public void setProtocolVersion(String protocolVersion) { props.setProperty(PROTOCOL_VERSION, protocolVersion); } public String getClientIntelligence() { return props.getProperty(CLIENT_INTELLIGENCE, ClientIntelligence.getDefault().name()); } public void setClientIntelligence(String clientIntelligence) { props.setProperty(CLIENT_INTELLIGENCE, clientIntelligence); } public int getConnectTimeout() { return props.getIntProperty(CONNECT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT); } public void setConnectTimeout(int connectTimeout) { props.setProperty(CONNECT_TIMEOUT, connectTimeout); } public boolean getUseSSL() { return props.getBooleanProperty(USE_SSL, false); } public void setUseSSL(boolean useSSL) { props.setProperty(USE_SSL, useSSL); } public String getKeyStoreFileName() { return props.getProperty(KEY_STORE_FILE_NAME); } public void setKeyStoreFileName(String keyStoreFileName) { props.setProperty(KEY_STORE_FILE_NAME, keyStoreFileName); } public String getKeyStoreType() { return props.getProperty(KEY_STORE_TYPE); } public void setKeyStoreType(String keyStoreType) { props.setProperty(KEY_STORE_TYPE, keyStoreType); } public String getKeyStorePassword() { return props.getProperty(KEY_STORE_PASSWORD); } public void setKeyStorePassword(String keyStorePassword) { props.setProperty(KEY_STORE_PASSWORD, keyStorePassword); } public void setKeyStoreCertificatePassword(String keyStoreCertificatePassword) { props.setProperty(KEY_STORE_CERTIFICATE_PASSWORD, keyStoreCertificatePassword); } public String getKeyAlias() { return props.getProperty(KEY_ALIAS); } public void setKeyAlias(String keyAlias) { props.setProperty(KEY_ALIAS, keyAlias); } public String getTrustStoreFileName() { return props.getProperty(TRUST_STORE_FILE_NAME); } public void setTrustStoreFileName(String trustStoreFileName) { props.setProperty(TRUST_STORE_FILE_NAME, trustStoreFileName); } public String getTrustStoreType() { return props.getProperty(TRUST_STORE_TYPE); } public void setTrustStoreType(String trustStoreType) { props.setProperty(TRUST_STORE_TYPE, trustStoreType); } public String getTrustStorePassword() { return props.getProperty(TRUST_STORE_PASSWORD); } public void setTrustStorePassword(String trustStorePassword) { props.setProperty(TRUST_STORE_PASSWORD, trustStorePassword); } /** * @deprecated Since 12.0 and will be removed in 15.0 */ @Deprecated public String getTrustStorePath() { return props.getProperty(TRUST_STORE_PATH); } /** * @deprecated Since 12.0 and will be removed in 15.0 */ @Deprecated public void setTrustStorePath(String trustStorePath) { props.setProperty(TRUST_STORE_PATH, trustStorePath); } public String getSSLProtocol() { return props.getProperty(SSL_PROTOCOL); } public void setSSLProtocol(String sslProtocol) { props.setProperty(SSL_PROTOCOL, sslProtocol); } public String getSniHostName() { return props.getProperty(SNI_HOST_NAME); } public void setSniHostName(String sniHostName) { props.setProperty(SNI_HOST_NAME, sniHostName); } public boolean getUseAuth() { return props.getBooleanProperty(USE_AUTH, false); } public void setUseAuth(boolean useAuth) { props.setProperty(USE_AUTH, useAuth); } public String getSaslMechanism() { return props.getProperty(SASL_MECHANISM); } public void setSaslMechanism(String saslMechanism) { props.setProperty(SASL_MECHANISM, saslMechanism); } public String getAuthUsername() { return props.getProperty(AUTH_USERNAME); } public void setAuthUsername(String authUsername) { props.setProperty(AUTH_USERNAME, authUsername); } public String getAuthPassword() { return props.getProperty(AUTH_PASSWORD); } public void setAuthPassword(String authPassword) { props.setProperty(AUTH_PASSWORD, authPassword); } public String getAuthToken() { return props.getProperty(AUTH_TOKEN); } public void setAuthToken(String authToken) { props.setProperty(AUTH_TOKEN, authToken); } public String getAuthRealm() { return props.getProperty(AUTH_REALM); } public void setAuthRealm(String authRealm) { props.setProperty(AUTH_REALM, authRealm); } public void setAuthServerName(String authServerName) { props.setProperty(AUTH_SERVER_NAME, authServerName); } public int getMaxRetries() { return props.getIntProperty(MAX_RETRIES, DEFAULT_MAX_RETRIES); } public void setMaxRetries(int maxRetries) { props.setProperty(MAX_RETRIES, maxRetries); } public int getBatchSize() { return props.getIntProperty(BATCH_SIZE, DEFAULT_BATCH_SIZE); } public void setBatchSize(int batchSize) { props.setProperty(BATCH_SIZE, batchSize); } public void setStatistics(boolean statistics) { props.setProperty(STATISTICS, statistics); } public boolean isStatistics() { return props.getBooleanProperty(STATISTICS, StatisticsConfiguration.ENABLED.getDefaultValue()); } public void setJmx(boolean jmx) { props.setProperty(JMX, jmx); } public boolean isJmx() { return props.getBooleanProperty(JMX, StatisticsConfiguration.JMX_ENABLED.getDefaultValue()); } public void setJmxName(String jmxName) { props.setProperty(JMX_NAME, jmxName); } public void getJmxName() { props.getProperty(JMX_NAME); } public void setJmxDomain(String jmxDomain) { props.setProperty(JMX_DOMAIN, jmxDomain); } public void getJmxDomain() { props.getProperty(JMX_DOMAIN); } public String getTransactionManagerLookup() { return props.getProperty(TRANSACTION_MANAGER_LOOKUP, TransactionConfigurationBuilder.defaultTransactionManagerLookup().getClass().getName(), true); } public NearCacheMode getNearCacheMode() { return props.getEnumProperty(NEAR_CACHE_MODE, NearCacheMode.class, NearCacheMode.DISABLED, true); } public void setNearCacheMode(String nearCacheMode) { props.setProperty(NEAR_CACHE_MODE, nearCacheMode); } public int getNearCacheMaxEntries() { return props.getIntProperty(NEAR_CACHE_MAX_ENTRIES, -1); } public void setNearCacheMaxEntries(int nearCacheMaxEntries) { props.setProperty(NEAR_CACHE_MAX_ENTRIES, nearCacheMaxEntries); } @Deprecated public String getNearCacheNamePattern() { return props.getProperty(NEAR_CACHE_NAME_PATTERN); } @Deprecated public void setNearCacheNamePattern(String nearCacheNamePattern) { props.setProperty(NEAR_CACHE_NAME_PATTERN, nearCacheNamePattern); } public int getConnectionPoolMaxActive() { return props.getIntProperty(CONNECTION_POOL_MAX_ACTIVE, DEFAULT_MAX_ACTIVE); } public void setConnectionPoolMaxActive(int connectionPoolMaxActive) { props.setProperty(CONNECTION_POOL_MAX_ACTIVE, connectionPoolMaxActive); } public long getConnectionPoolMaxWait() { return props.getLongProperty(CONNECTION_POOL_MAX_WAIT, DEFAULT_MAX_WAIT); } public void setConnectionPoolMaxWait(long connectionPoolMaxWait) { props.setProperty(CONNECTION_POOL_MAX_WAIT, connectionPoolMaxWait); } public int gtConnectionPoolMinIdle() { return props.getIntProperty(CONNECTION_POOL_MIN_IDLE, DEFAULT_MIN_IDLE); } public void setConnectionPoolMinIdle(int connectionPoolMinIdle) { props.setProperty(CONNECTION_POOL_MIN_IDLE, connectionPoolMinIdle); } public int getConnectionPoolMaxPendingRequests() { return props.getIntProperty(CONNECTION_POOL_MAX_PENDING_REQUESTS, DEFAULT_MAX_PENDING_REQUESTS); } public void setConnectionPoolMaxPendingRequests(int connectionPoolMaxPendingRequests) { props.setProperty(CONNECTION_POOL_MAX_PENDING_REQUESTS, connectionPoolMaxPendingRequests); } public long setConnectionPoolMinEvictableIdleTime() { return props.getLongProperty(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME, DEFAULT_MIN_EVICTABLE_IDLE_TIME); } public void setConnectionPoolMinEvictableIdleTime(long connectionPoolMinEvictableIdleTime) { props.setProperty(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME, connectionPoolMinEvictableIdleTime); } public ExhaustedAction getConnectionPoolExhaustedAction() { return props.getEnumProperty(CONNECTION_POOL_EXHAUSTED_ACTION, ExhaustedAction.class, ExhaustedAction.WAIT); } public void setConnectionPoolExhaustedAction(String connectionPoolExhaustedAction) { props.setProperty(CONNECTION_POOL_EXHAUSTED_ACTION, connectionPoolExhaustedAction); } public boolean isTracingPropagationEnabled() { return props.getBooleanProperty(TRACING_PROPAGATION_ENABLED, DEFAULT_TRACING_PROPAGATION_ENABLED); } public void setTracingPropagationEnabled(boolean tracingPropagationEnabled) { props.setProperty(TRACING_PROPAGATION_ENABLED, tracingPropagationEnabled); } /** * Is version previous to, and not including, 1.2? */ public static boolean isVersionPre12(Configuration cfg) { String version = cfg.version().toString(); return Objects.equals(version, "1.0") || Objects.equals(version, "1.1"); } public String getServerList(){ return props.getProperty(SERVER_LIST); } /** * @deprecated Use {@link #setJavaSerialAllowList(String)} instead. To be removed in 14.0. * @param javaSerialWhitelist */ @Deprecated public void setJavaSerialWhitelist(String javaSerialWhitelist) { setJavaSerialAllowList(javaSerialWhitelist); } public void setJavaSerialAllowList(String javaSerialAllowlist) { props.setProperty(JAVA_SERIAL_ALLOWLIST, javaSerialAllowlist); } public void setTransactionMode(String transactionMode) { props.setProperty(TRANSACTION_MODE, transactionMode); } public String getTransactionMode() { return props.getProperty(TRANSACTION_MODE); } public void setTransactionTimeout(int transactionTimeout) { props.setProperty(TRANSACTION_TIMEOUT, transactionTimeout); } public int getTransactionTimeout() { return props.getIntProperty(TRANSACTION_TIMEOUT, DEFAULT_SO_TIMEOUT); } }
24,857
36.324324
153
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/RemoteCacheSupport.java
package org.infinispan.client.hotrod.impl; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.infinispan.client.hotrod.impl.Util.await; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Function; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.RemoteCache; /** * Purpose: keep all delegating and unsupported methods in one place -> readability. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public abstract class RemoteCacheSupport<K, V> implements RemoteCache<K, V> { protected long defaultLifespan; protected long defaultMaxIdleTime; protected RemoteCacheSupport() { this(0, 0); } protected RemoteCacheSupport(long defaultLifespan, long defaultMaxIdleTime) { this.defaultLifespan = defaultLifespan; this.defaultMaxIdleTime = defaultMaxIdleTime; } @Override public final void putAll(Map<? extends K, ? extends V> map) { putAll(map, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit unit) { putAll(map, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public final void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { await(putAllAsync(map, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data) { return putAllAsync(data, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit unit) { return putAllAsync(data, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public final V putIfAbsent(K key, V value) { return putIfAbsent(key, value, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final V putIfAbsent(K key, V value, long lifespan, TimeUnit unit) { return putIfAbsent(key, value, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public final V putIfAbsent(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(putIfAbsentAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<V> putIfAbsentAsync(K key, V value) { return putIfAbsentAsync(key, value, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit) { return putIfAbsentAsync(key, value, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public final boolean replace(K key, V oldValue, V newValue) { return replace(key, oldValue, newValue, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit unit) { return replace(key, oldValue, value, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public final boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(replaceAsync(key, oldValue, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue) { return replaceAsync(key, oldValue, newValue, defaultLifespan, MILLISECONDS); } @Override public final CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit unit) { return replaceAsync(key, oldValue, newValue, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public final V replace(K key, V value) { return replace(key, value, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final V replace(K key, V value, long lifespan, TimeUnit unit) { return replace(key, value, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public final V replace(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(replaceAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<V> replaceAsync(K key, V value) { return replaceAsync(key, value, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit unit) { return replaceAsync(key, value, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public final V get(Object key) { return await(getAsync((K) key)); } @Override public abstract CompletableFuture<V> getAsync(K key); @Override public final Map<K, V> getAll(Set<? extends K> keys) { return await(getAllAsync(keys)); } @Override public abstract CompletableFuture<Map<K, V>> getAllAsync(Set<?> keys); @Override public final MetadataValue<V> getWithMetadata(K key) { return await(getWithMetadataAsync(key)); } @Override public abstract CompletableFuture<MetadataValue<V>> getWithMetadataAsync(K key); @Override public final boolean containsKey(Object key) { return await(containsKeyAsync((K) key)); } @Override public abstract CompletableFuture<Boolean> containsKeyAsync(K key); @Override public final V put(K key, V value) { return put(key, value, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final V put(K key, V value, long lifespan, TimeUnit unit) { return put(key, value, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public final V put(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(putAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<V> putAsync(K key, V value) { return putAsync(key, value, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit unit) { return putAsync(key, value, lifespan, unit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public final boolean replaceWithVersion(K key, V newValue, long version) { return replaceWithVersion(key, newValue, version, 0); } @Override public final boolean replaceWithVersion(K key, V newValue, long version, int lifespanSeconds) { return replaceWithVersion(key, newValue, version, lifespanSeconds, 0); } @Override public final boolean replaceWithVersion(K key, V newValue, long version, int lifespanSeconds, int maxIdleTimeSeconds) { return replaceWithVersion(key, newValue, version, lifespanSeconds, SECONDS, maxIdleTimeSeconds, SECONDS); } @Override public final boolean replaceWithVersion(K key, V newValue, long version, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { return await(replaceWithVersionAsync(key, newValue, version, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit)); } @Override public final CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version) { return replaceWithVersionAsync(key, newValue, version, 0); } @Override public final CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, int lifespanSeconds) { return replaceWithVersionAsync(key, newValue, version, lifespanSeconds, 0); } @Override public final CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, int lifespanSeconds, int maxIdleSeconds) { return replaceWithVersionAsync(key, newValue, version, lifespanSeconds, SECONDS, maxIdleSeconds, SECONDS); } @Override public final V remove(Object key) { return await(removeAsync(key)); } @Override public abstract CompletableFuture<V> removeAsync(Object key); @Override public final boolean remove(Object key, Object value) { return await(removeAsync(key, value)); } @Override public abstract CompletableFuture<Boolean> removeAsync(Object key, Object value); @Override public final boolean removeWithVersion(K key, long version) { return await(removeWithVersionAsync(key, version)); } @Override public abstract CompletableFuture<Boolean> removeWithVersionAsync(K key, long version); @Override public final V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return merge(key, value, remappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return merge(key, value, remappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public final V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(mergeAsync(key, value, remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return mergeAsync(key, value, remappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return mergeAsync(key, value, remappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit); @Override public final void clear() { await(clearAsync()); } @Override public final V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return compute(key, remappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return compute(key, remappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public final V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(computeAsync(key, remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return computeAsync(key, remappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeAsync(key, remappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public final V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { return computeIfAbsent(key, mappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeIfAbsent(key, mappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public final V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(computeIfAbsentAsync(key, mappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction) { return computeIfAbsentAsync(key, mappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeIfAbsentAsync(key, mappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public final V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return computeIfPresent(key, remappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeIfPresent(key, remappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public final V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return await(computeIfPresentAsync(key, remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit)); } @Override public final CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return computeIfPresentAsync(key, remappingFunction, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS); } @Override public final CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeIfPresentAsync(key, remappingFunction, lifespan, lifespanUnit, defaultMaxIdleTime, MILLISECONDS); } @Override public abstract CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); @Override public abstract void replaceAll(BiFunction<? super K, ? super V, ? extends V> function); @Override public final int size() { long size = await(sizeAsync()); return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size; } @Override public abstract CompletableFuture<Long> sizeAsync(); }
16,941
40.935644
214
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/InvalidatedNearRemoteCache.java
package org.infinispan.client.hotrod.impl; import static org.infinispan.client.hotrod.impl.Util.await; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.lang.invoke.MethodHandles; import java.net.SocketAddress; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.impl.operations.ClientListenerOperation; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.operations.RetryAwareCompletionStage; import org.infinispan.client.hotrod.impl.operations.UpdateBloomFilterOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.near.NearCacheService; /** * Near {@link org.infinispan.client.hotrod.RemoteCache} implementation enabling * * @param <K> * @param <V> */ public class InvalidatedNearRemoteCache<K, V> extends DelegatingRemoteCache<K, V> { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private static final boolean trace = log.isTraceEnabled(); private final NearCacheService<K, V> nearcache; private final ClientStatistics clientStatistics; // This field is used to control updating the near cache with updating the remote server's bloom filter // representation. This value will be non null when bloom filter is enabled, otherwise null. When this // value is even it means there is no bloom filter update being sent and the near cache can be updated // locally from reads. When a bloom filter is being replicated though the value will be odd and the // near cache cannot be updated. private final AtomicInteger bloomFilterUpdateVersion; private volatile SocketAddress listenerAddress; InvalidatedNearRemoteCache(InternalRemoteCache<K, V> remoteCache, ClientStatistics clientStatistics, NearCacheService<K, V> nearcache) { super(remoteCache); this.clientStatistics = clientStatistics; this.nearcache = nearcache; this.bloomFilterUpdateVersion = nearcache.getBloomFilterBits() > 0 ? new AtomicInteger() : null; } @Override <Key, Value> InternalRemoteCache<Key, Value> newDelegatingCache(InternalRemoteCache<Key, Value> innerCache) { return new InvalidatedNearRemoteCache<>(innerCache, clientStatistics, (NearCacheService<Key, Value>) nearcache); } public static <K, V> InvalidatedNearRemoteCache<K, V> delegatingNearCache(RemoteCacheImpl<K, V> remoteCache, NearCacheService<K, V> nearCacheService) { return new InvalidatedNearRemoteCache<>(remoteCache, remoteCache.clientStatistics, nearCacheService); } @Override public CompletableFuture<V> getAsync(Object key) { CompletableFuture<MetadataValue<V>> value = getWithMetadataAsync((K) key); return value.thenApply(v -> v != null ? v.getValue() : null); } private int getCurrentVersion() { if (bloomFilterUpdateVersion != null) { return bloomFilterUpdateVersion.get(); } return 0; } @Override public CompletableFuture<MetadataValue<V>> getWithMetadataAsync(K key) { MetadataValue<V> nearValue = nearcache.get(key); if (nearValue == null) { clientStatistics.incrementNearCacheMisses(); int prevVersion = getCurrentVersion(); RetryAwareCompletionStage<MetadataValue<V>> remoteValue = super.getWithMetadataAsync(key, listenerAddress); return remoteValue.thenApply(v -> { // We cannot cache the value if a retry was required - which means we did not talk to the listener node if (v != null) { // If previous version is odd we can't cache as that means it was started during // a bloom filter update. We also can't cache if the new version doesn't match the prior // as it overlapped a bloom update. if ((prevVersion & 1) == 1 || prevVersion != getCurrentVersion()) { if (trace) { log.tracef("Unable to cache returned value for key %s as operation was performed during a" + " bloom filter update"); } } // Having a listener address means it has a bloom filter. When we have a bloom filter we cannot // cache values upon a retry as we can't guarantee the bloom filter is updated on the server properly else if (listenerAddress != null && remoteValue.wasRetried()) { if (trace) { log.tracef("Unable to cache returned value for key %s as operation was retried", key); } } else { nearcache.putIfAbsent(key, v); if (v.getMaxIdle() > 0) { HOTROD.nearCacheMaxIdleUnsupported(); } } } return v; }).toCompletableFuture(); } else { clientStatistics.incrementNearCacheHits(); return CompletableFuture.completedFuture(nearValue); } } @Override public CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { if (maxIdleTime > 0) HOTROD.nearCacheMaxIdleUnsupported(); CompletableFuture<V> ret = super.putAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); return ret.thenApply(v -> { nearcache.remove(key); return v; }); } @Override public CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { if (maxIdleTime > 0) HOTROD.nearCacheMaxIdleUnsupported(); return super.putAllAsync(map, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit) .thenRun(() -> map.keySet().forEach(nearcache::remove)); } @Override public CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { if (maxIdleTime > 0) HOTROD.nearCacheMaxIdleUnsupported(); return invalidateNearCacheIfNeeded(delegate.hasForceReturnFlag(), key, super.replaceAsync(key, value, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit) ); } @Override public CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, long lifespan, TimeUnit lifespanTimeUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { if (maxIdleTime > 0) HOTROD.nearCacheMaxIdleUnsupported(); return super.replaceWithVersionAsync(key, newValue, version, lifespan, lifespanTimeUnit, maxIdleTime, maxIdleTimeUnit) .thenApply(removed -> { if (removed) nearcache.remove(key); return removed; }); } @Override public CompletableFuture<V> removeAsync(Object key) { return invalidateNearCacheIfNeeded(delegate.hasForceReturnFlag(), key, super.removeAsync(key)); } @Override public CompletableFuture<Boolean> removeWithVersionAsync(K key, long version) { return super.removeWithVersionAsync(key, version) .thenApply(removed -> { if (removed) nearcache.remove(key); // Eager invalidation to avoid race return removed; }); } @Override public CompletableFuture<Void> clearAsync() { return super.clearAsync().thenRun(nearcache::clear); } @SuppressWarnings("unchecked") CompletableFuture<V> invalidateNearCacheIfNeeded(boolean hasForceReturnValue, Object key, CompletableFuture<V> prev) { return prev.thenApply(v -> { if (!hasForceReturnValue || v != null) nearcache.remove((K) key); return v; }); } @Override public void start() { super.start(); listenerAddress = nearcache.start(this); } @Override public void stop() { nearcache.stop(this); super.stop(); } public void clearNearCache() { nearcache.clear(); } // Increments the bloom filter version if it is even and returns whether it was incremented private boolean incrementBloomVersionIfEven() { if (bloomFilterUpdateVersion != null) { int prev; do { prev = bloomFilterUpdateVersion.get(); // Odd number means we are already sending bloom filter if ((prev & 1) == 1) { return false; } } while (!bloomFilterUpdateVersion.compareAndSet(prev, prev + 1)); } return true; } CompletionStage<Void> incrementBloomVersionUponCompletion(CompletionStage<Void> stage) { if (bloomFilterUpdateVersion != null) { return stage .whenComplete((ignore, t) -> bloomFilterUpdateVersion.incrementAndGet()); } return stage; } @Override public CompletionStage<Void> updateBloomFilter() { // Not being able to increment the even version means we have a concurrent update - so skip if (!incrementBloomVersionIfEven()) { if (trace) { log.tracef("Already have a concurrent bloom filter update for listenerId(%s) - skipping", org.infinispan.commons.util.Util.printArray(nearcache.getListenerId())); } return CompletableFuture.completedFuture(null); } byte[] bloomFilterBits = nearcache.calculateBloomBits(); if (trace) { log.tracef("Sending bloom filter bits(%s) update to %s for listenerId(%s)", org.infinispan.commons.util.Util.printArray(bloomFilterBits), listenerAddress, org.infinispan.commons.util.Util.printArray(nearcache.getListenerId())); } OperationsFactory operationsFactory = getOperationsFactory(); UpdateBloomFilterOperation bloopOp = operationsFactory.newUpdateBloomFilterOperation(listenerAddress, bloomFilterBits); return incrementBloomVersionUponCompletion(bloopOp.execute()); } public SocketAddress getBloomListenerAddress() { return listenerAddress; } public void setBloomListenerAddress(SocketAddress socketAddress) { this.listenerAddress = socketAddress; } @Override public SocketAddress addNearCacheListener(Object listener, int bloomBits) { ClientListenerOperation op = getOperationsFactory().newAddNearCacheListenerOperation(listener, getDataFormat(), bloomBits, this); // no timeout, see below return await(op.execute()); } }
10,804
40.879845
181
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/HotRodURI.java
package org.infinispan.client.hotrod.impl; import java.net.InetSocketAddress; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.logging.Log; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class HotRodURI { public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static HotRodURI create(String uriString) { return create(URI.create(uriString)); } public static HotRodURI create(URI uri) { if (!"hotrod".equals(uri.getScheme()) && !"hotrods".equals(uri.getScheme())) { throw Log.HOTROD.notaHotRodURI(uri.toString()); } final List<InetSocketAddress> addresses; final String[] userInfo; if (uri.getHost() != null) { addresses = Collections.singletonList(InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort() < 0 ? ConfigurationProperties.DEFAULT_HOTROD_PORT : uri.getPort())); userInfo = uri.getUserInfo() != null ? uri.getUserInfo().split(":") : EMPTY_STRING_ARRAY; } else { // We need to handle this by hand String authority = uri.getAuthority(); final int at = authority.indexOf('@'); userInfo = at < 0 ? EMPTY_STRING_ARRAY : authority.substring(0, at).split(":"); String[] hosts = at < 0 ? authority.split(",") : authority.substring(at + 1).split(","); addresses = new ArrayList<>(hosts.length); for (String host : hosts) { int colon = host.lastIndexOf(':'); addresses.add(InetSocketAddress.createUnresolved(colon < 0 ? host : host.substring(0, colon), colon < 0 ? ConfigurationProperties.DEFAULT_HOTROD_PORT : Integer.parseInt(host.substring(colon + 1)))); } } Properties properties = new Properties(); if (uri.getQuery() != null) { String[] parts = uri.getQuery().split("&"); for (String part : parts) { int eq = part.indexOf('='); if (eq < 0) { throw Log.HOTROD.invalidPropertyFormat(part); } else { properties.setProperty(ConfigurationProperties.ICH + part.substring(0, eq), part.substring(eq + 1)); } } } return new HotRodURI(addresses, "hotrods".equals(uri.getScheme()), userInfo.length > 0 ? userInfo[0] : null, userInfo.length > 1 ? userInfo[1] : null, properties); } private final List<InetSocketAddress> addresses; private final boolean ssl; private final String username; private final String password; private final Properties properties; private HotRodURI(List<InetSocketAddress> addresses, boolean ssl, String username, String password, Properties properties) { this.addresses = addresses; this.ssl = ssl; this.username = username; this.password = password; this.properties = properties; } public List<InetSocketAddress> getAddresses() { return addresses; } public boolean isSsl() { return ssl; } public String getUsername() { return username; } public String getPassword() { return password; } public Properties getProperties() { return properties; } public ConfigurationBuilder toConfigurationBuilder() { return toConfigurationBuilder(new ConfigurationBuilder()); } public ConfigurationBuilder toConfigurationBuilder(ConfigurationBuilder builder) { for(InetSocketAddress address : addresses) { builder.addServer().host(address.getHostString()).port(address.getPort()); } if (ssl) { builder.security().ssl().enable(); } if (username != null) { builder.security().authentication().username(username); } if (password != null) { builder.security().authentication().password(password); } builder.withProperties(properties); return builder; } @Override public String toString() { return "HotRodURI{" + "addresses=" + addresses + ", ssl=" + ssl + ", username='" + username + '\'' + ", password='" + password + '\'' + ", properties=" + properties + '}'; } }
4,368
32.868217
210
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/CacheTopologyInfoImpl.java
package org.infinispan.client.hotrod.impl; import java.net.SocketAddress; import java.util.Map; import java.util.Set; import org.infinispan.client.hotrod.CacheTopologyInfo; /** * @author gustavonalle * @since 8.0 */ public class CacheTopologyInfoImpl implements CacheTopologyInfo { private final Map<SocketAddress, Set<Integer>> segmentsByServer; private final Integer numSegments; private final Integer topologyId; public CacheTopologyInfoImpl(Map<SocketAddress, Set<Integer>> segmentsByServer, Integer numSegments, Integer topologyId) { this.segmentsByServer = segmentsByServer; this.numSegments = numSegments; this.topologyId = topologyId; } @Override public Integer getNumSegments() { return numSegments; } @Override public Integer getTopologyId() { return topologyId; } @Override public Map<SocketAddress, Set<Integer>> getSegmentsPerServer() { return segmentsByServer; } @Override public String toString() { return "CacheTopologyInfoImpl{" + "segmentsByServer=" + segmentsByServer + ", numSegments=" + numSegments + ", topologyId=" + topologyId + '}'; } }
1,222
24.479167
125
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/TimeUnitParam.java
package org.infinispan.client.hotrod.impl; import java.util.EnumMap; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Time unit representation for HotRod * * @author gustavonalle * @since 8.0 */ public class TimeUnitParam { private static final Map<TimeUnit, Byte> timeUnitToByte = new EnumMap<>(TimeUnit.class); static { timeUnitToByte.put(TimeUnit.SECONDS, (byte) 0); timeUnitToByte.put(TimeUnit.MILLISECONDS, (byte) 1); timeUnitToByte.put(TimeUnit.NANOSECONDS, (byte) 2); timeUnitToByte.put(TimeUnit.MICROSECONDS, (byte) 3); timeUnitToByte.put(TimeUnit.MINUTES, (byte) 4); timeUnitToByte.put(TimeUnit.HOURS, (byte) 5); timeUnitToByte.put(TimeUnit.DAYS, (byte) 6); } private static final byte TIME_UNIT_DEFAULT = (byte) 7; private static final byte TIME_UNIT_INFINITE = (byte) 8; private static byte encodeDuration(long duration, TimeUnit timeUnit) { return duration == 0 ? TIME_UNIT_DEFAULT : duration < 0 ? TIME_UNIT_INFINITE : timeUnitToByte.get(timeUnit); } public static byte encodeTimeUnits(long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { byte encodedLifespan = encodeDuration(lifespan, lifespanTimeUnit); byte encodedMaxIdle = encodeDuration(maxIdle, maxIdleTimeUnit); return (byte) (encodedLifespan << 4 | encodedMaxIdle); } }
1,395
33.9
121
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/MetadataValueImpl.java
package org.infinispan.client.hotrod.impl; import org.infinispan.client.hotrod.MetadataValue; /** * MetadataValueImpl. * * @author Tristan Tarrant * @since 5.2 */ public class MetadataValueImpl<V> extends VersionedValueImpl<V> implements MetadataValue<V> { private final long created; private final int lifespan; private final long lastUsed; private final int maxIdle; public MetadataValueImpl(long created, int lifespan, long lastUsed, int maxIdle, long version, V value) { super(version, value); this.created = created; this.lifespan = lifespan; this.lastUsed = lastUsed; this.maxIdle = maxIdle; } @Override public long getCreated() { return created; } @Override public int getLifespan() { return lifespan; } @Override public long getLastUsed() { return lastUsed; } @Override public int getMaxIdle() { return maxIdle; } @Override public String toString() { return "MetadataValueImpl [created=" + created + ", lifespan=" + lifespan + ", lastUsed=" + lastUsed + ", maxIdle=" + maxIdle + ", getVersion()=" + getVersion() + ", getValue()=" + getValue() + "]"; } }
1,212
21.886792
166
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/InternalRemoteCache.java
package org.infinispan.client.hotrod.impl; import java.net.SocketAddress; import java.util.Map; import java.util.concurrent.CompletionStage; import javax.management.ObjectName; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.client.hotrod.impl.operations.RetryAwareCompletionStage; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.IntSet; public interface InternalRemoteCache<K, V> extends RemoteCache<K, V> { CloseableIterator<K> keyIterator(IntSet segments); CloseableIterator<Map.Entry<K, V>> entryIterator(IntSet segments); default boolean removeEntry(Map.Entry<K, V> entry) { return removeEntry(entry.getKey(), entry.getValue()); } default boolean removeEntry(K key, V value) { VersionedValue<V> versionedValue = getWithMetadata(key); return versionedValue != null && value.equals(versionedValue.getValue()) && removeWithVersion(key, versionedValue.getVersion()); } RetryAwareCompletionStage<MetadataValue<V>> getWithMetadataAsync(K key, SocketAddress preferredAddres); @Override InternalRemoteCache<K, V> withFlags(Flag... flags); @Override <T, U> InternalRemoteCache<T, U> withDataFormat(DataFormat dataFormat); boolean hasForceReturnFlag(); void resolveStorage(boolean objectStorage); @Override ClientStatistics clientStatistics(); void init(OperationsFactory operationsFactory, Configuration configuration, ObjectName jmxParent); void init(OperationsFactory operationsFactory, Configuration configuration); OperationsFactory getOperationsFactory(); boolean isObjectStorage(); K keyAsObjectIfNeeded(Object key); byte[] keyToBytes(Object o); CompletionStage<PingResponse> ping(); /** * Add a client listener to handle near cache with bloom filter optimization * The listener object must be annotated with @{@link org.infinispan.client.hotrod.annotation.ClientListener} annotation. */ SocketAddress addNearCacheListener(Object listener, int bloomBits); /** * Sends the current bloom filter to the listener node where a near cache listener is installed. If this * cache does not have near caching this will return an already completed stage. * @return stage that when complete the filter was sent to the listener node */ CompletionStage<Void> updateBloomFilter(); }
2,801
34.025
124
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/RemoteCacheEntrySet.java
package org.infinispan.client.hotrod.impl; import java.util.AbstractSet; import java.util.Map; import java.util.Spliterator; import java.util.stream.Stream; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableIteratorSet; import org.infinispan.commons.util.CloseableSpliterator; import org.infinispan.commons.util.Closeables; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.RemovableCloseableIterator; class RemoteCacheEntrySet<K, V> extends AbstractSet<Map.Entry<K, V>> implements CloseableIteratorSet<Map.Entry<K, V>> { private final InternalRemoteCache<K, V> remoteCache; private final IntSet segments; public RemoteCacheEntrySet(InternalRemoteCache<K, V> remoteCache, IntSet segments) { this.remoteCache = remoteCache; this.segments = segments; } @Override public CloseableIterator<Map.Entry<K, V>> iterator() { return new RemovableCloseableIterator<>(remoteCache.entryIterator(segments), this::remove); } @Override public CloseableSpliterator<Map.Entry<K, V>> spliterator() { return Closeables.spliterator(iterator(), Long.MAX_VALUE, Spliterator.NONNULL | Spliterator.CONCURRENT); } @Override public Stream<Map.Entry<K, V>> stream() { return Closeables.stream(spliterator(), false); } @Override public Stream<Map.Entry<K, V>> parallelStream() { return Closeables.stream(spliterator(), true); } @Override public int size() { return remoteCache.size(); } @Override public void clear() { remoteCache.clear(); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } //noinspection unchecked Map.Entry<K, V> entry = (Map.Entry<K, V>) o; V value = remoteCache.get(entry.getKey()); return value != null && value.equals(entry.getValue()); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } //noinspection unchecked Map.Entry<K, V> entry = (Map.Entry<K, V>) o; return remoteCache.removeEntry(entry); } }
2,189
28.2
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/RemoteCacheKeySet.java
package org.infinispan.client.hotrod.impl; import java.util.AbstractSet; import java.util.Collection; import java.util.Spliterator; import java.util.stream.Stream; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableIteratorSet; import org.infinispan.commons.util.CloseableSpliterator; import org.infinispan.commons.util.Closeables; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.RemovableCloseableIterator; class RemoteCacheKeySet<K> extends AbstractSet<K> implements CloseableIteratorSet<K> { private final InternalRemoteCache<K, ?> remoteCache; private final IntSet segments; RemoteCacheKeySet(InternalRemoteCache<K, ?> remoteCache, IntSet segments) { this.remoteCache = remoteCache; this.segments = segments; } @Override public CloseableIterator<K> iterator() { CloseableIterator<K> keyIterator = remoteCache.keyIterator(segments); return new RemovableCloseableIterator<>(keyIterator, this::remove); } @Override public CloseableSpliterator<K> spliterator() { return Closeables.spliterator(iterator(), Long.MAX_VALUE, Spliterator.NONNULL | Spliterator.CONCURRENT | Spliterator.DISTINCT); } @Override public Stream<K> stream() { return Closeables.stream(spliterator(), false); } @Override public Stream<K> parallelStream() { return Closeables.stream(spliterator(), true); } @Override public int size() { return remoteCache.size(); } @Override public void clear() { remoteCache.clear(); } @Override public boolean contains(Object o) { return remoteCache.containsKey(o); } @Override public boolean remove(Object o) { return remoteCache.remove(o) != null; } @Override public boolean removeAll(Collection<?> c) { boolean removedSomething = false; for (Object key : c) { removedSomething |= remove(key); } return removedSomething; } }
2,026
26.026667
110
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/VersionedMetadataImpl.java
package org.infinispan.client.hotrod.impl; import org.infinispan.client.hotrod.VersionedMetadata; /** * @author Tristan Tarrant * @since 9.0 */ public class VersionedMetadataImpl implements VersionedMetadata { private final long created; private final int lifespan; private final long lastUsed; private final int maxIdle; private final long version; public VersionedMetadataImpl(long created, int lifespan, long lastUsed, int maxIdle, long version) { this.created = created; this.lifespan = lifespan; this.lastUsed = lastUsed; this.maxIdle = maxIdle; this.version = version; } public long getCreated() { return created; } public int getLifespan() { return lifespan; } public long getLastUsed() { return lastUsed; } public int getMaxIdle() { return maxIdle; } public long getVersion() { return version; } }
929
19.666667
103
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/ServerStatisticsImpl.java
package org.infinispan.client.hotrod.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.infinispan.client.hotrod.ServerStatistics; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ public class ServerStatisticsImpl implements ServerStatistics { private final Map<String, String> stats = new HashMap<>(); @Override public Map<String, String> getStatsMap() { return Collections.unmodifiableMap(stats); } @Override public String getStatistic(String statsName) { return stats.get(statsName); } public void addStats(String name, String value) { stats.put(name, value); } public int size() { return stats.size(); } @Override public Integer getIntStatistic(String statsName) { String value = stats.get(statsName); return value == null ? null : Integer.parseInt(value); } }
904
21.073171
63
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/ClientTopology.java
package org.infinispan.client.hotrod.impl; import java.util.Objects; import org.infinispan.client.hotrod.configuration.ClientIntelligence; /** * Keeps the Hot Rod client topology information together: topology id and client intelligence. * * @since 14.0 */ public final class ClientTopology { private final int topologyId; private final ClientIntelligence clientIntelligence; public ClientTopology(int topologyId, ClientIntelligence clientIntelligence) { this.topologyId = topologyId; this.clientIntelligence = Objects.requireNonNull(clientIntelligence); } public int getTopologyId() { return topologyId; } public ClientIntelligence getClientIntelligence() { return clientIntelligence; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientTopology that = (ClientTopology) o; return topologyId == that.topologyId && clientIntelligence == that.clientIntelligence; } @Override public int hashCode() { int result = topologyId; result = 31 * result + clientIntelligence.hashCode(); return result; } @Override public String toString() { return "ClientTopology{" + "topologyId=" + topologyId + ", clientIntelligence=" + clientIntelligence + '}'; } }
1,404
24.545455
95
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/StreamingRemoteCacheImpl.java
package org.infinispan.client.hotrod.impl; import static org.infinispan.client.hotrod.impl.Util.await; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.StreamingRemoteCache; import org.infinispan.client.hotrod.VersionedMetadata; import org.infinispan.client.hotrod.impl.operations.GetStreamOperation; import org.infinispan.client.hotrod.impl.operations.PutStreamOperation; /** * Implementation of {@link StreamingRemoteCache} * * @author Tristan Tarrant * @since 9.0 */ public class StreamingRemoteCacheImpl<K> implements StreamingRemoteCache<K> { private final InternalRemoteCache<K, ?> cache; public StreamingRemoteCacheImpl(InternalRemoteCache<K, ?> cache) { this.cache = cache; } @Override public <T extends InputStream & VersionedMetadata> T get(K key) { GetStreamOperation op = cache.getOperationsFactory().newGetStreamOperation(cache.keyAsObjectIfNeeded(key), cache.keyToBytes(key), 0); return (T) await(op.execute()); } @Override public OutputStream put(K key) { return put(key, -1, TimeUnit.SECONDS, -1, TimeUnit.SECONDS); } @Override public OutputStream put(K key, long lifespan, TimeUnit unit) { return put(key, lifespan, unit, -1, TimeUnit.SECONDS); } @Override public OutputStream put(K key, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { PutStreamOperation op = cache.getOperationsFactory().newPutStreamOperation(cache.keyAsObjectIfNeeded(key), cache.keyToBytes(key), lifespan, lifespanUnit, maxIdle, maxIdleUnit); return await(op.execute()); } @Override public OutputStream putIfAbsent(K key) { return putIfAbsent(key, -1, TimeUnit.SECONDS, -1, TimeUnit.SECONDS); } @Override public OutputStream putIfAbsent(K key, long lifespan, TimeUnit unit) { return putIfAbsent(key, lifespan, unit, -1, TimeUnit.SECONDS); } @Override public OutputStream putIfAbsent(K key, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { PutStreamOperation op = cache.getOperationsFactory().newPutIfAbsentStreamOperation(cache.keyAsObjectIfNeeded(key), cache.keyToBytes(key), lifespan, lifespanUnit, maxIdle, maxIdleUnit); return await(op.execute()); } @Override public OutputStream replaceWithVersion(K key, long version) { return replaceWithVersion(key, version, -1, TimeUnit.SECONDS, -1, TimeUnit.SECONDS); } @Override public OutputStream replaceWithVersion(K key, long version, long lifespan, TimeUnit unit) { return replaceWithVersion(key, version, lifespan, unit, -1, TimeUnit.SECONDS); } @Override public OutputStream replaceWithVersion(K key, long version, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { PutStreamOperation op = cache.getOperationsFactory().newPutStreamOperation(cache.keyAsObjectIfNeeded(key), cache.keyToBytes(key), version, lifespan, lifespanUnit, maxIdle, maxIdleUnit); return await(op.execute()); } }
3,094
36.743902
191
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/RemoteCacheValuesCollection.java
package org.infinispan.client.hotrod.impl; import java.util.AbstractCollection; import java.util.Map; import java.util.Objects; import java.util.Spliterator; import java.util.stream.Stream; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableIteratorCollection; import org.infinispan.commons.util.CloseableSpliterator; import org.infinispan.commons.util.Closeables; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IteratorMapper; import org.infinispan.commons.util.RemovableCloseableIterator; class RemoteCacheValuesCollection<V> extends AbstractCollection<V> implements CloseableIteratorCollection<V> { private final InternalRemoteCache<?, V> remoteCache; private final IntSet segments; RemoteCacheValuesCollection(InternalRemoteCache<?, V> remoteCache, IntSet segments) { this.remoteCache = remoteCache; this.segments = segments; } @Override public CloseableIterator<V> iterator() { CloseableIterator<Map.Entry<?, V>> entryIterator = ((InternalRemoteCache) remoteCache).entryIterator(segments); return new IteratorMapper<>(new RemovableCloseableIterator<>(entryIterator, e -> remoteCache.remove(e.getKey(), e.getValue())), // Convert to V for user Map.Entry::getValue); } @Override public CloseableSpliterator<V> spliterator() { return Closeables.spliterator(iterator(), Long.MAX_VALUE, Spliterator.NONNULL | Spliterator.CONCURRENT); } @Override public Stream<V> stream() { return Closeables.stream(spliterator(), false); } @Override public Stream<V> parallelStream() { return Closeables.stream(spliterator(), true); } @Override public int size() { return remoteCache.size(); } @Override public void clear() { remoteCache.clear(); } @Override public boolean contains(Object o) { // TODO: This would be more efficient if done on the server as a task or separate protocol // Have to close the stream, just in case stream terminates early try (Stream<V> stream = stream()) { return stream.anyMatch(v -> Objects.deepEquals(v, o)); } } // This method can terminate early so we have to make sure to close iterator @Override public boolean remove(Object o) { Objects.requireNonNull(o); try (CloseableIterator<V> iter = iterator()) { while (iter.hasNext()) { if (o.equals(iter.next())) { iter.remove(); return true; } } } return false; } }
2,616
30.53012
133
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/ClientStatistics.java
package org.infinispan.client.hotrod.impl; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import org.infinispan.client.hotrod.jmx.RemoteCacheClientStatisticsMXBean; import org.infinispan.client.hotrod.near.NearCacheService; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.concurrent.StripedCounters; public final class ClientStatistics implements RemoteCacheClientStatisticsMXBean { private final boolean enabled; private final AtomicLong startNanoseconds = new AtomicLong(0); private final AtomicLong resetNanoseconds = new AtomicLong(0); private final NearCacheService nearCacheService; private final TimeService timeService; private final StripedCounters<StripeB> counters = new StripedCounters<>(StripeC::new); ClientStatistics(boolean enabled, TimeService timeService, NearCacheService nearCacheService) { this.enabled = enabled; this.timeService = timeService; this.nearCacheService = nearCacheService; if (nearCacheService != null) nearCacheService.setInvalidationCallback(this::incrementNearCacheInvalidations); } ClientStatistics(boolean enabled, TimeService timeService) { this(enabled, timeService, null); } public boolean isEnabled() { return enabled; } @Override public long getRemoteHits() { return counters.get(StripeB.remoteCacheHitsFieldUpdater); } @Override public long getRemoteMisses() { return counters.get(StripeB.remoteCacheMissesFieldUpdater); } @Override public long getAverageRemoteReadTime() { long total = counters.get(StripeB.remoteCacheHitsFieldUpdater) + counters.get(StripeB.remoteCacheMissesFieldUpdater); if (total == 0) return 0; total = (counters.get(StripeB.remoteCacheHitsTimeFieldUpdater) + counters.get(StripeB.remoteCacheMissesTimeFieldUpdater)) / total; return TimeUnit.NANOSECONDS.toMillis(total); } @Override public long getRemoteStores() { return counters.get(StripeB.remoteCacheStoresFieldUpdater); } @Override public long getAverageRemoteStoreTime() { long total = counters.get(StripeB.remoteCacheStoresFieldUpdater); if (total == 0) return 0; total = counters.get(StripeB.remoteCacheStoresTimeFieldUpdater) / total; return TimeUnit.NANOSECONDS.toMillis(total); } @Override public long getRemoteRemoves() { return counters.get(StripeB.remoteCacheRemovesFieldUpdater); } @Override public long getAverageRemoteRemovesTime() { long total = counters.get(StripeB.remoteCacheRemovesFieldUpdater); if (total == 0) return 0; total = counters.get(StripeB.remoteCacheRemovesTimeFieldUpdater) / total; return TimeUnit.NANOSECONDS.toMillis(total); } @Override public long getNearCacheHits() { return counters.get(StripeB.nearCacheHitsFieldUpdater); } @Override public long getNearCacheMisses() { return counters.get(StripeB.nearCacheMissesFieldUpdater); } @Override public long getNearCacheInvalidations() { return counters.get(StripeB.nearCacheInvalidationsFieldUpdater); } @Override public long getNearCacheSize() { return nearCacheService != null ? nearCacheService.size() : 0; } public long time() { return timeService.time(); } public void dataRead(boolean foundValue, long startTimeNanoSeconds, int count) { long duration = timeService.timeDuration(startTimeNanoSeconds, TimeUnit.NANOSECONDS); StripeB stripe = counters.stripeForCurrentThread(); if (foundValue) { counters.add(StripeB.remoteCacheHitsTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheHitsFieldUpdater, stripe, count); } else { counters.add(StripeB.remoteCacheMissesTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheMissesFieldUpdater, stripe, count); } } public void dataStore(long startTimeNanoSeconds, int count) { long duration = timeService.timeDuration(startTimeNanoSeconds, TimeUnit.NANOSECONDS); StripeB stripe = counters.stripeForCurrentThread(); counters.add(StripeB.remoteCacheStoresTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheStoresFieldUpdater, stripe, count); } public void dataRemove(long startTimeNanoSeconds, int count) { long duration = timeService.timeDuration(startTimeNanoSeconds, TimeUnit.NANOSECONDS); StripeB stripe = counters.stripeForCurrentThread(); counters.add(StripeB.remoteCacheRemovesTimeFieldUpdater, stripe, duration); counters.add(StripeB.remoteCacheRemovesFieldUpdater, stripe, count); } public void incrementNearCacheMisses() { counters.increment(StripeB.nearCacheMissesFieldUpdater, counters.stripeForCurrentThread()); } public void incrementNearCacheHits() { counters.increment(StripeB.nearCacheHitsFieldUpdater, counters.stripeForCurrentThread()); } public void incrementNearCacheInvalidations() { counters.increment(StripeB.nearCacheInvalidationsFieldUpdater, counters.stripeForCurrentThread()); } @Override public void resetStatistics() { counters.reset(StripeB.remoteCacheHitsFieldUpdater); counters.reset(StripeB.remoteCacheHitsTimeFieldUpdater); counters.reset(StripeB.remoteCacheMissesFieldUpdater); counters.reset(StripeB.remoteCacheMissesTimeFieldUpdater); counters.reset(StripeB.remoteCacheRemovesFieldUpdater); counters.reset(StripeB.remoteCacheRemovesTimeFieldUpdater); counters.reset(StripeB.remoteCacheStoresFieldUpdater); counters.reset(StripeB.remoteCacheStoresTimeFieldUpdater); counters.reset(StripeB.nearCacheHitsFieldUpdater); counters.reset(StripeB.nearCacheMissesFieldUpdater); counters.reset(StripeB.nearCacheInvalidationsFieldUpdater); startNanoseconds.set(timeService.time()); resetNanoseconds.set(startNanoseconds.get()); } @Override public long getTimeSinceReset() { return timeService.timeDuration(resetNanoseconds.get(), TimeUnit.SECONDS); } /** * It returns a {@link ClientStatistics} instance to be used when the statistics aren't needed. * * @return a disabled {@link ClientStatistics} instance. */ public static ClientStatistics dummyClientStatistics(TimeService timeService) { return new ClientStatistics(false, timeService); } private static class StripeA { @SuppressWarnings("unused") private long slack1, slack2, slack3, slack4, slack5, slack6, slack7, slack8; } @SuppressWarnings("VolatileLongOrDoubleField") private static class StripeB extends StripeA { static final AtomicLongFieldUpdater<StripeB> remoteCacheHitsFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheHits"); static final AtomicLongFieldUpdater<StripeB> remoteCacheHitsTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheHitsTime"); static final AtomicLongFieldUpdater<StripeB> remoteCacheMissesFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheMisses"); static final AtomicLongFieldUpdater<StripeB> remoteCacheMissesTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheMissesTime"); static final AtomicLongFieldUpdater<StripeB> remoteCacheRemovesFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheRemoves"); static final AtomicLongFieldUpdater<StripeB> remoteCacheRemovesTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheRemovesTime"); static final AtomicLongFieldUpdater<StripeB> remoteCacheStoresFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheStores"); static final AtomicLongFieldUpdater<StripeB> remoteCacheStoresTimeFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "remoteCacheStoresTime"); static final AtomicLongFieldUpdater<StripeB> nearCacheHitsFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "nearCacheHits"); static final AtomicLongFieldUpdater<StripeB> nearCacheMissesFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "nearCacheMisses"); static final AtomicLongFieldUpdater<StripeB> nearCacheInvalidationsFieldUpdater = AtomicLongFieldUpdater.newUpdater(StripeB.class, "nearCacheInvalidations"); private volatile long remoteCacheHits = 0; private volatile long remoteCacheHitsTime = 0; private volatile long remoteCacheMisses = 0; private volatile long remoteCacheMissesTime = 0; private volatile long remoteCacheRemoves = 0; private volatile long remoteCacheRemovesTime = 0; private volatile long remoteCacheStores = 0; private volatile long remoteCacheStoresTime = 0; private volatile long nearCacheHits = 0; private volatile long nearCacheMisses = 0; private volatile long nearCacheInvalidations = 0; } private static final class StripeC extends StripeB { @SuppressWarnings("unused") private long slack1, slack2, slack3, slack4, slack5, slack6, slack7, slack8; } }
9,441
40.964444
136
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/RemoteCacheManagerAdminImpl.java
package org.infinispan.client.hotrod.impl; import static org.infinispan.client.hotrod.impl.Util.await; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.RemoteCacheManagerAdmin; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.commons.configuration.BasicConfiguration; /** * @author Tristan Tarrant * @since 9.1 */ public class RemoteCacheManagerAdminImpl implements RemoteCacheManagerAdmin { public static final String CACHE_NAME = "name"; public static final String CACHE_TEMPLATE = "template"; public static final String CACHE_CONFIGURATION = "configuration"; public static final String ATTRIBUTE = "attribute"; public static final String VALUE = "value"; public static final String FLAGS = "flags"; private final RemoteCacheManager cacheManager; private final OperationsFactory operationsFactory; private final EnumSet<AdminFlag> flags; private final Consumer<String> remover; public RemoteCacheManagerAdminImpl(RemoteCacheManager cacheManager, OperationsFactory operationsFactory, EnumSet<AdminFlag> flags, Consumer<String> remover) { this.cacheManager = cacheManager; this.operationsFactory = operationsFactory; this.flags = flags; this.remover = remover; } @Override public <K, V> RemoteCache<K, V> createCache(String name, String template) throws HotRodClientException { Map<String, byte[]> params = new HashMap<>(2); params.put(CACHE_NAME, string(name)); if (template != null) params.put(CACHE_TEMPLATE, string(template)); if (flags != null && !flags.isEmpty()) params.put(FLAGS, flags(flags)); await(operationsFactory.newAdminOperation("@@cache@create", params).execute()); return cacheManager.getCache(name); } @Override public <K, V> RemoteCache<K, V> createCache(String name, DefaultTemplate template) throws HotRodClientException { return createCache(name, template.getTemplateName()); } @Override public <K, V> RemoteCache<K, V> createCache(String name, BasicConfiguration configuration) throws HotRodClientException { Map<String, byte[]> params = new HashMap<>(2); params.put(CACHE_NAME, string(name)); if (configuration != null) params.put(CACHE_CONFIGURATION, string(configuration.toStringConfiguration(name))); if (flags != null && !flags.isEmpty()) params.put(FLAGS, flags(flags)); await(operationsFactory.newAdminOperation("@@cache@create", params).execute()); return cacheManager.getCache(name); } @Override public <K, V> RemoteCache<K, V> getOrCreateCache(String name, String template) throws HotRodClientException { Map<String, byte[]> params = new HashMap<>(2); params.put(CACHE_NAME, string(name)); if (template != null) params.put(CACHE_TEMPLATE, string(template)); if (flags != null && !flags.isEmpty()) params.put(FLAGS, flags(flags)); await(operationsFactory.newAdminOperation("@@cache@getorcreate", params).execute()); return cacheManager.getCache(name); } @Override public <K, V> RemoteCache<K, V> getOrCreateCache(String name, DefaultTemplate template) throws HotRodClientException { return getOrCreateCache(name, template.getTemplateName()); } @Override public <K, V> RemoteCache<K, V> getOrCreateCache(String name, BasicConfiguration configuration) throws HotRodClientException { Map<String, byte[]> params = new HashMap<>(2); params.put(CACHE_NAME, string(name)); if (configuration != null) params.put(CACHE_CONFIGURATION, string(configuration.toStringConfiguration(name))); if (flags != null && !flags.isEmpty()) params.put(FLAGS, flags(flags)); await(operationsFactory.newAdminOperation("@@cache@getorcreate", params).execute()); return cacheManager.getCache(name); } @Override public void removeCache(String name) { remover.accept(name); Map<String, byte[]> params = new HashMap<>(2); params.put(CACHE_NAME, string(name)); if (flags != null && !flags.isEmpty()) params.put(FLAGS, flags(flags)); await(operationsFactory.newAdminOperation("@@cache@remove", params).execute()); } @Override public RemoteCacheManagerAdmin withFlags(AdminFlag... flags) { EnumSet<AdminFlag> newFlags = EnumSet.copyOf(this.flags); for(AdminFlag flag : flags) newFlags.add(flag); return new RemoteCacheManagerAdminImpl(cacheManager, operationsFactory, newFlags, remover); } @Override public RemoteCacheManagerAdmin withFlags(EnumSet<AdminFlag> flags) { EnumSet<AdminFlag> newFlags = EnumSet.copyOf(this.flags); newFlags.addAll(flags); return new RemoteCacheManagerAdminImpl(cacheManager, operationsFactory, newFlags, remover); } @Override public void reindexCache(String name) throws HotRodClientException { await(operationsFactory.newAdminOperation("@@cache@reindex", Collections.singletonMap(CACHE_NAME, string(name))).execute()); } @Override public void updateIndexSchema(String name) throws HotRodClientException { await(operationsFactory.newAdminOperation("@@cache@updateindexschema", Collections.singletonMap(CACHE_NAME, string(name))).execute()); } @Override public void updateConfigurationAttribute(String name, String attribute, String value) throws HotRodClientException { Map<String, byte[]> params = new HashMap<>(4); params.put(CACHE_NAME, string(name)); params.put(ATTRIBUTE, string(attribute)); params.put(VALUE, string(value)); if (flags != null && !flags.isEmpty()) { params.put(FLAGS, flags(flags)); } await(operationsFactory.newAdminOperation("@@cache@updateConfigurationAttribute", params).execute()); } @Override public void createTemplate(String name, BasicConfiguration configuration) { Map<String, byte[]> params = new HashMap<>(2); params.put(CACHE_NAME, string(name)); if (configuration != null) params.put(CACHE_CONFIGURATION, string(configuration.toStringConfiguration(name))); if (flags != null && !flags.isEmpty()) params.put(FLAGS, flags(flags)); await(operationsFactory.newAdminOperation("@@template@create", params).execute()); } @Override public void removeTemplate(String name) { Map<String, byte[]> params = new HashMap<>(2); params.put(CACHE_NAME, string(name)); if (flags != null && !flags.isEmpty()) params.put(FLAGS, flags(flags)); await(operationsFactory.newAdminOperation("@@template@remove", params).execute()); } private static byte[] flags(EnumSet<AdminFlag> flags) { String sFlags = flags.stream().map(AdminFlag::toString).collect(Collectors.joining(",")); return string(sFlags); } private static byte[] string(String s) { return s.getBytes(HotRodConstants.HOTROD_STRING_CHARSET); } }
7,337
42.678571
161
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/MarshallerRegistry.java
package org.infinispan.client.hotrod.impl; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.Marshaller; /** * A registry of {@link Marshaller} along with its {@link MediaType}. * * @since 9.3 */ public final class MarshallerRegistry { public static final Log log = LogFactory.getLog(MarshallerRegistry.class, Log.class); private final Map<MediaType, Marshaller> marshallerByMediaType = new ConcurrentHashMap<>(); public void registerMarshaller(Marshaller marshaller) { marshallerByMediaType.put(marshaller.mediaType().withoutParameters(), marshaller); } public Marshaller getMarshaller(MediaType mediaType) { return marshallerByMediaType.get(mediaType); } public Marshaller getMarshaller(Class<? extends Marshaller> marshallerClass) { return marshallerByMediaType.values().stream() .filter(m -> m.getClass().equals(marshallerClass)).findFirst().orElse(null); } }
1,150
30.972222
94
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/DelegatingRemoteCache.java
package org.infinispan.client.hotrod.impl; import java.net.SocketAddress; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Function; import javax.management.ObjectName; import org.infinispan.client.hotrod.CacheTopologyInfo; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.RemoteCacheContainer; import org.infinispan.client.hotrod.ServerStatistics; import org.infinispan.client.hotrod.StreamingRemoteCache; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.operations.PingResponse; import org.infinispan.client.hotrod.impl.operations.RetryAwareCompletionStage; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableIteratorCollection; import org.infinispan.commons.util.CloseableIteratorSet; import org.infinispan.commons.util.IntSet; import org.infinispan.query.dsl.Query; import org.reactivestreams.Publisher; /** * Delegates all invocations to the provided underlying {@link InternalRemoteCache} but provides extensibility to intercept * when a method is invoked. Currently all methods are supported except for iterators produced from the * {@link #keyIterator(IntSet)} and {@link #entryIterator(IntSet)} which are known to invoke back into the delegate cache. * @param <K> key type * @param <V> value type */ public abstract class DelegatingRemoteCache<K, V> extends RemoteCacheSupport<K, V> implements InternalRemoteCache<K, V> { protected final InternalRemoteCache<K, V> delegate; protected DelegatingRemoteCache(InternalRemoteCache<K, V> delegate) { this.delegate = delegate; } abstract <Key, Value> InternalRemoteCache<Key, Value> newDelegatingCache(InternalRemoteCache<Key, Value> innerCache); @Override public CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.putAllAsync(data, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public CompletableFuture<Void> clearAsync() { return delegate.clearAsync(); } @Override public ClientStatistics clientStatistics() { return delegate.clientStatistics(); } @Override public ServerStatistics serverStatistics() { return delegate.serverStatistics(); } @Override public CompletionStage<ServerStatistics> serverStatisticsAsync() { return delegate.serverStatisticsAsync(); } @Override public InternalRemoteCache<K, V> withFlags(Flag... flags) { InternalRemoteCache<K, V> newCache = delegate.withFlags(flags); if (newCache != delegate) { return newDelegatingCache(newCache); } return this; } @Override public RemoteCacheContainer getRemoteCacheContainer() { return delegate.getRemoteCacheContainer(); } @Override public CompletableFuture<Map<K, V>> getAllAsync(Set<?> keys) { return delegate.getAllAsync(keys); } @Override public String getProtocolVersion() { return delegate.getProtocolVersion(); } @Override public void addClientListener(Object listener) { delegate.addClientListener(listener); } @Override public void addClientListener(Object listener, Object[] filterFactoryParams, Object[] converterFactoryParams) { delegate.addClientListener(listener, filterFactoryParams, converterFactoryParams); } @Override public void removeClientListener(Object listener) { delegate.removeClientListener(listener); } @Override public SocketAddress addNearCacheListener(Object listener, int bloomBits) { return delegate.addNearCacheListener(listener, bloomBits); } @Override public Set<Object> getListeners() { return delegate.getListeners(); } @Override public <T> T execute(String taskName, Map<String, ?> params) { return delegate.execute(taskName, params); } @Override public CacheTopologyInfo getCacheTopologyInfo() { return delegate.getCacheTopologyInfo(); } @Override public StreamingRemoteCache<K> streaming() { return delegate.streaming(); } @Override public <T, U> InternalRemoteCache<T, U> withDataFormat(DataFormat dataFormat) { InternalRemoteCache<T, U> newCache = delegate.withDataFormat(dataFormat); if (newCache != delegate) { return newDelegatingCache(newCache); } //noinspection unchecked return (InternalRemoteCache<T, U>) this; } @Override public DataFormat getDataFormat() { return delegate.getDataFormat(); } @Override public boolean isTransactional() { return delegate.isTransactional(); } @Override public CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.putIfAbsentAsync(key, value, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.replaceAsync(key, oldValue, newValue, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.replaceAsync(key, value, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public CompletableFuture<V> getAsync(K key) { return delegate.getAsync(key); } @Override public CompletableFuture<MetadataValue<V>> getWithMetadataAsync(K key) { return delegate.getWithMetadataAsync(key); } @Override public RetryAwareCompletionStage<MetadataValue<V>> getWithMetadataAsync(K key, SocketAddress preferredAddres) { return delegate.getWithMetadataAsync(key, preferredAddres); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean containsValue(Object value) { return delegate.containsValue(value); } @Override public CloseableIteratorSet<K> keySet(IntSet segments) { return new RemoteCacheKeySet<>(this, segments); } @Override public CloseableIteratorCollection<V> values(IntSet segments) { return new RemoteCacheValuesCollection<>(this, segments); } @Override public CloseableIteratorSet<Entry<K, V>> entrySet(IntSet segments) { return new RemoteCacheEntrySet<>(this, segments); } @Override public CompletableFuture<Boolean> containsKeyAsync(K key) { return delegate.containsKeyAsync(key); } @Override public CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.putAsync(key, value, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public CompletableFuture<Boolean> replaceWithVersionAsync(K key, V newValue, long version, long lifespanSeconds, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit) { return delegate.replaceWithVersionAsync(key, newValue, version, lifespanSeconds, lifespanTimeUnit, maxIdle, maxIdleTimeUnit); } @Override public CloseableIterator<Entry<Object, Object>> retrieveEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { return delegate.retrieveEntries(filterConverterFactory, filterConverterParams, segments, batchSize); } @Override public <E> Publisher<Entry<K, E>> publishEntries(String filterConverterFactory, Object[] filterConverterParams, Set<Integer> segments, int batchSize) { return delegate.publishEntries(filterConverterFactory, filterConverterParams, segments, batchSize); } @Override public CloseableIterator<Entry<Object, Object>> retrieveEntriesByQuery(Query<?> filterQuery, Set<Integer> segments, int batchSize) { return delegate.retrieveEntriesByQuery(filterQuery, segments, batchSize); } @Override public <E> Publisher<Entry<K, E>> publishEntriesByQuery(Query<?> filterQuery, Set<Integer> segments, int batchSize) { return delegate.publishEntriesByQuery(filterQuery, segments, batchSize); } @Override public CloseableIterator<Entry<Object, MetadataValue<Object>>> retrieveEntriesWithMetadata(Set<Integer> segments, int batchSize) { return delegate.retrieveEntriesWithMetadata(segments, batchSize); } @Override public Publisher<Entry<K, MetadataValue<V>>> publishEntriesWithMetadata(Set<Integer> segments, int batchSize) { return delegate.publishEntriesWithMetadata(segments, batchSize); } @Override public CompletableFuture<V> removeAsync(Object key) { return delegate.removeAsync(key); } @Override public CompletableFuture<Boolean> removeAsync(Object key, Object value) { return delegate.removeAsync(key, value); } @Override public CompletableFuture<Boolean> removeWithVersionAsync(K key, long version) { return delegate.removeWithVersionAsync(key, version); } @Override public CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return delegate.mergeAsync(key, value, remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } @Override public CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.computeAsync(key, remappingFunction, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.computeIfAbsentAsync(key, mappingFunction, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) { return delegate.computeIfPresentAsync(key, remappingFunction, lifespan, lifespanUnit, maxIdle, maxIdleUnit); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { delegate.replaceAll(function); } @Override public CompletableFuture<Long> sizeAsync() { return delegate.sizeAsync(); } @Override public String getName() { return delegate.getName(); } @Override public String getVersion() { return delegate.getVersion(); } @Override public void start() { delegate.start(); } @Override public void stop() { delegate.stop(); } @Override public CloseableIterator<K> keyIterator(IntSet segments) { return delegate.keyIterator(segments); } @Override public CloseableIterator<Entry<K, V>> entryIterator(IntSet segments) { return delegate.entryIterator(segments); } @Override public boolean hasForceReturnFlag() { return delegate.hasForceReturnFlag(); } @Override public void resolveStorage(boolean objectStorage) { delegate.resolveStorage(objectStorage); } @Override public K keyAsObjectIfNeeded(Object key) { return delegate.keyAsObjectIfNeeded(key); } @Override public byte[] keyToBytes(Object o) { return delegate.keyToBytes(o); } @Override public void init(OperationsFactory operationsFactory, Configuration configuration, ObjectName jmxParent) { delegate.init(operationsFactory, configuration, jmxParent); } @Override public void init(OperationsFactory operationsFactory, Configuration configuration) { delegate.init(operationsFactory, configuration); } @Override public OperationsFactory getOperationsFactory() { return delegate.getOperationsFactory(); } @Override public boolean isObjectStorage() { return delegate.isObjectStorage(); } @Override public CompletionStage<PingResponse> ping() { return delegate.ping(); } @Override public CompletionStage<Void> updateBloomFilter() { return delegate.updateBloomFilter(); } }
12,870
32.693717
206
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/VersionedOperationResponse.java
package org.infinispan.client.hotrod.impl; /** * @author Mircea.Markus@jboss.com * @since 4.1 */ public class VersionedOperationResponse<V> { public enum RspCode { SUCCESS(true), NO_SUCH_KEY(false), MODIFIED_KEY(false); private boolean isModified; RspCode(boolean modified) { isModified = modified; } public boolean isUpdated() { return isModified; } } private V value; private RspCode code; public VersionedOperationResponse(V value, RspCode code) { this.value = value; this.code = code; } public V getValue() { return value; } public RspCode getCode() { return code; } }
691
16.3
61
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/Util.java
package org.infinispan.client.hotrod.impl; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.net.SocketTimeoutException; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.transaction.xa.Xid; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; import org.infinispan.client.hotrod.impl.transaction.operations.PrepareTransactionOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.commons.CacheException; import org.infinispan.commons.marshall.WrappedByteArray; public class Util { private final static long BIG_DELAY_NANOS = TimeUnit.DAYS.toNanos(1); private static final Xid DUMMY_XID = new Xid() { @Override public int getFormatId() { return 0; } @Override public byte[] getGlobalTransactionId() { return new byte[]{1}; } @Override public byte[] getBranchQualifier() { return new byte[]{1}; } }; private Util() { } public static <T> T await(CompletionStage<T> cf) { return await(cf.toCompletableFuture()); } public static <T> T await(CompletableFuture<T> cf) { try { // timed wait does not do busy waiting return cf.get(BIG_DELAY_NANOS, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { // Need to restore interrupt status because InterruptedException cannot be sent back as is Thread.currentThread().interrupt(); throw new HotRodClientException(e); } catch (ExecutionException e) { throw rewrap(e); } catch (TimeoutException e) { throw new IllegalStateException(e); } } public static <T> T await(CompletableFuture<T> cf, long timeoutMillis) { try { return cf.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // Need to restore interrupt status because InterruptedException cannot be sent back as is Thread.currentThread().interrupt(); throw new HotRodClientException(e); } catch (ExecutionException e) { throw rewrap(e); } catch (TimeoutException e) { cf.cancel(false); throw new TransportException(new SocketTimeoutException(), null); } } protected static RuntimeException rewrap(ExecutionException e) { if (e.getCause() instanceof HotRodClientException) { return (HotRodClientException) e.getCause(); } else if (e.getCause() instanceof CacheException) { return (CacheException) e.getCause(); } else { return new TransportException(e.getCause(), null); } } public static CompletionStage<Boolean> checkTransactionSupport(String cacheName, OperationsFactory factory) { PrepareTransactionOperation op = factory.newPrepareTransactionOperation(DUMMY_XID, true, Collections.emptyList(), false, 60000); return op.execute().handle((integer, throwable) -> { if (throwable != null) { HOTROD.invalidTxServerConfig(cacheName, throwable); } return throwable == null; }); } public static boolean checkTransactionSupport(String cacheName, OperationsFactory factory, Log log) { PrepareTransactionOperation op = factory.newPrepareTransactionOperation(DUMMY_XID, true, Collections.emptyList(), false, 60000); try { return op.execute().handle((integer, throwable) -> { if (throwable != null) { HOTROD.invalidTxServerConfig(cacheName, throwable); } return throwable == null; }).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { log.debugf("Exception while checking transaction support in server", e); } return false; } public static WrappedByteArray wrapBytes(byte[] cacheName) { WrappedByteArray wrappedCacheName; if (cacheName == null || cacheName.length == 0) { wrappedCacheName = WrappedByteArray.EMPTY_BYTES; } else { wrappedCacheName = new WrappedByteArray(cacheName); } return wrappedCacheName; } }
4,561
34.640625
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/iteration/KeyTracker.java
package org.infinispan.client.hotrod.impl.iteration; import java.util.Set; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.util.IntSet; /** * @author gustavonalle * @since 8.0 */ public interface KeyTracker { boolean track(byte[] key, short status, ClassAllowList allowList); void segmentsFinished(IntSet finishedSegments); Set<Integer> missedSegments(); }
417
19.9
69
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/iteration/NoOpSegmentKeyTracker.java
package org.infinispan.client.hotrod.impl.iteration; import java.util.Set; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.util.IntSet; /** * @author gustavonalle * @since 8.0 */ class NoOpSegmentKeyTracker implements KeyTracker { @Override public boolean track(byte[] key, short status, ClassAllowList allowList) { return true; } @Override public void segmentsFinished(IntSet finishedSegments) { } @Override public Set<Integer> missedSegments() { return null; } }
556
18.206897
77
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/iteration/KeyTrackerFactory.java
package org.infinispan.client.hotrod.impl.iteration; import java.util.Set; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; /** * @author gustavonalle * @since 8.0 */ final class KeyTrackerFactory { private KeyTrackerFactory() { } public static KeyTracker create(DataFormat dataFormat, ConsistentHash hash, int topologyId, Set<Integer> segments) { if (topologyId == -1) return new NoOpSegmentKeyTracker(); if (hash == null) return new ReplKeyTracker(); return new SegmentKeyTracker(dataFormat, (SegmentConsistentHash) hash, segments); } }
728
28.16
119
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/iteration/SegmentKeyTracker.java
package org.infinispan.client.hotrod.impl.iteration; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.function.IntConsumer; import java.util.stream.IntStream; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.Util; /** * @author gustavonalle * @since 8.0 */ class SegmentKeyTracker implements KeyTracker { private static final Log log = LogFactory.getLog(SegmentKeyTracker.class); private final AtomicReferenceArray<Set<WrappedByteArray>> keysPerSegment; private final SegmentConsistentHash segmentConsistentHash; private final DataFormat dataFormat; public SegmentKeyTracker(DataFormat dataFormat, SegmentConsistentHash segmentConsistentHash, Set<Integer> segments) { this.dataFormat = dataFormat; int numSegments = segmentConsistentHash.getNumSegments(); keysPerSegment = new AtomicReferenceArray<>(numSegments); if (log.isTraceEnabled()) log.tracef("Created SegmentKeyTracker with %d segments, filter %s", numSegments, segments); this.segmentConsistentHash = segmentConsistentHash; IntStream segmentStream = segments == null ? IntStream.range(0, segmentConsistentHash.getNumSegments()) : segments.stream().mapToInt(i -> i); segmentStream.forEach(i -> keysPerSegment.set(i, new HashSet<>())); } public boolean track(byte[] key, short status, ClassAllowList allowList) { int segment = dataFormat.isObjectStorage() ? segmentConsistentHash.getSegment(dataFormat.keyToObj(key, allowList)) : segmentConsistentHash.getSegment(key); Set<WrappedByteArray> keys = keysPerSegment.get(segment); if (keys == null) throw new IllegalStateException("Segment " + segment + " already completed"); boolean result = keys.add(new WrappedByteArray(key)); if (log.isTraceEnabled()) log.trackingSegmentKey(Util.printArray(key), segment, !result); return result; } public Set<Integer> missedSegments() { int length = keysPerSegment.length(); if (length == 0) return null; Set<Integer> missed = new HashSet<>(length); for (int i = 0; i < keysPerSegment.length(); i++) { if (keysPerSegment.get(i) != null) { missed.add(i); } } return missed; } public void segmentsFinished(IntSet finishedSegments) { if (finishedSegments != null) { if (log.isTraceEnabled()) log.tracef("Removing completed segments %s", finishedSegments); finishedSegments.forEach((IntConsumer) seg -> keysPerSegment.set(seg, null)); } } }
3,020
39.824324
120
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/iteration/RemoteInnerPublisherHandler.java
package org.infinispan.client.hotrod.impl.iteration; import java.lang.invoke.MethodHandles; import java.net.SocketAddress; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.infinispan.client.hotrod.exceptions.RemoteIllegalLifecycleStateException; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.client.hotrod.impl.operations.IterationNextResponse; import org.infinispan.client.hotrod.impl.operations.IterationStartResponse; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.reactive.AbstractAsyncPublisherHandler; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.logging.TraceException; import io.netty.channel.Channel; class RemoteInnerPublisherHandler<K, E> extends AbstractAsyncPublisherHandler<Map.Entry<SocketAddress, IntSet>, Map.Entry<K, E>, IterationStartResponse, IterationNextResponse<K, E>> { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); protected final RemotePublisher<K, E> publisher; // Need to be volatile since cancel can come on a different thread protected volatile Channel channel; private volatile byte[] iterationId; private AtomicBoolean cancelled = new AtomicBoolean(); protected RemoteInnerPublisherHandler(RemotePublisher<K, E> parent, int batchSize, Supplier<Map.Entry<SocketAddress, IntSet>> supplier, Map.Entry<SocketAddress, IntSet> firstTarget) { super(batchSize, supplier, firstTarget); this.publisher = parent; } private String iterationId() { return publisher.iterationId(iterationId); } @Override protected void sendCancel(Map.Entry<SocketAddress, IntSet> target) { if (!cancelled.getAndSet(true)) { actualCancel(); } } private void actualCancel() { if (iterationId != null && channel != null) { // Just let cancel complete asynchronously publisher.sendCancel(iterationId, channel); } } @Override protected CompletionStage<IterationStartResponse> sendInitialCommand( Map.Entry<SocketAddress, IntSet> target, int batchSize) { SocketAddress address = target.getKey(); IntSet segments = target.getValue(); log.tracef("Starting iteration with segments %s", segments); return publisher.newIteratorStartOperation(address, segments, batchSize); } @Override protected CompletionStage<IterationNextResponse<K, E>> sendNextCommand(Map.Entry<SocketAddress, IntSet> target, int batchSize) { return publisher.newIteratorNextOperation(iterationId, channel); } @Override protected long handleInitialResponse(IterationStartResponse startResponse, Map.Entry<SocketAddress, IntSet> target) { this.channel = startResponse.getChannel(); this.iterationId = startResponse.getIterationId(); if (log.isDebugEnabled()) { log.iterationTransportObtained(channel.remoteAddress(), iterationId()); log.startedIteration(iterationId()); } // We could have been cancelled while the initial response was sent if (cancelled.get()) { actualCancel(); } return 0; } @Override protected long handleNextResponse(IterationNextResponse<K, E> nextResponse, Map.Entry<SocketAddress, IntSet> target) { if (!nextResponse.hasMore()) { // server doesn't clean up when complete sendCancel(target); publisher.completeSegments(target.getValue()); targetComplete(); } IntSet completedSegments = nextResponse.getCompletedSegments(); if (completedSegments != null && log.isTraceEnabled()) { IntSet targetSegments = target.getValue(); if (targetSegments != null) { targetSegments.removeAll(completedSegments); } } publisher.completeSegments(completedSegments); List<Map.Entry<K, E>> entries = nextResponse.getEntries(); for (Map.Entry<K, E> entry : entries) { if (!onNext(entry)) { break; } } return entries.size(); } @Override protected void handleThrowableInResponse(Throwable t, Map.Entry<SocketAddress, IntSet> target) { if (t instanceof TransportException || t instanceof RemoteIllegalLifecycleStateException) { log.throwableDuringPublisher(t); if (log.isTraceEnabled()) { IntSet targetSegments = target.getValue(); if (targetSegments != null) { log.tracef("There are still outstanding segments %s that will need to be retried", targetSegments); } } publisher.erroredServer(target.getKey()); // Try next target if possible targetComplete(); accept(0); } else { t.addSuppressed(new TraceException()); super.handleThrowableInResponse(t, target); } } }
5,090
36.711111
131
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/iteration/ReplKeyTracker.java
package org.infinispan.client.hotrod.impl.iteration; import java.util.HashSet; import java.util.Set; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.util.IntSet; /** * Tracks all keys seen during iteration. Depends on ISPN-5451 to be done more efficiently, by discarding segments as * soon as they are completed iterating. * * @author gustavonalle * @since 8.0 */ class ReplKeyTracker implements KeyTracker { private Set<WrappedByteArray> keys = new HashSet<>(); @Override public boolean track(byte[] key, short status, ClassAllowList allowList) { return keys.add(new WrappedByteArray(key)); } @Override public void segmentsFinished(IntSet finishedSegments) { } @Override public Set<Integer> missedSegments() { return null; } }
882
24.228571
117
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/iteration/RemotePublisher.java
package org.infinispan.client.hotrod.impl.iteration; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.lang.invoke.MethodHandles; import java.net.SocketAddress; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash; import org.infinispan.client.hotrod.impl.operations.IterationEndResponse; import org.infinispan.client.hotrod.impl.operations.IterationNextOperation; import org.infinispan.client.hotrod.impl.operations.IterationNextResponse; import org.infinispan.client.hotrod.impl.operations.IterationStartOperation; import org.infinispan.client.hotrod.impl.operations.IterationStartResponse; import org.infinispan.client.hotrod.impl.operations.OperationsFactory; 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.reactive.RxJavaInterop; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import io.netty.channel.Channel; import io.reactivex.rxjava3.core.Flowable; public class RemotePublisher<K, E> implements Publisher<Map.Entry<K, E>> { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private final OperationsFactory operationsFactory; private final String filterConverterFactory; private final byte[][] filterParams; private final IntSet segments; private final int batchSize; private final boolean metadata; private final DataFormat dataFormat; private final KeyTracker segmentKeyTracker; private final Set<SocketAddress> failedServers = ConcurrentHashMap.newKeySet(); public RemotePublisher(OperationsFactory operationsFactory, String filterConverterFactory, byte[][] filterParams, Set<Integer> segments, int batchSize, boolean metadata, DataFormat dataFormat) { this.operationsFactory = operationsFactory; this.filterConverterFactory = filterConverterFactory; this.filterParams = filterParams; SegmentConsistentHash segmentConsistentHash = (SegmentConsistentHash) operationsFactory.getConsistentHash(); if (segments == null) { if (segmentConsistentHash != null) { int maxSegment = segmentConsistentHash.getNumSegments(); this.segments = IntSets.concurrentSet(maxSegment); for (int i = 0; i < maxSegment; ++i) { this.segments.set(i); } } else { this.segments = null; } } else { this.segments = IntSets.concurrentCopyFrom(IntSets.from(segments), Collections.max(segments) + 1); } this.batchSize = batchSize; this.metadata = metadata; this.dataFormat = dataFormat; this.segmentKeyTracker = KeyTrackerFactory.create(dataFormat, segmentConsistentHash, operationsFactory.getTopologyId(), segments); } @Override public void subscribe(Subscriber<? super Map.Entry<K, E>> subscriber) { // Segments can be null if we weren't provided any and we don't have a ConsistentHash if (segments == null) { AtomicBoolean shouldRetry = new AtomicBoolean(true); RemoteInnerPublisherHandler<K, E> innerHandler = new RemoteInnerPublisherHandler<K, E>(this, batchSize, () -> { // Note that this publisher will continue to return empty entries until it has completed a given // target without encountering a Throwable if (shouldRetry.getAndSet(false)) { return new AbstractMap.SimpleImmutableEntry<>(null, null); } return null; }, null) { @Override protected void handleThrowableInResponse(Throwable t, Map.Entry<SocketAddress, IntSet> target) { // Let it retry again if necessary shouldRetry.set(true); super.handleThrowableInResponse(t, target); } }; innerHandler.startPublisher().subscribe(subscriber); return; } Flowable.just(segments) .map(segments -> { Map<SocketAddress, Set<Integer>> segmentsByAddress = operationsFactory.getPrimarySegmentsByAddress(); Map<SocketAddress, IntSet> actualTargets = new HashMap<>(segmentsByAddress.size()); for (Map.Entry<SocketAddress, Set<Integer>> entry : segmentsByAddress.entrySet()) { SocketAddress targetAddress = entry.getKey(); if (failedServers.contains(targetAddress)) { targetAddress = null; } IntSet segmentsNeeded = null; Set<Integer> targetSegments = entry.getValue(); for (int targetSegment : targetSegments) { if (segments.contains(targetSegment)) { if (segmentsNeeded == null) { segmentsNeeded = IntSets.mutableEmptySet(); } segmentsNeeded.set(targetSegment); } } if (segmentsNeeded != null) { actualTargets.put(targetAddress, segmentsNeeded); } } // If no addresses could handle the segments directly - then just send to any node all segments if (actualTargets.isEmpty()) { actualTargets.put(null, segments); } return actualTargets; }).flatMap(actualTargets -> { int batchSize = (this.batchSize / actualTargets.size()) + 1; return Flowable.fromIterable(actualTargets.entrySet()) .map(entry -> { RemoteInnerPublisherHandler<K, E> innerHandler = new RemoteInnerPublisherHandler<>(this, batchSize, () -> null, entry); return innerHandler.startPublisher(); }).flatMap(RxJavaInterop.identityFunction(), actualTargets.size()); }) .repeatUntil(() -> { log.tracef("Segments left to process are %s", segments); return segments.isEmpty(); }).subscribe(subscriber); } void erroredServer(SocketAddress socketAddress) { failedServers.add(socketAddress); } CompletionStage<Void> sendCancel(byte[] iterationId, Channel channel) { CompletionStage<IterationEndResponse> endResponseStage = operationsFactory.newIterationEndOperation(iterationId, channel).execute(); return endResponseStage.handle((endResponse, t) -> { if (t != null) { HOTROD.ignoringErrorDuringIterationClose(iterationId(iterationId), t); } else { short status = endResponse.getStatus(); if (HotRodConstants.isSuccess(status) && HOTROD.isDebugEnabled()) { HOTROD.iterationClosed(iterationId(iterationId)); } if (HotRodConstants.isInvalidIteration(status)) { throw HOTROD.errorClosingIteration(iterationId(iterationId)); } } return null; }); } String iterationId(byte[] iterationId) { return new String(iterationId, HotRodConstants.HOTROD_STRING_CHARSET); } void completeSegments(IntSet completedSegments) { if (segments != null) { segments.removeAll(completedSegments); } } CompletionStage<IterationStartResponse> newIteratorStartOperation(SocketAddress address, IntSet segments, int batchSize) { IterationStartOperation iterationStartOperation = operationsFactory.newIterationStartOperation(filterConverterFactory, filterParams, segments, batchSize, metadata, dataFormat, address); return iterationStartOperation.execute(); } CompletionStage<IterationNextResponse<K, E>> newIteratorNextOperation(byte[] iterationId, Channel channel) { IterationNextOperation<K, E> iterationNextOperation = operationsFactory.newIterationNextOperation(iterationId, channel, segmentKeyTracker, dataFormat); return iterationNextOperation.execute(); } }
8,610
44.321053
138
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/async/DefaultAsyncExecutorFactory.java
package org.infinispan.client.hotrod.impl.async; import static org.infinispan.client.hotrod.logging.Log.HOTROD; import java.util.Properties; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.executors.NonBlockingResource; /** * Default implementation for {@link org.infinispan.commons.executors.ExecutorFactory} based on an {@link * ThreadPoolExecutor}. * * @author Mircea.Markus@jboss.com * @since 4.1 */ public class DefaultAsyncExecutorFactory implements ExecutorFactory { public static final String THREAD_NAME = "HotRod-client-async-pool"; private static final Log log = LogFactory.getLog(DefaultAsyncExecutorFactory.class); private static final AtomicInteger factoryCounter = new AtomicInteger(0); private final AtomicInteger threadCounter = new AtomicInteger(0); @Override public ThreadPoolExecutor getExecutor(Properties p) { ConfigurationProperties cp = new ConfigurationProperties(p); int factoryIndex = DefaultAsyncExecutorFactory.factoryCounter.incrementAndGet(); String threadNamePrefix = cp.getDefaultExecutorFactoryThreadNamePrefix(); String threadNameSuffix = cp.getDefaultExecutorFactoryThreadNameSuffix(); ISPNNonBlockingThreadGroup nonBlockingThreadGroup = new ISPNNonBlockingThreadGroup(threadNamePrefix + "-group"); ThreadFactory tf = r -> { int threadIndex = threadCounter.incrementAndGet(); Thread th = new Thread(nonBlockingThreadGroup, r, threadNamePrefix + "-" + factoryIndex + "-" + threadIndex + threadNameSuffix); th.setDaemon(true); return th; }; log.debugf("Creating executor %s-%d", threadNamePrefix, factoryIndex); return new ThreadPoolExecutor(cp.getDefaultExecutorFactoryPoolSize(), cp.getDefaultExecutorFactoryPoolSize(), 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), tf, (r, executor) -> { int poolSize = cp.getDefaultExecutorFactoryPoolSize(); HOTROD.cannotCreateAsyncThread(poolSize); throw new RejectedExecutionException("Too few threads: " + poolSize); }); } static final class ISPNNonBlockingThreadGroup extends ThreadGroup implements NonBlockingResource { ISPNNonBlockingThreadGroup(String name) { super(name); } } }
2,754
43.435484
137
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/topology/ClusterInfo.java
package org.infinispan.client.hotrod.impl.topology; import java.net.InetSocketAddress; import java.util.List; import java.util.Objects; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.commons.util.Immutables; /** * Cluster definition * * @author Dan Berindei */ public class ClusterInfo { private final String clusterName; private final List<InetSocketAddress> servers; // Topology age provides a way to avoid concurrent cluster view changes, // affecting a cluster switch. After a cluster switch, the topology age is // increased and so any old requests that might have received topology // updates won't be allowed to apply since they refer to older views. private final int topologyAge; private final ClientIntelligence intelligence; public ClusterInfo(String clusterName, List<InetSocketAddress> servers, ClientIntelligence intelligence) { this(clusterName, servers, -1, intelligence); } private ClusterInfo(String clusterName, List<InetSocketAddress> servers, int topologyAge, ClientIntelligence intelligence) { this.clusterName = clusterName; this.servers = Immutables.immutableListCopy(servers); this.topologyAge = topologyAge; this.intelligence = Objects.requireNonNull(intelligence); } public ClusterInfo withTopologyAge(int topologyAge) { return new ClusterInfo(clusterName, servers, topologyAge, intelligence); } public String getName() { return clusterName; } public List<InetSocketAddress> getInitialServers() { return servers; } public int getTopologyAge() { return topologyAge; } public ClientIntelligence getIntelligence() { return intelligence; } @Override public String toString() { return "ClusterInfo{" + "name='" + clusterName + '\'' + ", servers=" + servers + ", age=" + topologyAge + ", intelligence=" + intelligence + '}'; } }
2,011
29.484848
127
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/topology/CacheInfo.java
package org.infinispan.client.hotrod.impl.topology; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.CacheTopologyInfo; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.impl.CacheTopologyInfoImpl; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.commons.util.Immutables; import org.infinispan.commons.util.IntSets; /** * Holds all the cluster topology information the client has for a single cache. * * <p>Each segment is mapped to a single server, even though the Hot Rod protocol and {@link ConsistentHash} * implementations allow more than one owner.</p> * * @author Dan Berindei * @since 13.0 */ public class CacheInfo { private final String cacheName; // The topology age at the time this topology was received private final int topologyAge; // The balancer is final, but using it still needs synchronization because it is not thread-safe private final FailoverRequestBalancingStrategy balancer; private final int numSegments; private final List<InetSocketAddress> servers; private final Map<SocketAddress, Set<Integer>> primarySegments; private final ConsistentHash consistentHash; private final AtomicReference<ClientTopology> clientTopologyRef; private final ClientTopology clientTopology; public CacheInfo(WrappedBytes cacheName, FailoverRequestBalancingStrategy balancer, int topologyAge, List<InetSocketAddress> servers, ClientIntelligence intelligence) { this.balancer = balancer; this.topologyAge = topologyAge; this.cacheName = cacheName == null || cacheName.getLength() == 0 ? "<default>" : new String(cacheName.getBytes(), HotRodConstants.HOTROD_STRING_CHARSET); this.numSegments = -1; this.clientTopology = new ClientTopology(HotRodConstants.DEFAULT_CACHE_TOPOLOGY, intelligence); this.consistentHash = null; this.servers = Immutables.immutableListCopy(servers); // Before the first topology update or after a topology-aware (non-hash) topology update this.primarySegments = null; clientTopologyRef = new AtomicReference<>(clientTopology); } public void updateBalancerServers() { // The servers list is immutable, so it doesn't matter that the balancer see it as a Collection<SocketAddress> balancer.setServers((List) servers); } public CacheInfo withNewServers(int topologyAge, int topologyId, List<InetSocketAddress> servers) { return withNewServers(topologyAge, topologyId, servers, clientTopologyRef.get().getClientIntelligence()); } public CacheInfo withNewServers(int topologyAge, int topologyId, List<InetSocketAddress> servers, ClientIntelligence intelligence) { return new CacheInfo(cacheName, balancer, topologyAge, servers, null, -1, clientTopologyRef, new ClientTopology(topologyId, intelligence)); } public CacheInfo withNewHash(int topologyAge, int topologyId, List<InetSocketAddress> servers, ConsistentHash consistentHash, int numSegments) { return new CacheInfo(cacheName, balancer, topologyAge, servers, consistentHash, numSegments, clientTopologyRef, new ClientTopology(topologyId, getIntelligence())); } private CacheInfo(String cacheName, FailoverRequestBalancingStrategy balancer, int topologyAge, List<InetSocketAddress> servers, ConsistentHash consistentHash, int numSegments, AtomicReference<ClientTopology> clientTopologyRef, ClientTopology clientTopology) { this.balancer = balancer; this.topologyAge = topologyAge; this.cacheName = cacheName; this.numSegments = numSegments; this.consistentHash = consistentHash; this.clientTopology = clientTopology; this.clientTopologyRef = clientTopologyRef; this.servers = Immutables.immutableListCopy(servers); if (numSegments > 0) { // After the servers sent a hash-aware topology update this.primarySegments = consistentHash.getPrimarySegmentsByServer(); } else { // Before the first topology update or after a topology-aware (non-hash) topology update this.primarySegments = null; } } public String getCacheName() { return cacheName; } public int getTopologyAge() { return topologyAge; } public FailoverRequestBalancingStrategy getBalancer() { return balancer; } public int getNumSegments() { return numSegments; } public int getTopologyId() { return clientTopology.getTopologyId(); } public AtomicReference<ClientTopology> getClientTopologyRef() { return clientTopologyRef; } public List<InetSocketAddress> getServers() { return servers; } public Map<SocketAddress, Set<Integer>> getPrimarySegments() { if (primarySegments == null) { return Collections.emptyMap(); } return primarySegments; } public ConsistentHash getConsistentHash() { return consistentHash; } public CacheTopologyInfo getCacheTopologyInfo() { Map<SocketAddress, Set<Integer>> segmentsByServer; if (consistentHash != null) { segmentsByServer = consistentHash.getSegmentsByServer(); } else { segmentsByServer = new HashMap<>(servers.size()); for (InetSocketAddress server : servers) { segmentsByServer.put(server, IntSets.immutableEmptySet()); } } return new CacheTopologyInfoImpl(segmentsByServer, numSegments > 0 ? numSegments : null, getTopologyId()); } private ClientIntelligence getIntelligence() { return clientTopology.getClientIntelligence(); } public void updateClientTopologyRef() { clientTopologyRef.set(clientTopology); } }
6,376
37.648485
171
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/RemoteMultimapCacheImpl.java
package org.infinispan.client.hotrod.impl.multimap; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.util.Collection; import java.util.concurrent.CompletableFuture; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.exceptions.RemoteCacheManagerNotStartedException; import org.infinispan.client.hotrod.impl.InternalRemoteCache; import org.infinispan.client.hotrod.impl.RemoteCacheImpl; import org.infinispan.client.hotrod.impl.multimap.operations.ContainsEntryMultimapOperation; import org.infinispan.client.hotrod.impl.multimap.operations.ContainsKeyMultimapOperation; import org.infinispan.client.hotrod.impl.multimap.operations.ContainsValueMultimapOperation; import org.infinispan.client.hotrod.impl.multimap.operations.GetKeyMultimapOperation; import org.infinispan.client.hotrod.impl.multimap.operations.GetKeyWithMetadataMultimapOperation; import org.infinispan.client.hotrod.impl.multimap.operations.MultimapOperationsFactory; import org.infinispan.client.hotrod.impl.multimap.operations.PutKeyValueMultimapOperation; import org.infinispan.client.hotrod.impl.multimap.operations.RemoveEntryMultimapOperation; import org.infinispan.client.hotrod.impl.multimap.operations.RemoveKeyMultimapOperation; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.multimap.MetadataCollection; import org.infinispan.client.hotrod.multimap.RemoteMultimapCache; import org.infinispan.commons.marshall.AdaptiveBufferSizePredictor; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.Marshaller; /** * Remote implementation of {@link RemoteMultimapCache} * * @author karesti@redhat.com * @since 9.2 */ public class RemoteMultimapCacheImpl<K, V> implements RemoteMultimapCache<K, V> { private static final Log log = LogFactory.getLog(RemoteMultimapCacheImpl.class, Log.class); private final InternalRemoteCache<K, Collection<V>> cache; private final RemoteCacheManager remoteCacheManager; private MultimapOperationsFactory operationsFactory; private Marshaller marshaller; private final BufferSizePredictor keySizePredictor = new AdaptiveBufferSizePredictor(); private final BufferSizePredictor valueSizePredictor = new AdaptiveBufferSizePredictor(); private long defaultLifespan = 0; private long defaultMaxIdleTime = 0; private final boolean supportsDuplicates; public void init() { operationsFactory = new MultimapOperationsFactory(remoteCacheManager.getChannelFactory(), cache.getName(), remoteCacheManager.getConfiguration(), cache.getDataFormat(), cache.clientStatistics()); this.marshaller = remoteCacheManager.getMarshaller(); } public RemoteMultimapCacheImpl(RemoteCacheManager rcm, RemoteCache<K, Collection<V>> cache) { this(rcm, cache, false); } public RemoteMultimapCacheImpl(RemoteCacheManager rcm, RemoteCache<K, Collection<V>> cache, boolean supportsDuplicates) { if (log.isTraceEnabled()) { log.tracef("Creating multimap remote cache: %s", cache.getName()); } this.cache = (RemoteCacheImpl<K, Collection<V>>) cache; this.remoteCacheManager = rcm; this.supportsDuplicates = supportsDuplicates; } @Override public CompletableFuture<Void> put(K key, V value) { if (log.isTraceEnabled()) { log.tracef("About to add (K,V): (%s, %s) lifespan:%d, maxIdle:%d", key, value, defaultLifespan, defaultMaxIdleTime); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); PutKeyValueMultimapOperation op = operationsFactory.newPutKeyValueOperation(objectKey, marshallKey, marshallValue, defaultLifespan, MILLISECONDS, defaultMaxIdleTime, MILLISECONDS, supportsDuplicates); return op.execute(); } @Override public CompletableFuture<Collection<V>> get(K key) { if (log.isTraceEnabled()) { log.tracef("About to call get (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); GetKeyMultimapOperation<V> gco = operationsFactory.newGetKeyMultimapOperation(objectKey, marshallKey, supportsDuplicates); return gco.execute(); } @Override public CompletableFuture<MetadataCollection<V>> getWithMetadata(K key) { if (log.isTraceEnabled()) { log.tracef("About to call getWithMetadata (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); GetKeyWithMetadataMultimapOperation<V> operation = operationsFactory.newGetKeyWithMetadataMultimapOperation(objectKey, marshallKey, supportsDuplicates); return operation.execute(); } @Override public CompletableFuture<Boolean> remove(K key) { if (log.isTraceEnabled()) { log.tracef("About to remove (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); RemoveKeyMultimapOperation removeOperation = operationsFactory.newRemoveKeyOperation(objectKey, marshallKey, supportsDuplicates); return removeOperation.execute(); } @Override public CompletableFuture<Boolean> remove(K key, V value) { if (log.isTraceEnabled()) { log.tracef("About to remove (K,V): (%s, %s)", key, value); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); RemoveEntryMultimapOperation removeOperation = operationsFactory.newRemoveEntryOperation(objectKey, marshallKey, marshallValue, supportsDuplicates); return removeOperation.execute(); } @Override public CompletableFuture<Boolean> containsKey(K key) { if (log.isTraceEnabled()) { log.tracef("About to call contains (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); ContainsKeyMultimapOperation containsKeyOperation = operationsFactory.newContainsKeyOperation(objectKey, marshallKey, supportsDuplicates); return containsKeyOperation.execute(); } @Override public CompletableFuture<Boolean> containsValue(V value) { if (log.isTraceEnabled()) { log.tracef("About to call contains (V): (%s)", value); } assertRemoteCacheManagerIsStarted(); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); ContainsValueMultimapOperation containsValueOperation = operationsFactory.newContainsValueOperation(marshallValue, supportsDuplicates); return containsValueOperation.execute(); } @Override public CompletableFuture<Boolean> containsEntry(K key, V value) { if (log.isTraceEnabled()) { log.tracef("About to call contais(K,V): (%s, %s)", key, value); } assertRemoteCacheManagerIsStarted(); K objectKey = isObjectStorage() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, keySizePredictor); byte[] marshallValue = MarshallerUtil.obj2bytes(marshaller, value, valueSizePredictor); ContainsEntryMultimapOperation containsOperation = operationsFactory.newContainsEntryOperation(objectKey, marshallKey, marshallValue, supportsDuplicates); return containsOperation.execute(); } @Override public CompletableFuture<Long> size() { if (log.isTraceEnabled()) { log.trace("About to call size"); } assertRemoteCacheManagerIsStarted(); return operationsFactory.newSizeOperation(supportsDuplicates).execute(); } @Override public boolean supportsDuplicates() { return supportsDuplicates; } private void assertRemoteCacheManagerIsStarted() { if (!remoteCacheManager.isStarted()) { String message = "Cannot perform operations on a multimap cache associated with an unstarted RemoteMultimapCacheManager."; if (log.isInfoEnabled()) { log.unstartedRemoteCacheManager(); } throw new RemoteCacheManagerNotStartedException(message); } } private boolean isObjectStorage() { return cache.isObjectStorage(); } }
9,144
44.049261
160
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/protocol/MultimapHotRodConstants.java
package org.infinispan.client.hotrod.impl.multimap.protocol; /** * Multimap hotrod constants * * @author Katia Aresti * @since 9.2 */ public interface MultimapHotRodConstants { // requests byte GET_MULTIMAP_REQUEST = 0x67; byte GET_MULTIMAP_WITH_METADATA_REQUEST = 0x69; byte PUT_MULTIMAP_REQUEST = 0x6B; byte REMOVE_KEY_MULTIMAP_REQUEST = 0x6D; byte REMOVE_ENTRY_MULTIMAP_REQUEST = 0x6F; byte SIZE_MULTIMAP_REQUEST = 0x71; byte CONTAINS_ENTRY_REQUEST = 0x73; byte CONTAINS_KEY_MULTIMAP_REQUEST = 0x75; short CONTAINS_VALUE_MULTIMAP_REQUEST = 0x77; // responses byte GET_MULTIMAP_RESPONSE = 0x68; byte GET_MULTIMAP_WITH_METADATA_RESPONSE = 0x6A; byte PUT_MULTIMAP_RESPONSE = 0x6C; byte REMOVE_KEY_MULTIMAP_RESPONSE = 0x6E; byte REMOVE_ENTRY_MULTIMAP_RESPONSE = 0x70; byte SIZE_MULTIMAP_RESPONSE = 0x72; byte CONTAINS_ENTRY_RESPONSE = 0x74; short CONTAINS_KEY_MULTIMAP_RESPONSE = 0x76; short CONTAINS_VALUE_MULTIMAP_RESPONSE = 0x78; }
1,002
29.393939
60
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/RemoveEntryMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_ENTRY_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_ENTRY_MULTIMAP_RESPONSE; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; /** * Implements "remove" for multimap as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Immutable public class RemoveEntryMultimapOperation extends AbstractMultimapKeyValueOperation<Boolean> { public RemoveEntryMultimapOperation(ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(REMOVE_ENTRY_MULTIMAP_REQUEST, REMOVE_ENTRY_MULTIMAP_RESPONSE, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, -1, TimeUnit.MILLISECONDS, -1, TimeUnit.MILLISECONDS, null, clientStatistics, supportsDuplicates); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
2,271
42.692308
130
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/GetKeyWithMetadataMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_WITH_METADATA_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_WITH_METADATA_RESPONSE; import static org.infinispan.client.hotrod.marshall.MarshallerUtil.bytes2obj; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.multimap.metadata.MetadataCollectionImpl; 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.impl.transport.netty.HeaderDecoder; import org.infinispan.client.hotrod.logging.Log; import org.infinispan.client.hotrod.logging.LogFactory; import org.infinispan.client.hotrod.multimap.MetadataCollection; /** * Implements "getWithMetadata" as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod protocol * specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Immutable public class GetKeyWithMetadataMultimapOperation<V> extends AbstractMultimapKeyOperation<MetadataCollection<V>> { private static final Log log = LogFactory.getLog(GetKeyWithMetadataMultimapOperation.class); public GetKeyWithMetadataMultimapOperation(ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(GET_MULTIMAP_WITH_METADATA_REQUEST, GET_MULTIMAP_WITH_METADATA_RESPONSE, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(new MetadataCollectionImpl<>(Collections.emptySet())); return; } if (!HotRodConstants.isSuccess(status)) { complete(null); return; } short flags = buf.readByte(); long creation = -1; int lifespan = -1; long lastUsed = -1; int maxIdle = -1; if ((flags & INFINITE_LIFESPAN) != INFINITE_LIFESPAN) { creation = buf.readLong(); lifespan = ByteBufUtil.readVInt(buf); } if ((flags & INFINITE_MAXIDLE) != INFINITE_MAXIDLE) { lastUsed = buf.readLong(); maxIdle = ByteBufUtil.readVInt(buf); } long version = buf.readLong(); if (log.isTraceEnabled()) { log.tracef("Received version: %d", version); } int size = ByteBufUtil.readVInt(buf); Collection<V> values = new ArrayList<>(size); for (int i = 0; i < size; ++i) { V value = bytes2obj(channelFactory.getMarshaller(), ByteBufUtil.readArray(buf), dataFormat().isObjectStorage(), cfg.getClassAllowList()); values.add(value); } complete(new MetadataCollectionImpl<>(values, creation, lifespan, lastUsed, maxIdle, version)); } }
3,751
45.320988
152
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/RemoveKeyMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_KEY_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_KEY_MULTIMAP_RESPONSE; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; /** * Implements "remove" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot * Rod protocol specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class RemoveKeyMultimapOperation extends AbstractMultimapKeyOperation<Boolean> { public RemoveKeyMultimapOperation(ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(REMOVE_KEY_MULTIMAP_REQUEST, REMOVE_KEY_MULTIMAP_RESPONSE, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, null, clientStatistics, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
1,870
46.974359
179
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/SizeMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.SIZE_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.SIZE_MULTIMAP_RESPONSE; 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.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; /** * Implements "size" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class SizeMultimapOperation extends RetryOnFailureOperation<Long> { private final boolean supportsDuplicates; protected SizeMultimapOperation(Codec codec, ChannelFactory channelFactory, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, boolean supportsDuplicates) { super(SIZE_MULTIMAP_REQUEST, SIZE_MULTIMAP_RESPONSE, codec, channelFactory, cacheName, clientTopology, flags, cfg, null, null); this.supportsDuplicates = supportsDuplicates; } @Override protected void executeOperation(Channel channel) { sendHeaderAndRead(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(ByteBufUtil.readVLong(buf)); } @Override protected void sendHeaderAndRead(Channel channel) { scheduleRead(channel); sendHeader(channel); } @Override protected void sendHeader(Channel channel) { ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + codec.estimateSizeMultimapSupportsDuplicated()); codec.writeHeader(buf, header); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
2,352
38.216667
204
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/AbstractMultimapKeyOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.AbstractKeyOperation; import org.infinispan.client.hotrod.impl.transport.netty.ByteBufUtil; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; public abstract class AbstractMultimapKeyOperation<V> extends AbstractKeyOperation<V> { protected final boolean supportsDuplicates; public AbstractMultimapKeyOperation(short requestCode, short responseCode, ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(requestCode, responseCode, channelFactory.getNegotiatedCodec(), channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, null); this.supportsDuplicates = supportsDuplicates; } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendArrayOperation(channel, keyBytes); } @Override protected void sendArrayOperation(Channel channel, byte[] array) { ByteBuf buf = channel.alloc().buffer(codec.estimateHeaderSize(header) + ByteBufUtil.estimateArraySize(array) + codec.estimateSizeMultimapSupportsDuplicated()); codec.writeHeader(buf, header); ByteBufUtil.writeArray(buf, array); codec.writeMultimapSupportDuplicates(buf, supportsDuplicates); channel.writeAndFlush(buf); } }
2,040
45.386364
167
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/ContainsKeyMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_KEY_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.CONTAINS_KEY_MULTIMAP_RESPONSE; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; /** * Implements "contains key" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot * Rod protocol specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class ContainsKeyMultimapOperation extends AbstractMultimapKeyOperation<Boolean> { public ContainsKeyMultimapOperation(ChannelFactory transportFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(CONTAINS_KEY_MULTIMAP_REQUEST, CONTAINS_KEY_MULTIMAP_RESPONSE, transportFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, null, clientStatistics, supportsDuplicates); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
1,933
47.35
134
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/GetKeyMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.GET_MULTIMAP_RESPONSE; import static org.infinispan.client.hotrod.marshall.MarshallerUtil.bytes2obj; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import net.jcip.annotations.Immutable; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; 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.impl.transport.netty.HeaderDecoder; /** * Implements "get" for multimap as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Immutable public class GetKeyMultimapOperation<V> extends AbstractMultimapKeyOperation<Collection<V>> { private int size; private Collection<V> result; public GetKeyMultimapOperation(ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, DataFormat dataFormat, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(GET_MULTIMAP_REQUEST, GET_MULTIMAP_RESPONSE, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, dataFormat, clientStatistics, supportsDuplicates); } @Override protected void reset() { super.reset(); result = null; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Collections.emptySet()); return; } else if (result == null) { size = ByteBufUtil.readVInt(buf); result = supportsDuplicates ? new ArrayList<>(size) : new HashSet<>(size); decoder.checkpoint(); } while (result.size() < size) { V value = bytes2obj(channelFactory.getMarshaller(), ByteBufUtil.readArray(buf), dataFormat().isObjectStorage(), cfg.getClassAllowList()); result.add(value); decoder.checkpoint(); } complete(result); } }
2,807
40.910448
146
java
null
infinispan-main/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/multimap/operations/PutKeyValueMultimapOperation.java
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.PUT_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.PUT_MULTIMAP_RESPONSE; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.InvalidResponseException; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; /** * Implements "put" for multimap cache as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Immutable public class PutKeyValueMultimapOperation extends AbstractMultimapKeyValueOperation<Void> { public PutKeyValueMultimapOperation(ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, long lifespan, TimeUnit lifespanTimeUnit, long maxIdle, TimeUnit maxIdleTimeUnit, DataFormat dataFormat, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(PUT_MULTIMAP_REQUEST, PUT_MULTIMAP_RESPONSE, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, lifespan, lifespanTimeUnit, maxIdle, maxIdleTimeUnit, dataFormat, clientStatistics, supportsDuplicates); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (!HotRodConstants.isSuccess(status)) { throw new InvalidResponseException("Unexpected response status: " + Integer.toHexString(status)); } complete(null); } }
2,542
46.092593
135
java