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/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/DefaultCacheManagerProvider.java
package org.infinispan.hibernate.cache.commons; import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_INFINISPAN_CONFIG_RESOURCE; import static org.infinispan.hibernate.cache.spi.InfinispanProperties.INFINISPAN_CONFIG_RESOURCE_PROP; import static org.infinispan.hibernate.cache.spi.InfinispanProperties.INFINISPAN_GLOBAL_STATISTICS_PROP; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.ServiceRegistry; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.FileLookup; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.spi.EmbeddedCacheManagerProvider; import org.infinispan.hibernate.cache.spi.InfinispanProperties; import org.infinispan.jboss.marshalling.core.JBossUserMarshaller; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; /** * Default {@link EmbeddedCacheManagerProvider} implementation. * * @author Paul Ferraro * @since 9.2 */ public class DefaultCacheManagerProvider implements EmbeddedCacheManagerProvider { private static final InfinispanMessageLogger LOGGER = InfinispanMessageLogger.Provider.getLog(DefaultCacheManagerProvider.class); private final ServiceRegistry registry; public DefaultCacheManagerProvider(ServiceRegistry registry) { this.registry = registry; } @Override public EmbeddedCacheManager getEmbeddedCacheManager(Properties properties) { return new DefaultCacheManager(loadConfiguration(this.registry, properties), true); } // This is public for reuse by tests public static ConfigurationBuilderHolder loadConfiguration(ServiceRegistry registry, Properties properties) { String config = ConfigurationHelper.extractPropertyValue(INFINISPAN_CONFIG_RESOURCE_PROP, properties); ConfigurationBuilderHolder holder = loadConfiguration(registry, (config != null) ? config : DEF_INFINISPAN_CONFIG_RESOURCE); // Override statistics if enabled via properties String globalStatsProperty = ConfigurationHelper.extractPropertyValue(INFINISPAN_GLOBAL_STATISTICS_PROP, properties); if (globalStatsProperty != null) { holder.getGlobalConfigurationBuilder().jmx().enabled(Boolean.parseBoolean(globalStatsProperty)); } holder.getGlobalConfigurationBuilder().serialization().marshaller(new JBossUserMarshaller()); return holder; } public static ConfigurationBuilderHolder loadConfiguration(ServiceRegistry registry, String config) { ClassLoaderService.Work<ConfigurationBuilderHolder> work = classLoader -> { ClassLoader infinispanClassLoader = InfinispanProperties.class.getClassLoader(); try (InputStream input = lookupFile(config, classLoader, infinispanClassLoader)) { return parse(input, infinispanClassLoader, MediaType.fromExtension(config)); } catch (IOException e) { throw LOGGER.unableToCreateCacheManager(e); } }; return registry.getService(ClassLoaderService.class).workWithClassLoader(work); } private static InputStream lookupFile(String configFile, ClassLoader classLoader, ClassLoader strictClassLoader) throws FileNotFoundException { FileLookup fileLookup = FileLookupFactory.newInstance(); InputStream input = fileLookup.lookupFile(configFile, classLoader); // when it's not a user-provided configuration file, it might be a default configuration file, // and if that's included in [this] module might not be visible to the ClassLoaderService: if (input == null) { // This time use lookupFile*Strict* so to provide an exception if we can't find it yet: input = fileLookup.lookupFileStrict(configFile, strictClassLoader); } return input; } private static ConfigurationBuilderHolder parse(InputStream input, ClassLoader classLoader, MediaType mediaType) { ParserRegistry parser = new ParserRegistry(classLoader); // Infinispan requires the context ClassLoader to have full visibility on all // its components and eventual extension points even *during* configuration parsing. Thread currentThread = Thread.currentThread(); ClassLoader originalClassLoader = currentThread.getContextClassLoader(); try { currentThread.setContextClassLoader(classLoader); ConfigurationBuilderHolder builderHolder = parser.parse(input, ConfigurationResourceResolvers.DEFAULT, mediaType); // Workaround Infinispan's ClassLoader strategies to bend to our will: builderHolder.getGlobalConfigurationBuilder().classLoader(classLoader); return builderHolder; } finally { currentThread.setContextClassLoader(originalClassLoader); } } }
5,296
49.932692
146
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/InfinispanDataRegion.java
package org.infinispan.hibernate.cache.commons; import java.util.Comparator; import org.infinispan.functional.MetaParam; public interface InfinispanDataRegion extends InfinispanBaseRegion { long getTombstoneExpiration(); MetaParam.MetaLifespan getExpiringMetaParam(); Comparator<Object> getComparator(String subclass); }
336
21.466667
68
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/package-info.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ /** * Internal utilities for the Infinispan integration */ package org.infinispan.hibernate.cache.commons.util;
352
28.416667
94
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/BeginInvalidationCommand.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Objects; import org.infinispan.commands.CommandInvocationId; import org.infinispan.commands.write.InvalidateCommand; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class BeginInvalidationCommand extends InvalidateCommand { private Object lockOwner; public BeginInvalidationCommand() { } public BeginInvalidationCommand(long flagsBitSet, CommandInvocationId commandInvocationId, Object[] keys, Object lockOwner) { super(flagsBitSet, commandInvocationId, keys); this.lockOwner = lockOwner; } public Object getLockOwner() { return lockOwner; } @Override public void writeTo(ObjectOutput output) throws IOException { super.writeTo(output); LockOwner.writeTo( output, lockOwner ); } @Override public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); lockOwner = LockOwner.readFrom( input ); } @Override public byte getCommandId() { return CacheCommandIds.BEGIN_INVALIDATION; } @Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } if (o instanceof BeginInvalidationCommand) { BeginInvalidationCommand bic = (BeginInvalidationCommand) o; return Objects.equals(lockOwner, bic.lockOwner); } else { return false; } } @Override public int hashCode() { return super.hashCode() + (lockOwner == null ? 0 : lockOwner.hashCode()); } @Override public String toString() { return "BeginInvalidationCommand{keys=" + Arrays.toString(keys) + ", sessionTransactionId=" + lockOwner + '}'; } }
1,974
24.320513
126
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/InfinispanMessageLogger.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.WARN; import javax.naming.NamingException; import org.hibernate.cache.CacheException; import org.infinispan.hibernate.cache.spi.InfinispanProperties; import org.infinispan.util.ByteString; 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 jakarta.transaction.SystemException; /** * The jboss-logging {@link MessageLogger} for the hibernate-infinispan module. It reserves message ids ranging from * 25001 to 30000 inclusively. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @MessageLogger(projectCode = "HHH") public interface InfinispanMessageLogger extends BasicLogger { // Workaround for JBLOGGING-120: cannot add static interface method class Provider { public static InfinispanMessageLogger getLog(Class clazz) { return Logger.getMessageLogger(InfinispanMessageLogger.class, clazz.getName()); } } @Message(value = "Pending-puts cache must not be clustered!", id = 25001) CacheException pendingPutsMustNotBeClustered(); @Message(value = "Pending-puts cache must not be transactional!", id = 25002) CacheException pendingPutsMustNotBeTransactional(); @LogMessage(level = WARN) @Message(value = "Pending-puts cache configuration should be a template.", id = 25003) void pendingPutsShouldBeTemplate(); @Message(value = "Pending-puts cache must have expiration.max-idle set", id = 25004) CacheException pendingPutsMustHaveMaxIdle(); @LogMessage(level = WARN) @Message(value = "Property '" + InfinispanProperties.INFINISPAN_USE_SYNCHRONIZATION_PROP + "' is deprecated; 2LC with transactional cache must always use synchronizations.", id = 25005) void propertyUseSynchronizationDeprecated(); @LogMessage(level = ERROR) @Message(value = "Custom cache configuration '%s' was requested for type %s but it was not found!", id = 25006) void customConfigForTypeNotFound(String cacheName, String type); @LogMessage(level = ERROR) @Message(value = "Custom cache configuration '%s' was requested for region %s but it was not found - using configuration by type (%s).", id = 25007) void customConfigForRegionNotFound(String templateCacheName, String regionName, String type); @Message(value = "Timestamps cache must not use eviction!", id = 25008) CacheException timestampsMustNotUseEviction(); @Message(value = "Unable to start region factory", id = 25009) CacheException unableToStart(@Cause Throwable t); @Message(value = "Unable to create default cache manager", id = 25010) CacheException unableToCreateCacheManager(@Cause Throwable t); @Message(value = "Infinispan custom cache command factory not installed (possibly because the classloader where Infinispan lives couldn't find the Hibernate Infinispan cache provider)", id = 25011) CacheException cannotInstallCommandFactory(); @LogMessage(level = WARN) @Message(value = "Requesting TRANSACTIONAL cache concurrency strategy but the cache is not configured as transactional.", id = 25012) void transactionalStrategyNonTransactionalCache(); @LogMessage(level = WARN) @Message(value = "Requesting READ_WRITE cache concurrency strategy but the cache was configured as transactional.", id = 25013) void readWriteStrategyTransactionalCache(); @LogMessage(level = WARN) @Message(value = "Setting eviction on cache using tombstones can introduce inconsistencies!", id = 25014) void evictionWithTombstones(); @LogMessage(level = ERROR) @Message(value = "Failure updating cache in afterCompletion, will retry", id = 25015) void failureInAfterCompletion(@Cause Throwable e); @LogMessage(level = ERROR) @Message(value = "Failed to end invalidating pending putFromLoad calls for key %s from region %s; the key won't be cached until invalidation expires.", id = 25016) void failedEndInvalidating(Object key, ByteString name); @Message(value = "Unable to retrieve CacheManager from JNDI [%s]", id = 25017) CacheException unableToRetrieveCmFromJndi(String jndiNamespace); @LogMessage(level = WARN) @Message(value = "Unable to release initial context", id = 25018) void unableToReleaseContext(@Cause NamingException ne); @LogMessage(level = WARN) @Message(value = "Use non-transactional query caches for best performance!", id = 25019) void useNonTransactionalQueryCache(); @LogMessage(level = ERROR) @Message(value = "Unable to broadcast invalidations as a part of the prepare phase. Rolling back.", id = 25020) void unableToRollbackInvalidationsDuringPrepare(@Cause Throwable t); @Message(value = "Could not suspend transaction", id = 25021) CacheException cannotSuspendTx(@Cause SystemException se); @Message(value = "Could not resume transaction", id = 25022) CacheException cannotResumeTx(@Cause Exception e); @Message(value = "Unable to get current transaction", id = 25023) CacheException cannotGetCurrentTx(@Cause SystemException e); @Message(value = "Failed to invalidate pending putFromLoad calls for key %s from region %s", id = 25024) CacheException failedInvalidatePendingPut(Object key, String regionName); @LogMessage(level = ERROR) @Message(value = "Failed to invalidate pending putFromLoad calls for region %s", id = 25025) void failedInvalidateRegion(String regionName); @Message(value = "Property '" + InfinispanProperties.CACHE_MANAGER_RESOURCE_PROP + "' not set", id = 25026) CacheException propertyCacheManagerResourceNotSet(); @Message(value = "Timestamp cache cannot be configured with invalidation", id = 25027) CacheException timestampsMustNotUseInvalidation(); @LogMessage(level = WARN) @Message(value = "Ignoring deprecated property '%s'", id = 25028) void ignoringDeprecatedProperty(String deprecated); @LogMessage(level = WARN) @Message(value = "Property '%s' is deprecated, please use '%s' instead", id = 25029) void deprecatedProperty(String deprecated, String alternative); @LogMessage(level = WARN) @Message(value = "Transactional caches are not supported. The configuration option will be ignored; please unset.", id = 25030) void transactionalConfigurationIgnored(); @LogMessage(level = WARN) @Message(value = "Configuration for pending-puts cache '%s' is already defined - another instance of SessionFactory was not closed properly.", id = 25031) void pendingPutsCacheAlreadyDefined(String pendingPutsName); @LogMessage(level = WARN) @Message(value = "Cache configuration '%s' is present but the use has not been defined through " + InfinispanProperties.PREFIX + "%s" + InfinispanProperties.CONFIG_SUFFIX + "=%s", id = 25032) void regionNameMatchesCacheName(String regionName, String regionName2, String regionName3); @LogMessage(level = WARN) @Message(value = "Configuration properties contain record for unqualified region name '%s' but it should contain qualified region name '%s'", id = 25033) void usingUnqualifiedNameInConfiguration(String unqualifiedRegionName, String cacheName); @LogMessage(level = WARN) @Message(value = "Configuration for unqualified region name '%s' is defined but the cache will use qualified name '%s'", id = 25034) void configurationWithUnqualifiedName(String unqualifiedRegionName, String cacheName); @LogMessage(level = ERROR) @Message(value = "Operation #%d scheduled to complete before transaction completion failed", id = 25035) void failureBeforeTransactionCompletion(int index, @Cause Exception e); @LogMessage(level = ERROR) @Message(value = "Operation #%d scheduled after transaction completion failed (transaction successful? %s)", id = 25036) void failureAfterTransactionCompletion(int index, boolean successful, @Cause Exception e); }
8,107
46.415205
198
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/TombstoneUpdate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import org.infinispan.commands.functional.functions.InjectableComponent; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.functional.EntryView; import org.infinispan.functional.MetaParam; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import java.util.UUID; import java.util.function.Function; /** * Request to update cache either as a result of putFromLoad (if {@link #getValue()} is non-null * or evict (if it is null). * * This object should *not* be stored in cache. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class TombstoneUpdate<T> implements Function<EntryView.ReadWriteEntryView<Object, Object>, Void>, InjectableComponent { private static final UUID ZERO = new UUID(0, 0); private final long timestamp; private final T value; private transient InfinispanDataRegion region; public TombstoneUpdate(long timestamp, T value) { this.timestamp = timestamp; this.value = value; } public long getTimestamp() { return timestamp; } public T getValue() { return value; } @Override public String toString() { final StringBuilder sb = new StringBuilder("TombstoneUpdate{"); sb.append("timestamp=").append(timestamp); sb.append(", value=").append(value); sb.append('}'); return sb.toString(); } @Override public Void apply(EntryView.ReadWriteEntryView<Object, Object> view) { Object storedValue = view.find().orElse(null); if (value == null) { if (storedValue != null && !(storedValue instanceof Tombstone)) { // We have to keep Tombstone, because otherwise putFromLoad could insert a stale entry // (after it has been already updated and *then* evicted) view.set(new Tombstone(ZERO, timestamp), region.getExpiringMetaParam()); } // otherwise it's eviction } else if (storedValue instanceof Tombstone) { Tombstone tombstone = (Tombstone) storedValue; if (tombstone.getLastTimestamp() < timestamp) { view.set(value); } } else if (storedValue == null) { // async putFromLoads shouldn't cross the invalidation timestamp if (region.getLastRegionInvalidation() < timestamp) { view.set(value); } } else { // Don't do anything locally. This could be the async remote write, though, when local // value has been already updated: let it propagate to remote nodes, too view.set(storedValue, view.findMetaParam(MetaParam.MetaLifespan.class).get()); } return null; } @Override public void inject(ComponentRegistry registry) { region = registry.getComponent(InfinispanDataRegion.class); } public static class Externalizer implements AdvancedExternalizer<TombstoneUpdate> { @Override public Set<Class<? extends TombstoneUpdate>> getTypeClasses() { return Collections.singleton(TombstoneUpdate.class); } @Override public Integer getId() { return Externalizers.TOMBSTONE_UPDATE; } @Override public void writeObject(ObjectOutput output, TombstoneUpdate object) throws IOException { output.writeObject(object.getValue()); output.writeLong(object.getTimestamp()); } @Override public TombstoneUpdate readObject(ObjectInput input) throws IOException, ClassNotFoundException { Object value = input.readObject(); long timestamp = input.readLong(); return new TombstoneUpdate(timestamp, value); } } }
3,801
30.683333
126
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/LifecycleCallbacks.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import java.util.Map; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; @InfinispanModule(name = "hibernate-cache-commons", requiredModules = "core") public class LifecycleCallbacks implements ModuleLifecycle { @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalCfg) { Map<Integer, AdvancedExternalizer<?>> externalizerMap = globalCfg.serialization().advancedExternalizers(); externalizerMap.put( Externalizers.UUID, new Externalizers.UUIDExternalizer() ); externalizerMap.put( Externalizers.TOMBSTONE, new Tombstone.Externalizer() ); externalizerMap.put( Externalizers.EXCLUDE_TOMBSTONES_FILTER, new Tombstone.ExcludeTombstonesFilterExternalizer() ); externalizerMap.put( Externalizers.TOMBSTONE_UPDATE, new TombstoneUpdate.Externalizer() ); externalizerMap.put( Externalizers.FUTURE_UPDATE, new FutureUpdate.Externalizer() ); externalizerMap.put( Externalizers.VERSIONED_ENTRY, new VersionedEntry.Externalizer() ); externalizerMap.put( Externalizers.EXCLUDE_EMPTY_VERSIONED_ENTRY, new VersionedEntry.ExcludeEmptyVersionedEntryExternalizer() ); } }
1,654
49.151515
130
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/EvictAllCommand.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.concurrent.CompletionStage; import org.infinispan.commands.remote.BaseRpcCommand; import org.infinispan.factories.ComponentRegistry; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.util.ByteString; import org.infinispan.commons.util.concurrent.CompletableFutures; /** * Evict all command * * @author Galder Zamarreño * @since 4.0 */ public class EvictAllCommand extends BaseRpcCommand { private final InfinispanBaseRegion region; /** * Evict all command constructor. * * @param regionName name of the region to evict * @param region to evict */ public EvictAllCommand(ByteString regionName, InfinispanBaseRegion region) { // region name and cache names are the same... super( regionName ); this.region = region; } /** * Evict all command constructor. * * @param regionName name of the region to evict */ public EvictAllCommand(ByteString regionName) { this( regionName, null ); } @Override public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable { // When a node is joining the cluster, it may receive an EvictAllCommand before the regions // are started up. It's safe to ignore such invalidation at this point since no data got in. if (region != null) { region.invalidateRegion(); } return CompletableFutures.completedNull(); } @Override public byte getCommandId() { return CacheCommandIds.EVICT_ALL; } @Override public void writeTo(ObjectOutput output) { // No-op } @Override public boolean isReturnValueExpected() { return false; } @Override public void readFrom(ObjectInput input) { // No-op } }
2,051
24.333333
94
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/Tombstone.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import org.infinispan.commands.functional.functions.InjectableComponent; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.functional.EntryView; import org.infinispan.functional.MetaParam; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.function.Function; import java.util.function.Predicate; /** * This is used both as the storage in entry, and for efficiency also directly in the cache.put() commands. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class Tombstone implements Function<EntryView.ReadWriteEntryView<Object, Object>, Void>, InjectableComponent, CompletableFunction { public static final ExcludeTombstonesFilter EXCLUDE_TOMBSTONES = new ExcludeTombstonesFilter(); // the format of data is repeated (timestamp, UUID.LSB, UUID.MSB) private final long[] data; private transient InfinispanDataRegion region; private transient boolean complete; public Tombstone(UUID uuid, long timestamp) { this.data = new long[] { timestamp, uuid.getLeastSignificantBits(), uuid.getMostSignificantBits() }; } private Tombstone(long[] data) { this.data = data; } public long getLastTimestamp() { long max = data[0]; for (int i = 3; i < data.length; i += 3) { max = Math.max(max, data[i]); } return max; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Tombstone{"); for (int i = 0; i < data.length; i += 3) { if (i != 0) { sb.append(", "); } sb.append(new UUID(data[i + 2], data[i + 1])).append('=').append(data[i]); } sb.append('}'); return sb.toString(); } public Tombstone merge(Tombstone update) { assert update != null; assert update.data.length == 3; int toRemove = 0; for (int i = 0; i < data.length; i += 3) { if (data[i] < update.data[0]) { toRemove += 3; } else if (update.data[1] == data[i + 1] && update.data[2] == data[i + 2]) { // UUID matches - second update during retry? toRemove += 3; } } if (data.length == toRemove) { // applying the update second time? return update; } else { long[] newData = new long[data.length - toRemove + 3]; // 3 for the update int j = 0; boolean uuidMatch = false; for (int i = 0; i < data.length; i += 3) { if (data[i] < update.data[0]) { // This is an old eviction continue; } else if (update.data[1] == data[i + 1] && update.data[2] == data[i + 2]) { // UUID matches System.arraycopy(update.data, 0, newData, j, 3); uuidMatch = true; j += 3; } else { System.arraycopy(data, i, newData, j, 3); j += 3; } } assert (uuidMatch && j == newData.length) || (!uuidMatch && j == newData.length - 3); if (!uuidMatch) { System.arraycopy(update.data, 0, newData, j, 3); } return new Tombstone(newData); } } public Object applyUpdate(UUID uuid, long timestamp, Object value) { int toRemove = 0; for (int i = 0; i < data.length; i += 3) { if (data[i] < timestamp) { toRemove += 3; } else if (uuid.getLeastSignificantBits() == data[i + 1] && uuid.getMostSignificantBits() == data[i + 2]) { toRemove += 3; } } if (data.length == toRemove) { if (value == null) { return new Tombstone(uuid, timestamp); } else { return value; } } else { long[] newData = new long[data.length - toRemove + 3]; // 3 for the update int j = 0; boolean uuidMatch = false; for (int i = 0; i < data.length; i += 3) { if (data[i] < timestamp) { // This is an old eviction continue; } else if (uuid.getLeastSignificantBits() == data[i + 1] && uuid.getMostSignificantBits() == data[i + 2]) { newData[j] = timestamp; newData[j + 1] = uuid.getLeastSignificantBits(); newData[j + 2] = uuid.getMostSignificantBits(); uuidMatch = true; j += 3; } else { System.arraycopy(data, i, newData, j, 3); j += 3; } } assert (uuidMatch && j == newData.length) || (!uuidMatch && j == newData.length - 3); if (!uuidMatch) { newData[j] = timestamp; newData[j + 1] = uuid.getLeastSignificantBits(); newData[j + 2] = uuid.getMostSignificantBits(); } return new Tombstone(newData); } } // Used only for testing purposes public int size() { return data.length / 3; } @Override public Void apply(EntryView.ReadWriteEntryView<Object, Object> view) { Object storedValue = view.find().orElse(null); MetaParam.MetaLifespan expiringMetaParam = region.getExpiringMetaParam(); if (storedValue instanceof Tombstone) { view.set(((Tombstone) storedValue).merge(this), expiringMetaParam); } else { view.set(this, expiringMetaParam); } return null; } @Override public void inject(ComponentRegistry registry) { region = registry.getComponent(InfinispanDataRegion.class); } @Override public boolean isComplete() { return complete; } @Override public void markComplete() { complete = true; } public static class Externalizer implements AdvancedExternalizer<Tombstone> { @Override public Set<Class<? extends Tombstone>> getTypeClasses() { return Collections.<Class<? extends Tombstone>>singleton(Tombstone.class); } @Override public Integer getId() { return Externalizers.TOMBSTONE; } @Override public void writeObject(ObjectOutput output, Tombstone tombstone) throws IOException { output.writeInt(tombstone.data.length); for (int i = 0; i < tombstone.data.length; ++i) { output.writeLong(tombstone.data[i]); } } @Override public Tombstone readObject(ObjectInput input) throws IOException, ClassNotFoundException { int length = input.readInt(); long[] data = new long[length]; for (int i = 0; i < data.length; ++i) { data[i] = input.readLong(); } return new Tombstone(data); } } public static class ExcludeTombstonesFilter implements Predicate<Map.Entry<Object, Object>> { private ExcludeTombstonesFilter() {} @Override public boolean test(Map.Entry<Object, Object> entry) { return !(entry.getValue() instanceof Tombstone); } } public static class ExcludeTombstonesFilterExternalizer implements AdvancedExternalizer<ExcludeTombstonesFilter> { @Override public Set<Class<? extends ExcludeTombstonesFilter>> getTypeClasses() { return Collections.<Class<? extends ExcludeTombstonesFilter>>singleton(ExcludeTombstonesFilter.class); } @Override public Integer getId() { return Externalizers.EXCLUDE_TOMBSTONES_FILTER; } @Override public void writeObject(ObjectOutput output, ExcludeTombstonesFilter object) throws IOException { } @Override public ExcludeTombstonesFilter readObject(ObjectInput input) throws IOException, ClassNotFoundException { return EXCLUDE_TOMBSTONES; } } }
7,315
27.80315
138
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/EndInvalidationCommand.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.concurrent.CompletionStage; import org.infinispan.commands.remote.BaseRpcCommand; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.util.Util; import org.infinispan.factories.ComponentRegistry; import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator; import org.infinispan.util.ByteString; import org.infinispan.commons.util.concurrent.CompletableFutures; /** * Sent in commit phase (after DB commit) to remote nodes in order to stop invalidating * putFromLoads. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class EndInvalidationCommand extends BaseRpcCommand { private Object[] keys; private Object lockOwner; public EndInvalidationCommand(ByteString cacheName) { this(cacheName, null, null); } /** * @param cacheName name of the cache to evict */ public EndInvalidationCommand(ByteString cacheName, Object[] keys, Object lockOwner) { super(cacheName); this.keys = keys; this.lockOwner = lockOwner; } @Override public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) { for (Object key : keys) { PutFromLoadValidator putFromLoadValidator = componentRegistry.getComponent(PutFromLoadValidator.class); putFromLoadValidator.endInvalidatingKey(lockOwner, key); } return CompletableFutures.completedNull(); } @Override public byte getCommandId() { return CacheCommandIds.END_INVALIDATION; } @Override public void writeTo(ObjectOutput output) throws IOException { MarshallUtil.marshallArray(keys, output); LockOwner.writeTo( output, lockOwner ); } @Override public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { keys = MarshallUtil.unmarshallArray(input, Util::objectArray); lockOwner = LockOwner.readFrom(input); } @Override public boolean isReturnValueExpected() { return false; } @Override public boolean canBlock() { return true; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof EndInvalidationCommand)) { return false; } EndInvalidationCommand that = (EndInvalidationCommand) o; if (cacheName == null ? cacheName != null : !cacheName.equals(that.cacheName)) { return false; } if (!Arrays.equals(keys, that.keys)) { return false; } return !(lockOwner != null ? !lockOwner.equals(that.lockOwner) : that.lockOwner != null); } @Override public int hashCode() { int result = cacheName != null ? cacheName.hashCode() : 0; result = 31 * result + (keys != null ? Arrays.hashCode(keys) : 0); result = 31 * result + (lockOwner != null ? lockOwner.hashCode() : 0); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder("EndInvalidationCommand{"); sb.append("cacheName=").append(cacheName); sb.append(", keys=").append(Arrays.toString(keys)); sb.append(", sessionTransactionId=").append(lockOwner); sb.append('}'); return sb.toString(); } }
3,416
27.239669
106
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/CompletableFunction.java
package org.infinispan.hibernate.cache.commons.util; /** * Called by {@link org.infinispan.hibernate.cache.commons.access.LockingInterceptor} when the function * was applied locally (after unlocking the entry and we're just waiting for the replication. * Note: we don't mind if the command is retried, the important part is that it was already applied locally. */ public interface CompletableFunction { boolean isComplete(); void markComplete(); }
459
37.333333
108
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/CacheCommandIds.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; /** * Command id range assigned to Hibernate second level cache: 120 - 139 * * @author Galder Zamarreño * @since 4.0 */ public interface CacheCommandIds { /** * {@link EvictAllCommand} id */ byte EVICT_ALL = 120; /** * {@link EndInvalidationCommand} id */ byte END_INVALIDATION = 121; /** * {@link BeginInvalidationCommand} id */ byte BEGIN_INVALIDATION = 122; }
679
20.935484
94
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/Externalizers.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import org.infinispan.commons.marshall.AdvancedExternalizer; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import java.util.UUID; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class Externalizers { public final static int UUID = 1200; public final static int TOMBSTONE = 1201; public final static int EXCLUDE_TOMBSTONES_FILTER = 1202; public final static int TOMBSTONE_UPDATE = 1203; public final static int FUTURE_UPDATE = 1204; public final static int VALUE_EXTRACTOR = 1205; public final static int VERSIONED_ENTRY = 1206; public final static int EXCLUDE_EMPTY_VERSIONED_ENTRY = 1207; public final static int FILTER_NULL_VALUE_CONVERTER = 1208; public final static int NULL_VALUE = 1209; public static class UUIDExternalizer implements AdvancedExternalizer<UUID> { @Override public Set<Class<? extends UUID>> getTypeClasses() { return Collections.<Class<? extends UUID>>singleton(UUID.class); } @Override public Integer getId() { return UUID; } @Override public void writeObject(ObjectOutput output, UUID uuid) throws IOException { output.writeLong(uuid.getMostSignificantBits()); output.writeLong(uuid.getLeastSignificantBits()); } @Override public UUID readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new UUID(input.readLong(), input.readLong()); } } }
1,755
29.275862
94
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/VersionedEntry.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import org.hibernate.cache.spi.entry.CacheEntry; import org.hibernate.cache.spi.entry.StructuredCacheEntry; import org.infinispan.commands.functional.functions.InjectableComponent; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.functional.EntryView; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class VersionedEntry implements Function<EntryView.ReadWriteEntryView<Object, Object>, Void>, InjectableComponent { private static final Log log = LogFactory.getLog(VersionedEntry.class); public static final ExcludeEmptyFilter EXCLUDE_EMPTY_VERSIONED_ENTRY = new ExcludeEmptyFilter(); private final Object value; private final Object version; private final long timestamp; private transient InfinispanDataRegion region; public VersionedEntry(long timestamp) { this(null, null, timestamp); } public VersionedEntry(Object value, Object version, long timestamp) { this.value = value; this.version = version; this.timestamp = timestamp; } public Object getValue() { return value; } public Object getVersion() { return version; } public long getTimestamp() { return timestamp; } @Override public String toString() { final StringBuilder sb = new StringBuilder("VersionedEntry{"); sb.append("value=").append(value); sb.append(", version=").append(version); sb.append(", timestamp=").append(timestamp); sb.append('}'); return sb.toString(); } @Override public Void apply(EntryView.ReadWriteEntryView<Object, Object> view) { if (log.isTraceEnabled()) { log.tracef("Applying %s to %s", this, view.find().orElse(null)); } if (version == null) { // eviction or post-commit removal: we'll store it with given timestamp view.set(this, region.getExpiringMetaParam()); return null; } Object oldValue = view.find().orElse(null); Object oldVersion = null; long oldTimestamp = Long.MIN_VALUE; if (oldValue instanceof VersionedEntry) { VersionedEntry oldVersionedEntry = (VersionedEntry) oldValue; oldVersion = oldVersionedEntry.version; oldTimestamp = oldVersionedEntry.timestamp; oldValue = oldVersionedEntry.value; } else { oldVersion = findVersion(oldValue); } if (oldVersion == null) { assert oldValue == null || oldTimestamp != Long.MIN_VALUE : oldValue; if (timestamp <= oldTimestamp) { // either putFromLoad or regular update/insert - in either case this update might come // when it was evicted/region-invalidated. In both cases, with old timestamp we'll leave // the invalid value assert oldValue == null; } else { view.set(value instanceof CacheEntry ? value : this); } return null; } else { Comparator<Object> versionComparator = null; String subclass = findSubclass(value); if (subclass != null) { versionComparator = region.getComparator(subclass); if (versionComparator == null) { log.errorf("Cannot find comparator for %s", subclass); } } if (versionComparator == null) { view.set(new VersionedEntry(null, null, timestamp), region.getExpiringMetaParam()); } else { int compareResult = versionComparator.compare(version, oldVersion); if (log.isTraceEnabled()) { log.tracef("Comparing %s and %s -> %d (using %s)", version, oldVersion, compareResult, versionComparator); } if (value == null && compareResult >= 0) { view.set(this, region.getExpiringMetaParam()); } else if (compareResult > 0) { view.set(value instanceof CacheEntry ? value : this); } } } return null; } private Object findVersion(Object entry) { if (entry instanceof CacheEntry) { // with UnstructuredCacheEntry return ((CacheEntry) entry).getVersion(); } else if (entry instanceof Map) { return ((Map) entry).get(StructuredCacheEntry.VERSION_KEY); } else { return null; } } private String findSubclass(Object entry) { // we won't find subclass for structured collections if (entry instanceof CacheEntry) { return ((CacheEntry) this.value).getSubclass(); } else if (entry instanceof Map) { Object maybeSubclass = ((Map) entry).get(StructuredCacheEntry.SUBCLASS_KEY); return maybeSubclass instanceof String ? (String) maybeSubclass : null; } else { return null; } } @Override public void inject(ComponentRegistry registry) { region = registry.getComponent(InfinispanDataRegion.class); } private static class ExcludeEmptyFilter implements Predicate<Map.Entry<Object, Object>> { @Override public boolean test(Map.Entry<Object, Object> entry) { if (entry.getValue() instanceof VersionedEntry) { return ((VersionedEntry) entry.getValue()).getValue() != null; } return true; } } public static class Externalizer implements AdvancedExternalizer<VersionedEntry> { @Override public Set<Class<? extends VersionedEntry>> getTypeClasses() { return Collections.<Class<? extends VersionedEntry>>singleton(VersionedEntry.class); } @Override public Integer getId() { return Externalizers.VERSIONED_ENTRY; } @Override public void writeObject(ObjectOutput output, VersionedEntry object) throws IOException { output.writeObject(object.value); output.writeObject(object.version); output.writeLong(object.timestamp); } @Override public VersionedEntry readObject(ObjectInput input) throws IOException, ClassNotFoundException { Object value = input.readObject(); Object version = input.readObject(); long timestamp = input.readLong(); return new VersionedEntry(value, version, timestamp); } } public static class ExcludeEmptyVersionedEntryExternalizer implements AdvancedExternalizer<ExcludeEmptyFilter> { @Override public Set<Class<? extends ExcludeEmptyFilter>> getTypeClasses() { return Collections.<Class<? extends ExcludeEmptyFilter>>singleton(ExcludeEmptyFilter.class); } @Override public Integer getId() { return Externalizers.EXCLUDE_EMPTY_VERSIONED_ENTRY; } @Override public void writeObject(ObjectOutput output, ExcludeEmptyFilter object) throws IOException { } @Override public ExcludeEmptyFilter readObject(ObjectInput input) throws IOException, ClassNotFoundException { return EXCLUDE_EMPTY_VERSIONED_ENTRY; } } }
7,022
30.922727
122
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/FutureUpdate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import org.infinispan.commands.functional.functions.InjectableComponent; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.functional.EntryView; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import java.util.UUID; import java.util.function.Function; /** * Request to update the tombstone, coming from insert/update/remove operation. * * This object should *not* be stored in cache. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class FutureUpdate implements Function<EntryView.ReadWriteEntryView<Object, Object>, Void>, InjectableComponent { private final UUID uuid; private final long timestamp; private final Object value; private transient InfinispanDataRegion region; public FutureUpdate(UUID uuid, long timestamp, Object value) { this.uuid = uuid; this.timestamp = timestamp; this.value = value; } @Override public String toString() { final StringBuilder sb = new StringBuilder("FutureUpdate{"); sb.append("uuid=").append(uuid); sb.append(", timestamp=").append(timestamp); sb.append(", value=").append(value); sb.append('}'); return sb.toString(); } public UUID getUuid() { return uuid; } public Object getValue() { return value; } public long getTimestamp() { return timestamp; } @Override public Void apply(EntryView.ReadWriteEntryView<Object, Object> view) { Object storedValue = view.find().orElse(null); if (storedValue instanceof Tombstone) { // Note that the update has to keep tombstone even if the transaction was unsuccessful; // before write we have removed the value and we have to protect the entry against stale putFromLoads Tombstone tombstone = (Tombstone) storedValue; Object result = tombstone.applyUpdate(uuid, timestamp, this.value); if (result instanceof Tombstone) { view.set(result, region.getExpiringMetaParam()); } else { view.set(result); } } // Else: this is an async future update, and it's timestamp may be vastly outdated // We need to first execute the async update and then local one, because if we're on the primary // owner the local future update would fail the async one. // TODO: There is some discrepancy with TombstoneUpdate handling which does not fail the update return null; } @Override public void inject(ComponentRegistry registry) { region = registry.getComponent(InfinispanDataRegion.class); } public static class Externalizer implements AdvancedExternalizer<FutureUpdate> { @Override public void writeObject(ObjectOutput output, FutureUpdate object) throws IOException { output.writeLong(object.uuid.getMostSignificantBits()); output.writeLong(object.uuid.getLeastSignificantBits()); output.writeLong(object.timestamp); output.writeObject(object.value); } @Override public FutureUpdate readObject(ObjectInput input) throws IOException, ClassNotFoundException { long msb = input.readLong(); long lsb = input.readLong(); long timestamp = input.readLong(); Object value = input.readObject(); return new FutureUpdate(new UUID(msb, lsb), timestamp, value); } @Override public Set<Class<? extends FutureUpdate>> getTypeClasses() { return Collections.<Class<? extends FutureUpdate>>singleton(FutureUpdate.class); } @Override public Integer getId() { return Externalizers.FUTURE_UPDATE; } } }
3,857
31.15
120
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/CacheCommandExtensions.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import org.infinispan.commands.module.ModuleCommandExtensions; import org.infinispan.commands.module.ModuleCommandFactory; import org.kohsuke.MetaInfServices; /** * Command extensions for second-level cache use case * * @author Galder Zamarreño * @since 4.0 */ @MetaInfServices(ModuleCommandExtensions.class) public class CacheCommandExtensions implements ModuleCommandExtensions { final CacheCommandFactory cacheCommandFactory = new CacheCommandFactory(); @Override public ModuleCommandFactory getModuleCommandFactory() { return cacheCommandFactory; } }
859
29.714286
94
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/LockOwner.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.infinispan.commands.CommandInvocationId; final class LockOwner { private LockOwner() { } static void writeTo(ObjectOutput out, Object lockOwner) throws IOException { if (lockOwner instanceof CommandInvocationId) { out.writeByte( 0 ); CommandInvocationId.writeTo( out, (CommandInvocationId) lockOwner ); } else { out.writeByte( 1 ); out.writeObject(lockOwner); } } static Object readFrom(ObjectInput in) throws IOException, ClassNotFoundException { byte lockOwnerType = in.readByte(); switch ( lockOwnerType ) { case 0: return CommandInvocationId.readFrom( in ); case 1: return in.readObject(); default: throw new IllegalStateException( "Unknown lock owner type" + lockOwnerType ); } } }
1,133
24.772727
94
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/Caches.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.CloseableIterable; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.Flag; import org.infinispan.filter.AcceptAllKeyValueFilter; import org.infinispan.filter.CacheFilters; import org.infinispan.filter.Converter; import org.infinispan.filter.KeyValueFilter; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.impl.VoidResponseCollector; import org.infinispan.util.ByteString; import jakarta.transaction.Status; import jakarta.transaction.TransactionManager; /** * Helper for dealing with Infinispan cache instances. * * @author Galder Zamarreño * @since 4.1 */ public class Caches { private Caches() { // Suppresses default constructor, ensuring non-instantiability. } /** * Call an operation within a transaction. This method guarantees that the * right pattern is used to make sure that the transaction is always either * committed or rollback. * * @param cache instance whose transaction manager to use * @param c callable instance to run within a transaction * @param <T> type of callable return * @return returns whatever the callable returns * @throws Exception if any operation within the transaction fails */ public static <T> T withinTx( AdvancedCache cache, Callable<T> c) throws Exception { // Retrieve transaction manager return withinTx( cache.getTransactionManager(), c ); } /** * Call an operation within a transaction. This method guarantees that the * right pattern is used to make sure that the transaction is always either * committed or rollbacked. * * @param tm transaction manager * @param c callable instance to run within a transaction * @param <T> type of callable return * @return returns whatever the callable returns * @throws Exception if any operation within the transaction fails */ public static <T> T withinTx( TransactionManager tm, Callable<T> c) throws Exception { if ( tm == null ) { try { return c.call(); } catch (Exception e) { throw e; } } else { tm.begin(); try { return c.call(); } catch (Exception e) { tm.setRollbackOnly(); throw e; } finally { if ( tm.getStatus() == Status.STATUS_ACTIVE ) { tm.commit(); } else { tm.rollback(); } } } } public static void withinTx(TransactionManager tm, final Runnable runnable) throws Exception { withinTx(tm, new Callable<Void>() { @Override public Void call() throws Exception { runnable.run(); return null; } }); } /** * Transform a given cache into a local cache * * @param cache to be transformed * @return a cache that operates only in local-mode */ public static AdvancedCache localCache(AdvancedCache cache) { return cache.withFlags( Flag.CACHE_MODE_LOCAL ); } /** * Transform a given cache into a cache that ignores return values for * operations returning previous values, i.e. {@link AdvancedCache#put(Object, Object)} * * @param cache to be transformed * @return a cache that ignores return values */ public static AdvancedCache ignoreReturnValuesCache(AdvancedCache cache) { return cache.withFlags( Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES ); } /** * Transform a given cache into a cache that ignores return values for * operations returning previous values, i.e. {@link AdvancedCache#put(Object, Object)}, * adding an extra flag. * * @param cache to be transformed * @param extraFlag to add to the returned cache * @return a cache that ignores return values */ public static AdvancedCache ignoreReturnValuesCache( AdvancedCache cache, Flag extraFlag) { return cache.withFlags( Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP, Flag.IGNORE_RETURN_VALUES, extraFlag ); } /** * Transform a given cache into a cache that writes cache entries without * waiting for them to complete, adding an extra flag. * * @param cache to be transformed * @param extraFlag to add to the returned cache * @return a cache that writes asynchronously */ public static AdvancedCache asyncWriteCache( AdvancedCache cache, Flag extraFlag) { return cache.withFlags( Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP, Flag.FORCE_ASYNCHRONOUS, extraFlag ); } /** * Transform a given cache into a cache that fails silently if cache writes fail. * * @param cache to be transformed * @return a cache that fails silently if cache writes fail */ public static AdvancedCache failSilentWriteCache(AdvancedCache cache) { return cache.withFlags( Flag.FAIL_SILENTLY, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP ); } /** * Transform a given cache into a cache that fails silently if * cache writes fail, adding an extra flag. * * @param cache to be transformed * @param extraFlag to be added to returned cache * @return a cache that fails silently if cache writes fail */ public static AdvancedCache failSilentWriteCache( AdvancedCache cache, Flag extraFlag) { return cache.withFlags( Flag.FAIL_SILENTLY, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP, extraFlag ); } /** * Transform a given cache into a cache that fails silently if * cache reads fail. * * @param cache to be transformed * @return a cache that fails silently if cache reads fail */ public static AdvancedCache failSilentReadCache(AdvancedCache cache) { return cache.withFlags( Flag.FAIL_SILENTLY, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT ); } /** * Broadcast an evict-all command with the given cache instance. * @param cache instance used to broadcast command * */ public static void broadcastEvictAll(AdvancedCache cache) { final RpcManager rpcManager = cache.getRpcManager(); if (rpcManager != null) { final EvictAllCommand cmd = new EvictAllCommand(ByteString.fromString(cache.getName())); if (isSynchronousCache(cache)) { rpcManager.blocking(rpcManager.invokeCommandOnAll(cmd, VoidResponseCollector.validOnly(), rpcManager.getSyncRpcOptions())); } else { rpcManager.sendToAll(cmd, DeliverOrder.PER_SENDER); } } } /** * Indicates whether the given cache is configured with * {@link org.infinispan.configuration.cache.CacheMode#INVALIDATION_ASYNC} or * {@link org.infinispan.configuration.cache.CacheMode#INVALIDATION_SYNC}. * * @param cache to check for invalidation configuration * @return true if the cache is configured with invalidation, false otherwise */ public static boolean isInvalidationCache(AdvancedCache cache) { return cache.getCacheConfiguration() .clustering().cacheMode().isInvalidation(); } /** * Indicates whether the given cache is configured with * {@link org.infinispan.configuration.cache.CacheMode#REPL_SYNC}, * {@link org.infinispan.configuration.cache.CacheMode#INVALIDATION_SYNC}, or * {@link org.infinispan.configuration.cache.CacheMode#DIST_SYNC}. * * @param cache to check for synchronous configuration * @return true if the cache is configured with synchronous mode, false otherwise */ public static boolean isSynchronousCache(AdvancedCache cache) { return cache.getCacheConfiguration() .clustering().cacheMode().isSynchronous(); } /** * Indicates whether the given cache is configured to cluster its contents. * A cache is considered to clustered if it's configured with any cache mode * except {@link org.infinispan.configuration.cache.CacheMode#LOCAL} * * @param cache to check whether it clusters its contents * @return true if the cache is configured with clustering, false otherwise */ public static boolean isClustered(AdvancedCache cache) { return cache.getCacheConfiguration() .clustering().cacheMode().isClustered(); } public static boolean isTransactionalCache(AdvancedCache cache) { return cache.getCacheConfiguration().transaction().transactionMode().isTransactional(); } public static void removeAll(AdvancedCache cache) { CloseableIterator it = cache.keySet().iterator(); try { while (it.hasNext()) { // Cannot use it.next(); it.remove() due to ISPN-5653 cache.remove(it.next()); } } finally { it.close(); } } /** * This interface is provided for convenient fluent use of CloseableIterable */ public interface CollectableCloseableIterable<T> extends CloseableIterable<T> { Set<T> toSet(); } public interface MapCollectableCloseableIterable<K, V> extends CloseableIterable<CacheEntry<K, V>> { Map<K, V> toMap(); } public static <K, V> MapCollectableCloseableIterable<K, V> entrySet(AdvancedCache<K, V> cache) { return entrySet(cache, (KeyValueFilter<K, V>) AcceptAllKeyValueFilter.getInstance()); } public static <K, V> MapCollectableCloseableIterable<K, V> entrySet(AdvancedCache<K, V> cache, KeyValueFilter<K, V> filter) { if (cache.getCacheConfiguration().transaction().transactionMode().isTransactional()) { // Dummy read to enlist the LocalTransaction as workaround for ISPN-5676 cache.containsKey(false); } // HHH-10023: we can't use values() CloseableIterator<CacheEntry<K, V>> iterator = Closeables.iterator( cache.cacheEntrySet().stream().filter(CacheFilters.predicate(filter))); return new MapCollectableCloseableIterableImpl<K, V>(iterator); } public static <K, V, T> MapCollectableCloseableIterable<K, T> entrySet(AdvancedCache<K, V> cache, KeyValueFilter<K, V> filter, Converter<K, V, T> converter) { if (cache.getCacheConfiguration().transaction().transactionMode().isTransactional()) { // Dummy read to enlist the LocalTransaction as workaround for ISPN-5676 cache.containsKey(false); } // HHH-10023: we can't use values() CloseableIterator<CacheEntry<K, T>> it = Closeables.iterator(cache.cacheEntrySet().stream() .filter(CacheFilters.predicate(filter)) .map(CacheFilters.function(converter))); return new MapCollectableCloseableIterableImpl<K, T>(it); } /* Function<CacheEntry<K, V>, T> */ private interface Selector<K, V, T> { Selector KEY = new Selector<Object, Void, Object>() { @Override public Object apply(CacheEntry<Object, Void> entry) { return entry.getKey(); } }; Selector VALUE = new Selector<Object, Object, Object>() { @Override public Object apply(CacheEntry<Object, Object> entry) { return entry.getValue(); } }; T apply(CacheEntry<K, V> entry); } private static class CollectableCloseableIterableImpl<K, V, T> implements CollectableCloseableIterable<T> { private final CloseableIterable<CacheEntry<K, V>> entryIterable; private final Selector<K, V, T> selector; public CollectableCloseableIterableImpl(CloseableIterable<CacheEntry<K, V>> entryIterable, Selector<K, V, T> selector) { this.entryIterable = entryIterable; this.selector = selector; } @Override public void close() { entryIterable.close(); } @Override public CloseableIterator<T> iterator() { final CloseableIterator<CacheEntry<K, V>> entryIterator = entryIterable.iterator(); return new CloseableIterator<T>() { @Override public void close() { entryIterator.close(); } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public T next() { return selector.apply(entryIterator.next()); } @Override public void remove() { throw new UnsupportedOperationException( "remove() not supported" ); } }; } @Override public String toString() { CloseableIterator<CacheEntry<K, V>> it = entryIterable.iterator(); try { if (!it.hasNext()) { return "[]"; } StringBuilder sb = new StringBuilder(); sb.append('['); for (; ; ) { CacheEntry<K, V> entry = it.next(); sb.append(selector.apply(entry)); if (!it.hasNext()) { return sb.append(']').toString(); } sb.append(',').append(' '); } } finally { it.close(); } } @Override public Set toSet() { HashSet set = new HashSet(); CloseableIterator it = iterator(); try { while (it.hasNext()) { set.add(it.next()); } } finally { it.close(); } return set; } } private static class MapCollectableCloseableIterableImpl<K, V> implements MapCollectableCloseableIterable<K, V> { private final CloseableIterator<CacheEntry<K, V>> it; public MapCollectableCloseableIterableImpl(CloseableIterator<CacheEntry<K, V>> it) { this.it = it; } @Override public Map<K, V> toMap() { Map<K, V> map = new HashMap<K, V>(); try { while (it.hasNext()) { CacheEntry<K, V> entry = it.next(); V value = entry.getValue(); if (value != null) { map.put(entry.getKey(), value); } } return map; } finally { it.close(); } } @Override public String toString() { try { if (!it.hasNext()) { return "{}"; } StringBuilder sb = new StringBuilder(); sb.append('{'); for (; ; ) { CacheEntry<K, V> entry = it.next(); sb.append(entry.getKey()).append('=').append(entry.getValue()); if (!it.hasNext()) { return sb.append('}').toString(); } sb.append(',').append(' '); } } finally { it.close(); } } @Override public void close() { it.close(); } @Override public CloseableIterator<CacheEntry<K, V>> iterator() { return it; } } }
14,159
27.839104
159
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/InvocationAfterCompletion.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import org.hibernate.HibernateException; import org.infinispan.hibernate.cache.commons.access.SessionAccess.TransactionCoordinatorAccess; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public abstract class InvocationAfterCompletion implements Synchronization { protected static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( InvocationAfterCompletion.class ); protected final TransactionCoordinatorAccess tc; protected final boolean requiresTransaction; public InvocationAfterCompletion(TransactionCoordinatorAccess tc, boolean requiresTransaction) { this.tc = tc; this.requiresTransaction = requiresTransaction; } @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { switch (status) { case Status.STATUS_COMMITTING: case Status.STATUS_COMMITTED: invokeIsolated(true); break; default: // it would be nicer to react only on ROLLING_BACK and ROLLED_BACK statuses // but TransactionCoordinator gives us UNKNOWN on rollback invokeIsolated(false); break; } } protected void invokeIsolated(final boolean success) { try { tc.delegateWork((executor, connection) -> { invoke(success); return null; }, requiresTransaction); } catch (HibernateException e) { // silently fail any exceptions if (log.isTraceEnabled()) { log.trace("Exception during query cache update", e); } } } protected abstract void invoke(boolean success); }
1,872
27.815385
129
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/util/CacheCommandFactory.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.util; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.module.ModuleCommandFactory; import org.infinispan.commands.remote.CacheRpcCommand; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.util.ByteString; /** * Command factory * * @author Galder Zamarreño * @since 4.0 */ public class CacheCommandFactory implements ModuleCommandFactory { /** * Keeps track of regions to which second-level cache specific commands have been plugged. * The regions are keyed by cache name (which is qualified), not by region name that is unqualified in Hibernate 5.3+ */ private ConcurrentMap<ByteString, InfinispanBaseRegion> allRegions = new ConcurrentHashMap<>(); /** * Add region so that commands can be cleared on shutdown. * * @param region instance to keep track of */ public void addRegion(InfinispanBaseRegion region) { allRegions.put(ByteString.fromString(region.getCache().getName()), region); } /** * Clear all regions from this command factory. * * @param regions collection of regions to clear */ public void clearRegions(Collection<? extends InfinispanBaseRegion> regions) { regions.forEach(region -> allRegions.remove(ByteString.fromString(region.getCache().getName()))); } @Override public Map<Byte, Class<? extends ReplicableCommand>> getModuleCommands() { final Map<Byte, Class<? extends ReplicableCommand>> map = new HashMap<Byte, Class<? extends ReplicableCommand>>( 3 ); map.put( CacheCommandIds.EVICT_ALL, EvictAllCommand.class ); map.put( CacheCommandIds.END_INVALIDATION, EndInvalidationCommand.class ); map.put( CacheCommandIds.BEGIN_INVALIDATION, BeginInvalidationCommand.class ); return map; } @Override public CacheRpcCommand fromStream(byte commandId, ByteString cacheName) { CacheRpcCommand c; switch ( commandId ) { case CacheCommandIds.EVICT_ALL: c = new EvictAllCommand(cacheName, allRegions.get(cacheName)); break; case CacheCommandIds.END_INVALIDATION: c = new EndInvalidationCommand(cacheName); break; default: throw new IllegalArgumentException( "Not registered to handle command id " + commandId ); } return c; } @Override public ReplicableCommand fromStream(byte commandId) { ReplicableCommand c; switch ( commandId ) { case CacheCommandIds.BEGIN_INVALIDATION: c = new BeginInvalidationCommand(); break; default: throw new IllegalArgumentException( "Not registered to handle command id " + commandId ); } return c; } }
3,026
31.902174
120
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/package-info.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ /** * Internal Infinispan-based implementation of the cache region access strategies */ package org.infinispan.hibernate.cache.commons.access;
383
31
94
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/LockingInterceptor.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.infinispan.commands.functional.ReadWriteKeyCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.distribution.Ownership; import org.infinispan.hibernate.cache.commons.util.CompletableFunction; import org.infinispan.interceptors.InvocationFinallyFunction; import org.infinispan.interceptors.InvocationStage; import org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor; import org.infinispan.util.concurrent.TimeoutException; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * With regular {@link org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor}, * async replication does not work in combination with synchronous replication: sync replication * relies on locking to order writes on backup while async replication relies on FIFO-ordering * from primary to backup. If these two combine, there's a possibility that on backup two modifications * modifications will proceed concurrently. * Similar issue threatens consistency when the command has {@link org.infinispan.context.Flag#CACHE_MODE_LOCAL} * - these commands don't acquire locks either. * * Therefore, this interceptor locks the entry all the time. {@link UnorderedDistributionInterceptor} does not forward * the message from non-origin to any other node, and the distribution interceptor won't block on RPC but will return * {@link CompletableFuture} and we'll wait for it here. */ public class LockingInterceptor extends NonTransactionalLockingInterceptor { private static final Log log = LogFactory.getLog(LockingInterceptor.class); protected final InvocationFinallyFunction<DataWriteCommand> unlockAllReturnCheckCompletableFutureHandler = (rCtx, rCommand, rv, throwable) -> { lockManager.unlockAll(rCtx); if (throwable != null) throw throwable; if (rv instanceof CompletableFuture) { // See CompletableFunction javadoc for explanation if (rCommand instanceof ReadWriteKeyCommand) { Function function = ((ReadWriteKeyCommand) rCommand).getFunction(); if (function instanceof CompletableFunction) { ((CompletableFunction) function).markComplete(); } } // Similar to CompletableFunction above, signals that the command has been applied for non-functional commands rCommand.setFlagsBitSet(rCommand.getFlagsBitSet() & ~FlagBitSets.FORCE_WRITE_LOCK); // The future is produced in UnorderedDistributionInterceptor. // We need the EWI to commit the entry & unlock before the remote call completes // but here we wait for the other nodes, without blocking concurrent updates. return asyncValue((CompletableFuture) rv); } else { return rv; } }; protected final InvocationFinallyFunction<DataWriteCommand> invokeNextAndUnlock = (rCtx, dataWriteCommand, rv, throwable) -> { if (throwable != null) { lockManager.unlockAll(rCtx); if (throwable instanceof TimeoutException && dataWriteCommand.hasAnyFlag(FlagBitSets.FAIL_SILENTLY)) { dataWriteCommand.fail(); return null; } throw throwable; } else { return invokeNextAndHandle(rCtx, dataWriteCommand, unlockAllReturnCheckCompletableFutureHandler); } }; @Override protected Object visitDataWriteCommand(InvocationContext ctx, DataWriteCommand command) { try { if (log.isTraceEnabled()) { Ownership ownership = cdl.getCacheTopology().getDistribution(command.getKey()).writeOwnership(); log.tracef( "Am I owner for key=%s ? %s", command.getKey(), ownership); } if (ctx.getLockOwner() == null) { ctx.setLockOwner( command.getCommandInvocationId() ); } InvocationStage lockStage = lockAndRecord(ctx, command, command.getKey(), getLockTimeoutMillis(command)); return lockStage.andHandle(ctx, command, invokeNextAndUnlock); } catch (Throwable t) { lockManager.unlockAll(ctx); throw t; } } }
4,617
45.18
146
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/UnorderedReplicationLogic.java
package org.infinispan.hibernate.cache.commons.access; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.locking.ClusteringDependentLogic; public class UnorderedReplicationLogic extends ClusteringDependentLogic.ReplicationLogic { @Override public Commit commitType( FlagAffectedCommand command, InvocationContext ctx, int segment, boolean removed) { Commit commit = super.commitType( command, ctx, segment, removed ); return commit == Commit.NO_COMMIT ? Commit.COMMIT_LOCAL : commit; } }
608
34.823529
92
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/TombstoneAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.concurrent.CompletableFuture; import org.hibernate.cache.CacheException; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.Param; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.hibernate.cache.commons.access.SessionAccess.TransactionCoordinatorAccess; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.Caches; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.commons.util.Tombstone; import org.infinispan.hibernate.cache.commons.util.TombstoneUpdate; import org.hibernate.cache.spi.access.SoftLock; import org.infinispan.AdvancedCache; import org.infinispan.configuration.cache.Configuration; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class TombstoneAccessDelegate implements AccessDelegate { protected static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( TombstoneAccessDelegate.class ); private static final SessionAccess SESSION_ACCESS = SessionAccess.findSessionAccess(); protected final InfinispanDataRegion region; protected final AdvancedCache cache; protected final FunctionalMap.ReadWriteMap<Object, Object> writeMap; protected final FunctionalMap.ReadWriteMap<Object, Object> asyncWriteMap; private final boolean requiresTransaction; private final FunctionalMap.ReadWriteMap<Object, Object> putFromLoadMap; public TombstoneAccessDelegate(InfinispanDataRegion region) { this.region = region; this.cache = region.getCache(); FunctionalMapImpl<Object, Object> fmap = FunctionalMapImpl.create(cache).withParams(Param.PersistenceMode.SKIP_LOAD); writeMap = ReadWriteMapImpl.create(fmap); // Note that correct behaviour of local and async writes depends on LockingInterceptor (see there for details) asyncWriteMap = ReadWriteMapImpl.create(fmap).withParams(Param.ReplicationMode.ASYNC); putFromLoadMap = ReadWriteMapImpl.create(fmap).withParams(Param.LockingMode.TRY_LOCK, Param.ReplicationMode.ASYNC); Configuration configuration = this.cache.getCacheConfiguration(); if (configuration.clustering().cacheMode().isInvalidation()) { throw new IllegalArgumentException("For tombstone-based caching, invalidation cache is not allowed."); } if (configuration.transaction().transactionMode().isTransactional()) { throw new IllegalArgumentException("Currently transactional caches are not supported."); } requiresTransaction = configuration.transaction().transactionMode().isTransactional() && !configuration.transaction().autoCommit(); } @Override public Object get(Object session, Object key, long txTimestamp) throws CacheException { if (txTimestamp < region.getLastRegionInvalidation() ) { return null; } Object value = cache.get(key); if (value instanceof Tombstone) { return null; } else { return value; } } @Override public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version) { return putFromLoad(session, key, value, txTimestamp, version, false); } @Override public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { long lastRegionInvalidation = region.getLastRegionInvalidation(); if (txTimestamp < lastRegionInvalidation) { log.tracef("putFromLoad not executed since tx started at %d, before last region invalidation finished = %d", txTimestamp, lastRegionInvalidation); return false; } if (minimalPutOverride) { Object prev = cache.get(key); if (prev instanceof Tombstone) { Tombstone tombstone = (Tombstone) prev; long lastTimestamp = tombstone.getLastTimestamp(); if (txTimestamp <= lastTimestamp) { log.tracef("putFromLoad not executed since tx started at %d, before last invalidation finished = %d", txTimestamp, lastTimestamp); return false; } } else if (prev != null) { log.tracef("putFromLoad not executed since cache contains %s", prev); return false; } } // we can't use putForExternalRead since the PFER flag means that entry is not wrapped into context // when it is present in the container. TombstoneCallInterceptor will deal with this. CompletableFuture<Void> future = putFromLoadMap.eval(key, new TombstoneUpdate<>(SESSION_ACCESS.getTimestamp(session), value)); assert future.isDone(); // async try-locking should be done immediately return true; } @Override public boolean insert(Object session, Object key, Object value, Object version) throws CacheException { write(session, key, value); return true; } @Override public boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { write(session, key, value); return true; } @Override public void remove(Object session, Object key) throws CacheException { write(session, key, null); } protected void write(Object session, Object key, Object value) { TransactionCoordinatorAccess tc = SESSION_ACCESS.getTransactionCoordinator(session); long timestamp = SESSION_ACCESS.getTimestamp(session); FutureUpdateSynchronization sync = new FutureUpdateSynchronization(tc, asyncWriteMap, requiresTransaction, key, value, region, timestamp); // The update will be invalidating all putFromLoads for the duration of expiration or until removed by the synchronization Tombstone tombstone = new Tombstone(sync.getUuid(), region.nextTimestamp() + region.getTombstoneExpiration()); // The outcome of this operation is actually defined in TombstoneCallInterceptor // Metadata in PKVC are cleared and set in the interceptor, too writeMap.eval(key, tombstone).join(); tc.registerLocalSynchronization(sync); } @Override public void lockAll() throws CacheException { region.beginInvalidation(); } @Override public void unlockAll() throws CacheException { region.endInvalidation(); } @Override public void removeAll() throws CacheException { Caches.broadcastEvictAll(cache); } @Override public void evict(Object key) throws CacheException { writeMap.eval(key, new TombstoneUpdate<>(region.nextTimestamp(), null)).join(); } @Override public void evictAll() throws CacheException { region.beginInvalidation(); try { Caches.broadcastEvictAll(cache); } finally { region.endInvalidation(); } } @Override public void unlockItem(Object session, Object key) throws CacheException { } @Override public boolean afterInsert(Object session, Object key, Object value, Object version) { return false; } @Override public boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) { return false; } }
7,208
38.828729
155
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/NonTxInvalidationInterceptor.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.concurrent.CompletableFuture; import org.infinispan.commands.CommandInvocationId; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.util.EnumUtil; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.factories.annotations.Inject; import org.infinispan.hibernate.cache.commons.util.BeginInvalidationCommand; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.interceptors.InvocationSuccessFunction; import org.infinispan.interceptors.impl.InvalidationInterceptor; import org.infinispan.jmx.annotations.MBean; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.LocalModeAddress; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.impl.VoidResponseCollector; import org.infinispan.util.concurrent.locks.RemoteLockCommand; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This interceptor should completely replace default InvalidationInterceptor. * We need to send custom invalidation commands with transaction identifier (as the invalidation) * since we have to do a two-phase invalidation (releasing the locks as JTA synchronization), * although the cache itself is non-transactional. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ @MBean(objectName = "Invalidation", description = "Component responsible for invalidating entries on remote caches when entries are written to locally.") public class NonTxInvalidationInterceptor extends BaseInvalidationInterceptor { @Inject Transport transport; private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(InvalidationInterceptor.class); private static final Log ispnLog = LogFactory.getLog(NonTxInvalidationInterceptor.class); private final InvocationSuccessFunction<RemoveCommand> handleWriteReturn = this::handleWriteReturn; private final InvocationSuccessFunction<RemoveCommand> handleEvictReturn = this::handleEvictReturn; @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { assert command.hasAnyFlag(FlagBitSets.PUT_FOR_EXTERNAL_READ); return invokeNext(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) { throw new UnsupportedOperationException("Unexpected replace"); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { // This is how we differentiate write/remove and evict; remove sends BeginInvalidateComand while evict just InvalidateCommand boolean isEvict = !command.hasAnyFlag(FlagBitSets.FORCE_WRITE_LOCK); return invokeNextThenApply(ctx, command, isEvict ? handleEvictReturn : handleWriteReturn); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) { Object retval = invokeNext(ctx, command); if (!isLocalModeForced(command)) { // just broadcast the clear command - this is simplest! if (ctx.isOriginLocal()) { command.setTopologyId(rpcManager.getTopologyId()); if (isSynchronous(command)) { return asyncValue(rpcManager.invokeCommandOnAll(command, VoidResponseCollector.ignoreLeavers(), syncRpcOptions)); } else { rpcManager.sendToAll(command, DeliverOrder.NONE); } } } return retval; } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { throw new UnsupportedOperationException("Unexpected putAll"); } private <T extends WriteCommand & RemoteLockCommand> CompletableFuture<?> invalidateAcrossCluster( T command, boolean isTransactional, Object key, Object keyLockOwner) { // increment invalidations counter if statistics maintained incrementInvalidations(); InvalidateCommand invalidateCommand; if (!isLocalModeForced(command)) { if (isTransactional) { Address address = transport != null ? transport.getAddress() : LocalModeAddress.INSTANCE; invalidateCommand = new BeginInvalidationCommand(EnumUtil.EMPTY_BIT_SET, CommandInvocationId.generateId(address), new Object[] {key}, keyLockOwner); } else { invalidateCommand = commandsFactory.buildInvalidateCommand(EnumUtil.EMPTY_BIT_SET, new Object[] {key }); } invalidateCommand.setTopologyId(rpcManager.getTopologyId()); if (isSynchronous(command)) { return rpcManager.invokeCommandOnAll(invalidateCommand, VoidResponseCollector.ignoreLeavers(), syncRpcOptions) .toCompletableFuture(); } else { rpcManager.sendToAll(invalidateCommand, DeliverOrder.NONE); } } return null; } @Override protected Log getLog() { return ispnLog; } private Object handleWriteReturn(InvocationContext ctx, RemoveCommand removeCmd, Object rv) { if ( removeCmd.isSuccessful()) { return invalidateAcrossCluster(removeCmd, true, removeCmd.getKey(), removeCmd.getKeyLockOwner()); } return null; } private Object handleEvictReturn(InvocationContext ctx, RemoveCommand removeCmd, Object rv) { if ( removeCmd.isSuccessful()) { return invalidateAcrossCluster(removeCmd, false, removeCmd.getKey(), removeCmd.getKeyLockOwner()); } return null; } }
6,046
41.584507
153
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/SessionAccess.java
package org.infinispan.hibernate.cache.commons.access; import java.util.ServiceLoader; import org.hibernate.jdbc.WorkExecutorVisitable; import jakarta.transaction.Synchronization; public interface SessionAccess { TransactionCoordinatorAccess getTransactionCoordinator(Object session); long getTimestamp(Object session); static SessionAccess findSessionAccess() { ServiceLoader<SessionAccess> loader = ServiceLoader.load(SessionAccess.class, SessionAccess.class.getClassLoader()); return loader.iterator().next(); } interface TransactionCoordinatorAccess { void registerLocalSynchronization(Synchronization sync); void delegateWork(WorkExecutorVisitable<Void> workExecutorVisitable, boolean requiresTransaction); boolean isJoined(); } }
797
24.741935
122
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/TxPutFromLoadInterceptor.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.tx.RollbackCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.RemoveExpiredCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.DistributionManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.hibernate.cache.commons.util.EndInvalidationCommand; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.interceptors.impl.BaseRpcInterceptor; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.ByteString; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Intercepts transactions in Infinispan, calling {@link PutFromLoadValidator#beginInvalidatingKey(Object, Object)} * before locks are acquired (and the entry is invalidated) and sends {@link EndInvalidationCommand} to release * invalidation throught {@link PutFromLoadValidator#endInvalidatingKey(Object, Object)} after the transaction * is committed. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ class TxPutFromLoadInterceptor extends BaseRpcInterceptor { private final static InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(TxPutFromLoadInterceptor.class); private static final Log ispnLog = LogFactory.getLog(TxPutFromLoadInterceptor.class); private final PutFromLoadValidator putFromLoadValidator; private final ByteString cacheName; @Inject RpcManager rpcManager; @Inject InternalDataContainer dataContainer; @Inject DistributionManager distributionManager; public TxPutFromLoadInterceptor(PutFromLoadValidator putFromLoadValidator, ByteString cacheName) { this.putFromLoadValidator = putFromLoadValidator; this.cacheName = cacheName; } private void beginInvalidating(InvocationContext ctx, Object key) { TxInvocationContext txCtx = (TxInvocationContext) ctx; // make sure that the command is registered in the transaction txCtx.addAffectedKey(key); GlobalTransaction globalTransaction = txCtx.getGlobalTransaction(); if (!putFromLoadValidator.beginInvalidatingKey(globalTransaction, key)) { throw log.failedInvalidatePendingPut(key, cacheName.toString()); } } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { if (!command.hasAnyFlag(FlagBitSets.PUT_FOR_EXTERNAL_READ)) { beginInvalidating(ctx, command.getKey()); } return invokeNext(ctx, command); } @Override public Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) throws Throwable { return invokeNext(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { beginInvalidating(ctx, command.getKey()); return invokeNext(ctx, command); } // We need to intercept PrepareCommand, not InvalidateCommand since the interception takes // place before EntryWrappingInterceptor and the PrepareCommand is multiplexed into InvalidateCommands // as part of EntryWrappingInterceptor @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) { if (ctx.isOriginLocal()) { // We can't wait to commit phase to remove the entry locally (invalidations are processed in 1pc // on remote nodes, so only local case matters here). The problem is that while the entry is locked // reads still can take place and we can read outdated collection after reading updated entity // owning this collection from DB; when this happens, the version lock on entity cannot protect // us against concurrent modification of the collection. Therefore, we need to remove the entry // here (even without lock!) and let possible update happen in commit phase. for (WriteCommand wc : command.getModifications()) { for (Object key : wc.getAffectedKeys()) { dataContainer.remove(key); } } } else { for (WriteCommand wc : command.getModifications()) { Collection<?> keys = wc.getAffectedKeys(); if (log.isTraceEnabled()) { log.tracef("Invalidating keys %s with lock owner %s", keys, ctx.getLockOwner()); } for (Object key : keys ) { putFromLoadValidator.beginInvalidatingKey(ctx.getLockOwner(), key); } } } return invokeNext(ctx, command); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) { if (log.isTraceEnabled()) { log.tracef( "Commit command received, end invalidation" ); } return endInvalidationAndInvokeNextInterceptor(ctx, command); } @Override public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) { if (log.isTraceEnabled()) { log.tracef( "Rollback command received, end invalidation" ); } return endInvalidationAndInvokeNextInterceptor(ctx, command); } protected Object endInvalidationAndInvokeNextInterceptor(TxInvocationContext<?> ctx, VisitableCommand command) { if (ctx.isOriginLocal()) { // We cannot use directly ctx.getAffectedKeys() and that includes keys from local-only operations. // During evictAll inside transaction this would cause unnecessary invalidate command if (!ctx.getModifications().isEmpty()) { Object[] keys = ctx.getModifications().stream() .flatMap(mod -> mod.getAffectedKeys().stream()).distinct().toArray(); if (log.isTraceEnabled()) { log.tracef( "Sending end invalidation for keys %s asynchronously, modifications are %s", Arrays.toString(keys), ctx.getCacheTransaction().getModifications()); } GlobalTransaction globalTransaction = ctx.getGlobalTransaction(); EndInvalidationCommand commitCommand = new EndInvalidationCommand(cacheName, keys, globalTransaction); List<Address> members = distributionManager.getCacheTopology().getMembers(); rpcManager.sendToMany(members, commitCommand, DeliverOrder.NONE); // If the transaction is not successful, *RegionAccessStrategy would not be called, therefore // we have to end invalidation from here manually (in successful case as well) for (Object key : keys) { putFromLoadValidator.endInvalidatingKey(globalTransaction, key); } } } return invokeNext(ctx, command); } @Override protected Log getLog() { return ispnLog; } }
7,264
40.752874
124
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/TxInvalidationCacheAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.SoftLock; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; /** * Delegate for transactional caches * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class TxInvalidationCacheAccessDelegate extends InvalidationCacheAccessDelegate { public TxInvalidationCacheAccessDelegate(InfinispanDataRegion region, PutFromLoadValidator validator) { super(region, validator); } @Override @SuppressWarnings("UnusedParameters") public boolean insert(Object session, Object key, Object value, Object version) throws CacheException { if ( !region.checkValid() ) { return false; } // We need to be invalidating even for regular writes; if we were not and the write was followed by eviction // (or any other invalidation), naked put that was started after the eviction ended but before this insert // ended could insert the stale entry into the cache (since the entry was removed by eviction). // The beginInvalidateKey(...) is called from TxPutFromLoadInterceptor because we need the global transaction id. writeCache.put(key, value); return true; } @Override @SuppressWarnings("UnusedParameters") public boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { // We update whether or not the region is valid. Other nodes // may have already restored the region so they need to // be informed of the change. // We need to be invalidating even for regular writes; if we were not and the write was followed by eviction // (or any other invalidation), naked put that was started after the eviction ended but before this update // ended could insert the stale entry into the cache (since the entry was removed by eviction). // The beginInvalidateKey(...) is called from TxPutFromLoadInterceptor because we need the global transaction id. writeCache.put(key, value); return true; } @Override public boolean afterInsert(Object session, Object key, Object value, Object version) { // The endInvalidatingKey(...) is called from TxPutFromLoadInterceptor because we need the global transaction id. return false; } @Override public boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) { // The endInvalidatingKey(...) is called from TxPutFromLoadInterceptor because we need the global transaction id. return false; } }
2,813
40.382353
133
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/InvalidationCacheAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import org.hibernate.cache.CacheException; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.Caches; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.AdvancedCache; /** * * @author Brian Stansberry * @author Galder Zamarreño * @since 3.5 */ public abstract class InvalidationCacheAccessDelegate implements AccessDelegate { protected static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( InvalidationCacheAccessDelegate.class ); protected final AdvancedCache cache; protected final InfinispanDataRegion region; protected final PutFromLoadValidator putValidator; protected final AdvancedCache<Object, Object> writeCache; /** * Create a new transactional access delegate instance. * * @param region to control access to * @param validator put from load validator */ @SuppressWarnings("unchecked") protected InvalidationCacheAccessDelegate(InfinispanDataRegion region, PutFromLoadValidator validator) { this.region = region; this.cache = region.getCache(); this.putValidator = validator; this.writeCache = Caches.ignoreReturnValuesCache( cache ); } /** * Attempt to retrieve an object from the cache. * * * @param session * @param key The key of the item to be retrieved * @param txTimestamp a timestamp prior to the transaction start time * @return the cached object or <tt>null</tt> * @throws CacheException if the cache retrieval failed */ @Override @SuppressWarnings("UnusedParameters") public Object get(Object session, Object key, long txTimestamp) throws CacheException { if ( !region.checkValid() ) { return null; } final Object val = cache.get( key ); if (val == null && session != null) { putValidator.registerPendingPut(session, key, txTimestamp ); } return val; } @Override public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version) { return putFromLoad(session, key, value, txTimestamp, version, false ); } /** * Attempt to cache an object, after loading from the database, explicitly * specifying the minimalPut behavior. * * @param session Current session * @param key The item key * @param value The item * @param txTimestamp a timestamp prior to the transaction start time * @param version the item version number * @param minimalPutOverride Explicit minimalPut flag * @return <tt>true</tt> if the object was successfully cached * @throws CacheException if storing the object failed */ @Override @SuppressWarnings("UnusedParameters") public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { if ( !region.checkValid() ) { if (log.isTraceEnabled()) { log.tracef( "Region %s not valid", region.getName() ); } return false; } // In theory, since putForExternalRead is already as minimal as it can // get, we shouldn't be need this check. However, without the check and // without https://issues.jboss.org/browse/ISPN-1986, it's impossible to // know whether the put actually occurred. Knowing this is crucial so // that Hibernate can expose accurate statistics. if ( minimalPutOverride && cache.containsKey( key ) ) { return false; } PutFromLoadValidator.Lock lock = putValidator.acquirePutFromLoadLock(session, key, txTimestamp); if ( lock == null) { if (log.isTraceEnabled()) { log.tracef( "Put from load lock not acquired for key %s", key ); } return false; } try { writeCache.putForExternalRead( key, value ); } finally { putValidator.releasePutFromLoadLock( key, lock); } return true; } @Override public void remove(Object session, Object key) throws CacheException { // We update whether or not the region is valid. Other nodes // may have already restored the region so they need to // be informed of the change. writeCache.remove(key); } @Override public void lockAll() throws CacheException { if (!putValidator.beginInvalidatingRegion()) { log.failedInvalidateRegion(region.getName()); } } @Override public void unlockAll() throws CacheException { putValidator.endInvalidatingRegion(); } @Override public void removeAll() throws CacheException { Caches.removeAll(cache); } @Override public void evict(Object key) throws CacheException { writeCache.remove( key ); } @Override public void evictAll() throws CacheException { try { if (!putValidator.beginInvalidatingRegion()) { log.failedInvalidateRegion(region.getName()); } // Invalidate the local region and then go remote region.invalidateRegion(); Caches.broadcastEvictAll(cache); } finally { putValidator.endInvalidatingRegion(); } } @Override public void unlockItem(Object session, Object key) throws CacheException { } }
5,296
29.796512
135
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/BaseInvalidationInterceptor.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.infinispan.Cache; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.context.Flag; import org.infinispan.distribution.DistributionManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.interceptors.impl.BaseRpcInterceptor; import org.infinispan.jmx.JmxStatisticsExposer; import org.infinispan.jmx.annotations.DataType; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedAttribute; import org.infinispan.jmx.annotations.ManagedOperation; import org.infinispan.jmx.annotations.MeasurementType; import org.infinispan.jmx.annotations.Parameter; import org.infinispan.remoting.rpc.RpcOptions; import org.infinispan.remoting.transport.Address; import org.infinispan.util.ByteString; @MBean public abstract class BaseInvalidationInterceptor extends BaseRpcInterceptor implements JmxStatisticsExposer { private final AtomicLong invalidations = new AtomicLong(0); @Inject protected CommandsFactory commandsFactory; @Inject protected DistributionManager distributionManager; @Inject protected Cache cache; protected ByteString cacheName; protected boolean statisticsEnabled; protected RpcOptions syncRpcOptions; @Start void start() { this.cacheName = ByteString.fromString(cache.getName()); this.setStatisticsEnabled(cacheConfiguration.statistics().enabled()); syncRpcOptions = rpcManager.getSyncRpcOptions(); } @ManagedOperation( description = "Resets statistics gathered by this component", displayName = "Reset statistics" ) public void resetStatistics() { invalidations.set(0); } @ManagedAttribute( displayName = "Statistics enabled", description = "Enables or disables the gathering of statistics by this component", dataType = DataType.TRAIT, writable = true ) public boolean getStatisticsEnabled() { return this.statisticsEnabled; } public void setStatisticsEnabled(@Parameter(name = "enabled", description = "Whether statistics should be enabled or disabled (true/false)") boolean enabled) { this.statisticsEnabled = enabled; } @ManagedAttribute( description = "Number of invalidations", displayName = "Number of invalidations", measurementType = MeasurementType.TRENDSUP ) public long getInvalidations() { return invalidations.get(); } protected void incrementInvalidations() { if (statisticsEnabled) { invalidations.incrementAndGet(); } } protected List<Address> getMembers() { return distributionManager.getCacheTopology().getMembers(); } protected boolean isPutForExternalRead(FlagAffectedCommand command) { if (command.hasFlag(Flag.PUT_FOR_EXTERNAL_READ)) { return true; } return false; } }
3,160
31.255102
160
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/InvalidationSynchronization.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import jakarta.transaction.Status; /** * Synchronization that should release the locks after invalidation is complete. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class InvalidationSynchronization implements jakarta.transaction.Synchronization { private final static InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(InvalidationSynchronization.class); private final Object lockOwner; private final NonTxPutFromLoadInterceptor nonTxPutFromLoadInterceptor; private final Object key; public InvalidationSynchronization(NonTxPutFromLoadInterceptor nonTxPutFromLoadInterceptor, Object key, Object lockOwner) { assert lockOwner != null; this.nonTxPutFromLoadInterceptor = nonTxPutFromLoadInterceptor; this.key = key; this.lockOwner = lockOwner; } @Override public void beforeCompletion() {} @Override public void afterCompletion(int status) { if (log.isTraceEnabled()) { log.tracef("After completion callback with status %d", status); } nonTxPutFromLoadInterceptor.endInvalidating(key, lockOwner, status == Status.STATUS_COMMITTED || status == Status.STATUS_COMMITTING); } }
1,513
34.209302
135
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/LocalInvalidationSynchronization.java
package org.infinispan.hibernate.cache.commons.access; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; public class LocalInvalidationSynchronization implements Synchronization { private final static InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(LocalInvalidationSynchronization.class); private final Object lockOwner; private final PutFromLoadValidator validator; private final Object key; public LocalInvalidationSynchronization(PutFromLoadValidator validator, Object key, Object lockOwner) { assert lockOwner != null; this.validator = validator; this.key = key; this.lockOwner = lockOwner; } @Override public void beforeCompletion() {} @Override public void afterCompletion(int status) { if (log.isTraceEnabled()) { log.tracef("After completion callback with status %d", status); } validator.endInvalidatingKey(lockOwner, key, status == Status.STATUS_COMMITTED || status == Status.STATUS_COMMITTING); } }
1,129
33.242424
134
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/AccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.SoftLock; /** * Defines the strategy for access to entity or collection data in a Infinispan instance. * <p/> * The intent of this class is to encapsulate common code and serve as a delegate for * {@link org.hibernate.cache.spi.access.EntityRegionAccessStrategy} * and {@link org.hibernate.cache.spi.access.CollectionRegionAccessStrategy} implementations. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public interface AccessDelegate { Object get(Object session, Object key, long txTimestamp) throws CacheException; /** * Attempt to cache an object, after loading from the database. * * @param session Current session * @param key The item key * @param value The item * @param txTimestamp a timestamp prior to the transaction start time * @param version the item version number * @return <tt>true</tt> if the object was successfully cached */ boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version); /** * Attempt to cache an object, after loading from the database, explicitly * specifying the minimalPut behavior. * * @param session Current session. * @param key The item key * @param value The item * @param txTimestamp a timestamp prior to the transaction start time * @param version the item version number * @param minimalPutOverride Explicit minimalPut flag * @return <tt>true</tt> if the object was successfully cached * @throws org.hibernate.cache.CacheException Propogated from underlying {@link org.hibernate.cache.spi.Region} */ boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException; /** * Called after an item has been inserted (before the transaction completes), * instead of calling evict(). * * @param session Current session * @param key The item key * @param value The item * @param version The item's version value * @return Were the contents of the cache actual changed by this operation? * @throws CacheException if the insert fails */ boolean insert(Object session, Object key, Object value, Object version) throws CacheException; /** * Called after an item has been updated (before the transaction completes), * instead of calling evict(). * * @param session Current session * @param key The item key * @param value The item * @param currentVersion The item's current version value * @param previousVersion The item's previous version value * @return Whether the contents of the cache actual changed by this operation * @throws CacheException if the update fails */ boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException; /** * Called after an item has become stale (before the transaction completes). * * @param session Current session * @param key The key of the item to remove * @throws CacheException if removing the cached item fails */ void remove(Object session, Object key) throws CacheException; /** * Called just before the delegate will have all entries removed. Any work to prevent concurrent modifications * while this occurs should happen here * @throws CacheException if locking had an issue */ void lockAll() throws CacheException; /** * Called just after the delegate had all entries removed via {@link #removeAll()}. Any work required to allow * for new modifications to happen should be done here * @throws CacheException if unlocking had an issue */ void unlockAll() throws CacheException; /** * Called to evict data from the entire region * * @throws CacheException if eviction the region fails */ void removeAll() throws CacheException; /** * Forcibly evict an item from the cache immediately without regard for transaction * isolation. * * @param key The key of the item to remove * @throws CacheException if evicting the item fails */ void evict(Object key) throws CacheException; /** * Forcibly evict all items from the cache immediately without regard for transaction * isolation. * * @throws CacheException if evicting items fails */ void evictAll() throws CacheException; /** * Called when we have finished the attempted update/delete (which may or * may not have been successful), after transaction completion. This method * is used by "asynchronous" concurrency strategies. * * * @param session * @param key The item key * @throws org.hibernate.cache.CacheException Propogated from underlying {@link org.hibernate.cache.spi.Region} */ void unlockItem(Object session, Object key) throws CacheException; /** * Called after an item has been inserted (after the transaction completes), * instead of calling release(). * This method is used by "asynchronous" concurrency strategies. * * * @param session * @param key The item key * @param value The item * @param version The item's version value * @return Were the contents of the cache actual changed by this operation? * @throws CacheException Propagated from underlying {@link org.hibernate.cache.spi.Region} */ boolean afterInsert(Object session, Object key, Object value, Object version); /** * Called after an item has been updated (after the transaction completes), * instead of calling release(). This method is used by "asynchronous" * concurrency strategies. * * * @param session * @param key The item key * @param value The item * @param currentVersion The item's current version value * @param previousVersion The item's previous version value * @param lock The lock previously obtained from {@link #lockItem} * @return Were the contents of the cache actual changed by this operation? * @throws CacheException Propagated from underlying {@link org.hibernate.cache.spi.Region} */ boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock); }
6,369
36.251462
125
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/UnorderedDistributionInterceptor.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.List; import java.util.concurrent.CompletionStage; import org.infinispan.commands.functional.ReadWriteKeyCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.commands.write.IracPutKeyValueCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.interceptors.distribution.NonTxDistributionInterceptor; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.impl.MapResponseCollector; import org.infinispan.statetransfer.OutdatedTopologyException; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Since the applied functions do not rely on the order how these are applied (the updates are commutative), * this interceptor simply sends any command to all other owners without ordering them through primary owner. * Note that {@link LockingInterceptor} is required in the stack as locking on backup is not guaranteed * by primary owner. */ public class UnorderedDistributionInterceptor extends NonTxDistributionInterceptor { private static final Log log = LogFactory.getLog(UnorderedDistributionInterceptor.class); @Inject DistributionManager distributionManager; private boolean isReplicated; @Start public void start() { isReplicated = cacheConfiguration.clustering().cacheMode().isReplicated(); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { return handleDataWriteCommand(ctx, command); } @Override public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) { return handleDataWriteCommand(ctx, command); } @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) { return handleDataWriteCommand(ctx, command); } private Object handleDataWriteCommand(InvocationContext ctx, DataWriteCommand command) { if (command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL)) { // for state-transfer related writes return invokeNext(ctx, command); } int commandTopologyId = command.getTopologyId(); LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); if (commandTopologyId != -1 && currentTopologyId != commandTopologyId) { throw OutdatedTopologyException.RETRY_NEXT_TOPOLOGY; } if (isReplicated) { // local result is always ignored return invokeNextAndHandle(ctx, command, (rCtx, rCommand, rv, throwable) -> { CompletionStage<?> remoteInvocation = invokeRemotelyAsync(null, rCtx, rCommand); if (remoteInvocation != null) { return remoteInvocation.thenApply(responses -> rv); } return rv; }); } else { List<Address> owners = cacheTopology.getDistribution(command.getKey()).writeOwners(); if (owners.contains(rpcManager.getAddress())) { return invokeNextAndHandle( ctx, command, (rCtx, rCommand, rv, throwable) -> { CompletionStage<?> remoteInvocation = invokeRemotelyAsync(owners, rCtx, rCommand); if (remoteInvocation != null) { return remoteInvocation.thenApply(responses -> rv); } return rv; }); } else { log.tracef("Not invoking %s on %s since it is not an owner", command, rpcManager.getAddress()); if (ctx.isOriginLocal() && command.isSuccessful()) { // This is called with the entry locked. In order to avoid deadlocks we must not wait for RPC while // holding the lock, therefore we'll return a future and wait for it in LockingInterceptor after // unlocking (and committing) the entry. if (isSynchronous(command)) { return rpcManager.invokeCommand(owners, command, MapResponseCollector.ignoreLeavers(owners.size()), rpcManager.getSyncRpcOptions()); } else { rpcManager.sendToMany(owners, command, DeliverOrder.NONE); } } return null; } } } private CompletionStage<?> invokeRemotelyAsync(List<Address> finalOwners, InvocationContext rCtx, WriteCommand writeCmd) { if (rCtx.isOriginLocal() && writeCmd.isSuccessful()) { // This is called with the entry locked. In order to avoid deadlocks we must not wait for RPC while // holding the lock, therefore we'll return a future and wait for it in LockingInterceptor after // unlocking (and committing) the entry. if (isSynchronous(writeCmd)) { if (finalOwners != null) { return rpcManager.invokeCommand( finalOwners, writeCmd, MapResponseCollector.ignoreLeavers(finalOwners.size()), rpcManager.getSyncRpcOptions()); } else { return rpcManager.invokeCommandOnAll(writeCmd, MapResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); } } else { rpcManager.sendToMany(finalOwners, writeCmd, DeliverOrder.NONE); } } return null; } }
5,774
42.097015
129
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/NonTxPutFromLoadInterceptor.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.context.InvocationContext; import org.infinispan.factories.annotations.Inject; import org.infinispan.hibernate.cache.commons.util.BeginInvalidationCommand; import org.infinispan.hibernate.cache.commons.util.EndInvalidationCommand; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.util.ByteString; /** * Non-transactional counterpart of {@link TxPutFromLoadInterceptor}. * Invokes {@link PutFromLoadValidator#beginInvalidatingKey(Object, Object)} for each invalidation from * remote node ({@link BeginInvalidationCommand} and sends {@link EndInvalidationCommand} after the transaction * is complete, with help of {@link InvalidationSynchronization}; * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class NonTxPutFromLoadInterceptor extends BaseCustomAsyncInterceptor { private final static InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(NonTxPutFromLoadInterceptor.class); private final ByteString cacheName; private final PutFromLoadValidator putFromLoadValidator; @Inject RpcManager rpcManager; public NonTxPutFromLoadInterceptor(PutFromLoadValidator putFromLoadValidator, ByteString cacheName) { this.putFromLoadValidator = putFromLoadValidator; this.cacheName = cacheName; } @Override public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) { if (!ctx.isOriginLocal() && command instanceof BeginInvalidationCommand) { for (Object key : command.getKeys()) { putFromLoadValidator.beginInvalidatingKey(((BeginInvalidationCommand) command).getLockOwner(), key); } } return invokeNext(ctx, command); } public void endInvalidating(Object key, Object lockOwner, boolean successful) { assert lockOwner != null; if (!putFromLoadValidator.endInvalidatingKey(lockOwner, key, successful)) { log.failedEndInvalidating(key, cacheName); } rpcManager.sendToAll(new EndInvalidationCommand(cacheName, new Object[] {key}, lockOwner), DeliverOrder.NONE); } }
2,552
43.017241
127
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/TxInvalidationInterceptor.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CompletionStage; import org.infinispan.commands.AbstractVisitor; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.TopologyAffectedCommand; import org.infinispan.commands.control.LockControlCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.util.EnumUtil; import org.infinispan.context.Flag; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.LocalTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.interceptors.InvocationSuccessFunction; import org.infinispan.jmx.annotations.MBean; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.impl.VoidResponseCollector; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This interceptor acts as a replacement to the replication interceptor when the CacheImpl is configured with * ClusteredSyncMode as INVALIDATE. * <p/> * The idea is that rather than replicating changes to all caches in a cluster when write methods are called, simply * broadcast an {@link InvalidateCommand} on the remote caches containing all keys modified. This allows the remote * cache to look up the value in a shared cache loader which would have been updated with the changes. * * @author Manik Surtani * @author Galder Zamarreño * @author Mircea.Markus@jboss.com * @since 4.0 */ @MBean(objectName = "Invalidation", description = "Component responsible for invalidating entries on remote caches when entries are written to locally.") public class TxInvalidationInterceptor extends BaseInvalidationInterceptor { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( TxInvalidationInterceptor.class ); private static final Log ispnLog = LogFactory.getLog(TxInvalidationInterceptor.class); private final InvocationSuccessFunction<ClearCommand> broadcastClearIfNotLocal = this::broadcastClearIfNotLocal; private final InvocationSuccessFunction<PrepareCommand> broadcastInvalidateForPrepare = this::broadcastInvalidateForPrepare; private final InvocationSuccessFunction<CommitCommand> handleCommit = this::handleCommit; @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { if ( !isPutForExternalRead( command ) ) { return handleInvalidate( ctx, command, command.getKey() ); } return invokeNext( ctx, command ); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) { return handleInvalidate( ctx, command, command.getKey() ); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { return handleInvalidate( ctx, command, command.getKey() ); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) { return invokeNextThenApply(ctx, command, broadcastClearIfNotLocal); } private Object broadcastClearIfNotLocal(InvocationContext rCtx, ClearCommand rCommand, Object rv) { if ( !isLocalModeForced( rCommand ) ) { // just broadcast the clear command - this is simplest! if ( rCtx.isOriginLocal() ) { rCommand.setTopologyId(rpcManager.getTopologyId()); if (isSynchronous(rCommand)) { // the result value will be ignored, we don't need to propagate rv return asyncValue(rpcManager.invokeCommandOnAll(rCommand, VoidResponseCollector.ignoreLeavers(), syncRpcOptions)); } else { rpcManager.sendToAll(rCommand, DeliverOrder.NONE); } } } return rv; } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { return handleInvalidate( ctx, command, command.getMap().keySet().toArray() ); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) { return invokeNextThenApply(ctx, command, broadcastInvalidateForPrepare); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { if (!shouldInvokeRemoteTxCommand(ctx)) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, handleCommit); } private Object handleCommit(InvocationContext ctx, CommitCommand command, Object ignored) { try { CompletionStage<Void> remoteInvocation = rpcManager.invokeCommandOnAll(command, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); return asyncValue(remoteInvocation); } catch (Throwable t) { throw t; } } private Object broadcastInvalidateForPrepare(InvocationContext rCtx, PrepareCommand prepareCmd, Object rv) throws Throwable { log.tracef("Entering InvalidationInterceptor's prepare phase"); // fetch the modifications before the transaction is committed (and thus removed from the txTable) TxInvocationContext txCtx = (TxInvocationContext) rCtx; if ( shouldInvokeRemoteTxCommand( txCtx ) ) { if ( txCtx.getTransaction() == null ) { throw new IllegalStateException( "We must have an associated transaction" ); } CompletionStage<Void> completion = broadcastInvalidateForPrepare(prepareCmd, txCtx); if (completion != null) { return asyncValue(completion); } else { return rv; } } else { log.tracef( "Nothing to invalidate - no modifications in the transaction." ); } return rv; } @Override public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) { Object retVal = invokeNext( ctx, command ); if ( ctx.isOriginLocal() ) { //unlock will happen async as it is a best effort boolean sync = !command.isUnlock(); List<Address> members = getMembers(); ( (LocalTxInvocationContext) ctx ).remoteLocksAcquired(members); command.setTopologyId(rpcManager.getTopologyId()); if (sync) { return asyncValue(rpcManager.invokeCommandOnAll(command, VoidResponseCollector.ignoreLeavers(), syncRpcOptions)); } else { rpcManager.sendToAll(command, DeliverOrder.NONE); } } return retVal; } private Object handleInvalidate(InvocationContext ctx, WriteCommand command, Object... keys) { return invokeNextThenApply(ctx, command, (rCtx, writeCmd, rv) -> { if (!writeCmd.isSuccessful() || rCtx.isInTxScope()) { return rv; } if (keys == null || keys.length == 0) { return rv; } if (isLocalModeForced( writeCmd )) { return rv; } CompletionStage<Void> completion = invalidateAcrossCluster(isSynchronous(writeCmd), keys, rCtx, true, rpcManager.getTopologyId()); return completion != null ? asyncValue(completion) : rv; } ); } private CompletionStage<Void> broadcastInvalidateForPrepare(PrepareCommand prepareCmd, InvocationContext ctx) throws Throwable { // A prepare does not carry flags, so skip checking whether is local or not if ( ctx.isInTxScope() ) { List<WriteCommand> modifications = prepareCmd.getModifications(); if ( modifications.isEmpty() ) { return null; } InvalidationFilterVisitor filterVisitor = new InvalidationFilterVisitor( modifications.size() ); filterVisitor.visitCollection( null, modifications ); if ( filterVisitor.containsPutForExternalRead ) { log.trace("Modification list contains a putForExternalRead operation. Not invalidating."); } else if ( filterVisitor.containsLocalModeFlag ) { log.trace("Modification list contains a local mode flagged operation. Not invalidating."); } else { try { CompletionStage<Void> completion = invalidateAcrossCluster(defaultSynchronous, filterVisitor.result.toArray(), ctx, prepareCmd.isOnePhaseCommit(), prepareCmd.getTopologyId()); if (completion != null) { return completion.exceptionally(t -> { log.unableToRollbackInvalidationsDuringPrepare( t ); throw CompletableFutures.asCompletionException(t); }); } } catch (Throwable t) { log.unableToRollbackInvalidationsDuringPrepare( t ); throw t; } } } return null; } @Override protected Log getLog() { return ispnLog; } public static class InvalidationFilterVisitor extends AbstractVisitor { Set<Object> result; public boolean containsPutForExternalRead = false; public boolean containsLocalModeFlag = false; public InvalidationFilterVisitor(int maxSetSize) { result = new HashSet<>( maxSetSize ); } private void processCommand(FlagAffectedCommand command) { containsLocalModeFlag = containsLocalModeFlag || ( command.getFlags() != null && command.getFlags().contains( Flag.CACHE_MODE_LOCAL ) ); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { processCommand( command ); containsPutForExternalRead = containsPutForExternalRead || ( command.getFlags() != null && command.getFlags().contains( Flag.PUT_FOR_EXTERNAL_READ ) ); result.add( command.getKey() ); return null; } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { processCommand( command ); result.add( command.getKey() ); return null; } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { processCommand( command ); result.addAll( command.getAffectedKeys() ); return null; } } private CompletionStage<Void> invalidateAcrossCluster(boolean synchronous, Object[] keys, InvocationContext ctx, boolean onePhaseCommit, int topologyId) { // increment invalidations counter if statistics maintained incrementInvalidations(); InvalidateCommand invalidateCommand = commandsFactory.buildInvalidateCommand(EnumUtil.EMPTY_BIT_SET, keys); TopologyAffectedCommand command = invalidateCommand; if ( ctx.isInTxScope() ) { TxInvocationContext txCtx = (TxInvocationContext) ctx; command = commandsFactory.buildPrepareCommand(txCtx.getGlobalTransaction(), Collections.singletonList(invalidateCommand), onePhaseCommit); } command.setTopologyId(topologyId); if (synchronous) { return rpcManager.invokeCommandOnAll(command, VoidResponseCollector.ignoreLeavers(), syncRpcOptions); } else { rpcManager.sendToAll(command, DeliverOrder.NONE); } return null; } }
11,732
38.908163
153
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/FutureUpdateSynchronization.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.UUID; import org.infinispan.commons.util.Util; import org.infinispan.functional.FunctionalMap; import org.infinispan.hibernate.cache.commons.access.SessionAccess.TransactionCoordinatorAccess; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.FutureUpdate; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.commons.util.InvocationAfterCompletion; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class FutureUpdateSynchronization extends InvocationAfterCompletion { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( FutureUpdateSynchronization.class ); private final UUID uuid = Util.threadLocalRandomUUID(); private final Object key; private final Object value; private final InfinispanDataRegion region; private final long sessionTimestamp; private final FunctionalMap.ReadWriteMap<Object, Object> rwMap; public FutureUpdateSynchronization(TransactionCoordinatorAccess tc, FunctionalMap.ReadWriteMap<Object, Object> rwMap, boolean requiresTransaction, Object key, Object value, InfinispanDataRegion region, long sessionTimestamp) { super(tc, requiresTransaction); this.rwMap = rwMap; this.key = key; this.value = value; this.region = region; this.sessionTimestamp = sessionTimestamp; } public UUID getUuid() { return uuid; } @Override protected void invoke(boolean success) { // If the region was invalidated during this session, we can't know that the value we're inserting is valid // so we'll just null the tombstone if (sessionTimestamp < region.getLastRegionInvalidation()) { success = false; } // Exceptions in #afterCompletion() are silently ignored, since the transaction // is already committed in DB. However we must not return until we update the cache. FutureUpdate futureUpdate = new FutureUpdate(uuid, region.nextTimestamp(), success ? this.value : null); for (;;) { try { // We expect that when the transaction completes further reads from cache will return the updated value. // UnorderedDistributionInterceptor makes sure that the update is executed on the node first, and here // we're waiting for the local update. The remote update does not concern us - the cache is async and // we won't wait for that. rwMap.eval(key, futureUpdate).join(); return; } catch (Exception e) { log.failureInAfterCompletion(e); } } } }
2,846
38.541667
147
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/NonStrictAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.Comparator; import java.util.concurrent.CompletableFuture; import org.hibernate.cache.CacheException; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.Param; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.hibernate.cache.commons.access.SessionAccess.TransactionCoordinatorAccess; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.Caches; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.commons.util.VersionedEntry; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.cache.spi.entry.CacheEntry; import org.infinispan.AdvancedCache; import org.infinispan.configuration.cache.Configuration; /** * Access delegate that relaxes the consistency a bit: stale reads are prohibited only after the transaction * commits. This should also be able to work with async caches, and that would allow the replication delay * even after the commit. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class NonStrictAccessDelegate implements AccessDelegate { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog( NonStrictAccessDelegate.class ); private static final SessionAccess SESSION_ACCESS = SessionAccess.findSessionAccess(); protected final InfinispanDataRegion region; private final AdvancedCache cache; protected final FunctionalMap.ReadWriteMap<Object, Object> writeMap; private final FunctionalMap.ReadWriteMap<Object, Object> putFromLoadMap; private final Comparator versionComparator; public NonStrictAccessDelegate(InfinispanDataRegion region, Comparator versionComparator) { this.region = region; this.cache = region.getCache(); FunctionalMapImpl fmap = FunctionalMapImpl.create(cache).withParams(Param.PersistenceMode.SKIP_LOAD); this.writeMap = ReadWriteMapImpl.create(fmap); // Note that correct behaviour of local and async writes depends on LockingInterceptor (see there for details) this.putFromLoadMap = ReadWriteMapImpl.create(fmap).withParams(Param.LockingMode.TRY_LOCK, Param.ReplicationMode.ASYNC); Configuration configuration = cache.getCacheConfiguration(); if (configuration.clustering().cacheMode().isInvalidation()) { throw new IllegalArgumentException("Nonstrict-read-write mode cannot use invalidation."); } if (configuration.transaction().transactionMode().isTransactional()) { throw new IllegalArgumentException("Currently transactional caches are not supported."); } this.versionComparator = versionComparator; if (versionComparator == null) { throw new IllegalArgumentException("This strategy requires versioned entities/collections but region " + region.getName() + " contains non-versioned data!"); } } @Override public Object get(Object session, Object key, long txTimestamp) throws CacheException { if (txTimestamp < region.getLastRegionInvalidation() ) { return null; } Object value = cache.get(key); if (value instanceof VersionedEntry) { return ((VersionedEntry) value).getValue(); } return value; } @Override public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version) { return putFromLoad(session, key, value, txTimestamp, version, false); } @Override public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { long lastRegionInvalidation = region.getLastRegionInvalidation(); if (txTimestamp < lastRegionInvalidation) { log.tracef("putFromLoad not executed since tx started at %d, before last region invalidation finished = %d", txTimestamp, lastRegionInvalidation); return false; } assert version != null; if (minimalPutOverride) { Object prev = cache.get(key); if (prev != null) { Object oldVersion = getVersion(prev); if (oldVersion != null) { if (versionComparator.compare(version, oldVersion) <= 0) { if (log.isTraceEnabled()) { log.tracef("putFromLoad not executed since version(%s) <= oldVersion(%s)", version, oldVersion); } return false; } } else if (prev instanceof VersionedEntry && txTimestamp <= ((VersionedEntry) prev).getTimestamp()) { if (log.isTraceEnabled()) { log.tracef("putFromLoad not executed since tx started at %d and entry was invalidated at %d", txTimestamp, ((VersionedEntry) prev).getTimestamp()); } return false; } } } // we can't use putForExternalRead since the PFER flag means that entry is not wrapped into context // when it is present in the container. TombstoneCallInterceptor will deal with this. // Even if value is instanceof CacheEntry, we have to wrap it in VersionedEntry and add transaction timestamp. // Otherwise, old eviction record wouldn't be overwritten. CompletableFuture<Void> future = putFromLoadMap.eval(key, new VersionedEntry(value, version, txTimestamp)); // Rethrow exceptions future.join(); return true; } @Override public boolean insert(Object session, Object key, Object value, Object version) throws CacheException { return false; } @Override public boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { return false; } @Override public void remove(Object session, Object key) throws CacheException { // there's no 'afterRemove', so we have to use our own synchronization // the API does not provide version of removed item but we can't load it from the cache // as that would be prone to race conditions - if the entry was updated in the meantime // the remove could be discarded and we would end up with stale record // See VersionedTest#testCollectionUpdate for such situation TransactionCoordinatorAccess transactionCoordinator = SESSION_ACCESS.getTransactionCoordinator(session); RemovalSynchronization sync = new RemovalSynchronization(transactionCoordinator, writeMap, region, key); transactionCoordinator.registerLocalSynchronization(sync); } @Override public void lockAll() throws CacheException { region.beginInvalidation(); } @Override public void unlockAll() throws CacheException { region.endInvalidation(); } @Override public void removeAll() throws CacheException { Caches.broadcastEvictAll(cache); } @Override public void evict(Object key) throws CacheException { writeMap.eval(key, new VersionedEntry(region.nextTimestamp())).join(); } @Override public void evictAll() throws CacheException { region.beginInvalidation(); try { Caches.broadcastEvictAll(cache); } finally { region.endInvalidation(); } } @Override public void unlockItem(Object session, Object key) throws CacheException { } @Override public boolean afterInsert(Object session, Object key, Object value, Object version) { assert value != null; assert version != null; writeMap.eval(key, new VersionedEntry(value, version, SESSION_ACCESS.getTimestamp(session))).join(); return true; } @Override public boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) { assert value != null; assert currentVersion != null; writeMap.eval(key, new VersionedEntry(value, currentVersion, SESSION_ACCESS.getTimestamp(session))).join(); return true; } protected Object getVersion(Object value) { if (value instanceof CacheEntry) { return ((CacheEntry) value).getVersion(); } else if (value instanceof VersionedEntry) { return ((VersionedEntry) value).getVersion(); } return null; } }
8,098
38.125604
160
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/NonTxInvalidationCacheAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import org.hibernate.cache.CacheException; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.InvocationContextFactory; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.factories.ComponentRegistry; import org.hibernate.cache.spi.access.SoftLock; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.interceptors.AsyncInterceptorChain; /** * Delegate for non-transactional caches * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class NonTxInvalidationCacheAccessDelegate extends InvalidationCacheAccessDelegate { private static final SessionAccess SESSION_ACCESS = SessionAccess.findSessionAccess(); // FORCE_WRITE_LOCK is a here used as a marker for NonTxInvalidationInterceptor // that this is not an eviction and should result in BeginInvalidateCommand private static final long REMOVE_FLAGS = FlagBitSets.IGNORE_RETURN_VALUES | FlagBitSets.FORCE_WRITE_LOCK; protected final AsyncInterceptorChain invoker; private final CommandsFactory commandsFactory; private final KeyPartitioner keyPartitioner; private final InvocationContextFactory contextFactory; protected final NonTxPutFromLoadInterceptor nonTxPutFromLoadInterceptor; protected final boolean isLocal; public NonTxInvalidationCacheAccessDelegate(InfinispanDataRegion region, PutFromLoadValidator validator) { super(region, validator); isLocal = !region.getCache().getCacheConfiguration().clustering().cacheMode().isClustered(); ComponentRegistry cr = region.getCache().getComponentRegistry(); invoker = cr.getComponent(AsyncInterceptorChain.class); commandsFactory = cr.getComponent(CommandsFactory.class); keyPartitioner = cr.getComponent(KeyPartitioner.class); contextFactory = cr.getComponent(InvocationContextFactory.class); nonTxPutFromLoadInterceptor = cr.getComponent(NonTxPutFromLoadInterceptor.class); } @Override @SuppressWarnings("UnusedParameters") public boolean insert(Object session, Object key, Object value, Object version) throws CacheException { if ( !region.checkValid() ) { return false; } write(session, key, value); return true; } @Override @SuppressWarnings("UnusedParameters") public boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { // We update whether or not the region is valid. Other nodes // may have already restored the region so they need to // be informed of the change. write(session, key, value); return true; } @Override public void remove(Object session, Object key) throws CacheException { // We update whether or not the region is valid. Other nodes // may have already restored the region so they need to // be informed of the change. write(session, key, null); } private void write(Object session, Object key, Object value) { // We need to be invalidating even for regular writes; if we were not and the write was followed by eviction // (or any other invalidation), naked put that was started after the eviction ended but before this insert/update // ended could insert the stale entry into the cache (since the entry was removed by eviction). if (isLocal) { // Lock owner is not serialized in local mode so we can use anything (only equals and hashCode are needed) Object lockOwner = new Object(); registerLocalInvalidation(session, lockOwner, key); if (!putValidator.beginInvalidatingWithPFER(lockOwner, key, value)) { throw log.failedInvalidatePendingPut(key, region.getName()); } // Make use of the simple cache mode here cache.remove(key); } else { RemoveCommand command = commandsFactory.buildRemoveCommand(key, null, keyPartitioner.getSegment(key), REMOVE_FLAGS); registerClusteredInvalidation(session, command.getKeyLockOwner(), command.getKey()); if (!putValidator.beginInvalidatingWithPFER(command.getKeyLockOwner(), key, value)) { throw log.failedInvalidatePendingPut(key, region.getName()); } InvocationContext ctx = contextFactory.createSingleKeyNonTxInvocationContext(); ctx.setLockOwner(command.getKeyLockOwner()); invoke(session, ctx, command); } } protected void invoke(Object session, InvocationContext ctx, RemoveCommand command) { invoker.invoke(ctx, command); } @Override public boolean afterInsert(Object session, Object key, Object value, Object version) { // endInvalidatingKeys is called from NonTxInvalidationInterceptor, from the synchronization callback return false; } @Override public boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) { // endInvalidatingKeys is called from NonTxInvalidationInterceptor, from the synchronization callback return false; } @Override public void removeAll() throws CacheException { cache.clear(); } protected void registerLocalInvalidation(Object session, Object lockOwner, Object key) { SessionAccess.TransactionCoordinatorAccess transactionCoordinator = SESSION_ACCESS.getTransactionCoordinator(session); if (transactionCoordinator == null) { return; } if (log.isTraceEnabled()) { log.tracef("Registering synchronization on transaction in %s, cache %s: %s", lockOwner, cache.getName(), key); } transactionCoordinator.registerLocalSynchronization(new LocalInvalidationSynchronization(putValidator, key, lockOwner)); } protected void registerClusteredInvalidation(Object session, Object lockOwner, Object key) { SessionAccess.TransactionCoordinatorAccess transactionCoordinator = SESSION_ACCESS.getTransactionCoordinator(session); if (transactionCoordinator == null) { return; } if (log.isTraceEnabled()) { log.tracef("Registering synchronization on transaction in %s, cache %s: %s", lockOwner, cache.getName(), key); } transactionCoordinator.registerLocalSynchronization(new InvalidationSynchronization(nonTxPutFromLoadInterceptor, key, lockOwner)); } }
6,585
43.802721
133
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/RemovalSynchronization.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import org.infinispan.functional.FunctionalMap; import org.infinispan.hibernate.cache.commons.access.SessionAccess.TransactionCoordinatorAccess; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.InvocationAfterCompletion; import org.infinispan.hibernate.cache.commons.util.VersionedEntry; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class RemovalSynchronization extends InvocationAfterCompletion { private final InfinispanDataRegion region; private final Object key; private final FunctionalMap.ReadWriteMap<Object, Object> rwMap; public RemovalSynchronization(TransactionCoordinatorAccess tc, FunctionalMap.ReadWriteMap<Object, Object> rwMap, InfinispanDataRegion region, Object key) { super(tc, false); this.rwMap = rwMap; this.region = region; this.key = key; } @Override protected void invoke(boolean success) { if (success) { rwMap.eval(key, new VersionedEntry(region.nextTimestamp())).join(); } } }
1,313
34.513514
156
java
null
infinispan-main/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/PutFromLoadValidator.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.commons.access; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.engine.spi.SessionImplementor; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.hibernate.cache.commons.TimeSource; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.spi.InfinispanProperties; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.EntryWrappingInterceptor; import org.infinispan.interceptors.impl.InvalidationInterceptor; import org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.ByteString; /** * Encapsulates logic to allow a {@link InvalidationCacheAccessDelegate} to determine * whether a {@link InvalidationCacheAccessDelegate#putFromLoad(Object, Object, Object, long, Object, boolean)} * call should be allowed to update the cache. A <code>putFromLoad</code> has * the potential to store stale data, since the data may have been removed from the * database and the cache between the time when the data was read from the database * and the actual call to <code>putFromLoad</code>. * <p> * The expected usage of this class by a thread that read the cache and did * not find data is: * <p/> * <ol> * <li> Call {@link #registerPendingPut(Object, Object, long)}</li> * <li> Read the database</li> * <li> Call {@link #acquirePutFromLoadLock(Object, Object, long)} * <li> if above returns <code>null</code>, the thread should not cache the data; * only if above returns instance of <code>AcquiredLock</code>, put data in the cache and...</li> * <li> then call {@link #releasePutFromLoadLock(Object, Lock)}</li> * </ol> * </p> * <p/> * <p> * The expected usage by a thread that is taking an action such that any pending * <code>putFromLoad</code> may have stale data and should not cache it is to either * call * <p/> * <ul> * <li> {@link #beginInvalidatingKey(Object, Object)} (for a single key invalidation)</li> * <li>or {@link #beginInvalidatingRegion()} followed by {@link #endInvalidatingRegion()} * (for a general invalidation all pending puts)</li> * </ul> * After transaction commit (when the DB is updated) {@link #endInvalidatingKey(Object, Object)} should * be called in order to allow further attempts to cache entry. * </p> * <p/> * <p> * This class also supports the concept of "naked puts", which are calls to * {@link #acquirePutFromLoadLock(Object, Object, long)} without a preceding {@link #registerPendingPut(Object, Object, long)}. * Besides not acquiring lock in {@link #registerPendingPut(Object, Object, long)} this can happen when collection * elements are loaded after the collection has not been found in the cache, where the elements * don't have their own table but can be listed as 'select ... from Element where collection_id = ...'. * Naked puts are handled according to txTimestamp obtained by calling {@link RegionFactory#nextTimestamp()} * before the transaction is started. The timestamp is compared with timestamp of last invalidation end time * and the write to the cache is denied if it is lower or equal. * </p> * * @author Brian Stansberry * @version $Revision: $ */ public class PutFromLoadValidator { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(PutFromLoadValidator.class); /** * Period after which ongoing invalidation is removed. Value is retrieved from cache configuration. */ private final long expirationPeriod; /** * Registry of expected, future, isPutValid calls. If a key+owner is registered in this map, it * is not a "naked put" and is allowed to proceed. */ private final Cache<Object, PendingPutMap> pendingPuts; /** * Main cache where the entities/collections are stored. This is not modified from within this class. */ private final AdvancedCache cache; private final TimeSource timeSource; /** * The time of the last call to {@link #endInvalidatingRegion()}. Puts from transactions started after * this timestamp are denied. */ private volatile long regionInvalidationTimestamp = Long.MIN_VALUE; /** * Number of ongoing concurrent invalidations. */ private int regionInvalidations = 0; /** * Creates a new put from load validator instance. * * @param pendingPutsConfiguration * @param cache Cache instance on which to store pending put information. */ public PutFromLoadValidator(AdvancedCache cache, TimeSource timeSource, Configuration pendingPutsConfiguration) { this(cache, timeSource, cache.getCacheManager(), pendingPutsConfiguration); } /** * Creates a new put from load validator instance. * @param cache Cache instance on which to store pending put information. * @param timeSource * @param cacheManager where to find a cache to store pending put information * @param pendingPutsConfiguration */ public PutFromLoadValidator(AdvancedCache cache, TimeSource timeSource, EmbeddedCacheManager cacheManager, Configuration pendingPutsConfiguration) { this.timeSource = timeSource; String pendingPutsName = getPendingPutsName(cache); if (cacheManager.getCacheConfiguration(pendingPutsName) != null) { log.pendingPutsCacheAlreadyDefined(pendingPutsName); } else { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.read(pendingPutsConfiguration); configurationBuilder.template(false); cacheManager.defineConfiguration(pendingPutsName, configurationBuilder.build()); } if (pendingPutsConfiguration.expiration() != null && pendingPutsConfiguration.expiration().maxIdle() > 0) { this.expirationPeriod = pendingPutsConfiguration.expiration().maxIdle(); } else { throw log.pendingPutsMustHaveMaxIdle(); } this.cache = cache; this.pendingPuts = cacheManager.getCache(pendingPutsName); // The session factory might have been closed but it uses a pre-existing cache manager, so start just in case this.pendingPuts.start(); CacheMode cacheMode = cache.getCacheConfiguration().clustering().cacheMode(); // Since we need to intercept both invalidations of entries that are in the cache and those // that are not, we need to use custom interceptor, not listeners (which fire only for present entries). if (cacheMode.isClustered()) { if (!cacheMode.isInvalidation()) { throw new IllegalArgumentException("PutFromLoadValidator in clustered caches requires invalidation mode."); } addToCache(cache, this); } } private String getPendingPutsName(AdvancedCache cache) { return cache.getName() + "-" + InfinispanProperties.DEF_PENDING_PUTS_RESOURCE; } /** * Besides the call from constructor, this should be called only from tests when mocking the validator. */ public static void addToCache(AdvancedCache cache, PutFromLoadValidator validator) { AsyncInterceptorChain chain = cache.getAsyncInterceptorChain(); List<AsyncInterceptor> interceptors = chain.getInterceptors(); log.debugf("Interceptor chain was: ", interceptors); int position = 0; // add interceptor before uses exact match, not instanceof match int entryWrappingPosition = 0; for (AsyncInterceptor ci : interceptors) { if (ci instanceof EntryWrappingInterceptor) { entryWrappingPosition = position; } position++; } boolean transactional = cache.getCacheConfiguration().transaction().transactionMode().isTransactional(); BasicComponentRegistry componentRegistry = cache.getComponentRegistry().getComponent(BasicComponentRegistry.class); if (transactional) { TxInvalidationInterceptor txInvalidationInterceptor = new TxInvalidationInterceptor(); // We have to use replaceComponent because tests call addToCache more than once componentRegistry.replaceComponent(TxInvalidationInterceptor.class.getName(), txInvalidationInterceptor, true); componentRegistry.getComponent(TxInvalidationInterceptor.class).running(); chain.replaceInterceptor(txInvalidationInterceptor, InvalidationInterceptor.class); // Note that invalidation does *NOT* acquire locks; therefore, we have to start invalidating before // wrapping the entry, since if putFromLoad was invoked between wrap and beginInvalidatingKey, the invalidation // would not commit the entry removal (as during wrap the entry was not in cache) TxPutFromLoadInterceptor txPutFromLoadInterceptor = new TxPutFromLoadInterceptor(validator, ByteString.fromString(cache.getName())); componentRegistry.replaceComponent(TxPutFromLoadInterceptor.class.getName(), txPutFromLoadInterceptor, true); componentRegistry.getComponent(TxPutFromLoadInterceptor.class).running(); chain.addInterceptor(txPutFromLoadInterceptor, entryWrappingPosition); } else { NonTxPutFromLoadInterceptor nonTxPutFromLoadInterceptor = new NonTxPutFromLoadInterceptor(validator, ByteString.fromString(cache.getName())); componentRegistry.replaceComponent(NonTxPutFromLoadInterceptor.class.getName(), nonTxPutFromLoadInterceptor, true); componentRegistry.getComponent(NonTxPutFromLoadInterceptor.class).running(); chain.addInterceptor(nonTxPutFromLoadInterceptor, entryWrappingPosition); NonTxInvalidationInterceptor nonTxInvalidationInterceptor = new NonTxInvalidationInterceptor(); componentRegistry.replaceComponent(NonTxInvalidationInterceptor.class.getName(), nonTxInvalidationInterceptor, true); componentRegistry.getComponent(NonTxInvalidationInterceptor.class).running(); chain.replaceInterceptor(nonTxInvalidationInterceptor, InvalidationInterceptor.class); LockingInterceptor lockingInterceptor = new LockingInterceptor(); componentRegistry.replaceComponent(LockingInterceptor.class.getName(), lockingInterceptor, true); componentRegistry.getComponent(LockingInterceptor.class).running(); chain.replaceInterceptor(lockingInterceptor, NonTransactionalLockingInterceptor.class); } log.debugf("New interceptor chain is: ", cache.getAsyncInterceptorChain()); if (componentRegistry.getComponent(PutFromLoadValidator.class) == null) { componentRegistry.registerComponent(PutFromLoadValidator.class, validator, false); } else{ componentRegistry.replaceComponent(PutFromLoadValidator.class.getName(), validator, false); } } /** * This methods should be called only from tests; it removes existing validator from the cache structures * in order to replace it with new one. * * @param cache */ public static PutFromLoadValidator removeFromCache(AdvancedCache cache) { AsyncInterceptorChain chain = cache.getAsyncInterceptorChain(); BasicComponentRegistry cr = cache.getComponentRegistry().getComponent(BasicComponentRegistry.class); chain.removeInterceptor(TxPutFromLoadInterceptor.class); chain.removeInterceptor(NonTxPutFromLoadInterceptor.class); chain.getInterceptors().stream() .filter(BaseInvalidationInterceptor.class::isInstance).findFirst().map(AsyncInterceptor::getClass) .ifPresent(invalidationClass -> { InvalidationInterceptor invalidationInterceptor = new InvalidationInterceptor(); cr.replaceComponent(InvalidationInterceptor.class.getName(), invalidationInterceptor, true); cr.getComponent(InvalidationInterceptor.class).running(); chain.replaceInterceptor(invalidationInterceptor, invalidationClass); }); chain.getInterceptors().stream() .filter(LockingInterceptor.class::isInstance).findFirst().map(AsyncInterceptor::getClass) .ifPresent(invalidationClass -> { NonTransactionalLockingInterceptor lockingInterceptor = new NonTransactionalLockingInterceptor(); cr.replaceComponent(NonTransactionalLockingInterceptor.class.getName(), lockingInterceptor, true); cr.getComponent(NonTransactionalLockingInterceptor.class).running(); chain.replaceInterceptor(lockingInterceptor, LockingInterceptor.class); }); return cr.getComponent(PutFromLoadValidator.class).running(); } public void destroy() { pendingPuts.stop(); pendingPuts.getCacheManager().undefineConfiguration( pendingPuts.getName() ); } /** * Marker for lock acquired in {@link #acquirePutFromLoadLock(Object, Object, long)} */ public static abstract class Lock { private Lock() {} } /** * Acquire a lock giving the calling thread the right to put data in the * cache for the given key. * <p> * <strong>NOTE:</strong> A call to this method that returns <code>true</code> * should always be matched with a call to {@link #releasePutFromLoadLock(Object, Lock)}. * </p> * * @param session * @param key the key * * @param txTimestamp * @return <code>AcquiredLock</code> if the lock is acquired and the cache put * can proceed; <code>null</code> if the data should not be cached */ public Lock acquirePutFromLoadLock(Object session, Object key, long txTimestamp) { if (log.isTraceEnabled()) { log.tracef("acquirePutFromLoadLock(%s#%s, %d)", cache.getName(), key, txTimestamp); } boolean locked = false; PendingPutMap pending = pendingPuts.get( key ); for (;;) { try { if (pending != null) { locked = pending.acquireLock(100, TimeUnit.MILLISECONDS); if (locked) { boolean valid = false; try { if (pending.isRemoved()) { // this deals with a race between retrieving the map from cache vs. removing that // and locking the map pending.releaseLock(); locked = false; pending = null; if (log.isTraceEnabled()) { log.tracef("Record removed when waiting for the lock."); } continue; } final PendingPut toCancel = pending.remove(session); if (toCancel != null) { valid = !toCancel.completed; toCancel.completed = true; } else { // this is a naked put if (pending.hasInvalidator()) { valid = false; } // we need this check since registerPendingPut (creating new pp) can get between invalidation // and naked put caused by the invalidation else if (pending.lastInvalidationEnd != Long.MIN_VALUE) { // if this transaction started after last invalidation we can continue valid = txTimestamp > pending.lastInvalidationEnd; } else { valid = txTimestamp > regionInvalidationTimestamp; } } return valid ? pending : null; } finally { if (!valid && pending != null) { pending.releaseLock(); locked = false; } if (log.isTraceEnabled()) { log.tracef("acquirePutFromLoadLock(%s#%s, %d) ended with %s, valid: %s", cache.getName(), key, txTimestamp, pending, valid); } } } else { if (log.isTraceEnabled()) { log.tracef("acquirePutFromLoadLock(%s#%s, %d) failed to lock", cache.getName(), key, txTimestamp); } // oops, we have leaked record for this owner, but we don't want to wait here return null; } } else { long regionInvalidationTimestamp = this.regionInvalidationTimestamp; if (txTimestamp <= regionInvalidationTimestamp) { if (log.isTraceEnabled()) { log.tracef("acquirePutFromLoadLock(%s#%s, %d) failed due to region invalidated at %d", cache.getName(), key, txTimestamp, regionInvalidationTimestamp); } return null; } else { if (log.isTraceEnabled()) { log.tracef("Region invalidated at %d, this transaction started at %d", regionInvalidationTimestamp, txTimestamp); } } PendingPut pendingPut = new PendingPut(session); pending = new PendingPutMap(pendingPut); PendingPutMap existing = pendingPuts.putIfAbsent(key, pending); if (existing != null) { pending = existing; } // continue in next loop with lock acquisition } } catch (Throwable t) { if (locked) { pending.releaseLock(); } if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t); } } } } /** * Releases the lock previously obtained by a call to * {@link #acquirePutFromLoadLock(Object, Object, long)}. * * @param key the key */ public void releasePutFromLoadLock(Object key, Lock lock) { if (log.isTraceEnabled()) { log.tracef("releasePutFromLoadLock(%s#%s, %s)", cache.getName(), key, lock); } final PendingPutMap pending = (PendingPutMap) lock; if ( pending != null ) { if ( pending.canRemove() ) { pending.setRemoved(); pendingPuts.remove( key, pending ); } pending.releaseLock(); } } /** * Invalidates all {@link #registerPendingPut(Object, Object, long) previously registered pending puts} ensuring a subsequent call to * {@link #acquirePutFromLoadLock(Object, Object, long)} will return <code>false</code>. <p> This method will block until any * concurrent thread that has {@link #acquirePutFromLoadLock(Object, Object, long) acquired the putFromLoad lock} for the any key has * released the lock. This allows the caller to be certain the putFromLoad will not execute after this method returns, * possibly caching stale data. </p> * * @return <code>true</code> if the invalidation was successful; <code>false</code> if a problem occurred (which the * caller should treat as an exception condition) */ public boolean beginInvalidatingRegion() { if (log.isTraceEnabled()) { log.trace("Started invalidating region " + cache.getName()); } boolean ok = true; long now = timeSource.nextTimestamp(); // deny all puts until endInvalidatingRegion is called; at that time the region should be already // in INVALID state, therefore all new requests should be blocked and ongoing should fail by timestamp synchronized (this) { regionInvalidationTimestamp = Long.MAX_VALUE; regionInvalidations++; } try { // Acquire the lock for each entry to ensure any ongoing // work associated with it is completed before we return // We cannot erase the map: if there was ongoing invalidation and we removed it, registerPendingPut // started after that would have no way of finding out that the entity *is* invalidated (it was // removed from the cache and now the DB is about to be updated). for (Iterator<PendingPutMap> it = pendingPuts.values().iterator(); it.hasNext(); ) { PendingPutMap entry = it.next(); it.remove(); if (entry.acquireLock(60, TimeUnit.SECONDS)) { try { entry.invalidate(now); } finally { entry.releaseLock(); } } else { ok = false; } } } catch (Exception e) { ok = false; } return ok; } /** * Called when the region invalidation is finished. */ public void endInvalidatingRegion() { synchronized (this) { if (--regionInvalidations == 0) { regionInvalidationTimestamp = timeSource.nextTimestamp(); if (log.isTraceEnabled()) { log.tracef("Finished invalidating region %s at %d", cache.getName(), regionInvalidationTimestamp); } } else { if (log.isTraceEnabled()) { log.tracef("Finished invalidating region %s, but there are %d ongoing invalidations", cache.getName(), regionInvalidations); } } } } /** * Notifies this validator that it is expected that a database read followed by a subsequent {@link * #acquirePutFromLoadLock(Object, Object, long)} call will occur. The intent is this method would be called following a cache miss * wherein it is expected that a database read plus cache put will occur. Calling this method allows the validator to * treat the subsequent <code>acquirePutFromLoadLock</code> as if the database read occurred when this method was * invoked. This allows the validator to compare the timestamp of this call against the timestamp of subsequent removal * notifications. * * @param session * @param key key that will be used for subsequent cache put * @param txTimestamp */ public void registerPendingPut(Object session, Object key, long txTimestamp) { long invalidationTimestamp = this.regionInvalidationTimestamp; if (txTimestamp <= invalidationTimestamp) { if (log.isTraceEnabled()) { log.tracef("registerPendingPut(%s#%s, %d) skipped due to region invalidation (%d)", cache.getName(), key, txTimestamp, invalidationTimestamp); } return; } final PendingPut pendingPut = new PendingPut( session ); final PendingPutMap pendingForKey = new PendingPutMap( pendingPut ); for (;;) { final PendingPutMap existing = pendingPuts.putIfAbsent(key, pendingForKey); if (existing != null) { if (existing.acquireLock(10, TimeUnit.SECONDS)) { try { if (existing.isRemoved()) { if (log.isTraceEnabled()) { log.tracef("Record removed when waiting for the lock."); } continue; } if (!existing.hasInvalidator()) { existing.put(pendingPut); } } finally { existing.releaseLock(); } if (log.isTraceEnabled()) { log.tracef("registerPendingPut(%s#%s, %d) ended with %s", cache.getName(), key, txTimestamp, existing); } } else { if (log.isTraceEnabled()) { log.tracef("registerPendingPut(%s#%s, %d) failed to acquire lock", cache.getName(), key, txTimestamp); } // Can't get the lock; when we come back we'll be a "naked put" } } else { if (log.isTraceEnabled()) { log.tracef("registerPendingPut(%s#%s, %d) registered using putIfAbsent: %s", cache.getName(), key, txTimestamp, pendingForKey); } } return; } } /** * Invalidates any {@link #registerPendingPut(Object, Object, long) previously registered pending puts} * and disables further registrations ensuring a subsequent call to {@link #acquirePutFromLoadLock(Object, Object, long)} * will return <code>false</code>. <p> This method will block until any concurrent thread that has * {@link #acquirePutFromLoadLock(Object, Object, long) acquired the putFromLoad lock} for the given key * has released the lock. This allows the caller to be certain the putFromLoad will not execute after this method * returns, possibly caching stale data. </p> * After this transaction completes, {@link #endInvalidatingKey(Object, Object)} needs to be called } * * @param key key identifying data whose pending puts should be invalidated * * @return <code>true</code> if the invalidation was successful; <code>false</code> if a problem occurred (which the * caller should treat as an exception condition) */ public boolean beginInvalidatingKey(Object lockOwner, Object key) { return beginInvalidatingWithPFER(lockOwner, key, null); } public boolean beginInvalidatingWithPFER(Object lockOwner, Object key, Object valueForPFER) { for (;;) { PendingPutMap pending = new PendingPutMap(null); PendingPutMap prev = pendingPuts.putIfAbsent(key, pending); if (prev != null) { pending = prev; } if (pending.acquireLock(60, TimeUnit.SECONDS)) { try { if (pending.isRemoved()) { if (log.isTraceEnabled()) { log.tracef("Record removed when waiting for the lock."); } continue; } long now = timeSource.nextTimestamp(); if (log.isTraceEnabled()) { log.tracef("beginInvalidatingKey(%s#%s, %s) remove invalidator from %s", cache.getName(), key, lockOwnerToString(lockOwner), pending); } pending.invalidate(now); pending.addInvalidator(lockOwner, valueForPFER, now); } finally { pending.releaseLock(); } if (log.isTraceEnabled()) { log.tracef("beginInvalidatingKey(%s#%s, %s) ends with %s", cache.getName(), key, lockOwnerToString(lockOwner), pending); } return true; } else { log.tracef("beginInvalidatingKey(%s#%s, %s) failed to acquire lock", cache.getName(), key, lockOwnerToString(lockOwner)); return false; } } } public boolean endInvalidatingKey(Object lockOwner, Object key) { return endInvalidatingKey(lockOwner, key, false); } /** * Called after the transaction completes, allowing caching of entries. It is possible that this method * is called without previous invocation of {@link #beginInvalidatingKey(Object, Object)}, then it should be a no-op. * * @param lockOwner owner of the invalidation - transaction or thread * @param key * @return */ public boolean endInvalidatingKey(Object lockOwner, Object key, boolean doPFER) { PendingPutMap pending = pendingPuts.get(key); if (pending == null) { if (log.isTraceEnabled()) { log.tracef("endInvalidatingKey(%s#%s, %s) could not find pending puts", cache.getName(), key, lockOwnerToString(lockOwner)); } return true; } if (pending.acquireLock(60, TimeUnit.SECONDS)) { try { long now = timeSource.nextTimestamp(); pending.removeInvalidator(lockOwner, key, now, doPFER); // we can't remove the pending put yet because we wait for naked puts // pendingPuts should be configured with maxIdle time so won't have memory leak return true; } finally { pending.releaseLock(); if (log.isTraceEnabled()) { log.tracef("endInvalidatingKey(%s#%s, %s) ends with %s", cache.getName(), key, lockOwnerToString(lockOwner), pending); } } } else { if (log.isTraceEnabled()) { log.tracef("endInvalidatingKey(%s#%s, %s) failed to acquire lock", cache.getName(), key, lockOwnerToString(lockOwner)); } return false; } } // ---------------------------------------------------------------- Private // we can't use SessionImpl.toString() concurrently private static String lockOwnerToString(Object lockOwner) { return lockOwner instanceof SessionImplementor ? "Session#" + lockOwner.hashCode() : lockOwner.toString(); } public void removePendingPutsCache() { String pendingPutsName = getPendingPutsName( cache ); EmbeddedCacheManager cm = cache.getCacheManager(); cm.administration().removeCache( pendingPutsName ); } /** * Lazy-initialization map for PendingPut. Optimized for the expected usual case where only a * single put is pending for a given key. * <p/> * This class is NOT THREAD SAFE. All operations on it must be performed with the lock held. */ private class PendingPutMap extends Lock { // Number of pending puts which trigger garbage collection private static final int GC_THRESHOLD = 10; private PendingPut singlePendingPut; private Map<Object, PendingPut> fullMap; private final java.util.concurrent.locks.Lock lock = new ReentrantLock(); private Invalidator singleInvalidator; private Map<Object, Invalidator> invalidators; private long lastInvalidationEnd = Long.MIN_VALUE; private boolean removed = false; PendingPutMap(PendingPut singleItem) { this.singlePendingPut = singleItem; } // toString should be called only for debugging purposes public String toString() { if (lock.tryLock()) { try { StringBuilder sb = new StringBuilder(); sb.append("{ PendingPuts="); if (singlePendingPut == null) { if (fullMap == null) { sb.append("[]"); } else { sb.append(fullMap.values()); } } else { sb.append('[').append(singlePendingPut).append(']'); } sb.append(", Invalidators="); if (singleInvalidator == null) { if (invalidators == null) { sb.append("[]"); } else { sb.append(invalidators.values()); } } else { sb.append('[').append(singleInvalidator).append(']'); } sb.append(", LastInvalidationEnd="); if (lastInvalidationEnd == Long.MIN_VALUE) { sb.append("<none>"); } else { sb.append(lastInvalidationEnd); } return sb.append(", Removed=").append(removed).append("}").toString(); } finally { lock.unlock(); } } else { return "PendingPutMap: <locked>"; } } public void put(PendingPut pendingPut) { if ( singlePendingPut == null ) { if ( fullMap == null ) { // initial put singlePendingPut = pendingPut; } else { fullMap.put( pendingPut.owner, pendingPut ); if (fullMap.size() >= GC_THRESHOLD) { gc(); } } } else { // 2nd put; need a map fullMap = new HashMap<Object, PendingPut>( 4 ); fullMap.put( singlePendingPut.owner, singlePendingPut ); singlePendingPut = null; fullMap.put( pendingPut.owner, pendingPut ); } } public PendingPut remove(Object ownerForPut) { PendingPut removed = null; if ( fullMap == null ) { if ( singlePendingPut != null && singlePendingPut.owner.equals( ownerForPut ) ) { removed = singlePendingPut; singlePendingPut = null; } } else { removed = fullMap.remove( ownerForPut ); } return removed; } public int size() { return fullMap == null ? (singlePendingPut == null ? 0 : 1) : fullMap.size(); } public boolean acquireLock(long time, TimeUnit unit) { try { return lock.tryLock( time, unit ); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } public void releaseLock() { lock.unlock(); } public void invalidate(long now) { if ( singlePendingPut != null ) { if (singlePendingPut.invalidate(now, expirationPeriod)) { singlePendingPut = null; } } else if ( fullMap != null ) { for ( Iterator<PendingPut> it = fullMap.values().iterator(); it.hasNext(); ) { PendingPut pp = it.next(); if (pp.invalidate(now, expirationPeriod)) { it.remove(); } } } } /** * Running {@link #gc()} is important when the key is regularly queried but it is not * present in DB. In such case, the putFromLoad would not be called at all and we would * leak pending puts. Cache expiration should handle the case when the pending puts * are not accessed frequently; when these are accessed, we have to do the housekeeping * internally to prevent unlimited growth of the map. * The pending puts will get their timestamps when the map reaches {@link #GC_THRESHOLD} * entries; after expiration period these will be removed completely either through * invalidation or when we try to register next pending put. */ private void gc() { assert fullMap != null; long now = timeSource.nextTimestamp(); log.tracef("Contains %d, doing GC at %d, expiration %d", size(), now, expirationPeriod); for ( Iterator<PendingPut> it = fullMap.values().iterator(); it.hasNext(); ) { PendingPut pp = it.next(); if (pp.gc(now, expirationPeriod)) { it.remove(); } } } public void addInvalidator(Object owner, Object valueForPFER, long now) { assert owner != null; if (invalidators == null) { if (singleInvalidator == null) { singleInvalidator = new Invalidator(owner, now, valueForPFER); put(new PendingPut(owner)); } else { if (singleInvalidator.registeredTimestamp + expirationPeriod < now) { // override leaked invalidator singleInvalidator = new Invalidator(owner, now, valueForPFER); put(new PendingPut(owner)); } invalidators = new HashMap<Object, Invalidator>(); invalidators.put(singleInvalidator.owner, singleInvalidator); // with multiple invalidations the PFER must not be executed invalidators.put(owner, new Invalidator(owner, now, null)); singleInvalidator = null; } } else { long allowedRegistration = now - expirationPeriod; // remove leaked invalidators for (Iterator<Invalidator> it = invalidators.values().iterator(); it.hasNext(); ) { if (it.next().registeredTimestamp < allowedRegistration) { it.remove(); } } // With multiple invalidations in parallel we don't know the order in which // the writes were applied into DB and therefore we can't update the cache // with the most recent value. if (valueForPFER != null && invalidators.isEmpty()) { put(new PendingPut(owner)); } else { valueForPFER = null; } invalidators.put(owner, new Invalidator(owner, now, valueForPFER)); } } public boolean hasInvalidator() { return singleInvalidator != null || (invalidators != null && !invalidators.isEmpty()); } // Debug introspection method, do not use in production code! public Collection<Invalidator> getInvalidators() { lock.lock(); try { if (singleInvalidator != null) { return Collections.singleton(singleInvalidator); } else if (invalidators != null) { return new ArrayList<Invalidator>(invalidators.values()); } else { return Collections.EMPTY_LIST; } } finally { lock.unlock(); } } public void removeInvalidator(Object owner, Object key, long now, boolean doPFER) { if (invalidators == null) { if (singleInvalidator != null && singleInvalidator.owner.equals(owner)) { pferValueIfNeeded(owner, key, singleInvalidator.valueForPFER, doPFER); singleInvalidator = null; } } else { Invalidator invalidator = invalidators.remove(owner); if (invalidator != null) { pferValueIfNeeded(owner, key, invalidator.valueForPFER, doPFER); } } lastInvalidationEnd = Math.max(lastInvalidationEnd, now); } private void pferValueIfNeeded(Object owner, Object key, Object valueForPFER, boolean doPFER) { if (valueForPFER != null) { PendingPut pendingPut = remove(owner); if (doPFER && pendingPut != null && !pendingPut.completed) { cache.putForExternalRead(key, valueForPFER); } } } public boolean canRemove() { return size() == 0 && !hasInvalidator() && lastInvalidationEnd == Long.MIN_VALUE; } public void setRemoved() { removed = true; } public boolean isRemoved() { return removed; } } private static class PendingPut { private final Object owner; private boolean completed; // the timestamp is not filled during registration in order to avoid expensive currentTimeMillis() calls private long registeredTimestamp = Long.MIN_VALUE; private PendingPut(Object owner) { this.owner = owner; } public String toString() { // we can't use SessionImpl.toString() concurrently return (completed ? "C@" : "R@") + lockOwnerToString(owner); } public boolean invalidate(long now, long expirationPeriod) { completed = true; return gc(now, expirationPeriod); } public boolean gc(long now, long expirationPeriod) { if (registeredTimestamp == Long.MIN_VALUE) { registeredTimestamp = now; } else if (registeredTimestamp + expirationPeriod < now){ return true; // this is a leaked pending put } return false; } } private static class Invalidator { private final Object owner; private final long registeredTimestamp; private final Object valueForPFER; private Invalidator(Object owner, long registeredTimestamp, Object valueForPFER) { this.owner = owner; this.registeredTimestamp = registeredTimestamp; this.valueForPFER = valueForPFER; } @Override public String toString() { final StringBuilder sb = new StringBuilder("{"); sb.append("Owner=").append(lockOwnerToString(owner)); sb.append(", Timestamp=").append(registeredTimestamp); sb.append('}'); return sb.toString(); } } }
36,490
36.197757
158
java
null
infinispan-main/hibernate/cache-v62/src/test/java/org/infinispan/test/hibernate/cache/v62/util/TestInfinispanRegionFactory.java
package org.infinispan.test.hibernate.cache.v62.util; import java.util.Collection; import java.util.Properties; import java.util.function.Consumer; import java.util.function.Function; import org.hibernate.service.ServiceRegistry; import org.infinispan.AdvancedCache; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.hibernate.cache.commons.DataType; import org.infinispan.hibernate.cache.commons.DefaultCacheManagerProvider; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.hibernate.cache.commons.util.TestConfigurationHook; import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory; /** * Factory that should be overridden in tests. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class TestInfinispanRegionFactory extends InfinispanRegionFactory { private final TimeService timeService; private final TestConfigurationHook configurationHook; private final EmbeddedCacheManager providedManager; private final Consumer<EmbeddedCacheManager> afterManagerCreated; private final Function<AdvancedCache, AdvancedCache> wrapCache; public TestInfinispanRegionFactory(Properties properties) { timeService = (TimeService) properties.getOrDefault(TestRegionFactory.TIME_SERVICE, null); providedManager = (EmbeddedCacheManager) properties.getOrDefault(TestRegionFactory.MANAGER, null); afterManagerCreated = (Consumer<EmbeddedCacheManager>) properties.getOrDefault(TestRegionFactory.AFTER_MANAGER_CREATED, null); wrapCache = (Function<AdvancedCache, AdvancedCache>) properties.getOrDefault(TestRegionFactory.WRAP_CACHE, null); Class<TestConfigurationHook> hookClass = (Class<TestConfigurationHook>) properties.getOrDefault(TestRegionFactory.CONFIGURATION_HOOK, TestConfigurationHook.class); try { configurationHook = hookClass.getConstructor(Properties.class).newInstance(properties); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected EmbeddedCacheManager createCacheManager(Properties properties, ServiceRegistry serviceRegistry) { // If the cache manager has been provided by calling setCacheManager, don't create a new one EmbeddedCacheManager cacheManager = getCacheManager(); if (cacheManager != null) { return cacheManager; } else if (providedManager != null) { cacheManager = providedManager; } else { ConfigurationBuilderHolder holder = DefaultCacheManagerProvider.loadConfiguration(serviceRegistry, properties); configurationHook.amendConfiguration(holder); cacheManager = new DefaultCacheManager(holder, true); } if (afterManagerCreated != null) { afterManagerCreated.accept(cacheManager); } if (timeService != null) { BasicComponentRegistry basicComponentRegistry = cacheManager.getGlobalComponentRegistry().getComponent(BasicComponentRegistry.class); basicComponentRegistry.replaceComponent(TimeService.class.getName(), timeService, false); basicComponentRegistry.rewire(); } return cacheManager; } @Override protected AdvancedCache getCache(String cacheName, String unqualifiedRegionName, DataType type, Collection<String> legacyUnqualifiedNames) { AdvancedCache cache = super.getCache(cacheName, unqualifiedRegionName, type, legacyUnqualifiedNames); return wrapCache == null ? cache : wrapCache.apply(cache); } @Override public long nextTimestamp() { if (timeService == null) { return super.nextTimestamp(); } else { return timeService.wallClockTime(); } } /* Used for testing */ public String getBaseConfiguration(String regionName) { return baseConfigurations.get(regionName); } /* Used for testing */ public Configuration getConfigurationOverride(String regionName) { return configOverrides.get(regionName).build(false); } }
4,316
43.505155
169
java
null
infinispan-main/hibernate/cache-v62/src/test/java/org/infinispan/test/hibernate/cache/v62/util/TestRegionFactoryProviderImpl.java
package org.infinispan.test.hibernate.cache.v62.util; import java.util.Properties; import org.hibernate.Cache; import org.hibernate.cache.spi.RegionFactory; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory; import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactoryProvider; import org.infinispan.test.hibernate.cache.v62.functional.cluster.ClusterAwareRegionFactory; import org.kohsuke.MetaInfServices; @MetaInfServices(TestRegionFactoryProvider.class) public class TestRegionFactoryProviderImpl implements TestRegionFactoryProvider { @Override public Class<? extends RegionFactory> getRegionFactoryClass() { return TestInfinispanRegionFactory.class; } @Override public Class<? extends RegionFactory> getClusterAwareClass() { return ClusterAwareRegionFactory.class; } @Override public TestRegionFactory create(Properties properties) { return new TestRegionFactoryImpl(new TestInfinispanRegionFactory(properties)); } @Override public TestRegionFactory wrap(RegionFactory regionFactory) { return new TestRegionFactoryImpl((InfinispanRegionFactory) regionFactory); } @Override public TestRegionFactory findRegionFactory(Cache cache) { return new TestRegionFactoryImpl((InfinispanRegionFactory) ((org.hibernate.cache.spi.CacheImplementor) cache).getRegionFactory()); } @Override public InfinispanBaseRegion findTimestampsRegion(Cache cache) { return (InfinispanBaseRegion) ((org.hibernate.cache.spi.CacheImplementor) cache).getTimestampsCache().getRegion(); } @Override public boolean supportTransactionalCaches() { return false; } }
1,820
34.705882
136
java
null
infinispan-main/hibernate/cache-v62/src/test/java/org/infinispan/test/hibernate/cache/v62/util/BatchModeTransactionCoordinator.java
package org.infinispan.test.hibernate.cache.v62.util; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.sql.Connection; import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.Transaction; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.jpa.spi.JpaCompliance; import org.hibernate.resource.transaction.backend.jta.internal.JtaIsolationDelegate; import org.hibernate.resource.transaction.backend.jta.internal.StatusTranslator; import org.hibernate.resource.transaction.spi.IsolationDelegate; import org.hibernate.resource.transaction.spi.SynchronizationRegistry; import org.hibernate.resource.transaction.spi.TransactionCoordinator; import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder; import org.hibernate.resource.transaction.spi.TransactionObserver; import org.hibernate.resource.transaction.spi.TransactionStatus; import org.infinispan.transaction.tm.BatchModeTransactionManager; import org.infinispan.transaction.tm.EmbeddedTransaction; import jakarta.transaction.RollbackException; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; import jakarta.transaction.SystemException; /** * Mocks transaction coordinator when {@link org.hibernate.engine.spi.SessionImplementor} is only mocked * and {@link BatchModeTransactionManager} is used. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class BatchModeTransactionCoordinator implements TransactionCoordinator { private final BatchModeTransactionManager tm = BatchModeTransactionManager.getInstance(); private final TransactionDriver transactionDriver = new TransactionDriver() { @Override public void begin() { try { tm.begin(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void commit() { try { tm.commit(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void rollback() { try { tm.rollback(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public TransactionStatus getStatus() { EmbeddedTransaction transaction = tm.getTransaction(); return transaction == null ? TransactionStatus.NOT_ACTIVE : StatusTranslator.translate(transaction.getStatus()); } @Override public void markRollbackOnly() { throw new UnsupportedOperationException(); } }; @Override public void explicitJoin() { } @Override public boolean isJoined() { return true; } @Override public void pulse() { } @Override public TransactionDriver getTransactionDriverControl() { return transactionDriver; } @Override public SynchronizationRegistry getLocalSynchronizations() { return (SynchronizationRegistry) synchronization -> { try { BatchModeTransactionManager.getInstance() .getTransaction() .registerSynchronization(synchronization); } catch (RollbackException e) { throw new RuntimeException(e); } }; } @Override public JpaCompliance getJpaCompliance() { throw new UnsupportedOperationException(); } @Override public boolean isActive() { try { return BatchModeTransactionManager.getInstance().getStatus() == Status.STATUS_ACTIVE; } catch (SystemException e) { return false; } } @Override public IsolationDelegate createIsolationDelegate() { Connection connection = mock(Connection.class); JdbcConnectionAccess jdbcConnectionAccess = mock(JdbcConnectionAccess.class); try { when(jdbcConnectionAccess.obtainConnection()).thenReturn(connection); } catch (SQLException e) { } return new JtaIsolationDelegate(jdbcConnectionAccess, mock(SqlExceptionHelper.class), tm); } @Override public void addObserver(TransactionObserver observer) { throw new UnsupportedOperationException(); } @Override public void removeObserver(TransactionObserver observer) { throw new UnsupportedOperationException(); } @Override public TransactionCoordinatorBuilder getTransactionCoordinatorBuilder() { throw new UnsupportedOperationException(); } @Override public void setTimeOut(int seconds) { throw new UnsupportedOperationException(); } @Override public int getTimeOut() { throw new UnsupportedOperationException(); } public Transaction newTransaction() { return new BatchModeTransaction(); } public class BatchModeTransaction implements Transaction { @Override public void begin() { } @Override public void commit() { transactionDriver.commit(); } @Override public void rollback() { transactionDriver.rollback(); } @Override public void setRollbackOnly() { } @Override public boolean getRollbackOnly() { return false; } @Override public boolean isActive() { return false; } public TransactionStatus getStatus() { return transactionDriver.getStatus(); } @Override public void registerSynchronization(Synchronization synchronization) throws HibernateException { getLocalSynchronizations().registerSynchronization(synchronization); } @Override public void setTimeout(int seconds) { } @Override public int getTimeout() { return 0; } @Override public void markRollbackOnly() { transactionDriver.markRollbackOnly(); } } }
5,979
26.685185
121
java
null
infinispan-main/hibernate/cache-v62/src/test/java/org/infinispan/test/hibernate/cache/v62/util/TestRegionFactoryImpl.java
package org.infinispan.test.hibernate.cache.v62.util; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Comparator; import java.util.Properties; import org.hibernate.boot.internal.BootstrapContextImpl; import org.hibernate.boot.internal.MetadataBuilderImpl; import org.hibernate.boot.internal.SessionFactoryOptionsBuilder; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.cache.cfg.internal.DomainDataRegionConfigImpl; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Property; import org.hibernate.mapping.RootClass; import org.hibernate.service.ServiceRegistry; import org.hibernate.type.BasicType; import org.hibernate.type.descriptor.java.JavaType; import org.infinispan.configuration.cache.Configuration; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.hibernate.cache.commons.util.TestRegionFactory; class TestRegionFactoryImpl implements TestRegionFactory { private static final Comparator<Object> UNIVERSAL_COMPARATOR = (o1, o2) -> { if (o1 instanceof Long && o2 instanceof Long) { return ((Long) o1).compareTo((Long) o2); } else if (o1 instanceof Integer && o2 instanceof Integer) { return ((Integer) o1).compareTo((Integer) o2); } throw new UnsupportedOperationException(); }; private final InfinispanRegionFactory delegate; TestRegionFactoryImpl(InfinispanRegionFactory delegate) { this.delegate = delegate; } @Override public void start(ServiceRegistry serviceRegistry, Properties p) { StandardServiceRegistry standardServiceRegistry = (StandardServiceRegistry) serviceRegistry; BootstrapContextImpl bootstrapContext = new BootstrapContextImpl(standardServiceRegistry, new MetadataBuilderImpl.MetadataBuildingOptionsImpl(standardServiceRegistry)); SessionFactoryOptionsBuilder builder = new SessionFactoryOptionsBuilder(standardServiceRegistry, bootstrapContext); delegate.start(builder.buildOptions(), p); } @Override public void stop() { delegate.stop(); } @Override public void setCacheManager(EmbeddedCacheManager cm) { delegate.setCacheManager(cm); } @Override public EmbeddedCacheManager getCacheManager() { return delegate.getCacheManager(); } @Override public String getBaseConfiguration(String regionName) { if (delegate instanceof TestInfinispanRegionFactory) { return ((TestInfinispanRegionFactory) delegate).getBaseConfiguration(regionName); } throw new UnsupportedOperationException(); } @Override public Configuration getConfigurationOverride(String regionName) { if (delegate instanceof TestInfinispanRegionFactory) { return ((TestInfinispanRegionFactory) delegate).getConfigurationOverride(regionName); } throw new UnsupportedOperationException(); } @Override public Configuration getPendingPutsCacheConfiguration() { return delegate.getPendingPutsCacheConfiguration(); } @Override public InfinispanBaseRegion buildCollectionRegion(String regionName, AccessType accessType) { Collection collection = mock(Collection.class); when(collection.getRole()).thenReturn(regionName); when(collection.isMutable()).thenReturn(true); String rootClassName = regionName.indexOf('.') >= 0 ? regionName.substring(0, regionName.lastIndexOf('.')) : ""; RootClass owner = rootClassMock(rootClassName); when(collection.getOwner()).thenReturn(owner); DomainDataRegionConfigImpl config = new DomainDataRegionConfigImpl.Builder(regionName).addCollectionConfig(collection, accessType).build(); return (InfinispanBaseRegion) delegate.buildDomainDataRegion(config, null); } @Override public InfinispanBaseRegion buildEntityRegion(String regionName, AccessType accessType) { RootClass persistentClass = rootClassMock(regionName); DomainDataRegionConfigImpl config = new DomainDataRegionConfigImpl.Builder(regionName).addEntityConfig(persistentClass, accessType).build(); return (InfinispanBaseRegion) delegate.buildDomainDataRegion(config, null); } private RootClass rootClassMock(String entityName) { RootClass persistentClass = mock(RootClass.class); when(persistentClass.getRootClass()).thenReturn(persistentClass); when(persistentClass.getEntityName()).thenReturn(entityName); Property versionMock = mock(Property.class); BasicType<Object> typeMock = mock(BasicType.class); JavaType<Object> javaType = mock(JavaType.class); when(javaType.getComparator()).thenReturn(UNIVERSAL_COMPARATOR); when(typeMock.getJavaTypeDescriptor()).thenReturn(javaType); when(versionMock.getType()).thenReturn(typeMock); when(persistentClass.getVersion()).thenReturn(versionMock); when(persistentClass.isVersioned()).thenReturn(true); when(persistentClass.isMutable()).thenReturn(true); return persistentClass; } @Override public InfinispanBaseRegion buildTimestampsRegion(String regionName) { return (InfinispanBaseRegion) delegate.buildTimestampsRegion(regionName, null); } @Override public InfinispanBaseRegion buildQueryResultsRegion(String regionName) { return (InfinispanBaseRegion) delegate.buildQueryResultsRegion(regionName, null); } @Override public RegionFactory unwrap() { return delegate; } @Override public long nextTimestamp() { return delegate.nextTimestamp(); } }
5,803
39.587413
174
java
null
infinispan-main/hibernate/cache-v62/src/test/java/org/infinispan/test/hibernate/cache/v62/util/TestSessionAccessImpl.java
package org.infinispan.test.hibernate.cache.v62.util; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.cache.CacheException; import org.hibernate.cache.cfg.spi.DomainDataCachingConfig; import org.hibernate.cache.spi.CacheImplementor; import org.hibernate.cache.spi.CacheTransactionSynchronization; import org.hibernate.cache.spi.DirectAccessRegion; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.CachedDomainDataAccess; import org.hibernate.cache.spi.access.EntityDataAccess; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.transaction.internal.TransactionImpl; import org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.internal.AbstractSharedSessionContract; import org.hibernate.internal.SessionCreationOptions; import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.jpa.spi.JpaCompliance; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.query.Query; import org.hibernate.resource.jdbc.spi.JdbcSessionContext; import org.hibernate.resource.jdbc.spi.JdbcSessionOwner; import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl; import org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransactionAccess; import org.hibernate.resource.transaction.spi.TransactionCoordinator; import org.hibernate.resource.transaction.spi.TransactionCoordinatorOwner; import org.hibernate.service.ServiceRegistry; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.hibernate.cache.v62.impl.DomainDataRegionImpl; import org.infinispan.hibernate.cache.v62.impl.Sync; import org.infinispan.test.hibernate.cache.commons.util.BatchModeJtaPlatform; import org.infinispan.test.hibernate.cache.commons.util.JdbcResourceTransactionMock; import org.infinispan.test.hibernate.cache.commons.util.TestSessionAccess; import org.infinispan.util.ControlledTimeService; import org.kohsuke.MetaInfServices; import org.mockito.Mockito; import jakarta.persistence.FlushModeType; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; @MetaInfServices(TestSessionAccess.class) public class TestSessionAccessImpl implements TestSessionAccess { @Override public Object mockSessionImplementor() { return mock(SharedSessionContractImplementor.class); } @Override public Object mockSession(Class<? extends JtaPlatform> jtaPlatform, ControlledTimeService timeService, RegionFactory regionFactory) { SessionMock session = mock(SessionMock.class); when(session.isClosed()).thenReturn(false); when(session.isOpen()).thenReturn(true); TransactionCoordinator txCoord; if (jtaPlatform == BatchModeJtaPlatform.class) { BatchModeTransactionCoordinator batchModeTxCoord = new BatchModeTransactionCoordinator(); txCoord = batchModeTxCoord; when(session.getTransactionCoordinator()).thenReturn(txCoord); when(session.beginTransaction()).then(invocation -> { Transaction tx = batchModeTxCoord.newTransaction(); tx.begin(); return tx; }); } else if (jtaPlatform == null || jtaPlatform == NoJtaPlatform.class) { Connection connection = mock(Connection.class); JdbcConnectionAccess jdbcConnectionAccess = mock(JdbcConnectionAccess.class); try { when(jdbcConnectionAccess.obtainConnection()).thenReturn(connection); } catch (SQLException e) { // never thrown from mock } JdbcSessionOwner jdbcSessionOwner = mock(JdbcSessionOwner.class); when(jdbcSessionOwner.getJdbcConnectionAccess()).thenReturn(jdbcConnectionAccess); SqlExceptionHelper sqlExceptionHelper = mock(SqlExceptionHelper.class); JdbcServices jdbcServices = mock(JdbcServices.class); when(jdbcServices.getSqlExceptionHelper()).thenReturn(sqlExceptionHelper); ServiceRegistry serviceRegistry = mock(ServiceRegistry.class); when(serviceRegistry.getService(JdbcServices.class)).thenReturn(jdbcServices); JdbcSessionContext jdbcSessionContext = mock(JdbcSessionContext.class); when(jdbcSessionContext.getServiceRegistry()).thenReturn(serviceRegistry); JpaCompliance jpaCompliance = mock(JpaCompliance.class); when(jpaCompliance.isJpaTransactionComplianceEnabled()).thenReturn(true); SessionFactoryImplementor sessionFactory = mock(SessionFactoryImplementor.class); SessionFactoryOptions sessionFactoryOptions = mock(SessionFactoryOptions.class); when(sessionFactoryOptions.getJpaCompliance()).thenReturn(jpaCompliance); when(sessionFactory.getSessionFactoryOptions()).thenReturn(sessionFactoryOptions); when(jdbcSessionContext.getSessionFactory()).thenReturn(sessionFactory); when(jdbcSessionOwner.getJdbcSessionContext()).thenReturn(jdbcSessionContext); when(session.getSessionFactory()).thenReturn(sessionFactory); when(session.getFactory()).thenReturn(sessionFactory); NonJtaTransactionCoordinator txOwner = mock(NonJtaTransactionCoordinator.class); when(txOwner.getResourceLocalTransaction()).thenReturn(new JdbcResourceTransactionMock()); when(txOwner.getJdbcSessionOwner()).thenReturn(jdbcSessionOwner); when(txOwner.isActive()).thenReturn(true); txCoord = JdbcResourceLocalTransactionCoordinatorBuilderImpl.INSTANCE .buildTransactionCoordinator(txOwner, null); when(session.getTransactionCoordinator()).thenReturn(txCoord); when(session.beginTransaction()).then(invocation -> { Transaction tx = new TransactionImpl(txCoord, session); tx.begin(); return tx; }); } else { throw new IllegalStateException("Unknown JtaPlatform: " + jtaPlatform); } Sync sync = new Sync(regionFactory); TestSynchronization synchronization = new TestSynchronization(sync); CacheTransactionSynchronization cts = mock(Sync.class, Mockito.withSettings().defaultAnswer(invocation -> { if (!synchronization.registered) { txCoord.getLocalSynchronizations().registerSynchronization(synchronization); synchronization.registered = true; } return invocation.getMethod().invoke(sync, invocation.getArguments()); })); when(session.getCacheTransactionSynchronization()).thenReturn(cts); // Need to use to prevent invoking method doAnswer(___ -> timeService.wallClockTime()).when(cts).getCachingTimestamp(); return session; } @Override public Transaction beginTransaction(Object session) { return ((Session) session).beginTransaction(); } @Override public TestRegionAccessStrategy fromAccess(Object access) { return new TestRegionAccessStrategyImpl((CachedDomainDataAccess) access); } @Override public TestRegion fromRegion(InfinispanBaseRegion region) { return new TestRegionImpl((DirectAccessRegion) region); } @Override public List execQueryList(Object session, String query, String[]... params) { Query q = ((Session) session).createQuery(query); setParams(q, params); return q.list(); } @Override public List execQueryListAutoFlush(Object session, String query, String[]... params) { Query q = ((Session) session).createQuery(query).setFlushMode(FlushModeType.AUTO); setParams(q, params); return q.list(); } @Override public List execQueryListCacheable(Object session, String query) { return ((Session) session).createQuery(query).setCacheable(true).list(); } @Override public int execQueryUpdateAutoFlush(Object session, String query, String[]... params) { Query q = ((Session) session).createQuery(query).setFlushMode(FlushModeType.AUTO); setParams(q, params); return q.executeUpdate(); } public void setParams(Query q, String[][] params) { if (params.length > 0) { for (String[] param : params) { q.setParameter(param[0], param[1]); } } } @Override public void execQueryUpdate(Object session, String query) { ((Session) session).createQuery(query).executeUpdate(); } @Override public Object collectionAccess(InfinispanBaseRegion region, AccessType accessType) { DomainDataRegionImpl impl = (DomainDataRegionImpl) region; NavigableRole role = impl.config().getCollectionCaching().stream() .filter(c -> c.getAccessType() == accessType) .map(DomainDataCachingConfig::getNavigableRole) .findFirst().orElseThrow(() -> new IllegalArgumentException()); return impl.getCollectionDataAccess(role); } @Override public Object entityAccess(InfinispanBaseRegion region, AccessType accessType) { DomainDataRegionImpl impl = (DomainDataRegionImpl) region; NavigableRole role = impl.config().getEntityCaching().stream() .filter(c -> c.getAccessType() == accessType) .map(DomainDataCachingConfig::getNavigableRole) .findFirst().orElseThrow(() -> new IllegalArgumentException()); return impl.getEntityDataAccess(role); } @Override public InfinispanBaseRegion getRegion(SessionFactoryImplementor sessionFactory, String regionName) { return (InfinispanBaseRegion) sessionFactory.getCache().getRegion(regionName); } @Override public Collection<InfinispanBaseRegion> getAllRegions(SessionFactoryImplementor sessionFactory) { CacheImplementor cache = sessionFactory.getCache(); return cache.getCacheRegionNames().stream() .map(regionName -> (InfinispanBaseRegion) cache.getRegion(regionName)) .collect(Collectors.toList()); } private static SharedSessionContractImplementor unwrap(Object session) { return (SharedSessionContractImplementor) session; } private static final class TestRegionAccessStrategyImpl implements TestRegionAccessStrategy { private final CachedDomainDataAccess delegate; public TestRegionAccessStrategyImpl(CachedDomainDataAccess delegate) { this.delegate = delegate; } @Override public SoftLock lockItem(Object session, Object key, Object version) throws CacheException { return delegate.lockItem(unwrap(session), key, version); } @Override public void unlockItem(Object session, Object key, SoftLock lock) throws CacheException { delegate.unlockItem(unwrap(session), key, lock); } @Override public boolean afterInsert(Object session, Object key, Object value, Object version) throws CacheException { return unwrapEntity().afterInsert(unwrap(session), key, value, version); } @Override public boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { return unwrapEntity().afterUpdate(unwrap(session), key, value, currentVersion, previousVersion, lock); } @Override public Object get(Object session, Object key) throws CacheException { return delegate.get(unwrap(session), key); } @Override public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { return delegate.putFromLoad(unwrap(session), key, value, version, minimalPutOverride); } @Override public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version) throws CacheException { return delegate.putFromLoad(unwrap(session), key, value, version); } @Override public void remove(Object session, Object key) throws CacheException { delegate.remove(unwrap(session), key); } @Override public boolean insert(Object session, Object key, Object value, Object version) throws CacheException { return unwrapEntity().insert(unwrap(session), key, value, version); } @Override public boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { return unwrapEntity().update(unwrap(session), key, value, currentVersion, previousVersion); } @Override public SoftLock lockRegion() { return delegate.lockRegion(); } @Override public void unlockRegion(SoftLock softLock) { delegate.unlockRegion(softLock); } @Override public void evict(Object key) { delegate.evict(key); } @Override public void evictAll() { delegate.evictAll(); } @Override public void removeAll(Object session) { delegate.removeAll((SharedSessionContractImplementor) session); } private EntityDataAccess unwrapEntity() { return (EntityDataAccess) delegate; } } private abstract class SessionMock extends AbstractSharedSessionContract implements Session { public SessionMock(SessionFactoryImpl factory, SessionCreationOptions options) { super(factory, options); } @Override public SessionFactoryImplementor getSessionFactory() { return super.getSessionFactory(); } } private interface NonJtaTransactionCoordinator extends TransactionCoordinatorOwner, JdbcResourceTransactionAccess { } private static final class TestRegionImpl implements TestRegion { private final DirectAccessRegion delegate; private TestRegionImpl(DirectAccessRegion delegate) { this.delegate = delegate; } @Override public Object get(Object session, Object key) throws CacheException { return delegate.getFromCache(key, unwrap(session)); } @Override public void put(Object session, Object key, Object value) throws CacheException { delegate.putIntoCache(key, value, unwrap(session)); } @Override public void evict(Object key) { throw new UnsupportedOperationException(); } @Override public void evictAll() { delegate.clear(); } } private static class TestSynchronization implements Synchronization { private final Sync sync; private boolean registered; public TestSynchronization(Sync sync) { this.sync = sync; } @Override public void beforeCompletion() { sync.transactionCompleting(); } @Override public void afterCompletion(int status) { sync.transactionCompleted(status == Status.STATUS_COMMITTING || status == Status.STATUS_COMMITTED); } } }
15,696
39.665803
160
java
null
infinispan-main/hibernate/cache-v62/src/test/java/org/infinispan/test/hibernate/cache/v62/functional/cluster/ClusterAwareRegionFactory.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.test.hibernate.cache.v62.functional.cluster; import java.util.Map; import java.util.Properties; import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.cache.CacheException; import org.hibernate.cache.cfg.spi.DomainDataRegionBuildingContext; import org.hibernate.cache.cfg.spi.DomainDataRegionConfig; import org.hibernate.cache.spi.CacheTransactionSynchronization; import org.hibernate.cache.spi.DomainDataRegion; import org.hibernate.cache.spi.QueryResultsRegion; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.TimestampsRegion; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.hibernate.cache.commons.functional.cluster.ClusterAware; import org.infinispan.test.hibernate.cache.commons.functional.cluster.DualNodeTest; import org.infinispan.test.hibernate.cache.commons.util.CacheTestUtil; /** * ClusterAwareRegionFactory. * * @author Galder Zamarreño * @since 3.5 */ public class ClusterAwareRegionFactory implements RegionFactory { private InfinispanRegionFactory delegate; private String cacheManagerName; private boolean locallyAdded; public ClusterAwareRegionFactory(Properties props) { Class<? extends InfinispanRegionFactory> regionFactoryClass = (Class<InfinispanRegionFactory>) props.get(DualNodeTest.REGION_FACTORY_DELEGATE); delegate = CacheTestUtil.createRegionFactory(regionFactoryClass, props); } @Override public void start(SessionFactoryOptions settings, Map configValues) throws CacheException { cacheManagerName = (String) configValues.get(DualNodeTest.NODE_ID_PROP); EmbeddedCacheManager existing = ClusterAware.getCacheManager(cacheManagerName); locallyAdded = (existing == null); if (locallyAdded) { delegate.start(settings, configValues); ClusterAware.addCacheManager(cacheManagerName, delegate.getCacheManager()); } else { delegate.setCacheManager(existing); } } public void stop() { if (locallyAdded) ClusterAware.removeCacheManager(cacheManagerName); delegate.stop(); } @Override public DomainDataRegion buildDomainDataRegion(DomainDataRegionConfig regionConfig, DomainDataRegionBuildingContext buildingContext) { return delegate.buildDomainDataRegion(regionConfig, buildingContext); } @Override public QueryResultsRegion buildQueryResultsRegion(String regionName, SessionFactoryImplementor sessionFactory) throws CacheException { return delegate.buildQueryResultsRegion(regionName, sessionFactory); } @Override public TimestampsRegion buildTimestampsRegion(String regionName, SessionFactoryImplementor sessionFactory) throws CacheException { return delegate.buildTimestampsRegion(regionName, sessionFactory); } @Override public boolean isMinimalPutsEnabledByDefault() { return delegate.isMinimalPutsEnabledByDefault(); } @Override public AccessType getDefaultAccessType() { return AccessType.TRANSACTIONAL; } @Override public String qualify(String regionName) { return delegate.qualify(regionName); } public long nextTimestamp() { return delegate.nextTimestamp(); } @Override public CacheTransactionSynchronization createTransactionContext(SharedSessionContractImplementor session) { return delegate.createTransactionContext(session); } @Override public long getTimeout() { return delegate.getTimeout(); } }
4,017
34.245614
136
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/StrategyRegistrationProviderImpl.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62; import java.util.ArrayList; import java.util.List; import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.cache.spi.RegionFactory; import org.kohsuke.MetaInfServices; /** * Makes the contained region factory implementations available to the Hibernate * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service. * * @author Steve Ebersole */ @MetaInfServices(StrategyRegistrationProvider.class) public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { @Override public Iterable<StrategyRegistration> getStrategyRegistrations() { final List<StrategyRegistration> strategyRegistrations = new ArrayList<StrategyRegistration>(); strategyRegistrations.add( new SimpleStrategyRegistrationImpl<>( RegionFactory.class, InfinispanRegionFactory.class, "infinispan", "infinispan-jndi", InfinispanRegionFactory.class.getName(), InfinispanRegionFactory.class.getSimpleName() ) ); return strategyRegistrations; } }
1,585
35.883721
101
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/InfinispanRegionFactory.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ServiceLoader; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.cache.CacheException; import org.hibernate.cache.cfg.spi.DomainDataRegionBuildingContext; import org.hibernate.cache.cfg.spi.DomainDataRegionConfig; import org.hibernate.cache.internal.DefaultCacheKeysFactory; import org.hibernate.cache.spi.AbstractRegionFactory; import org.hibernate.cache.spi.CacheKeysFactory; import org.hibernate.cache.spi.CacheTransactionSynchronization; import org.hibernate.cache.spi.DomainDataRegion; import org.hibernate.cache.spi.QueryResultsRegion; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.SecondLevelCacheLogger; import org.hibernate.cache.spi.TimestampsRegion; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.support.RegionNameQualifier; import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.ServiceRegistry; import org.infinispan.AdvancedCache; import org.infinispan.commands.module.ModuleCommandFactory; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.hibernate.cache.commons.DataType; import org.infinispan.hibernate.cache.commons.DefaultCacheManagerProvider; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.hibernate.cache.commons.TimeSource; import org.infinispan.hibernate.cache.commons.util.CacheCommandFactory; import org.infinispan.hibernate.cache.commons.util.Caches; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.spi.EmbeddedCacheManagerProvider; import org.infinispan.hibernate.cache.spi.InfinispanProperties; import org.infinispan.hibernate.cache.v62.impl.ClusteredTimestampsRegionImpl; import org.infinispan.hibernate.cache.v62.impl.DomainDataRegionImpl; import org.infinispan.hibernate.cache.v62.impl.QueryResultsRegionImpl; import org.infinispan.hibernate.cache.v62.impl.Sync; import org.infinispan.hibernate.cache.v62.impl.TimestampsRegionImpl; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.transaction.TransactionMode; /** * A {@link RegionFactory} for <a href="http://www.jboss.org/infinispan">Infinispan</a>-backed cache * regions. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public class InfinispanRegionFactory implements RegionFactory, TimeSource, InfinispanProperties { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(InfinispanRegionFactory.class); /** * Defines custom mapping for regionName -> cacheName and also DataType.key -> cacheName * (for the case that you want to change the cache configuration for whole type) */ protected final Map<String, String> baseConfigurations = new HashMap<>(); /** * Defines configuration properties applied on top of configuration set in any file, by regionName or DataType.key */ protected final Map<String, ConfigurationBuilder> configOverrides = new HashMap<>(); private CacheKeysFactory cacheKeysFactory; private final Map<DataType, Configuration> dataTypeConfigurations = new HashMap<>(); private EmbeddedCacheManager manager; private List<InfinispanBaseRegion> regions = new ArrayList<>(); private SessionFactoryOptions settings; private Boolean globalStats; /** * Create a new instance using the default configuration. */ public InfinispanRegionFactory() { } /** * Create a new instance using conifguration properties in <code>props</code>. * * @param props Environmental properties; currently unused. */ @SuppressWarnings("UnusedParameters") public InfinispanRegionFactory(Properties props) { this(); } @Override public DomainDataRegion buildDomainDataRegion(DomainDataRegionConfig regionConfig, DomainDataRegionBuildingContext buildingContext) { log.debugf("Building domain data region [%s] entities=%s collections=%s naturalIds=%s", regionConfig.getRegionName(), regionConfig.getEntityCaching(), regionConfig.getCollectionCaching(), regionConfig.getNaturalIdCaching() ); // TODO: data type is probably deprecated, but we need it for backwards-compatible configuration DataType dataType; int entities = regionConfig.getEntityCaching().size(); int collections = regionConfig.getCollectionCaching().size(); int naturalIds = regionConfig.getNaturalIdCaching().size(); if (entities > 0 && collections == 0 && naturalIds == 0) { dataType = regionConfig.getEntityCaching().stream() .allMatch(c -> !c.isMutable()) ? DataType.IMMUTABLE_ENTITY : DataType.ENTITY; } else if (entities == 0 && collections > 0 && naturalIds == 0) { dataType = DataType.COLLECTION; } else if (entities == 0 && collections == 0 && naturalIds > 0) { dataType = DataType.NATURAL_ID; } else { // some mix, let's use entity dataType = DataType.ENTITY; } AdvancedCache cache = getCache(qualify(regionConfig.getRegionName()), regionConfig.getRegionName(), dataType, Collections.emptyList()); DomainDataRegionImpl region = new DomainDataRegionImpl(cache, regionConfig, this, getCacheKeysFactory()); startRegion(region); return region; } @Override public QueryResultsRegion buildQueryResultsRegion(String regionName, SessionFactoryImplementor sessionFactory) { log.debugf("Building query results cache region [%s]", regionName); List<String> legacyUnqualifiedNames = regionName.equals(RegionFactory.DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME) ? AbstractRegionFactory.LEGACY_QUERY_RESULTS_REGION_UNQUALIFIED_NAMES : Collections.emptyList(); AdvancedCache cache = getCache(qualify(regionName), regionName, DataType.QUERY, legacyUnqualifiedNames); QueryResultsRegionImpl region = new QueryResultsRegionImpl(cache, regionName, this); startRegion(region); return region; } @Override public TimestampsRegion buildTimestampsRegion(String regionName, SessionFactoryImplementor sessionFactory) { log.debugf("Building timestamps cache region [%s]", regionName); List<String> legacyUnqualifiedNames = regionName.equals(RegionFactory.DEFAULT_UPDATE_TIMESTAMPS_REGION_UNQUALIFIED_NAME) ? AbstractRegionFactory.LEGACY_UPDATE_TIMESTAMPS_REGION_UNQUALIFIED_NAMES : Collections.emptyList(); final AdvancedCache cache = getCache(qualify(regionName), regionName, DataType.TIMESTAMPS, legacyUnqualifiedNames); TimestampsRegionImpl region = createTimestampsRegion(cache, regionName); startRegion(region); return region; } protected TimestampsRegionImpl createTimestampsRegion( AdvancedCache cache, String regionName) { if (Caches.isClustered(cache)) { return new ClusteredTimestampsRegionImpl(cache, regionName, this); } else { return new TimestampsRegionImpl(cache, regionName, this); } } public Configuration getPendingPutsCacheConfiguration() { return dataTypeConfigurations.get(DataType.PENDING_PUTS); } protected CacheKeysFactory getCacheKeysFactory() { return cacheKeysFactory; } @Override public boolean isMinimalPutsEnabledByDefault() { return false; } @Override public AccessType getDefaultAccessType() { return AccessType.TRANSACTIONAL; } @Override public String qualify(String regionName) { return RegionNameQualifier.INSTANCE.qualify(regionName, settings); } @Override public CacheTransactionSynchronization createTransactionContext(SharedSessionContractImplementor session) { return new Sync(this); } @Override public long nextTimestamp() { return System.currentTimeMillis(); } public void setCacheManager(EmbeddedCacheManager manager) { this.manager = manager; } public EmbeddedCacheManager getCacheManager() { return manager; } @Override public void start(SessionFactoryOptions settings, Map configValues) throws CacheException { log.debug("Starting Infinispan region factory"); // determine the CacheKeysFactory to use... this.cacheKeysFactory = determineCacheKeysFactory(settings, configValues); try { this.settings = settings; for (Object k : configValues.keySet()) { final String key = (String) k; int prefixLoc; if ((prefixLoc = key.indexOf(PREFIX)) != -1) { parseProperty(prefixLoc, key, extractProperty(key, configValues)); } } String globalStatsStr = extractProperty(INFINISPAN_GLOBAL_STATISTICS_PROP, configValues); if (globalStatsStr != null) { globalStats = Boolean.parseBoolean(globalStatsStr); } if (configValues.containsKey(INFINISPAN_USE_SYNCHRONIZATION_PROP)) { log.propertyUseSynchronizationDeprecated(); } StandardServiceRegistry serviceRegistry = settings.getServiceRegistry(); manager = createCacheManager(toProperties(configValues), serviceRegistry); defineDataTypeCacheConfigurations(serviceRegistry); } catch (CacheException ce) { throw ce; } catch (Throwable t) { throw log.unableToStart(t); } } private Properties toProperties(Map<Object, Object> configValues) { Properties properties = new Properties(); for (Map.Entry<Object, Object> entry : configValues.entrySet()) { properties.put(entry.getKey(), entry.getValue()); } return properties; } private CacheKeysFactory determineCacheKeysFactory(SessionFactoryOptions settings, Map properties) { return settings.getServiceRegistry().getService(StrategySelector.class).resolveDefaultableStrategy( CacheKeysFactory.class, properties.get(AvailableSettings.CACHE_KEYS_FACTORY), DefaultCacheKeysFactory.INSTANCE ); } /* This method is overridden in WildFly, so the signature must not change. */ protected EmbeddedCacheManager createCacheManager(Properties properties, ServiceRegistry serviceRegistry) { for (EmbeddedCacheManagerProvider provider : ServiceLoader.load(EmbeddedCacheManagerProvider.class, EmbeddedCacheManagerProvider.class.getClassLoader())) { EmbeddedCacheManager cacheManager = provider.getEmbeddedCacheManager(properties); if (cacheManager != null) { return cacheManager; } } return new DefaultCacheManagerProvider(serviceRegistry).getEmbeddedCacheManager(properties); } @Override public void stop() { log.debug("Stop region factory"); stopCacheRegions(); stopCacheManager(); } protected void stopCacheRegions() { log.debug("Clear region references"); getCacheCommandFactory().clearRegions(regions); // Ensure we cleanup any caches we created regions.forEach(region -> { region.destroy(); manager.undefineConfiguration(region.getCache().getName()); }); regions.clear(); } protected void stopCacheManager() { log.debug("Stop cache manager"); manager.stop(); } private void startRegion(InfinispanBaseRegion region) { regions.add(region); getCacheCommandFactory().addRegion(region); } private void parseProperty(int prefixLoc, String key, String value) { final ConfigurationBuilder builder; int suffixLoc; if ((suffixLoc = key.indexOf(CONFIG_SUFFIX)) != -1 && !key.equals(INFINISPAN_CONFIG_RESOURCE_PROP)) { String regionName = key.substring(prefixLoc + PREFIX.length(), suffixLoc); baseConfigurations.put(regionName, value); } else if (key.contains(DEPRECATED_STRATEGY_SUFFIX)) { log.ignoringDeprecatedProperty(DEPRECATED_STRATEGY_SUFFIX); } else if ((suffixLoc = key.indexOf(WAKE_UP_INTERVAL_SUFFIX)) != -1 || (suffixLoc = key.indexOf(DEPRECATED_WAKE_UP_INTERVAL_SUFFIX)) != -1) { builder = getOrCreateConfig(prefixLoc, key, suffixLoc); builder.expiration().wakeUpInterval(Long.parseLong(value)); } else if ((suffixLoc = key.indexOf(SIZE_SUFFIX)) != -1) { builder = getOrCreateConfig(prefixLoc, key, suffixLoc); builder.memory().maxCount(Long.parseLong(value)); } else if ((suffixLoc = key.indexOf(DEPRECATED_MAX_ENTRIES_SUFFIX)) != -1) { log.deprecatedProperty(DEPRECATED_MAX_ENTRIES_SUFFIX, SIZE_SUFFIX); builder = getOrCreateConfig(prefixLoc, key, suffixLoc); builder.memory().maxCount(Long.parseLong(value)); } else if ((suffixLoc = key.indexOf(LIFESPAN_SUFFIX)) != -1) { builder = getOrCreateConfig(prefixLoc, key, suffixLoc); builder.expiration().lifespan(Long.parseLong(value)); } else if ((suffixLoc = key.indexOf(MAX_IDLE_SUFFIX)) != -1) { builder = getOrCreateConfig(prefixLoc, key, suffixLoc); builder.expiration().maxIdle(Long.parseLong(value)); } } private String extractProperty(String key, Map properties) { final String value = ConfigurationHelper.extractPropertyValue(key, properties); log.debugf("Configuration override via property %s: %s", key, value); return value; } private ConfigurationBuilder getOrCreateConfig(int prefixLoc, String key, int suffixLoc) { final String name = key.substring(prefixLoc + PREFIX.length(), suffixLoc); return configOverrides.computeIfAbsent(name, Void -> new ConfigurationBuilder()); } private void defineDataTypeCacheConfigurations(ServiceRegistry serviceRegistry) { String defaultResource = manager.getCacheManagerConfiguration().isClustered() ? DEF_INFINISPAN_CONFIG_RESOURCE : INFINISPAN_CONFIG_LOCAL_RESOURCE; ConfigurationBuilderHolder defaultConfiguration = DefaultCacheManagerProvider.loadConfiguration(serviceRegistry, defaultResource); for (DataType type : DataType.values()) { String cacheName = baseConfigurations.get(type.key); if (cacheName == null) { cacheName = type.defaultCacheName; } Configuration configuration = manager.getCacheConfiguration(cacheName); ConfigurationBuilder builder; if (configuration == null) { log.debugf("Cache configuration not found for %s", type); if (!cacheName.equals(type.defaultCacheName)) { log.customConfigForTypeNotFound(cacheName, type.key); } builder = defaultConfiguration.getNamedConfigurationBuilders().get(type.defaultCacheName); if (builder == null) { throw new IllegalStateException("Generic data types must have default configuration, none found for " + type); } } else { builder = new ConfigurationBuilder().read(configuration); } ConfigurationBuilder override = configOverrides.get(type.key); if (override != null) { builder.read(override.build(false)); } builder.template(true); unsetTransactions(builder); dataTypeConfigurations.put(type, builder.build()); } } protected AdvancedCache getCache(String cacheName, String unqualifiedRegionName, DataType type, Collection<String> legacyUnqualifiedNames) { if (!manager.cacheExists(cacheName)) { String templateCacheName = baseConfigurations.get(cacheName); Configuration configuration; ConfigurationBuilder builder = new ConfigurationBuilder(); if (templateCacheName == null) { templateCacheName = baseConfigurations.get(unqualifiedRegionName); if (templateCacheName != null) { log.usingUnqualifiedNameInConfiguration(unqualifiedRegionName, cacheName); } } if (templateCacheName != null) { configuration = manager.getCacheConfiguration(templateCacheName); if (configuration == null) { log.customConfigForRegionNotFound(templateCacheName, cacheName, type.key); } else { log.debugf("Region '%s' will use cache template '%s'", cacheName, templateCacheName); builder.read(configuration); unsetTransactions(builder); // do not apply data type overrides to regions that set special cache configuration if (templateCacheName.equals(cacheName)) { // we'll define the configuration at the end of this method manager.undefineConfiguration(cacheName); } } } else { configuration = manager.getCacheConfiguration(cacheName); if (configuration != null) { // While we could just use the defined configuration it's better to force user to include // the configuration properties so that it's obvious from persistence.xml that this entity // will get some special treatment. log.regionNameMatchesCacheName(cacheName, cacheName, cacheName); manager.undefineConfiguration(cacheName); } if (manager.getCacheConfiguration(unqualifiedRegionName) != null) { log.configurationWithUnqualifiedName(unqualifiedRegionName, cacheName); } } // Before the very default configuration for the type try legacy configuration names for (String legacyUnqualified : legacyUnqualifiedNames) { configuration = manager.getCacheConfiguration(qualify(legacyUnqualified)); if (configuration != null) { SecondLevelCacheLogger.L2CACHE_LOGGER.usingLegacyCacheName(cacheName, qualify(legacyUnqualified)); break; } configuration = manager.getCacheConfiguration(legacyUnqualified); if (configuration != null) { SecondLevelCacheLogger.L2CACHE_LOGGER.usingLegacyCacheName(cacheName, legacyUnqualified); break; } } if (configuration == null) { configuration = dataTypeConfigurations.get(type); if (configuration == null) { throw new IllegalStateException("Configuration not defined for type " + type.key); } builder.read(configuration); // overrides for data types are already applied, but we should check custom ones } ConfigurationBuilder override = configOverrides.get(cacheName); if (override != null) { log.debugf("Region '%s' has additional configuration set through properties.", cacheName); builder.read(override.build(false)); } if (globalStats != null) { builder.statistics().enabled(globalStats).available(globalStats); } configuration = builder.template(false).build(); type.validate(configuration); manager.defineConfiguration(cacheName, configuration); } final AdvancedCache cache = manager.getCache(cacheName).getAdvancedCache(); // TODO: not sure if this is needed in recent Infinispan if (!cache.getStatus().allowInvocations()) { cache.start(); } return cache; } private void unsetTransactions(ConfigurationBuilder builder) { if (builder.transaction().transactionMode().isTransactional()) { log.transactionalConfigurationIgnored(); builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL).transactionManagerLookup(null); } } private CacheCommandFactory getCacheCommandFactory() { final GlobalComponentRegistry globalCr = manager.getGlobalComponentRegistry(); final Map<Byte, ModuleCommandFactory> factories = globalCr.getComponent("org.infinispan.modules.command.factories"); for (ModuleCommandFactory factory : factories.values()) { if (factory instanceof CacheCommandFactory) { return (CacheCommandFactory) factory; } } throw log.cannotInstallCommandFactory(); } }
21,194
43.341004
161
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/access/SessionAccessImpl.java
package org.infinispan.hibernate.cache.v62.access; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.jdbc.WorkExecutorVisitable; import org.hibernate.resource.transaction.spi.TransactionCoordinator; import org.infinispan.hibernate.cache.commons.access.SessionAccess; import org.kohsuke.MetaInfServices; import jakarta.transaction.Synchronization; // Unlike its's counterparts in v51 and main module this shouldn't be used in production anymore @MetaInfServices(SessionAccess.class) public final class SessionAccessImpl implements SessionAccess { @Override public TransactionCoordinatorAccess getTransactionCoordinator(Object session) { return session == null ? null : new TransactionCoordinatorAccessImpl(unwrap(session).getTransactionCoordinator()); } @Override public long getTimestamp(Object session) { return unwrap(session).getCacheTransactionSynchronization().getCachingTimestamp(); } private static SharedSessionContractImplementor unwrap(Object session) { return (SharedSessionContractImplementor) session; } private static final class TransactionCoordinatorAccessImpl implements TransactionCoordinatorAccess { private final TransactionCoordinator txCoordinator; public TransactionCoordinatorAccessImpl(TransactionCoordinator txCoordinator) { this.txCoordinator = txCoordinator; } @Override public void registerLocalSynchronization(Synchronization sync) { txCoordinator.getLocalSynchronizations().registerSynchronization(sync); } @Override public void delegateWork(WorkExecutorVisitable<Void> workExecutorVisitable, boolean requiresTransaction) { txCoordinator.createIsolationDelegate().delegateWork(workExecutorVisitable, requiresTransaction); } @Override public boolean isJoined() { return txCoordinator.isJoined(); } } }
1,951
33.857143
112
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/ReadWriteEntityDataAccess.java
package org.infinispan.hibernate.cache.v62.impl; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.hibernate.cache.commons.access.AccessDelegate; class ReadWriteEntityDataAccess extends ReadOnlyEntityDataAccess { ReadWriteEntityDataAccess(AccessType accessType, AccessDelegate delegate, DomainDataRegionImpl region) { super(accessType, delegate, region); } public boolean update(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { return delegate.update(session, key, value, currentVersion, previousVersion); } public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { return delegate.afterUpdate(session, key, value, currentVersion, previousVersion, lock); } }
1,093
44.583333
183
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/ReadWriteNaturalDataAccess.java
package org.infinispan.hibernate.cache.v62.impl; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.hibernate.cache.commons.access.AccessDelegate; class ReadWriteNaturalDataAccess extends ReadOnlyNaturalDataAccess { ReadWriteNaturalDataAccess(AccessType accessType, AccessDelegate delegate, DomainDataRegionImpl region) { super(accessType, delegate, region); } @Override public boolean update(SharedSessionContractImplementor session, Object key, Object value) throws CacheException { return delegate.update(session, key, value, null, null); } @Override public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, SoftLock lock) throws CacheException { return delegate.afterUpdate(session, key, value, null, null, lock); } }
986
36.961538
136
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/ReadOnlyEntityDataAccess.java
package org.infinispan.hibernate.cache.v62.impl; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.EntityDataAccess; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.persister.entity.EntityPersister; import org.infinispan.hibernate.cache.commons.access.AccessDelegate; class ReadOnlyEntityDataAccess extends AbstractAccess implements EntityDataAccess { ReadOnlyEntityDataAccess(AccessType accessType, AccessDelegate delegate, DomainDataRegionImpl region) { super(accessType, delegate, region); } @Override public Object get(SharedSessionContractImplementor session, Object key) { return delegate.get(session, key, session.getCacheTransactionSynchronization().getCachingTimestamp()); } @Override public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, Object version) { return delegate.putFromLoad(session, key, value, session.getCacheTransactionSynchronization().getCachingTimestamp(), version); } @Override public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, Object version, boolean minimalPutOverride) { return delegate.putFromLoad(session, key, value, session.getCacheTransactionSynchronization().getCachingTimestamp(), version, minimalPutOverride); } @Override public boolean insert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException { return delegate.insert(session, key, value, version); } @Override public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException { return delegate.afterInsert(session, key, value, version); } @Override public boolean update(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } @Override public boolean afterUpdate(SharedSessionContractImplementor session, Object o, Object o1, Object o2, Object o3, SoftLock softLock) throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } @Override public SoftLock lockItem(SharedSessionContractImplementor session, Object o, Object o1) throws CacheException { return null; } @Override public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock softLock) throws CacheException { delegate.unlockItem(session, key); } @Override public void remove(SharedSessionContractImplementor session, Object key) throws CacheException { delegate.remove(session, key); } public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { return region.getCacheKeysFactory().createEntityKey(id, persister, factory, tenantIdentifier); } public Object getCacheKeyId(Object cacheKey) { return region.getCacheKeysFactory().getEntityId(cacheKey); } }
3,354
43.144737
163
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/Invocation.java
package org.infinispan.hibernate.cache.v62.impl; import java.util.concurrent.CompletableFuture; interface Invocation { CompletableFuture<?> invoke(boolean success); }
172
20.625
48
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/TombstoneAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.concurrent.CompletableFuture; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.Tombstone; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class TombstoneAccessDelegate extends org.infinispan.hibernate.cache.commons.access.TombstoneAccessDelegate { public TombstoneAccessDelegate(InfinispanDataRegion region) { super(region); } @Override protected void write(Object session, Object key, Object value) { Sync sync = (Sync) ((SharedSessionContractImplementor) session).getCacheTransactionSynchronization(); FutureUpdateInvocation invocation = new FutureUpdateInvocation(asyncWriteMap, key, value, region, sync.getCachingTimestamp()); sync.registerAfterCommit(invocation); // The update will be invalidating all putFromLoads for the duration of expiration or until removed by the synchronization Tombstone tombstone = new Tombstone(invocation.getUuid(), region.nextTimestamp() + region.getTombstoneExpiration()); CompletableFuture<Void> future = writeMap.eval(key, tombstone); if (tombstone.isComplete()) { sync.registerBeforeCommit(future); } else { log.trace("Tombstone was not applied immediately, waiting."); // Slow path: there's probably a locking conflict and we need to wait // until the command gets applied (and replicated, too!). future.join(); } } }
1,837
43.829268
132
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/FutureUpdateInvocation.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import org.infinispan.commons.util.Util; import org.infinispan.functional.FunctionalMap; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.FutureUpdate; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class FutureUpdateInvocation implements Invocation, BiFunction<Void, Throwable, Void> { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(FutureUpdateInvocation.class); private final UUID uuid = Util.threadLocalRandomUUID(); private final Object key; private final Object value; private final InfinispanDataRegion region; private final long sessionTimestamp; private final FunctionalMap.ReadWriteMap<Object, Object> rwMap; private final CompletableFuture<Void> future = new CompletableFuture<>(); public FutureUpdateInvocation(FunctionalMap.ReadWriteMap<Object, Object> rwMap, Object key, Object value, InfinispanDataRegion region, long sessionTimestamp) { this.rwMap = rwMap; this.key = key; this.value = value; this.region = region; this.sessionTimestamp = sessionTimestamp; } public UUID getUuid() { return uuid; } @Override public CompletableFuture<Void> invoke(boolean success) { // If the region was invalidated during this session, we can't know that the value we're inserting is valid // so we'll just null the tombstone if (sessionTimestamp < region.getLastRegionInvalidation()) { success = false; } // Exceptions in #afterCompletion() are silently ignored, since the transaction // is already committed in DB. However we must not return until we update the cache. FutureUpdate futureUpdate = new FutureUpdate(uuid, region.nextTimestamp(), success ? this.value : null); for (; ; ) { try { // We expect that when the transaction completes further reads from cache will return the updated value. // UnorderedDistributionInterceptor makes sure that the update is executed on the node first, and here // we're waiting for the local update. The remote update does not concern us - the cache is async and // we won't wait for that. rwMap.eval(key, futureUpdate).handle(this); return future; } catch (Exception e) { log.failureInAfterCompletion(e); } } } @Override public Void apply(Void nil, Throwable throwable) { if (throwable != null) { log.failureInAfterCompletion(throwable); invoke(false); } else { future.complete(null); } return null; } }
3,180
37.792683
124
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/AbstractAccess.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.DomainDataRegion; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.hibernate.cache.commons.access.AccessDelegate; /** * Collection region access for Infinispan. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ abstract class AbstractAccess { private final AccessType accessType; final AccessDelegate delegate; final DomainDataRegionImpl region; AbstractAccess(AccessType accessType, AccessDelegate delegate, DomainDataRegionImpl region) { this.accessType = accessType; this.delegate = delegate; this.region = region; } public void evict(Object key) throws CacheException { delegate.evict(key); } public void evictAll() throws CacheException { delegate.evictAll(); } public void removeAll(SharedSessionContractImplementor session) throws CacheException { delegate.removeAll(); } public SoftLock lockRegion() throws CacheException { delegate.lockAll(); return null; } public void unlockRegion(SoftLock lock) throws CacheException { delegate.unlockAll(); } public AccessType getAccessType() { return accessType; } public DomainDataRegion getRegion() { return region; } public boolean contains(Object key) { return delegate.get(null, key, Long.MAX_VALUE) != null; } }
1,834
26.38806
96
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/RemovalInvocation.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.concurrent.CompletableFuture; import org.infinispan.functional.FunctionalMap; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.VersionedEntry; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class RemovalInvocation implements Invocation { final CompletableFuture<Void> future; public RemovalInvocation(FunctionalMap.ReadWriteMap<Object, Object> rwMap, InfinispanDataRegion region, Object key) { this.future = rwMap.eval(key, new VersionedEntry(region.nextTimestamp())); } @Override public CompletableFuture<Void> invoke(boolean success) { if (success) { return future; } else { return null; } } }
1,051
29.941176
120
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/TimestampsRegionImpl.java
package org.infinispan.hibernate.cache.v62.impl; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.TimestampsRegion; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.AdvancedCache; import org.infinispan.context.Flag; import org.infinispan.hibernate.cache.commons.util.Caches; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; public class TimestampsRegionImpl extends BaseRegionImpl implements TimestampsRegion { private final AdvancedCache timestampsPutCache; public TimestampsRegionImpl(AdvancedCache cache, String name, InfinispanRegionFactory factory) { super(cache, name, factory); // Skip locking when updating timestamps to provide better performance // under highly concurrent insert scenarios, where update timestamps // for an entity/collection type are constantly updated, creating // contention. // // The worst it can happen is that an earlier an earlier timestamp // (i.e. ts=1) will override a later on (i.e. ts=2), so it means that // in highly concurrent environments, queries might be considered stale // earlier in time. The upside is that inserts/updates are way faster // in local set ups. this.timestampsPutCache = getTimestampsPutCache(cache); } protected AdvancedCache getTimestampsPutCache(AdvancedCache cache) { return Caches.ignoreReturnValuesCache(cache, Flag.SKIP_LOCKING); } @Override public Object getFromCache(Object key, SharedSessionContractImplementor session) { if (checkValid()) { return cache.get(key); } return null; } @Override public void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) { try { timestampsPutCache.put(key, value); } catch (CacheException e) { throw e; } catch (Exception e) { throw new CacheException(e); } } }
1,979
35.666667
99
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/LocalInvalidationInvocation.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.concurrent.CompletableFuture; import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; /** * Synchronization that should release the locks after invalidation is complete. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class LocalInvalidationInvocation implements Invocation { private final static InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(LocalInvalidationInvocation.class); private final Object lockOwner; private final PutFromLoadValidator validator; private final Object key; public LocalInvalidationInvocation(PutFromLoadValidator validator, Object key, Object lockOwner) { assert lockOwner != null; this.validator = validator; this.key = key; this.lockOwner = lockOwner; } @Override public CompletableFuture<Void> invoke(boolean success) { if (log.isTraceEnabled()) { log.tracef("After completion callback, success=%b", success); } validator.endInvalidatingKey(lockOwner, key, success); return null; } }
1,441
33.333333
129
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/Sync.java
package org.infinispan.hibernate.cache.v62.impl; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import org.hibernate.cache.spi.CacheTransactionSynchronization; import org.hibernate.cache.spi.RegionFactory; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; public class Sync implements CacheTransactionSynchronization { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(Sync.class); private final RegionFactory regionFactory; private long transactionStartTimestamp; // to save some allocations we're storing everything in a single array private Object[] tasks; private int index; public Sync(RegionFactory regionFactory) { this.regionFactory = regionFactory; transactionStartTimestamp = regionFactory.nextTimestamp(); } public void registerBeforeCommit(CompletableFuture<?> future) { add(future); } public void registerAfterCommit(Invocation invocation) { assert !(invocation instanceof CompletableFuture) : "Invocation must not extend CompletableFuture"; add(invocation); } private void add(Object task) { log.tracef("Adding %08x %s", System.identityHashCode(task), task); if (tasks == null) { tasks = new Object[4]; } else if (index == tasks.length) { tasks = Arrays.copyOf(tasks, tasks.length * 2); } tasks[index++] = task; } @Override public long getCurrentTransactionStartTimestamp() { return transactionStartTimestamp; } @Override public long getCachingTimestamp() { return transactionStartTimestamp; } @Override public void transactionJoined() { transactionStartTimestamp = regionFactory.nextTimestamp(); } @Override public void transactionCompleting() { if (log.isTraceEnabled()) { int done = 0, notDone = 0; for (int i = 0; i < index; ++i) { Object task = tasks[i]; if (task instanceof CompletableFuture) { if (((CompletableFuture) task).isDone()) { done++; } else { notDone++; } } } log.tracef("%d tasks done, %d tasks not done yet", done, notDone); } int count = 0; for (int i = 0; i < index; ++i) { Object task = tasks[i]; if (task instanceof CompletableFuture) { log.tracef("Waiting for %08x %s", System.identityHashCode(task), task); try { ((CompletableFuture) task).join(); } catch (CompletionException e) { log.debugf("Unable to complete task %08x before commit, rethrow exception", System.identityHashCode(task)); throw e; } tasks[i] = null; ++count; } else { log.tracef("Not waiting for %08x %s", System.identityHashCode(task), task); } } if (log.isTraceEnabled()) { log.tracef("Finished %d tasks before completion", count); } } @Override public void transactionCompleted(boolean successful) { if (!successful) { // When the transaction is rolled back transactionCompleting() is not called, // so we could have some completable futures waiting. transactionCompleting(); } int invoked = 0, waiting = 0; for (int i = 0; i < index; ++i) { Object invocation = tasks[i]; if (invocation == null) { continue; } try { tasks[i] = ((Invocation) invocation).invoke(successful); } catch (Exception e) { log.failureAfterTransactionCompletion(i, successful, e); tasks[i] = null; } invoked++; } for (int i = 0; i < index; ++i) { CompletableFuture<?> cf = (CompletableFuture<?>) tasks[i]; if (cf != null) { try { cf.join(); } catch (Exception e) { log.failureAfterTransactionCompletion(i, successful, e); } waiting++; } } if (log.isTraceEnabled()) { log.tracef("Invoked %d tasks after completion, %d are synchronous.", invoked, waiting); } } }
4,357
31.522388
122
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/ClusteredTimestampsRegionImpl.java
package org.infinispan.hibernate.cache.v62.impl; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.hibernate.cache.CacheException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.context.Flag; import org.infinispan.hibernate.cache.commons.util.Caches; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; @Listener public class ClusteredTimestampsRegionImpl extends TimestampsRegionImpl { /** * Maintains a local (authoritative) cache of timestamps along with the * replicated cache held in Infinispan. It listens for changes in the * cache and updates the local cache accordingly. This approach allows * timestamp changes to be replicated asynchronously. */ private final Map localCache = new ConcurrentHashMap(); /** * Clustered timestamps region constructor. * * @param cache instance to store update timestamps * @param name of the update timestamps region * @param factory for the update timestamps region */ public ClusteredTimestampsRegionImpl( AdvancedCache cache, String name, InfinispanRegionFactory factory) { super(cache, name, factory); cache.addListener(this); populateLocalCache(); } @Override protected AdvancedCache getTimestampsPutCache(AdvancedCache cache) { return Caches.asyncWriteCache(cache, Flag.SKIP_LOCKING); } @Override @SuppressWarnings("unchecked") public Object getFromCache(Object key, SharedSessionContractImplementor session) { Object value = localCache.get(key); if (value == null && checkValid()) { value = cache.get(key); if (value != null) { localCache.put(key, value); } } return value; } @Override public void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) { updateLocalCache(key, value); super.putIntoCache(key, value, session); } @Override public void invalidateRegion() { // Invalidate first super.invalidateRegion(); localCache.clear(); } @Override public void destroy() throws CacheException { localCache.clear(); cache.removeListener(this); super.destroy(); } /** * Brings all data from the distributed cache into our local cache. */ private void populateLocalCache() { try (CloseableIterator iterator = cache.keySet().iterator()) { while (iterator.hasNext()) { getFromCache(iterator.next(), null); } } } /** * Monitors cache events and updates the local cache * * @param event The event */ @CacheEntryModified @SuppressWarnings({"unused", "unchecked"}) public void nodeModified(CacheEntryModifiedEvent event) { if (!event.isPre()) { updateLocalCache(event.getKey(), event.getValue()); } } /** * Monitors cache events and updates the local cache * * @param event The event */ @CacheEntryRemoved @SuppressWarnings("unused") public void nodeRemoved(CacheEntryRemovedEvent event) { if (event.isPre()) { return; } localCache.remove(event.getKey()); } // TODO: with recent Infinispan we should access the cache directly private void updateLocalCache(Object key, Object value) { localCache.compute(key, (k, v) -> { if (v instanceof Number && value instanceof Number) { return Math.max(((Number) v).longValue(), ((Number) value).longValue()); } else { return value; } }); } }
4,107
29.887218
97
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/QueryResultsRegionImpl.java
package org.infinispan.hibernate.cache.v62.impl; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.QueryResultsRegion; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.AdvancedCache; import org.infinispan.context.Flag; import org.infinispan.hibernate.cache.commons.util.Caches; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; public final class QueryResultsRegionImpl extends BaseRegionImpl implements QueryResultsRegion { private final AdvancedCache<Object, Object> putCache; private final AdvancedCache<Object, Object> getCache; private final ConcurrentMap<Object, Map> transactionContext = new ConcurrentHashMap<>(); /** * Query region constructor * * @param cache instance to store queries * @param name of the query region * @param factory for the query region */ public QueryResultsRegionImpl(AdvancedCache cache, String name, InfinispanRegionFactory factory) { super(cache, name, factory); // If Infinispan is using INVALIDATION for query cache, we don't want to propagate changes. // We use the Timestamps cache to manage invalidation final boolean localOnly = Caches.isInvalidationCache(cache); this.putCache = localOnly ? Caches.failSilentWriteCache(cache, Flag.CACHE_MODE_LOCAL) : Caches.failSilentWriteCache(cache); this.getCache = Caches.failSilentReadCache(cache); } @Override public void clear() throws CacheException { transactionContext.clear(); // Invalidate the local region and then go remote invalidateRegion(); Caches.broadcastEvictAll(cache); } @Override public Object getFromCache(Object key, SharedSessionContractImplementor session) { if (!checkValid()) { return null; } // In Infinispan get doesn't acquire any locks, so no need to suspend the tx. // In the past, when get operations acquired locks, suspending the tx was a way // to avoid holding locks that would prevent updates. // Add a zero (or low) timeout option so we don't block // waiting for tx's that did a put to commit Object result = null; Map map = transactionContext.get(session); if (map != null) { result = map.get(key); } if (result == null) { result = getCache.get(key); } return result; } @Override public void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) { if (!checkValid()) { return; } // See HHH-7898: Even with FAIL_SILENTLY flag, failure to write in transaction // fails the whole transaction. It is an Infinispan quirk that cannot be fixed // ISPN-5356 tracks that. This is because if the transaction continued the // value could be committed on backup owners, including the failed operation, // and the result would not be consistent. Sync sync = (Sync) session.getCacheTransactionSynchronization(); if (sync != null && session.isTransactionInProgress()) { sync.registerAfterCommit(new PostTransactionQueryUpdate(session, key, value)); // no need to synchronize as the transaction will be accessed by only one thread transactionContext.computeIfAbsent(session, k -> new HashMap<>()).put(key, value); } else { putCache.put(key, value); } } private class PostTransactionQueryUpdate implements Invocation { private final Object session; private final Object key; private final Object value; PostTransactionQueryUpdate(Object session, Object key, Object value) { this.session = session; this.key = key; this.value = value; } @Override public CompletableFuture<Object> invoke(boolean success) { transactionContext.remove(session); if (success) { return putCache.putAsync(key, value); } else { return null; } } } }
4,248
36.27193
101
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/BaseRegionImpl.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.Map; import java.util.function.Predicate; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.ExtendedStatisticsSupport; import org.hibernate.cache.spi.Region; import org.hibernate.stat.CacheRegionStatistics; import org.infinispan.AdvancedCache; import org.infinispan.context.Flag; import org.infinispan.hibernate.cache.commons.InfinispanBaseRegion; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; /** * Support for Infinispan {@link Region}s. Handles common "utility" methods for an underlying named * Cache. In other words, this implementation doesn't actually read or write data. Subclasses are * expected to provide core cache interaction appropriate to the semantics needed. * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ abstract class BaseRegionImpl implements Region, InfinispanBaseRegion, ExtendedStatisticsSupport { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(BaseRegionImpl.class); private final String name; private final AdvancedCache localAndSkipLoadCache; final AdvancedCache cache; final InfinispanRegionFactory factory; private volatile long lastRegionInvalidation = Long.MIN_VALUE; private int invalidations = 0; Predicate<Map.Entry<Object, Object>> filter; /** * Base region constructor. * * @param cache instance for the region * @param name of the region * @param factory for this region */ BaseRegionImpl(AdvancedCache cache, String name, InfinispanRegionFactory factory) { this.cache = cache; this.name = name; this.factory = factory; this.localAndSkipLoadCache = cache.withFlags( Flag.CACHE_MODE_LOCAL, Flag.FAIL_SILENTLY, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, Flag.SKIP_CACHE_LOAD ); } @Override public String getName() { return name; } @Override public long nextTimestamp() { return factory.nextTimestamp(); } @Override public void destroy() throws CacheException { cache.stop(); } /** * Checks if the region is valid for operations such as storing new data * in the region, or retrieving data from the region. * * @return true if the region is valid, false otherwise */ @Override public boolean checkValid() { return lastRegionInvalidation != Long.MAX_VALUE; } @Override public void clear() { invalidateRegion(); } @Override public void beginInvalidation() { if (log.isTraceEnabled()) { log.trace("Begin invalidating region: " + name); } synchronized (this) { lastRegionInvalidation = Long.MAX_VALUE; ++invalidations; } runInvalidation(); } @Override public void endInvalidation() { synchronized (this) { if (--invalidations == 0) { lastRegionInvalidation = factory.nextTimestamp(); } } if (log.isTraceEnabled()) { log.trace("End invalidating region: " + name); } } @Override public long getLastRegionInvalidation() { return lastRegionInvalidation; } @Override public AdvancedCache getCache() { return cache; } protected void runInvalidation() { log.tracef("Non-transactional, clear in one go"); localAndSkipLoadCache.clear(); } @Override public InfinispanRegionFactory getRegionFactory() { return factory; } @Override public long getElementCountInMemory() { if (filter == null) { return localAndSkipLoadCache.size(); } else { return localAndSkipLoadCache.entrySet().stream().filter(filter).count(); } } @Override public long getElementCountOnDisk() { return CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN; } @Override public long getSizeInMemory() { return CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN; } }
4,378
26.71519
116
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/UpsertInvocation.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.concurrent.CompletableFuture; import org.infinispan.functional.FunctionalMap; import org.infinispan.hibernate.cache.commons.util.VersionedEntry; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class UpsertInvocation implements Invocation { private final FunctionalMap.ReadWriteMap<Object, Object> rwMap; private final Object key; private final VersionedEntry versionedEntry; public UpsertInvocation(FunctionalMap.ReadWriteMap<Object, Object> rwMap, Object key, VersionedEntry versionedEntry) { this.rwMap = rwMap; this.key = key; this.versionedEntry = versionedEntry; } @Override public CompletableFuture<Void> invoke(boolean success) { if (success) { return rwMap.eval(key, versionedEntry); } else { return null; } } }
1,122
29.351351
121
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/DomainDataRegionImpl.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.hibernate.cache.cfg.spi.CollectionDataCachingConfig; import org.hibernate.cache.cfg.spi.DomainDataCachingConfig; import org.hibernate.cache.cfg.spi.DomainDataRegionConfig; import org.hibernate.cache.cfg.spi.EntityDataCachingConfig; import org.hibernate.cache.cfg.spi.NaturalIdDataCachingConfig; import org.hibernate.cache.spi.CacheKeysFactory; import org.hibernate.cache.spi.DomainDataRegion; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.CollectionDataAccess; import org.hibernate.cache.spi.access.EntityDataAccess; import org.hibernate.cache.spi.access.NaturalIdDataAccess; import org.hibernate.metamodel.model.domain.NavigableRole; import org.infinispan.AdvancedCache; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.context.Flag; import org.infinispan.expiration.impl.ClusterExpirationManager; import org.infinispan.expiration.impl.ExpirationManagerImpl; import org.infinispan.expiration.impl.InternalExpirationManager; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.functional.MetaParam; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.access.AccessDelegate; import org.infinispan.hibernate.cache.commons.access.LockingInterceptor; import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator; import org.infinispan.hibernate.cache.commons.access.UnorderedDistributionInterceptor; import org.infinispan.hibernate.cache.commons.access.UnorderedReplicationLogic; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; import org.infinispan.hibernate.cache.commons.util.Tombstone; import org.infinispan.hibernate.cache.commons.util.VersionedEntry; import org.infinispan.hibernate.cache.v62.InfinispanRegionFactory; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.distribution.NonTxDistributionInterceptor; import org.infinispan.interceptors.distribution.TriangleDistributionInterceptor; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor; /** * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public class DomainDataRegionImpl extends BaseRegionImpl implements DomainDataRegion, InfinispanDataRegion { private static final InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(DomainDataRegionImpl.class); private final CacheKeysFactory cacheKeysFactory; private final DomainDataRegionConfig config; private final AdvancedCache<Object, Object> localCache; private final Map<String, Comparator<Object>> comparatorsByType = new HashMap<>(); private long tombstoneExpiration; private PutFromLoadValidator validator; private Strategy strategy; private MetaParam.MetaLifespan expiringMetaParam; protected enum Strategy { NONE, VALIDATION, TOMBSTONES, VERSIONED_ENTRIES } public DomainDataRegionImpl(AdvancedCache cache, DomainDataRegionConfig config, InfinispanRegionFactory factory, CacheKeysFactory cacheKeysFactory) { super(cache, config.getRegionName(), factory); this.config = config; this.cacheKeysFactory = cacheKeysFactory; localCache = cache.withFlags(Flag.CACHE_MODE_LOCAL); tombstoneExpiration = factory.getPendingPutsCacheConfiguration().expiration().maxIdle(); expiringMetaParam = new MetaParam.MetaLifespan(tombstoneExpiration); } @Override public EntityDataAccess getEntityDataAccess(NavigableRole rootEntityRole) { EntityDataCachingConfig entityConfig = findConfig(config.getEntityCaching(), rootEntityRole); AccessType accessType = entityConfig.getAccessType(); AccessDelegate accessDelegate = createAccessDelegate(accessType, entityConfig.isVersioned() ? entityConfig.getVersionComparatorAccess().get() : null); if (accessType == AccessType.READ_ONLY || !entityConfig.isMutable()) { return new ReadOnlyEntityDataAccess(accessType, accessDelegate, this); } else { return new ReadWriteEntityDataAccess(accessType, accessDelegate, this); } } @Override public NaturalIdDataAccess getNaturalIdDataAccess(NavigableRole rootEntityRole) { NaturalIdDataCachingConfig naturalIdConfig = findConfig(this.config.getNaturalIdCaching(), rootEntityRole); AccessType accessType = naturalIdConfig.getAccessType(); if (accessType == AccessType.NONSTRICT_READ_WRITE) { // We don't support nonstrict read write for natural ids as NSRW requires versions; // natural ids aren't versioned by definition (as the values are primary keys). accessType = AccessType.READ_WRITE; } AccessDelegate accessDelegate = createAccessDelegate(accessType, null); if (accessType == AccessType.READ_ONLY || !naturalIdConfig.isMutable()) { return new ReadOnlyNaturalDataAccess(accessType, accessDelegate, this); } else { return new ReadWriteNaturalDataAccess(accessType, accessDelegate, this); } } @Override public CollectionDataAccess getCollectionDataAccess(NavigableRole collectionRole) { CollectionDataCachingConfig collectionConfig = findConfig(this.config.getCollectionCaching(), collectionRole); AccessType accessType = collectionConfig.getAccessType(); AccessDelegate accessDelegate = createAccessDelegate(accessType, collectionConfig.getOwnerVersionComparator()); return new CollectionDataAccessImpl(this, accessDelegate, accessType); } private <T extends DomainDataCachingConfig> T findConfig(List<T> configs, NavigableRole role) { return configs.stream() .filter(c -> c.getNavigableRole().equals(role)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Cannot find configuration for " + role)); } public CacheKeysFactory getCacheKeysFactory() { return cacheKeysFactory; } private synchronized AccessDelegate createAccessDelegate(AccessType accessType, Comparator<Object> comparator) { CacheMode cacheMode = cache.getCacheConfiguration().clustering().cacheMode(); if (accessType == AccessType.NONSTRICT_READ_WRITE) { prepareForVersionedEntries(cacheMode); return new NonStrictAccessDelegate(this, comparator); } if (cacheMode.isDistributed() || cacheMode.isReplicated()) { prepareForTombstones(cacheMode); return new TombstoneAccessDelegate(this); } else { prepareForValidation(); return new NonTxInvalidationCacheAccessDelegate(this, validator); } } private void prepareForValidation() { if (strategy != null) { assert strategy == Strategy.VALIDATION; return; } validator = new PutFromLoadValidator(cache, factory, factory.getPendingPutsCacheConfiguration()); strategy = Strategy.VALIDATION; } private void prepareForVersionedEntries(CacheMode cacheMode) { if (strategy != null) { assert strategy == Strategy.VERSIONED_ENTRIES; return; } prepareCommon(cacheMode); filter = VersionedEntry.EXCLUDE_EMPTY_VERSIONED_ENTRY; for (EntityDataCachingConfig entityConfig : config.getEntityCaching()) { if (entityConfig.isVersioned()) { for (NavigableRole role : entityConfig.getCachedTypes()) { comparatorsByType.put(role.getNavigableName(), entityConfig.getVersionComparatorAccess().get()); } } } for (CollectionDataCachingConfig collectionConfig : config.getCollectionCaching()) { if (collectionConfig.isVersioned()) { comparatorsByType.put(collectionConfig.getNavigableRole().getNavigableName(), collectionConfig.getOwnerVersionComparator()); } } strategy = Strategy.VERSIONED_ENTRIES; } private void prepareForTombstones(CacheMode cacheMode) { if (strategy != null) { assert strategy == Strategy.TOMBSTONES; return; } Configuration configuration = cache.getCacheConfiguration(); if (configuration.memory().isEvictionEnabled()) { log.evictionWithTombstones(); } prepareCommon(cacheMode); filter = Tombstone.EXCLUDE_TOMBSTONES; strategy = Strategy.TOMBSTONES; } private void prepareCommon(CacheMode cacheMode) { BasicComponentRegistry registry = cache.getComponentRegistry().getComponent(BasicComponentRegistry.class); if (cacheMode.isReplicated() || cacheMode.isDistributed()) { AsyncInterceptorChain chain = cache.getAsyncInterceptorChain(); LockingInterceptor lockingInterceptor = new LockingInterceptor(); registry.registerComponent(LockingInterceptor.class, lockingInterceptor, true); registry.getComponent(LockingInterceptor.class).running(); if (!chain.addInterceptorBefore(lockingInterceptor, NonTransactionalLockingInterceptor.class)) { throw new IllegalStateException("Misconfigured cache, interceptor chain is " + chain); } chain.removeInterceptor(NonTransactionalLockingInterceptor.class); UnorderedDistributionInterceptor distributionInterceptor = new UnorderedDistributionInterceptor(); registry.registerComponent(UnorderedDistributionInterceptor.class, distributionInterceptor, true); registry.getComponent(UnorderedDistributionInterceptor.class).running(); if (!chain.addInterceptorBefore(distributionInterceptor, NonTxDistributionInterceptor.class) && !chain.addInterceptorBefore(distributionInterceptor, TriangleDistributionInterceptor.class)) { throw new IllegalStateException("Misconfigured cache, interceptor chain is " + chain); } chain.removeInterceptor(NonTxDistributionInterceptor.class); chain.removeInterceptor(TriangleDistributionInterceptor.class); } // ClusteredExpirationManager sends RemoteExpirationCommands to remote nodes which causes // undesired overhead. When get() triggers a RemoteExpirationCommand executed in async executor // this locks the entry for the duration of RPC, and putFromLoad with ZERO_LOCK_ACQUISITION_TIMEOUT // fails as it finds the entry being blocked. ComponentRef<InternalExpirationManager> ref = registry.getComponent(InternalExpirationManager.class); InternalExpirationManager expirationManager = ref.running(); if (expirationManager instanceof ClusterExpirationManager) { registry.replaceComponent(InternalExpirationManager.class.getName(), new ExpirationManagerImpl<>(), true); registry.getComponent(InternalExpirationManager.class).running(); registry.rewire(); // re-registering component does not stop the old one ((ClusterExpirationManager) expirationManager).stop(); } else if (expirationManager instanceof ExpirationManagerImpl) { // do nothing } else { throw new IllegalStateException("Expected clustered expiration manager, found " + expirationManager); } registry.registerComponent(InfinispanDataRegion.class, this, true); if (cacheMode.isClustered()) { UnorderedReplicationLogic replLogic = new UnorderedReplicationLogic(); registry.replaceComponent(ClusteringDependentLogic.class.getName(), replLogic, true); registry.getComponent(ClusteringDependentLogic.class).running(); registry.rewire(); } } public long getTombstoneExpiration() { return tombstoneExpiration; } @Override public MetaParam.MetaLifespan getExpiringMetaParam() { return expiringMetaParam; } @Override public Comparator<Object> getComparator(String subclass) { return comparatorsByType.get(subclass); } @Override protected void runInvalidation() { if (strategy == null) { throw new IllegalStateException("Strategy was not set"); } switch (strategy) { case NONE: case VALIDATION: super.runInvalidation(); return; case TOMBSTONES: removeEntries(entry -> localCache.remove(entry.getKey(), entry.getValue())); return; case VERSIONED_ENTRIES: // no need to use this as a function - simply override all VersionedEntry evict = new VersionedEntry(factory.nextTimestamp()); removeEntries(entry -> localCache.put(entry.getKey(), evict, tombstoneExpiration, TimeUnit.MILLISECONDS)); return; } } private void removeEntries(Consumer<Map.Entry<Object, Object>> remover) { // We can never use cache.clear() since tombstones must be kept. localCache.entrySet().stream().filter(filter).forEach(remover); } @Override public void destroy() throws CacheException { super.destroy(); if (validator != null) { validator.destroy(); } } // exposed just to help tests public DomainDataRegionConfig config() { return config; } }
13,784
43.61165
136
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/InvalidationInvocation.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.concurrent.CompletableFuture; import org.infinispan.hibernate.cache.commons.access.NonTxPutFromLoadInterceptor; import org.infinispan.hibernate.cache.commons.util.InfinispanMessageLogger; /** * Synchronization that should release the locks after invalidation is complete. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class InvalidationInvocation implements Invocation { private final static InfinispanMessageLogger log = InfinispanMessageLogger.Provider.getLog(InvalidationInvocation.class); private final Object lockOwner; private final NonTxPutFromLoadInterceptor nonTxPutFromLoadInterceptor; private final Object key; public InvalidationInvocation(NonTxPutFromLoadInterceptor nonTxPutFromLoadInterceptor, Object key, Object lockOwner) { assert lockOwner != null; this.nonTxPutFromLoadInterceptor = nonTxPutFromLoadInterceptor; this.key = key; this.lockOwner = lockOwner; } @Override public CompletableFuture<Void> invoke(boolean success) { if (log.isTraceEnabled()) { log.tracef("After completion callback, success=%b", success); } nonTxPutFromLoadInterceptor.endInvalidating(key, lockOwner, success); return null; } }
1,534
35.547619
124
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/ReadOnlyNaturalDataAccess.java
package org.infinispan.hibernate.cache.v62.impl; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.NaturalIdDataAccess; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.persister.entity.EntityPersister; import org.infinispan.hibernate.cache.commons.access.AccessDelegate; class ReadOnlyNaturalDataAccess extends AbstractAccess implements NaturalIdDataAccess { ReadOnlyNaturalDataAccess(AccessType accessType, AccessDelegate delegate, DomainDataRegionImpl region) { super(accessType, delegate, region); } @Override public boolean insert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException { return delegate.insert(session, key, value, null); } @Override public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value) throws CacheException { return delegate.afterInsert(session, key, value, null); } @Override public boolean update(SharedSessionContractImplementor session, Object key, Object value) throws CacheException { throw new UnsupportedOperationException("Illegal attempt to edit read only item"); } @Override public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, SoftLock lock) throws CacheException { return delegate.afterUpdate(session, key, value, null, null, lock); } @Override public Object get(SharedSessionContractImplementor session, Object key) throws CacheException { return delegate.get(session, key, session.getCacheTransactionSynchronization().getCachingTimestamp()); } @Override public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException { return delegate.putFromLoad(session, key, value, session.getCacheTransactionSynchronization().getCachingTimestamp(), version); } @Override public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, Object version, boolean minimalPutOverride) throws CacheException { return delegate.putFromLoad(session, key, value, session.getCacheTransactionSynchronization().getCachingTimestamp(), version, minimalPutOverride); } @Override public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException { return null; } @Override public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException { delegate.unlockItem(session, key); } @Override public void remove(SharedSessionContractImplementor session, Object key) throws CacheException { delegate.remove(session, key); } @Override public Object generateCacheKey(Object naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) { return region.getCacheKeysFactory().createNaturalIdKey(naturalIdValues, persister, session); } @Override public Object getNaturalIdValues(Object cacheKey) { return region.getCacheKeysFactory().getNaturalIdValues(cacheKey); } }
3,282
41.636364
165
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/CollectionDataAccessImpl.java
package org.infinispan.hibernate.cache.v62.impl; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.CollectionDataAccess; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.persister.collection.CollectionPersister; import org.infinispan.hibernate.cache.commons.access.AccessDelegate; public class CollectionDataAccessImpl extends AbstractAccess implements CollectionDataAccess { public CollectionDataAccessImpl(DomainDataRegionImpl region, AccessDelegate delegate, AccessType accessType) { super(accessType, delegate, region); } @Override public Object get(SharedSessionContractImplementor session, Object key) { return delegate.get(session, key, session.getCacheTransactionSynchronization().getCachingTimestamp()); } @Override public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, Object version) { return delegate.putFromLoad(session, key, value, session.getCacheTransactionSynchronization().getCachingTimestamp(), version); } @Override public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, Object version, boolean minimalPutOverride) { return delegate.putFromLoad(session, key, value, session.getCacheTransactionSynchronization().getCachingTimestamp(), version, minimalPutOverride); } @Override public void remove(SharedSessionContractImplementor session, Object key) throws CacheException { delegate.remove(session, key); } @Override public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException { return null; } @Override public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException { delegate.unlockItem(session, key); } @Override public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { return region.getCacheKeysFactory().createCollectionKey(id, persister, factory, tenantIdentifier); } @Override public Object getCacheKeyId(Object cacheKey) { return region.getCacheKeysFactory().getCollectionId(cacheKey); } }
2,454
40.610169
152
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/NonStrictAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.Comparator; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.util.VersionedEntry; /** * Access delegate that relaxes the consistency a bit: stale reads are prohibited only after the transaction * commits. This should also be able to work with async caches, and that would allow the replication delay * even after the commit. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class NonStrictAccessDelegate extends org.infinispan.hibernate.cache.commons.access.NonStrictAccessDelegate { public NonStrictAccessDelegate(InfinispanDataRegion region, Comparator versionComparator) { super(region, versionComparator); } @Override public void remove(Object session, Object key) throws CacheException { Sync sync = (Sync) ((SharedSessionContractImplementor) session).getCacheTransactionSynchronization(); sync.registerAfterCommit(new RemovalInvocation(writeMap, region, key)); } @Override public boolean insert(Object session, Object key, Object value, Object version) throws CacheException { // in order to leverage asynchronous execution we won't execute the updates in afterInsert/afterUpdate // but register our own synchronization (exchange allocation for latency) Sync sync = (Sync) ((SharedSessionContractImplementor) session).getCacheTransactionSynchronization(); sync.registerAfterCommit(new UpsertInvocation(writeMap, key, new VersionedEntry(value, version, sync.getCachingTimestamp()))); return false; } @Override public boolean update(Object session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { // in order to leverage asynchronous execution we won't execute the updates in afterInsert/afterUpdate // but register our own synchronization (exchange allocation for latency) Sync sync = (Sync) ((SharedSessionContractImplementor) session).getCacheTransactionSynchronization(); sync.registerAfterCommit(new UpsertInvocation(writeMap, key, new VersionedEntry(value, currentVersion, sync.getCachingTimestamp()))); return false; } @Override public boolean afterInsert(Object session, Object key, Object value, Object version) { // We have not modified the cache yet but in order to update stats we need to say we did return true; } @Override public boolean afterUpdate(Object session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) { // We have not modified the cache yet but in order to update stats we need to say we did return true; } }
3,132
47.2
139
java
null
infinispan-main/hibernate/cache-v62/src/main/java/org/infinispan/hibernate/cache/v62/impl/NonTxInvalidationCacheAccessDelegate.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.hibernate.cache.v62.impl; import java.util.concurrent.CompletableFuture; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.hibernate.cache.commons.InfinispanDataRegion; import org.infinispan.hibernate.cache.commons.access.PutFromLoadValidator; /** * Delegate for non-transactional invalidation caches * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ class NonTxInvalidationCacheAccessDelegate extends org.infinispan.hibernate.cache.commons.access.NonTxInvalidationCacheAccessDelegate { public NonTxInvalidationCacheAccessDelegate(InfinispanDataRegion region, PutFromLoadValidator validator) { super(region, validator); } @Override protected void registerLocalInvalidation(Object session, Object lockOwner, Object key) { Sync sync = (Sync) ((SharedSessionContractImplementor) session).getCacheTransactionSynchronization(); if (log.isTraceEnabled()) { log.tracef("Registering synchronization on transaction in %s, cache %s: %s", lockOwner, cache.getName(), key); } sync.registerAfterCommit(new LocalInvalidationInvocation(putValidator, key, lockOwner)); } @Override protected void registerClusteredInvalidation(Object session, Object lockOwner, Object key) { Sync sync = (Sync) ((SharedSessionContractImplementor) session).getCacheTransactionSynchronization(); if (log.isTraceEnabled()) { log.tracef("Registering synchronization on transaction in %s, cache %s: %s", lockOwner, cache.getName(), key); } sync.registerAfterCommit(new InvalidationInvocation(nonTxPutFromLoadInterceptor, key, lockOwner)); } @Override protected void invoke(Object session, InvocationContext ctx, RemoveCommand command) { CompletableFuture<Object> future = invoker.invokeAsync(ctx, command); // LockingInterceptor removes this flag when the command is applied and we only wait for RPC if (!command.hasAnyFlag(FlagBitSets.FORCE_WRITE_LOCK)) { Sync sync = (Sync) ((SharedSessionContractImplementor) session).getCacheTransactionSynchronization(); sync.registerBeforeCommit(future); } else { log.trace("Removal was not applied immediately, waiting."); future.join(); } } }
2,676
44.372881
135
java
null
infinispan-main/hibernate/cache-spi/src/main/java/org/infinispan/hibernate/cache/spi/EmbeddedCacheManagerProvider.java
package org.infinispan.hibernate.cache.spi; import java.util.Properties; import org.infinispan.manager.EmbeddedCacheManager; /** * Supplies an {@link EmbeddedCacheManager} for use by Infinispan implementation * of the {@link org.hibernate.cache.spi.RegionFactory}. * * @author Paul Ferraro * @since 9.2 */ public interface EmbeddedCacheManagerProvider { /** * Returns a {@link EmbeddedCacheManager} given the specified configuration properties. * @param properties configuration properties * @return a started cache manager. */ EmbeddedCacheManager getEmbeddedCacheManager(Properties properties); }
630
27.681818
90
java
null
infinispan-main/hibernate/cache-spi/src/main/java/org/infinispan/hibernate/cache/spi/InfinispanProperties.java
package org.infinispan.hibernate.cache.spi; import org.infinispan.manager.EmbeddedCacheManager; public interface InfinispanProperties { String PREFIX = "hibernate.cache.infinispan."; String CONFIG_SUFFIX = ".cfg"; String DEPRECATED_STRATEGY_SUFFIX = ".eviction.strategy"; String SIZE_SUFFIX = ".memory.size"; // The attribute was incorrectly named; in fact this sets expiration check interval // (eviction is triggered by writes, expiration is time-based) String DEPRECATED_WAKE_UP_INTERVAL_SUFFIX = ".eviction.wake_up_interval"; String DEPRECATED_MAX_ENTRIES_SUFFIX = ".eviction.max_entries"; String WAKE_UP_INTERVAL_SUFFIX = ".expiration.wake_up_interval"; String LIFESPAN_SUFFIX = ".expiration.lifespan"; String MAX_IDLE_SUFFIX = ".expiration.max_idle"; String ENTITY = "entity"; String NATURAL_ID = "naturalid"; String COLLECTION = "collection"; String IMMUTABLE_ENTITY = "immutable-entity"; String TIMESTAMPS = "timestamps"; String QUERY = "query"; String PENDING_PUTS = "pending-puts"; /** * Classpath or filesystem resource containing Infinispan configurations the factory should use. * * @see #DEF_INFINISPAN_CONFIG_RESOURCE */ String INFINISPAN_CONFIG_RESOURCE_PROP = "hibernate.cache.infinispan.cfg"; /** * Property name that controls whether Infinispan statistics are enabled. * The property value is expected to be a boolean true or false, and it * overrides statistic configuration in base Infinispan configuration, * if provided. */ String INFINISPAN_GLOBAL_STATISTICS_PROP = "hibernate.cache.infinispan.statistics"; /** * Property that controls whether Infinispan should interact with the * transaction manager as a {@link javax.transaction.Synchronization} or as * an XA resource. * @deprecated Infinispan Second Level Cache is designed to always register as synchronization * on transactional caches, or use non-transactional caches. * * @see #DEF_USE_SYNCHRONIZATION */ @Deprecated String INFINISPAN_USE_SYNCHRONIZATION_PROP = "hibernate.cache.infinispan.use_synchronization"; /** * Name of the configuration that should be used for natural id caches. * * @see #DEF_ENTITY_RESOURCE */ @SuppressWarnings("UnusedDeclaration") String NATURAL_ID_CACHE_RESOURCE_PROP = PREFIX + NATURAL_ID + CONFIG_SUFFIX; /** * Name of the configuration that should be used for entity caches. * * @see #DEF_ENTITY_RESOURCE */ @SuppressWarnings("UnusedDeclaration") String ENTITY_CACHE_RESOURCE_PROP = PREFIX + ENTITY + CONFIG_SUFFIX; /** * Name of the configuration that should be used for immutable entity caches. * Defaults to the same configuration as {@link #ENTITY_CACHE_RESOURCE_PROP} - {@link #DEF_ENTITY_RESOURCE} */ @SuppressWarnings("UnusedDeclaration") String IMMUTABLE_ENTITY_CACHE_RESOURCE_PROP = PREFIX + IMMUTABLE_ENTITY + CONFIG_SUFFIX; /** * Name of the configuration that should be used for collection caches. * No default value, as by default we try to use the same Infinispan cache * instance we use for entity caching. * * @see #ENTITY_CACHE_RESOURCE_PROP * @see #DEF_ENTITY_RESOURCE */ @SuppressWarnings("UnusedDeclaration") String COLLECTION_CACHE_RESOURCE_PROP = PREFIX + COLLECTION + CONFIG_SUFFIX; /** * Name of the configuration that should be used for timestamp caches. * * @see #DEF_TIMESTAMPS_RESOURCE */ @SuppressWarnings("UnusedDeclaration") String TIMESTAMPS_CACHE_RESOURCE_PROP = PREFIX + TIMESTAMPS + CONFIG_SUFFIX; /** * Name of the configuration that should be used for query caches. * * @see #DEF_QUERY_RESOURCE */ String QUERY_CACHE_RESOURCE_PROP = PREFIX + QUERY + CONFIG_SUFFIX; /** * Name of the configuration that should be used for pending-puts caches. * * @see #DEF_PENDING_PUTS_RESOURCE */ @SuppressWarnings("UnusedDeclaration") String PENDING_PUTS_CACHE_RESOURCE_PROP = PREFIX + PENDING_PUTS + CONFIG_SUFFIX; /** * Default value for {@link #INFINISPAN_CONFIG_RESOURCE_PROP}. Specifies the "infinispan-configs.xml" file in this package. */ String DEF_INFINISPAN_CONFIG_RESOURCE = "org/infinispan/hibernate/cache/commons/builder/infinispan-configs.xml"; /** * Default configuration for cases where non-clustered cache manager is provided. */ String INFINISPAN_CONFIG_LOCAL_RESOURCE = "org/infinispan/hibernate/cache/commons/builder/infinispan-configs-local.xml"; /** * Default value for {@link #ENTITY_CACHE_RESOURCE_PROP}. */ String DEF_ENTITY_RESOURCE = "entity"; /** * Default value for {@link #TIMESTAMPS_CACHE_RESOURCE_PROP}. */ String DEF_TIMESTAMPS_RESOURCE = "timestamps"; /** * Default value for {@link #QUERY_CACHE_RESOURCE_PROP}. */ String DEF_QUERY_RESOURCE = "local-query"; /** * Default value for {@link #PENDING_PUTS_CACHE_RESOURCE_PROP} */ String DEF_PENDING_PUTS_RESOURCE = "pending-puts"; /** * @deprecated Use {@link #DEF_PENDING_PUTS_RESOURCE} instead. */ @Deprecated String PENDING_PUTS_CACHE_NAME = DEF_PENDING_PUTS_RESOURCE; /** * Default value for {@link #INFINISPAN_USE_SYNCHRONIZATION_PROP}. */ boolean DEF_USE_SYNCHRONIZATION = true; /** * Specifies the JNDI name under which the {@link EmbeddedCacheManager} to use is bound. * There is no default value -- the user must specify the property. */ String CACHE_MANAGER_RESOURCE_PROP = "hibernate.cache.infinispan.cachemanager"; }
5,646
33.018072
126
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EmbeddedHotRodCacheListenerTest.java
package org.infinispan.it.endpoints; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test cache listeners bound to embedded cache and operation over HotRod cache. * * @author Jiri Holusa [jholusa@redhat.com] */ @Test(groups = "functional", testName = "it.endpoints.EmbeddedHotRodCacheListenerTest") public class EmbeddedHotRodCacheListenerTest extends AbstractInfinispanTest { EndpointsCacheFactory<String, String> cacheFactory; @BeforeMethod protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<String, String>().withCacheMode(CacheMode.LOCAL).build(); } @AfterMethod protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } public void testLoadingAndStoringEventsHotRod1() { Cache<String, String> embedded = cacheFactory.getEmbeddedCache(); RemoteCache<String, String> remote = cacheFactory.getHotRodCache(); TestCacheListener l = new TestCacheListener(); embedded.addListener(l); assertTrue(l.created.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.visited.isEmpty()); remote.put("k", "v"); assertEquals(1, l.createdCounter); assertEquals("v", l.created.get("k")); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.visited.isEmpty()); remote.put("key", "value"); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.visited.isEmpty()); remote.put("key", "modifiedValue"); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertEquals(1, l.modifiedCounter); assertEquals("modifiedValue", l.modified.get("key")); assertTrue(l.visited.isEmpty()); remote.replace("k", "replacedValue"); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertEquals(2, l.modifiedCounter); assertEquals("replacedValue", l.modified.get("k")); assertTrue(l.visited.isEmpty()); //resetting so don't have to type "== 2" etc. all over again l.reset(); Set<String> keys = new HashSet<>(); keys.add("k"); keys.add("key"); Map<String, String> results = remote.getAll(keys); assertTrue(l.created.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertEquals(2, l.visitedCounter); assertEquals("replacedValue", l.visited.get("k")); assertEquals("modifiedValue", l.visited.get("key")); l.reset(); remote.remove("key"); assertTrue(l.created.isEmpty()); assertEquals(1, l.removedCounter); assertEquals("modifiedValue", l.removed.get("key")); assertTrue(l.modified.isEmpty()); l.reset(); String value = remote.get("k"); assertTrue(l.created.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertEquals(1, l.visitedCounter); assertEquals("replacedValue", l.visited.get("k")); l.reset(); } public void testLoadingAndStoringEventsHotRod2() { Cache<String, String> embedded = cacheFactory.getEmbeddedCache(); RemoteCache<String, String> remote = cacheFactory.getHotRodCache(); TestCacheListener l = new TestCacheListener(); embedded.addListener(l); Map<String, String> tmp = new HashMap<String, String>(); tmp.put("key", "value"); tmp.put("key2", "value2"); remote.putAll(tmp); assertEquals(2, l.createdCounter); //one event for every put assertEquals("value", l.created.get("key")); assertEquals("value2", l.created.get("key2")); assertTrue(l.modified.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.visited.isEmpty()); l.reset(); remote.putIfAbsent("newKey", "newValue"); assertEquals(1, l.createdCounter); assertEquals("newValue", l.created.get("newKey")); assertTrue(l.modified.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.visited.isEmpty()); l.reset(); remote.putIfAbsent("newKey", "shouldNotBeAdded"); assertTrue(l.created.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.removed.isEmpty()); l.reset(); } public void testLoadingAndStoringWithVersionEventsHotRod() { Cache<String, String> embedded = cacheFactory.getEmbeddedCache(); RemoteCache<String, String> remote = cacheFactory.getHotRodCache(); TestCacheListener l = new TestCacheListener(); embedded.addListener(l); remote.put("key", "value"); VersionedValue oldVersionedValue = remote.getWithMetadata("key"); assertEquals("value", oldVersionedValue.getValue()); assertEquals(1, l.createdCounter); assertTrue(l.modified.isEmpty()); assertTrue(l.removed.isEmpty()); assertEquals(1, l.visitedCounter); assertEquals("value", l.visited.get("key")); remote.put("key2", "value2"); remote.put("key", "outOfVersionValue"); VersionedValue newVersionedValue = remote.getWithMetadata("key2"); l.reset(); remote.removeWithVersion("key", oldVersionedValue.getVersion()); assertTrue(l.created.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.removed.isEmpty()); assertEquals(1, l.visitedCounter); l.reset(); remote.removeWithVersion("key2", newVersionedValue.getVersion()); assertTrue(l.created.isEmpty()); assertTrue(l.modified.isEmpty()); assertEquals(1, l.removedCounter); assertEquals("value2", l.removed.get("key2")); assertEquals(1, l.visitedCounter); remote.put("newKey", "willBeOutOfDate"); VersionedValue oldVersionedValueToBeReplaced = remote.getWithMetadata("newKey"); remote.put("newKey", "changedValue"); l.reset(); remote.replaceWithVersion("newKey", "tryingToChangeButShouldNotSucceed", oldVersionedValueToBeReplaced.getVersion()); assertTrue(l.created.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.visited.isEmpty()); remote.put("newKey2", "willBeSuccessfullyChanged"); VersionedValue newVersionedValueToBeReplaced = remote.getWithMetadata("newKey2"); l.reset(); remote.replaceWithVersion("newKey2", "successfulChange", newVersionedValueToBeReplaced.getVersion()); assertTrue(l.created.isEmpty()); assertEquals(1, l.modifiedCounter); assertEquals("successfulChange", l.modified.get("newKey2")); assertTrue(l.removed.isEmpty()); assertTrue(l.visited.isEmpty()); l.reset(); } public void testLoadingAndStoringAsyncEventsHotRod() throws InterruptedException, ExecutionException, TimeoutException { Cache<String, String> embedded = cacheFactory.getEmbeddedCache(); RemoteCache<String, String> remote = cacheFactory.getHotRodCache(); TestCacheListener l = new TestCacheListener(); embedded.addListener(l); CompletableFuture future = remote.putAsync("k", "v"); future.get(60, TimeUnit.SECONDS); assertEquals(1, l.createdCounter); assertEquals("v", l.created.get("k")); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.visited.isEmpty()); CompletableFuture future2 = remote.putAsync("key", "value"); future2.get(60, TimeUnit.SECONDS); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.visited.isEmpty()); CompletableFuture future3 = remote.putAsync("key", "modifiedValue"); future3.get(60, TimeUnit.SECONDS); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertEquals(1, l.modifiedCounter); assertEquals("modifiedValue", l.modified.get("key")); assertTrue(l.visited.isEmpty()); CompletableFuture future4 = remote.replaceAsync("k", "replacedValue"); future4.get(60, TimeUnit.SECONDS); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertEquals(2, l.modifiedCounter); assertEquals("replacedValue", l.modified.get("k")); assertTrue(l.visited.isEmpty()); //resetting so don't have to type "== 2" etc. all over again l.reset(); CompletableFuture future5 = remote.removeAsync("key"); future5.get(60, TimeUnit.SECONDS); assertTrue(l.created.isEmpty()); assertEquals(1, l.removedCounter); assertEquals("modifiedValue", l.removed.get("key")); assertTrue(l.modified.isEmpty()); l.reset(); CompletableFuture future6 = remote.getAsync("k"); future6.get(60, TimeUnit.SECONDS); assertTrue(l.created.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertEquals(1, l.visitedCounter); assertEquals("replacedValue", l.visited.get("k")); l.reset(); } }
9,797
33.868327
123
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/DistEmbeddedHotRodBulkTest.java
package org.infinispan.it.endpoints; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Set; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.api.BasicCache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test embedded caches and Hot Rod endpoints for operations that retrieve data in bulk, i.e. keySet. * * @author Martin Gencur * @since 7.0 */ @Test(groups = "functional", testName = "it.endpoints.DistEmbeddedHotRodBulkTest") public class DistEmbeddedHotRodBulkTest extends AbstractInfinispanTest { private final int numOwners = 1; private EndpointsCacheFactory<String, Integer> cacheFactory1; private EndpointsCacheFactory<String, Integer> cacheFactory2; @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<String, Integer>().withCacheMode(CacheMode.DIST_SYNC) .withNumOwners(numOwners).withL1(false).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<String, Integer>().withCacheMode(CacheMode.DIST_SYNC) .withNumOwners(numOwners).withL1(false).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } private void populateCacheManager(BasicCache cache) { for (int i = 0; i < 100; i++) { cache.put("key" + i, i); } } public void testEmbeddedPutHotRodKeySet() { Cache<String, Integer> embedded = cacheFactory1.getEmbeddedCache(); RemoteCache<String, Integer> remote = cacheFactory2.getHotRodCache(); populateCacheManager(embedded); Set<String> keySet = remote.keySet(); assertEquals(100, keySet.size()); for(int i = 0; i < 100; i++) { assertTrue(keySet.contains("key" + i)); } } }
2,141
32.46875
111
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/CustomKey.java
package org.infinispan.it.endpoints; import java.io.Serializable; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class CustomKey implements Serializable { private String text; private Double doubleValue; private Float floatValue; private Boolean booleanValue; @ProtoFactory CustomKey(String text, Double doubleValue, Float floatValue, Boolean booleanValue) { this.text = text; this.doubleValue = doubleValue; this.floatValue = floatValue; this.booleanValue = booleanValue; } @ProtoField(number = 1) public String getText() { return text; } public void setText(String text) { this.text = text; } @ProtoField(number = 2) public Double getDoubleValue() { return doubleValue; } public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } @ProtoField(number = 3) public Float getFloatValue() { return floatValue; } public void setFloatValue(Float floatValue) { this.floatValue = floatValue; } @ProtoField(number = 4) public Boolean getBooleanValue() { return booleanValue; } public void setBooleanValue(Boolean booleanValue) { this.booleanValue = booleanValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomKey customKey = (CustomKey) o; if (!text.equals(customKey.text)) return false; if (!doubleValue.equals(customKey.doubleValue)) return false; if (!floatValue.equals(customKey.floatValue)) return false; return booleanValue.equals(customKey.booleanValue); } @Override public int hashCode() { int result = text.hashCode(); result = 31 * result + doubleValue.hashCode(); result = 31 * result + floatValue.hashCode(); result = 31 * result + booleanValue.hashCode(); return result; } }
2,035
24.135802
87
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/TestCacheListener.java
package org.infinispan.it.endpoints; import java.util.HashMap; import java.util.Map; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Cache listener for testing purposes with dedicated counter and field for every event so it can assure * that correct event was fired and data is readable. * * @author Jiri Holusa [jholusa@redhat.com] */ @Listener public class TestCacheListener { private static final Log log = LogFactory.getLog(TestCacheListener.class); //Map is used instead of List so we could test if key is correct too Map<Object, Object> created = new HashMap<Object, Object>(); Map<Object, Object> removed = new HashMap<Object, Object>(); Map<Object, Object> modified = new HashMap<Object, Object>(); Map<Object, Object> visited = new HashMap<Object, Object>(); int createdCounter = 0; int removedCounter = 0; int modifiedCounter = 0; int visitedCounter = 0; @SuppressWarnings("unused") @CacheEntryCreated public void handleCreated(CacheEntryCreatedEvent e) { if (!e.isPre()) { log.tracef("Created %s", e.getKey()); created.put(e.getKey(), e.getValue()); createdCounter++; } } @SuppressWarnings("unused") @CacheEntryRemoved public void handleRemoved(CacheEntryRemovedEvent e) { if (!e.isPre()) { log.tracef("Removed %s", e.getKey()); removed.put(e.getKey(), e.getOldValue()); removedCounter++; } } @SuppressWarnings("unused") @CacheEntryModified public void handleModified(CacheEntryModifiedEvent e) { if (!e.isPre()) { log.tracef("Modified %s", e.getKey()); modified.put(e.getKey(), e.getValue()); modifiedCounter++; } } @SuppressWarnings("unused") @CacheEntryVisited public void handleVisited(CacheEntryVisitedEvent e) { if (!e.isPre()) { log.tracef("Visited %s", e.getKey()); visited.put(e.getKey(), e.getValue()); visitedCounter++; } } void reset() { created.clear(); removed.clear(); modified.clear(); visited.clear(); createdCounter = 0; removedCounter = 0; modifiedCounter = 0; visitedCounter = 0; } }
2,952
31.450549
104
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EndpointITSCI.java
package org.infinispan.it.endpoints; import org.infinispan.client.hotrod.event.CustomEventLogListener; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; @AutoProtoSchemaBuilder( includeClasses = { CustomEventLogListener.CustomEvent.class, CustomKey.class, CryptoCurrency.class, EmbeddedRestHotRodTest.Person.class }, schemaFileName = "test.endpoints.it.proto", schemaFilePath = "proto/generated", schemaPackageName = EndpointITSCI.PACKAGE_NAME, service = false ) public interface EndpointITSCI extends SerializationContextInitializer { String PACKAGE_NAME = "org.infinispan.test.endpoint.it"; EndpointITSCI INSTANCE = new EndpointITSCIImpl(); static String getFQN(Class<?> messageClass) { return PACKAGE_NAME + "." + messageClass.getSimpleName(); } }
943
33.962963
72
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EndpointInteroperabilityTest.java
package org.infinispan.it.endpoints; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.startHotRodServer; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.server.core.test.ServerTestingUtil.findFreePort; import static org.infinispan.test.TestingUtil.killCacheManagers; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertTrue; import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals; import java.util.HashMap; import java.util.Map; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.RemoteCacheManagerAdmin; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfiguration; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.StandardConversions; import org.infinispan.commons.marshall.IdentityMarshaller; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.RequestHeader; import org.infinispan.rest.RestServer; import org.infinispan.rest.configuration.RestServerConfigurationBuilder; import org.infinispan.server.core.DummyServerManagement; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests for interoperability between REST and HotRod endpoints without using unmarshalled objects, * but relying on MediaType configuration, HTTP Headers and Hot Rod client DataFormat support. * * @since 9.2 */ @Test(groups = {"functional", "smoke"}, testName = "it.endpoints.EndpointInteroperabilityTest") public class EndpointInteroperabilityTest extends AbstractInfinispanTest { private static final String OCTET_STREAM_HEX = APPLICATION_OCTET_STREAM.withParameter("encoding", "hex").toString(); /** * Cache with no MediaType configuration, assumes K and V are application/unknown. */ private static final String DEFAULT_CACHE_NAME = "defaultCache"; /** * Cache that will hold marshalled entries, configured to use application/x-protostream for K and V. */ private static final String MARSHALLED_CACHE_NAME = "marshalledCache"; /** * Cache configured for text/plain for both K and V. */ private static final String STRING_CACHE_NAME = "stringsCaches"; private RestServer restServer; private HotRodServer hotRodServer; private RestClient restClient; private EmbeddedCacheManager cacheManager; private RemoteCache<byte[], byte[]> defaultRemoteCache; private RemoteCache<Object, Object> defaultMarshalledRemoteCache; private RemoteCache<String, String> stringRemoteCache; @BeforeClass protected void setup() throws Exception { cacheManager = TestCacheManagerFactory.createServerModeCacheManager(); cacheManager.defineConfiguration(DEFAULT_CACHE_NAME, getDefaultCacheConfiguration().build()); cacheManager.defineConfiguration(MARSHALLED_CACHE_NAME, getMarshalledCacheConfiguration().build()); cacheManager.defineConfiguration(STRING_CACHE_NAME, getStringsCacheConfiguration().build()); RestServerConfigurationBuilder builder = new RestServerConfigurationBuilder(); builder.port(findFreePort()); restServer = new RestServer(); restServer.setServerManagement(new DummyServerManagement(), true); restServer.start(builder.build(), cacheManager); RestClientConfigurationBuilder clientBuilder = new RestClientConfigurationBuilder(); RestClientConfiguration configuration = clientBuilder.addServer().host(restServer.getHost()).port(restServer.getPort()).build(); restClient = RestClient.forConfiguration(configuration); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); hotRodServer = startHotRodServer(cacheManager, serverBuilder); defaultRemoteCache = createRemoteCacheManager(IdentityMarshaller.INSTANCE).getCache(DEFAULT_CACHE_NAME); defaultMarshalledRemoteCache = createRemoteCacheManager(null).getCache(MARSHALLED_CACHE_NAME); stringRemoteCache = createRemoteCacheManager(new UTF8StringMarshaller()).getCache(STRING_CACHE_NAME); } private ConfigurationBuilder getDefaultCacheConfiguration() { return new ConfigurationBuilder(); } private ConfigurationBuilder getMarshalledCacheConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.encoding().key().mediaType(APPLICATION_PROTOSTREAM_TYPE); builder.encoding().value().mediaType(APPLICATION_PROTOSTREAM_TYPE); return builder; } private ConfigurationBuilder getStringsCacheConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.encoding().key().mediaType(TEXT_PLAIN_TYPE); builder.encoding().value().mediaType(TEXT_PLAIN_TYPE); return builder; } private RemoteCacheManager createRemoteCacheManager(Marshaller marshaller) { org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); builder.addServer().host("localhost").port(hotRodServer.getPort()); if (marshaller != null) { builder.marshaller(marshaller); } return new RemoteCacheManager(builder.build()); } @Test public void testStringKeysAndByteArrayValue() throws Exception { // The Hot Rod client writes marshalled content. The cache is explicitly configured with // 'application/x-protostream' for both K and V. String key = "string-1"; byte[] value = {1, 2, 3}; byte[] marshalledValue = new ProtoStreamMarshaller().objectToByteBuffer(value); defaultMarshalledRemoteCache.put(key, value); assertEquals(defaultMarshalledRemoteCache.get(key), value); // Read via Rest the raw content, as it is stored Object rawFromRest = new RestRequest().cache(MARSHALLED_CACHE_NAME) .key(key).accept(APPLICATION_PROTOSTREAM) .read(); assertArrayEquals((byte[]) rawFromRest, marshalledValue); // Write via rest raw bytes String otherKey = "string-2"; byte[] otherValue = {0x4, 0x5, 0x6}; byte[] otherValueMarshalled = new ProtoStreamMarshaller().objectToByteBuffer(otherValue); new RestRequest().cache(MARSHALLED_CACHE_NAME) .key(otherKey).value(otherValue, APPLICATION_OCTET_STREAM) .write(); // Read via Hot Rod assertEquals(defaultMarshalledRemoteCache.get(otherKey), otherValue); // Read via Hot Rod using a String key, and getting the raw value (as it is stored) back DataFormat format = DataFormat.builder() .keyType(TEXT_PLAIN) .valueType(APPLICATION_PROTOSTREAM).valueMarshaller(IdentityMarshaller.INSTANCE) .build(); byte[] rawValue = (byte[]) defaultMarshalledRemoteCache.withDataFormat(format).get(otherKey); assertArrayEquals(otherValueMarshalled, rawValue); // Read via Hot Rod using a String key, and getting the original value back DataFormat.builder().keyType(TEXT_PLAIN).build(); byte[] result = (byte[]) defaultMarshalledRemoteCache .withDataFormat(DataFormat.builder().keyType(TEXT_PLAIN).build()).get(otherKey); assertArrayEquals(otherValue, result); } @Test public void testIntegerKeysAndByteArrayValue() { String integerKeyType = "application/x-java-object; type=java.lang.Integer"; byte[] value = {12}; byte[] otherValue = "random".getBytes(UTF_8); // Write <Integer, byte[]> via Hot Rod (the HR client is configured with the default marshaller) defaultMarshalledRemoteCache.put(10, value); assertEquals(defaultMarshalledRemoteCache.get(10), value); // Read via Rest Object bytesFromRest = new RestRequest().cache(MARSHALLED_CACHE_NAME) .key("10", integerKeyType).accept(APPLICATION_OCTET_STREAM) .read(); assertArrayEquals((byte[]) bytesFromRest, value); // Write via rest new RestRequest().cache(MARSHALLED_CACHE_NAME).key("20", integerKeyType).value(otherValue).write(); // Read via Hot Rod assertEquals(defaultMarshalledRemoteCache.get(20), otherValue); } @Test public void testFloatKeysDoubleValues() throws Exception { String floatContentType = "application/x-java-object; type=java.lang.Float"; String doubleContentType = "application/x-java-object; type=java.lang.Double"; Marshaller marshaller = new ProtoStreamMarshaller(); Object key = 1.1f; Object value = 32.4d; byte[] valueMarshalled = marshaller.objectToByteBuffer(value); defaultMarshalledRemoteCache.put(key, value); assertEquals(defaultMarshalledRemoteCache.get(key), value); // Read via Rest the raw byte[] as marshalled by the client Object bytesFromRest = new RestRequest().cache(MARSHALLED_CACHE_NAME) .key(key.toString(), floatContentType) .accept(APPLICATION_PROTOSTREAM) .read(); assertArrayEquals((byte[]) bytesFromRest, valueMarshalled); // Read via Rest the value as String Object stringFromRest = new RestRequest().cache(MARSHALLED_CACHE_NAME) .key(key.toString(), floatContentType) .accept(TEXT_PLAIN) .read(); assertArrayEquals("32.4".getBytes(), (byte[]) stringFromRest); // Write via rest Object otherKey = 2.2f; Object otherValue = 123.0d; new RestRequest().cache(MARSHALLED_CACHE_NAME) .key(otherKey.toString(), floatContentType) .value(otherValue.toString(), doubleContentType) .write(); // Read via Hot Rod assertEquals(defaultMarshalledRemoteCache.get(otherKey), otherValue); } @Test public void testStringKeysAndStringValues() { // Write via Hot Rod (the HR client is configured with a String marshaller) stringRemoteCache.put("key", "true"); assertEquals(stringRemoteCache.get("key"), "true"); // Read via Rest Object bytesFromRest = new RestRequest().cache(STRING_CACHE_NAME).key("key").accept(TEXT_PLAIN).read(); assertEquals(asString(bytesFromRest), "true"); // Write via rest new RestRequest().cache(STRING_CACHE_NAME).key("key2").value("Testing").write(); // Read via Hot Rod assertEquals(stringRemoteCache.get("key2"), "Testing"); // Get values as JSON from Hot Rod Object jsonString = stringRemoteCache.withDataFormat(DataFormat.builder() .valueType(APPLICATION_JSON).valueMarshaller(new UTF8StringMarshaller()).build()) .get("key"); assertEquals("true", jsonString); } @Test public void testByteArrayKeysAndValuesWithMarshaller() throws Exception { // Write via Hot Rod using the default marshaller byte[] key = new byte[]{0x74, 0x18}; byte[] value = new byte[]{0x10, 0x20}; defaultMarshalledRemoteCache.put(key, value); assertArrayEquals((byte[]) defaultMarshalledRemoteCache.get(key), value); // Read via Rest Object bytesFromRest = new RestRequest().cache(MARSHALLED_CACHE_NAME) .key("0x7418", OCTET_STREAM_HEX) .accept(APPLICATION_OCTET_STREAM) .read(); assertEquals(bytesFromRest, value); // Read marshalled content directly Object marshalledContent = new RestRequest().cache(MARSHALLED_CACHE_NAME) .key("0x7418", OCTET_STREAM_HEX) .accept(APPLICATION_PROTOSTREAM) .read(); assertArrayEquals((byte[]) marshalledContent, new ProtoStreamMarshaller().objectToByteBuffer(value)); // Write via rest byte[] newKey = new byte[]{0x23}; // Write via rest new RestRequest().cache(MARSHALLED_CACHE_NAME) .key("0x23", OCTET_STREAM_HEX) .value(value) .write(); // Read via Hot Rod assertEquals(defaultMarshalledRemoteCache.get(newKey), value); } @Test public void testByteArrayKeysAndByteArrayValues() { // Write via Hot Rod the byte[] content directly byte[] key = new byte[]{0x13, 0x26}; byte[] value = new byte[]{10, 20}; defaultRemoteCache.put(key, value); assertArrayEquals(defaultRemoteCache.get(key), value); // Read via Rest Object bytesFromRest = new RestRequest().cache(DEFAULT_CACHE_NAME) .key("0x1326", OCTET_STREAM_HEX) .accept(APPLICATION_OCTET_STREAM) .read(); assertEquals(bytesFromRest, value); // Write via rest byte[] newKey = new byte[]{0, 0, 0, 1}; // Write via rest new RestRequest().cache(DEFAULT_CACHE_NAME) .key("0x00000001", OCTET_STREAM_HEX) .value(value) .write(); // Read via Hot Rod assertEquals(defaultRemoteCache.get(newKey), value); } @Test public void testCustomKeysAndByteValues() throws Exception { CustomKey objectKey = new CustomKey("a", 1.0d, 1.0f, true); ProtoStreamMarshaller marshaller = new ProtoStreamMarshaller(); marshaller.register(EndpointITSCI.INSTANCE); byte[] key = marshaller.objectToByteBuffer(objectKey); byte[] value = {12}; // Write <byte[], byte[]> via Hot Rod (the HR client is configured with a no-op marshaller) defaultRemoteCache.put(key, value); assertEquals(value, defaultRemoteCache.get(key)); String restKey = StandardConversions.bytesToHex(key); // Read via Rest Object bytesFromRest = new RestRequest().cache(DEFAULT_CACHE_NAME) .key(restKey, OCTET_STREAM_HEX).accept(APPLICATION_OCTET_STREAM) .read(); assertArrayEquals((byte[]) bytesFromRest, value); } @Test public void testCacheLifecycle() { // Write from Hot Rod stringRemoteCache.put("key", "Hello World"); assertEquals(stringRemoteCache.get("key"), "Hello World"); // Read from REST RestRequest restRequest = new RestRequest().cache(STRING_CACHE_NAME).key("key").accept(TEXT_PLAIN); assertEquals(restRequest.executeGet().getBody(), "Hello World"); // Delete the cache RemoteCacheManagerAdmin admin = stringRemoteCache.getRemoteCacheManager().administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE); admin.removeCache(stringRemoteCache.getName()); // Check cache not available assertClientError(() -> stringRemoteCache.get("key"), "CacheNotFoundException"); assertEquals(restRequest.executeGet().getStatus(), 404); // Recreate the cache RemoteCache<String, String> recreated = admin.getOrCreateCache(stringRemoteCache.getName(), new ConfigurationBuilder() .encoding().key().mediaType(TEXT_PLAIN_TYPE) .encoding().value().mediaType(TEXT_PLAIN_TYPE) .build()); // Write from Hot Rod recreated.put("key", "Hello World"); assertEquals(recreated.get("key"), "Hello World"); // Read from REST assertEquals(restRequest.executeGet().getBody(), "Hello World"); } private void assertClientError(Runnable runnable, String messagePart) { try { runnable.run(); } catch (Throwable t) { String message = t.getMessage(); assertTrue(message != null && message.contains(messagePart)); } } private String asString(Object content) { if (content instanceof byte[]) { return new String((byte[]) content, UTF_8); } return content.toString(); } private class RestRequest { private String cacheName; private Object key; private Object value; private String keyContentType; private MediaType accept; private String contentType; private RestCacheClient restCacheClient; public RestRequest cache(String cacheName) { this.cacheName = cacheName; this.restCacheClient = restClient.cache(cacheName); return this; } public RestRequest key(Object key) { this.key = key; return this; } public RestRequest key(Object key, String keyContentType) { this.key = key; this.keyContentType = keyContentType; return this; } public RestRequest value(Object value, String contentType) { this.value = value; this.contentType = contentType; return this; } public RestRequest value(Object value, MediaType contentType) { this.value = value; this.contentType = contentType.toString(); return this; } public RestRequest value(Object value) { this.value = value; return this; } RestRequest accept(MediaType valueContentType) { this.accept = valueContentType; return this; } void write() { RestEntity restEntity; if (this.value instanceof byte[]) { MediaType contentType = this.contentType == null ? APPLICATION_OCTET_STREAM : MediaType.fromString(this.contentType); restEntity = RestEntity.create(contentType, (byte[]) this.value); } else { String payload = this.value.toString(); MediaType contentType = this.contentType == null ? TEXT_PLAIN : MediaType.fromString(this.contentType); restEntity = RestEntity.create(contentType, payload); } RestResponse response; if (this.keyContentType != null) { response = join(restCacheClient.put(this.key.toString(), keyContentType, restEntity)); } else { response = join(restCacheClient.put(this.key.toString(), restEntity)); } assertEquals(204, response.getStatus()); } RestResponse executeGet() { Map<String, String> headers = new HashMap<>(); if (this.accept != null) { headers.put(RequestHeader.ACCEPT_HEADER.getValue(), this.accept.toString()); } if (keyContentType != null) { headers.put(RequestHeader.KEY_CONTENT_TYPE_HEADER.getValue(), this.keyContentType); } return join(restCacheClient.get(this.key.toString(), headers)); } Object read() { RestResponse response = executeGet(); assertEquals(response.getStatus(), 200); return response.getBodyAsByteArray(); } } @AfterClass protected void teardown() { defaultRemoteCache.getRemoteCacheManager().stop(); defaultMarshalledRemoteCache.getRemoteCacheManager().stop(); stringRemoteCache.getRemoteCacheManager().stop(); if (restServer != null) { try { restClient.close(); restServer.stop(); } catch (Exception ignored) { } } killCacheManagers(cacheManager); cacheManager = null; killServers(hotRodServer); hotRodServer = null; } }
20,687
38.784615
147
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/DistMemcachedEmbeddedTest.java
package org.infinispan.it.endpoints; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests embedded and Memcached in a distributed clustered environment, using SpyMemcachedMarshaller. * * @author Martin Gencur * @since 6.0 */ @Test(groups = "functional", testName = "it.endpoints.DistMemcachedEmbeddedTest") public class DistMemcachedEmbeddedTest extends AbstractInfinispanTest { private final int numOwners = 1; //make sure the number of entries is big enough so that at least on entry //is stored on non-local node to the Memcached client private final int numEntries = 100; private final String cacheName = "memcachedCache"; private EndpointsCacheFactory<String, Object> cacheFactory1; private EndpointsCacheFactory<String, Object> cacheFactory2; @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<String, Object>().withCacheName(cacheName) .withMarshaller(new SpyMemcachedMarshaller()).withCacheMode(CacheMode.DIST_SYNC).withNumOwners(numOwners).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<String, Object>().withCacheName(cacheName) .withMarshaller(new SpyMemcachedMarshaller()).withCacheMode(CacheMode.DIST_SYNC).withNumOwners(numOwners).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } public void testMemcachedPutEmbeddedGet() throws Exception { // 1. Put with Memcached for (int i = 0; i != numEntries; i++) { Future<Boolean> f = cacheFactory2.getMemcachedClient().set("k" + i, 0, "v" + i); assertTrue(f.get(60, TimeUnit.SECONDS)); } // 2. Get with Embedded from a different node for (int i = 0; i != numEntries; i++) { assertEquals("v" + i, cacheFactory1.getEmbeddedCache().get("k" + i)); cacheFactory1.getEmbeddedCache().remove("k" + i); } } public void testEmbeddedPutMemcachedGet() throws IOException { // 1. Put with Embedded for (int i = 0; i != numEntries; i++) { assertEquals(null, cacheFactory2.getEmbeddedCache().put("k" + i, "v" + i)); } // 2. Get with Memcached from a different node for (int i = 0; i != numEntries; i++) { assertEquals("v" + i, cacheFactory1.getMemcachedClient().get("k" + i)); } } }
2,788
37.205479
126
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/CryptoCurrency.java
package org.infinispan.it.endpoints; import java.io.Serializable; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; /** * @since 9.2 */ @Indexed public class CryptoCurrency implements Serializable { @ProtoField(number = 1) @Field(analyze = Analyze.NO,index = Index.YES, store = Store.NO) String description; @ProtoField(number = 2) @Field(index = Index.YES, store = Store.NO) Integer rank; CryptoCurrency() {} @ProtoFactory CryptoCurrency(String description, Integer rank) { this.description = description; this.rank = rank; } public String getDescription() { return description; } public Integer getRank() { return rank; } }
1,010
22.511628
67
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EmbeddedHotRodTest.java
package org.infinispan.it.endpoints; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.client.hotrod.event.CustomEventLogListener.CustomEvent; import org.infinispan.client.hotrod.event.CustomEventLogListener.DynamicConverterFactory; import org.infinispan.client.hotrod.event.CustomEventLogListener.DynamicCustomEventLogListener; import org.infinispan.client.hotrod.event.CustomEventLogListener.StaticConverterFactory; import org.infinispan.client.hotrod.event.CustomEventLogListener.StaticCustomEventLogListener; import org.infinispan.client.hotrod.event.EventLogListener; import org.infinispan.client.hotrod.event.EventLogListener.DynamicCacheEventFilterFactory; import org.infinispan.client.hotrod.event.EventLogListener.DynamicFilteredEventLogListener; import org.infinispan.client.hotrod.event.EventLogListener.StaticCacheEventFilterFactory; import org.infinispan.client.hotrod.event.EventLogListener.StaticFilteredEventLogListener; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test embedded caches and Hot Rod endpoints. * * @author Galder Zamarreño * @since 5.3 */ @Test(groups = "functional", testName = "it.endpoints.EmbeddedHotRodTest") public class EmbeddedHotRodTest extends AbstractInfinispanTest { EndpointsCacheFactory<Integer, String> cacheFactory; @BeforeClass protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<Integer, String>().withCacheMode(CacheMode.LOCAL) .withContextInitializer(EndpointITSCI.INSTANCE).build(); HotRodServer hotrod = cacheFactory.getHotrodServer(); hotrod.addCacheEventFilterFactory("static-filter-factory", new StaticCacheEventFilterFactory(2)); hotrod.addCacheEventFilterFactory("dynamic-filter-factory", new DynamicCacheEventFilterFactory()); hotrod.addCacheEventConverterFactory("static-converter-factory", new StaticConverterFactory()); hotrod.addCacheEventConverterFactory("dynamic-converter-factory", new DynamicConverterFactory()); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } private Cache<Integer, String> getEmbeddedCache() { return cacheFactory.getEmbeddedCache().getAdvancedCache(); } public void testEmbeddedPutHotRodGet() { final Integer key = 1; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, embedded.put(key, "v1")); assertEquals("v1", remote.get(key)); assertEquals("v1", embedded.put(key, "v2")); assertEquals("v2", remote.get(key)); assertEquals("v2", embedded.remove(key)); } public void testHotRodPutEmbeddedGet() { final Integer key = 2; RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); Cache<Integer, String> embedded = getEmbeddedCache(); assertEquals(null, remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); assertEquals("v1", embedded.get(key)); assertEquals(null, remote.put(key, "v2")); assertEquals("v2", remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v3")); assertEquals("v3", embedded.get(key)); assertEquals("v3", remote.withFlags(Flag.FORCE_RETURN_VALUE).remove(key)); } public void testEmbeddedPutIfAbsentHotRodGet() { final Integer key = 3; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, embedded.putIfAbsent(key, "v1")); assertEquals("v1", remote.get(key)); assertEquals("v1", embedded.putIfAbsent(key, "v2")); assertEquals("v1", remote.get(key)); assertEquals("v1", embedded.remove(key)); } public void testHotRodPutIfAbsentEmbeddedGet() { final Integer key = 4; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, remote.withFlags(Flag.FORCE_RETURN_VALUE).putIfAbsent(key, "v1")); assertEquals("v1", embedded.get(key)); assertEquals(null, remote.putIfAbsent(key, "v2")); assertEquals("v1", remote.withFlags(Flag.FORCE_RETURN_VALUE).putIfAbsent(key, "v2")); assertEquals("v1", embedded.get(key)); assertEquals("v1", remote.withFlags(Flag.FORCE_RETURN_VALUE).remove(key)); } public void testEmbeddedReplaceHotRodGet() { final Integer key = 5; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, embedded.replace(key, "v1")); assertEquals(null, embedded.put(key, "v1")); assertEquals("v1", embedded.replace(key, "v2")); assertEquals("v2", remote.get(key)); assertEquals("v2", embedded.remove(key)); } public void testHotRodReplaceEmbeddedGet() { final Integer key = 6; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, remote.withFlags(Flag.FORCE_RETURN_VALUE).replace(key, "v1")); assertEquals(null, remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); assertEquals("v1", remote.withFlags(Flag.FORCE_RETURN_VALUE).replace(key, "v2")); assertEquals("v2", embedded.get(key)); } public void testEmbeddedReplaceConditionalHotRodGet() { final Integer key = 7; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, embedded.put(key, "v1")); assertTrue(embedded.replace(key, "v1", "v2")); assertEquals("v2", remote.get(key)); assertEquals("v2", embedded.remove(key)); } public void testHotRodReplaceConditionalEmbeddedGet() { final Integer key = 8; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, remote.put(key, "v1")); VersionedValue<String> versioned = remote.getWithMetadata(key); assertEquals("v1", versioned.getValue()); assertTrue(0 != versioned.getVersion()); assertFalse(remote.replaceWithVersion(key, "v2", Long.MAX_VALUE)); assertTrue(remote.replaceWithVersion(key, "v2", versioned.getVersion())); assertEquals("v2", embedded.get(key)); assertEquals("v2", remote.withFlags(Flag.FORCE_RETURN_VALUE).remove(key)); } public void testEmbeddedRemoveHotRodGet() { final Integer key = 9; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, embedded.put(key, "v1")); assertEquals("v1", embedded.remove(key)); assertEquals(null, remote.get(key)); } public void testHotRodRemoveEmbeddedGet() { final Integer key = 10; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); assertEquals("v1", remote.withFlags(Flag.FORCE_RETURN_VALUE).remove(key)); assertEquals(null, embedded.get(key)); } public void testEmbeddedRemoveConditionalHotRodGet() { final Integer key = 11; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, embedded.put(key, "v1")); assertFalse(embedded.remove(key, "vX")); assertTrue(embedded.remove(key, "v1")); assertEquals(null, remote.get(key)); } public void testHotRodRemoveConditionalEmbeddedGet() { final Integer key = 12; Cache<Integer, String> embedded = getEmbeddedCache(); RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); assertEquals(null, remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); VersionedValue<String> versioned = remote.getWithMetadata(key); assertFalse(remote.withFlags(Flag.FORCE_RETURN_VALUE).removeWithVersion(key, Long.MAX_VALUE)); assertTrue(remote.withFlags(Flag.FORCE_RETURN_VALUE).removeWithVersion(key, versioned.getVersion())); assertEquals(null, embedded.get(key)); } public void testEventReceiveBasic() { EventLogListener<Integer> l = new EventLogListener<>(cacheFactory.getHotRodCache()); withClientListener(l, remote -> { l.expectNoEvents(); remote.remove(1); l.expectNoEvents(); remote.put(1, "one"); assertEquals("one", getEmbeddedCache().get(1)); l.expectOnlyCreatedEvent(1); remote.put(1, "new-one"); assertEquals("new-one", getEmbeddedCache().get(1)); l.expectOnlyModifiedEvent(1); remote.remove(1); l.expectOnlyRemovedEvent(1); }); } public void testEventReceiveConditional() { EventLogListener<Integer> l = new EventLogListener<>(cacheFactory.getHotRodCache()); withClientListener(l, remote -> { l.expectNoEvents(); // Put if absent remote.putIfAbsent(1, "one"); l.expectOnlyCreatedEvent(1); remote.putIfAbsent(1, "again"); l.expectNoEvents(); // Replace remote.replace(1, "newone"); l.expectOnlyModifiedEvent(1); // Replace with version remote.replaceWithVersion(1, "one", 0); l.expectNoEvents(); VersionedValue<?> versioned = remote.getWithMetadata(1); remote.replaceWithVersion(1, "one", versioned.getVersion()); l.expectOnlyModifiedEvent(1); // Remove with version remote.removeWithVersion(1, 0); l.expectNoEvents(); versioned = remote.getWithMetadata(1); remote.removeWithVersion(1, versioned.getVersion()); l.expectOnlyRemovedEvent(1); }); } public void testEventReplayAfterAddingListener() { EventLogWithStateListener<Integer> l = new EventLogWithStateListener<>(cacheFactory.getHotRodCache()); createRemove(); l.expectNoEvents(); withClientListener(l, remote -> { l.expectUnorderedEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, 1, 2); remote.remove(1); l.expectOnlyRemovedEvent(1); remote.remove(2); l.expectOnlyRemovedEvent(2); }); } public void testEventNoReplayAfterAddingListener() { createRemove(); EventLogListener<Integer> l = new EventLogListener<>(cacheFactory.getHotRodCache()); l.expectNoEvents(); withClientListener(l, remote -> { l.expectNoEvents(); remote.remove(1); l.expectOnlyRemovedEvent(1); remote.remove(2); l.expectOnlyRemovedEvent(2); }); } private void createRemove() { RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); Cache<Integer, String> embedded = getEmbeddedCache(); remote.put(1, "one"); assertEquals("one", embedded.get(1)); remote.put(2, "two"); assertEquals("two", embedded.get(2)); remote.put(3, "three"); assertEquals("three", embedded.get(3)); remote.remove(3); assertNull(embedded.get(3)); } public void testEventFilteringStatic() { StaticFilteredEventLogListener<Integer> l = new StaticFilteredEventLogListener<>(cacheFactory.getHotRodCache()); withClientListener(l, remote -> { l.expectNoEvents(); remote.put(1, "one"); Cache<Integer, String> embedded = getEmbeddedCache(); assertEquals("one", embedded.get(1)); l.expectNoEvents(); remote.put(2, "two"); assertEquals("two", embedded.get(2)); l.expectOnlyCreatedEvent(2); remote.remove(1); assertNull(embedded.get(1)); l.expectNoEvents(); remote.remove(2); assertNull(embedded.get(2)); l.expectOnlyRemovedEvent(2); }); } public void testEventFilteringDynamic() { RemoteCache<Integer, String> remote = cacheFactory.getHotRodCache(); DynamicFilteredEventLogListener<Integer> eventListener = new DynamicFilteredEventLogListener<>(remote); Cache<Integer, String> embedded = getEmbeddedCache(); remote.addClientListener(eventListener, new Object[]{3}, null); try { eventListener.expectNoEvents(); remote.put(1, "one"); assertEquals("one", embedded.get(1)); eventListener.expectNoEvents(); remote.put(2, "two"); assertEquals("two", embedded.get(2)); eventListener.expectNoEvents(); remote.put(3, "three"); assertEquals("three", embedded.get(3)); eventListener.expectOnlyCreatedEvent(3); remote.replace(1, "new-one"); assertEquals("new-one", embedded.get(1)); eventListener.expectNoEvents(); remote.replace(2, "new-two"); assertEquals("new-two", embedded.get(2)); eventListener.expectNoEvents(); remote.replace(3, "new-three"); assertEquals("new-three", embedded.get(3)); eventListener.expectOnlyModifiedEvent(3); remote.remove(1); assertNull(embedded.get(1)); eventListener.expectNoEvents(); remote.remove(2); assertNull(embedded.get(2)); eventListener.expectNoEvents(); remote.remove(3); assertNull(embedded.get(3)); eventListener.expectOnlyRemovedEvent(3); } finally { remote.removeClientListener(eventListener); } } public void testCustomEvents() { StaticCustomEventLogListener<Integer> l = new StaticCustomEventLogListener<>(cacheFactory.getHotRodCache()); withClientListener(l, remote -> { l.expectNoEvents(); remote.put(1, "one"); Cache<Integer, String> embedded = getEmbeddedCache(); assertEquals("one", embedded.get(1)); l.expectCreatedEvent(new CustomEvent(1, "one", 0)); remote.put(1, "new-one"); assertEquals("new-one", embedded.get(1)); l.expectModifiedEvent(new CustomEvent(1, "new-one", 0)); remote.remove(1); assertNull(embedded.get(1)); l.expectRemovedEvent(new CustomEvent(1, null, 0)); }); } public void testCustomEventsDynamic() { DynamicCustomEventLogListener<Integer> l = new DynamicCustomEventLogListener<>(cacheFactory.getHotRodCache()); withClientListener(l, null, new Object[]{2}, remote -> { l.expectNoEvents(); remote.put(1, "one"); Cache<Integer, String> embedded = getEmbeddedCache(); assertEquals("one", embedded.get(1)); l.expectCreatedEvent(new CustomEvent(1, "one", 0)); remote.put(2, "two"); assertEquals("two", embedded.get(2)); l.expectCreatedEvent(new CustomEvent(2, null, 0)); remote.remove(1); assertNull(embedded.get(1)); l.expectRemovedEvent(new CustomEvent(1, null, 0)); remote.remove(2); assertNull(embedded.get(2)); l.expectRemovedEvent(new CustomEvent(2, null, 0)); }); } @ClientListener(includeCurrentState = true) public static class EventLogWithStateListener<K> extends EventLogListener<K> { public EventLogWithStateListener(RemoteCache<K, ?> r) { super(r); } } }
16,290
41.646597
116
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EmbeddedRestMemcachedHotRodTest.java
package org.infinispan.it.endpoints; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotSame; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import net.spy.memcached.CASValue; /** * Test embedded caches, Hot Rod, REST and Memcached endpoints. * * @author Galder Zamarreño * @since 5.3 */ @Test(groups = {"functional", "smoke"}, testName = "it.endpoints.EmbeddedRestMemcachedHotRodTest") public class EmbeddedRestMemcachedHotRodTest extends AbstractInfinispanTest { final static String CACHE_NAME = "memcachedCache"; protected EndpointsCacheFactory<String, Object> cacheFactory; @BeforeClass protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<String, Object>().withCacheName(CACHE_NAME) .withMarshaller(new SpyMemcachedMarshaller()).withCacheMode(CacheMode.LOCAL).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } public void testMemcachedPutEmbeddedRestHotRodGetTest() throws Exception { final String key = "1"; // 1. Put with Memcached Future<Boolean> f = cacheFactory.getMemcachedClient().set(key, 0, "v1"); assertTrue(f.get(60, TimeUnit.SECONDS)); // 2. Get with Embedded assertEquals("v1", cacheFactory.getEmbeddedCache().get(key)); // 3. Get with REST RestResponse response = join(cacheFactory.getRestCacheClient().get(key, MediaType.TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals("v1", response.getBody()); // 4. Get with Hot Rod assertEquals("v1", cacheFactory.getHotRodCache().get(key)); } public void testEmbeddedPutMemcachedRestHotRodGetTest() { final String key = "2"; // 1. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key, "v1")); // 2. Get with Memcached assertEquals("v1", cacheFactory.getMemcachedClient().get(key)); // 3. Get with REST RestResponse response = join(cacheFactory.getRestCacheClient().get(key, MediaType.TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals("v1", response.getBody()); // 4. Get with Hot Rod assertEquals("v1", cacheFactory.getHotRodCache().get(key)); } public void testRestPutEmbeddedMemcachedHotRodGetTest() { final String key = "3"; // 1. Put with REST RestEntity value = RestEntity.create(MediaType.TEXT_PLAIN, "<hey>ho</hey>"); RestResponse response = join(cacheFactory.getRestCacheClient().put(key, value)); assertEquals(204, response.getStatus()); // 2. Get with Embedded (given a marshaller, it can unmarshall the result) assertEquals("<hey>ho</hey>", cacheFactory.getEmbeddedCache().get(key)); // 3. Get with Memcached (given a marshaller, it can unmarshall the result) assertEquals("<hey>ho</hey>", cacheFactory.getMemcachedClient().get(key)); // 4. Get with Hot Rod (given a marshaller, it can unmarshall the result) assertEquals("<hey>ho</hey>", cacheFactory.getHotRodCache().get(key)); } public void testHotRodPutEmbeddedMemcachedRestGetTest() { final String key = "4"; // 1. Put with Hot Rod RemoteCache<String, Object> remote = cacheFactory.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); // 2. Get with Embedded assertEquals("v1", cacheFactory.getEmbeddedCache().get(key)); // 3. Get with Memcached assertEquals("v1", cacheFactory.getMemcachedClient().get(key)); // 4. Get with REST RestResponse response = join(cacheFactory.getRestCacheClient().get(key, MediaType.TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals("v1", response.getBody()); } public void testEmbeddedReplaceMemcachedCASTest() throws Exception { final String key1 = "5"; // 1. Put with Memcached Future<Boolean> f = cacheFactory.getMemcachedClient().set(key1, 0, "v1"); assertTrue(f.get(60, TimeUnit.SECONDS)); CASValue oldValue = cacheFactory.getMemcachedClient().gets(key1); // 2. Replace with Embedded assertTrue(cacheFactory.getEmbeddedCache().replace(key1, "v1", "v2")); // 4. Get with Memcached and verify value/CAS CASValue newValue = cacheFactory.getMemcachedClient().gets(key1); assertEquals("v2", newValue.getValue()); assertNotSame("The version (CAS) should have changed, " + "oldCase=" + oldValue.getCas() + ", newCas=" + newValue.getCas(), oldValue.getCas(), newValue.getCas()); } public void testHotRodReplaceMemcachedCASTest() throws Exception { final String key1 = "6"; // 1. Put with Memcached Future<Boolean> f = cacheFactory.getMemcachedClient().set(key1, 0, "v1"); assertTrue(f.get(60, TimeUnit.SECONDS)); CASValue oldValue = cacheFactory.getMemcachedClient().gets(key1); // 2. Replace with Hot Rod VersionedValue versioned = cacheFactory.getHotRodCache().getWithMetadata(key1); assertTrue(cacheFactory.getHotRodCache().replaceWithVersion(key1, "v2", versioned.getVersion())); // 4. Get with Memcached and verify value/CAS CASValue newValue = cacheFactory.getMemcachedClient().gets(key1); assertEquals("v2", newValue.getValue()); assertTrue("The version (CAS) should have changed", oldValue.getCas() != newValue.getCas()); } public void testEmbeddedHotRodReplaceMemcachedCASTest() throws Exception { final String key1 = "7"; // 1. Put with Memcached Future<Boolean> f = cacheFactory.getMemcachedClient().set(key1, 0, "v1"); assertTrue(f.get(60, TimeUnit.SECONDS)); CASValue oldValue = cacheFactory.getMemcachedClient().gets(key1); // 2. Replace with Hot Rod VersionedValue versioned = cacheFactory.getHotRodCache().getWithMetadata(key1); assertTrue(cacheFactory.getHotRodCache().replaceWithVersion(key1, "v2", versioned.getVersion())); // 3. Replace with Embedded assertTrue(cacheFactory.getEmbeddedCache().replace(key1, "v2", "v3")); // 4. Get with Memcached and verify value/CAS CASValue newValue = cacheFactory.getMemcachedClient().gets(key1); assertEquals("v3", newValue.getValue()); assertTrue("The version (CAS) should have changed", oldValue.getCas() != newValue.getCas()); } }
7,209
37.972973
106
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/ByteArrayKeyReplEmbeddedHotRodTest.java
package org.infinispan.it.endpoints; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests embedded and Hot Rod in a replicated clustered environment using byte array keys. * * @author Martin Gencur * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "it.interop.ByteArrayKeyReplEmbeddedHotRodTest") public class ByteArrayKeyReplEmbeddedHotRodTest extends AbstractInfinispanTest { EndpointsCacheFactory<Object, Object> cacheFactory1; EndpointsCacheFactory<Object, Object> cacheFactory2; public void testHotRodPutEmbeddedGet() { final byte[] key = "4".getBytes(); final String value = "v1"; // 1. Put with HotRod RemoteCache<Object, Object> remote = cacheFactory1.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, value)); // 2. Get with Embedded assertEquals(value, cacheFactory2.getEmbeddedCache().get(key)); } public void testHotRodReplace() throws Exception { final byte[] key = "5".getBytes(); final String value1 = "v1"; final String value2 = "v2"; // 1. Put with HotRod RemoteCache<Object, Object> remote = cacheFactory1.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, value1)); // 2. Replace with HotRod VersionedValue versioned = cacheFactory1.getHotRodCache().getWithMetadata(key); assertTrue(cacheFactory1.getHotRodCache().replaceWithVersion(key, value2, versioned.getVersion())); } public void testHotRodRemove() throws Exception { final byte[] key = "7".getBytes(); final String value = "v1"; // 1. Put with HotRod RemoteCache<Object, Object> remote = cacheFactory1.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, value)); // 2. Removed with HotRod VersionedValue versioned = cacheFactory1.getHotRodCache().getWithMetadata(key); assertTrue(cacheFactory1.getHotRodCache().removeWithVersion(key, versioned.getVersion())); } //This test can fail only if there's a marshaller specified for EmbeddedTypeConverter public void testEmbeddedPutHotRodGet() throws Exception { final byte[] key = "8".getBytes(); final String value = "v1"; // 1. Put with Embedded assertNull(cacheFactory2.getEmbeddedCache().put(key, value)); // 2. Get with HotRod assertEquals(value, cacheFactory1.getHotRodCache().get(key)); } @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.REPL_SYNC).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.REPL_SYNC).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } }
3,349
35.813187
105
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/JsonIndexingProtobufStoreTest.java
package org.infinispan.it.endpoints; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import java.io.IOException; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.testng.annotations.Test; /** * Test for indexing json using protobuf underlying storage without forcing unmarshalled storage. * * @since 9.2 */ @Test(groups = "functional", testName = "it.endpoints.JsonIndexingProtobufStoreTest") public class JsonIndexingProtobufStoreTest extends BaseJsonTest { @Override protected ConfigurationBuilder getIndexCacheConfiguration() { ConfigurationBuilder indexedCache = new ConfigurationBuilder(); indexedCache.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.test.endpoint.it.CryptoCurrency"); indexedCache.encoding().key().mediaType(APPLICATION_PROTOSTREAM_TYPE); indexedCache.encoding().value().mediaType(APPLICATION_PROTOSTREAM_TYPE); return indexedCache; } @Override protected RemoteCacheManager createRemoteCacheManager() throws IOException { SerializationContextInitializer sci = EndpointITSCI.INSTANCE; RemoteCacheManager remoteCacheManager = new RemoteCacheManager(new org.infinispan.client.hotrod.configuration.ConfigurationBuilder() .addServer().host("localhost").port(hotRodServer.getPort()) .addContextInitializer(sci) .build()); //initialize server-side serialization context RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME); metadataCache.put(sci.getProtoFileName(), sci.getProtoFile()); return remoteCacheManager; } }
2,096
39.326923
138
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/ByteArrayValueReplEmbeddedHotRodTest.java
package org.infinispan.it.endpoints; import static org.testng.AssertJUnit.assertArrayEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests embedded and Hot Rod in a replicated clustered environment using byte array values. * * @author Martin Gencur * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "it.interop.ByteArrayValueReplEmbeddedHotRodTest") public class ByteArrayValueReplEmbeddedHotRodTest extends AbstractInfinispanTest { EndpointsCacheFactory<Object, Object> cacheFactory1; EndpointsCacheFactory<Object, Object> cacheFactory2; public void testHotRodPutEmbeddedGet() { final String key = "4"; final byte[] value = "v1".getBytes(); // 1. Put with HotRod RemoteCache<Object, Object> remote = cacheFactory1.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, value)); // 2. Get with Embedded assertArrayEquals(value, (byte[]) cacheFactory2.getEmbeddedCache().get(key)); } public void testHotRodReplace() { final String key = "5"; final byte[] value1 = "v1".getBytes(); final byte[] value2 = "v2".getBytes(); // 1. Put with HotRod RemoteCache<Object, Object> remote = cacheFactory1.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, value1)); // 2. Replace with HotRod VersionedValue<?> versioned = cacheFactory1.getHotRodCache().getWithMetadata(key); assertTrue(cacheFactory1.getHotRodCache().replaceWithVersion(key, value2, versioned.getVersion())); } public void testHotRodRemove() { final String key = "7"; final byte[] value = "v1".getBytes(); // 1. Put with HotRod RemoteCache<Object, Object> remote = cacheFactory1.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, value)); // 2. Remove with HotRod VersionedValue<?> versioned = cacheFactory1.getHotRodCache().getWithMetadata(key); assertTrue(cacheFactory1.getHotRodCache().removeWithVersion(key, versioned.getVersion())); } //This test can fail only if there's a marshaller specified for EmbeddedTypeConverter public void testEmbeddedPutHotRodGet() { final String key = "8"; final byte[] value = "v1".getBytes(); // 1. Put with Embedded assertNull(cacheFactory2.getEmbeddedCache().put(key, value)); // 2. Get with HotRod assertArrayEquals(value, (byte[]) cacheFactory1.getHotRodCache().get(key)); } @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.REPL_SYNC).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.REPL_SYNC).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } }
3,353
35.857143
105
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/ProtoRegistrationJsonTest.java
package org.infinispan.it.endpoints; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.Assert.assertEquals; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.protostream.SerializationContextInitializer; import org.testng.annotations.Test; /** * Tests interoperability between rest and hot rod for json indexing and querying, with the * schema registration done via rest * * @since 9.2 */ @Test(groups = "functional", testName = "it.endpoints.ProtoRegistrationJsonTest") public class ProtoRegistrationJsonTest extends JsonIndexingProtobufStoreTest { @Override protected RemoteCacheManager createRemoteCacheManager() { SerializationContextInitializer sci = EndpointITSCI.INSTANCE; RemoteCacheManager remoteCacheManager = new RemoteCacheManager(new org.infinispan.client.hotrod.configuration.ConfigurationBuilder() .addServer().host("localhost").port(hotRodServer.getPort()) .addContextInitializer(sci) .build()); //initialize server-side serialization context via rest endpoint RestEntity protoFile = RestEntity.create(MediaType.TEXT_PLAIN, sci.getProtoFile()); RestResponse response = join(restClient.cache(PROTOBUF_METADATA_CACHE_NAME).put(sci.getProtoFileName(), protoFile)); assertEquals(response.getStatus(), 204); return remoteCacheManager; } }
1,681
41.05
138
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/JsonPojoStoreTest.java
package org.infinispan.it.endpoints; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests for indexing json using object storage. The entity {@link CryptoCurrency} is annotated with both Protobuf and * Hibernate Search. * * @since 9.2 */ @Test(groups = "functional", testName = "it.endpoints.JsonPojoStoreTest") public class JsonPojoStoreTest extends BaseJsonTest { @Override protected ConfigurationBuilder getIndexCacheConfiguration() { ConfigurationBuilder indexedCache = new ConfigurationBuilder(); indexedCache.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntities(CryptoCurrency.class); indexedCache.encoding().key().mediaType(APPLICATION_OBJECT_TYPE); indexedCache.encoding().value().mediaType(APPLICATION_OBJECT_TYPE); return indexedCache; } @Override protected RemoteCacheManager createRemoteCacheManager() { return new RemoteCacheManager(new org.infinispan.client.hotrod.configuration.ConfigurationBuilder() .addServer().host("localhost").port(hotRodServer.getPort()) .addContextInitializers(EndpointITSCI.INSTANCE) .build()); } @Override protected String getJsonType() { return CryptoCurrency.class.getName(); } }
1,550
32.717391
118
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/DistL1EmbeddedHotRodTest.java
package org.infinispan.it.endpoints; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.getSplitIntKeyForServer; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "it.endpoints.DistL1EmbeddedHotRodTest") public class DistL1EmbeddedHotRodTest extends AbstractInfinispanTest { private static final int NUM_OWNERS = 1; private EndpointsCacheFactory<Integer, String> cacheFactory1; private EndpointsCacheFactory<Integer, String> cacheFactory2; @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<Integer, String>().withCacheMode(CacheMode.DIST_SYNC) .withNumOwners(NUM_OWNERS).withL1(true).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<Integer, String>().withCacheMode(CacheMode.DIST_SYNC) .withNumOwners(NUM_OWNERS).withL1(true).build(); List<Cache<Integer, String>> caches = Arrays.asList(cacheFactory1.getEmbeddedCache(), cacheFactory2.getEmbeddedCache()); TestingUtil.blockUntilViewsReceived(30000, caches); TestingUtil.waitForNoRebalance(caches); assertTrue(cacheFactory1.getHotRodCache().isEmpty()); assertTrue(cacheFactory2.getHotRodCache().isEmpty()); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } public void testEmbeddedPutHotRodGetFromL1() { Cache<Integer, String> embedded1 = cacheFactory1.getEmbeddedCache(); Cache<Integer, String> embedded2 = cacheFactory2.getEmbeddedCache(); Integer key = getSplitIntKeyForServer(cacheFactory1.getHotrodServer(), cacheFactory2.getHotrodServer(), null); // Put it owner, forcing the remote node to get it from L1 embedded1.put(key, "uno"); // Should get it from L1 assertEquals("uno", cacheFactory1.getHotRodCache().get(key)); assertEquals("uno", cacheFactory1.getHotRodCache().get(key)); } }
2,394
38.262295
126
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/ByteArrayValueDistEmbeddedHotRodTest.java
package org.infinispan.it.endpoints; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests embedded and Hot Rod in a distributed clustered environment using byte array values. * * @author Martin Gencur * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "it.interop.ByteArrayValueDistEmbeddedHotRodTest") public class ByteArrayValueDistEmbeddedHotRodTest extends ByteArrayValueReplEmbeddedHotRodTest { @Override @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.DIST_SYNC).withNumOwners(1) .withL1(false).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.DIST_SYNC).withNumOwners(1) .withL1(false).build(); } @Override @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } }
1,090
31.088235
111
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/ByteArrayKeyDistEmbeddedHotRodTest.java
package org.infinispan.it.endpoints; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests embedded and Hot Rod interoperability in a distributed clustered environment using byte array keys. * * @author Martin Gencur * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "it.interop.ByteArrayKeyDistEmbeddedHotRodTest") public class ByteArrayKeyDistEmbeddedHotRodTest extends ByteArrayKeyReplEmbeddedHotRodTest { @Override @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.DIST_SYNC).withNumOwners(1) .withL1(false).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.DIST_SYNC).withNumOwners(1) .withL1(false).build(); } @Override @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } }
1,099
31.352941
111
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/DistEmbeddedRestHotRodTest.java
package org.infinispan.it.endpoints; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests embedded, Hot Rod and REST in a distributed clustered environment. * * @author Martin Gencur * @since 6.0 */ @Test(groups = "functional", testName = "it.interop.DistEmbeddedRestHotRodTest") public class DistEmbeddedRestHotRodTest extends ReplEmbeddedRestHotRodTest { @Override @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.DIST_SYNC) .withNumOwners(1).withL1(false).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.DIST_SYNC) .withNumOwners(1).withL1(false).build(); } @Override @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } }
1,019
29.909091
94
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EmbeddedRestCacheListenerTest.java
package org.infinispan.it.endpoints; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test cache listeners bound to embedded cache and operation over REST cache. * * @author Jiri Holusa [jholusa@redhat.com] */ @Test(groups = "functional", testName = "it.endpoints.EmbeddedRestCacheListenerTest") public class EmbeddedRestCacheListenerTest extends AbstractInfinispanTest { EndpointsCacheFactory<String, String> cacheFactory; @BeforeMethod protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<String, String>().withCacheMode(CacheMode.LOCAL).build(); } @AfterMethod protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } public void testLoadingAndStoringEventsRest() { Cache<String, String> embedded = cacheFactory.getEmbeddedCache(); RestCacheClient remote = cacheFactory.getRestCacheClient(); TestCacheListener l = new TestCacheListener(); embedded.addListener(l); assertTrue(l.created.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertTrue(l.visited.isEmpty()); RestEntity v = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "v".getBytes()); join(remote.put("k", v)); assertEquals(1, l.createdCounter); assertEquals("v".getBytes(), (byte[]) l.created.get("k")); assertTrue(l.removed.isEmpty()); assertEquals(0, l.modifiedCounter); assertTrue(l.visited.isEmpty()); RestEntity value = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "value".getBytes()); join(remote.put("key", value)); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertEquals(0, l.modifiedCounter); assertTrue(l.visited.isEmpty()); RestEntity modifiedValue = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "modifiedValue".getBytes()); join(remote.put("key", modifiedValue)); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertEquals(1, l.modifiedCounter); assertEquals("modifiedValue".getBytes(), (byte[]) l.modified.get("key")); assertTrue(l.visited.isEmpty()); RestEntity replacedValue = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "replacedValue".getBytes()); join(remote.put("k", replacedValue)); assertEquals(2, l.createdCounter); assertTrue(l.removed.isEmpty()); assertEquals(2, l.modifiedCounter); assertEquals("replacedValue".getBytes(), (byte[]) l.modified.get("k")); assertTrue(l.visited.isEmpty()); //resetting so don't have to type "== 2" etc. all over again l.reset(); join(remote.remove("key")); assertTrue(l.created.isEmpty()); assertEquals(1, l.removedCounter); assertEquals("modifiedValue".getBytes(), (byte[]) l.removed.get("key")); assertTrue(l.modified.isEmpty()); l.reset(); join(remote.get("k")); assertTrue(l.created.isEmpty()); assertTrue(l.removed.isEmpty()); assertTrue(l.modified.isEmpty()); assertEquals(1, l.visitedCounter); assertEquals("replacedValue".getBytes(), (byte[]) l.visited.get("k")); l.reset(); } }
3,789
33.770642
115
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/ReplEmbeddedRestHotRodTest.java
package org.infinispan.it.endpoints; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import org.infinispan.Cache; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests embedded, Hot Rod and REST in a replicated clustered environment. * * @author Galder Zamarreño * @since 5.3 */ @Test(groups = "functional", testName = "it.endpoints.ReplEmbeddedRestHotRodTest") public class ReplEmbeddedRestHotRodTest extends AbstractInfinispanTest { EndpointsCacheFactory<Object, Object> cacheFactory1; EndpointsCacheFactory<Object, Object> cacheFactory2; @BeforeClass protected void setup() throws Exception { cacheFactory1 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.REPL_SYNC).build(); cacheFactory2 = new EndpointsCacheFactory.Builder<>().withCacheMode(CacheMode.REPL_SYNC).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory1, cacheFactory2); } public void testRestPutEmbeddedHotRodGet() { final String key = "1"; // 1. Put with REST RestEntity value = RestEntity.create(MediaType.TEXT_PLAIN, "<hey>ho</hey>".getBytes()); RestResponse response = join(cacheFactory1.getRestCacheClient().put(key, value)); assertEquals(204, response.getStatus()); // 2. Get with Embedded Cache embeddedCache = cacheFactory2.getEmbeddedCache().getAdvancedCache(); assertEquals("<hey>ho</hey>", embeddedCache.get(key)); // 3. Get with Hot Rod assertEquals("<hey>ho</hey>", cacheFactory2.getHotRodCache().get(key)); } public void testEmbeddedPutRestHotRodGet() { final String key = "2"; // 1. Put with Embedded Cache cache = cacheFactory2.getEmbeddedCache().getAdvancedCache(); assertNull(cache.put(key, "v1")); // 2. Get with Hot Rod via remote client, will use the configured encoding assertEquals("v1", cacheFactory1.getHotRodCache().get(key)); // 3. Get with REST, specifying the results as 'text' RestResponse response = join(cacheFactory2.getRestCacheClient().get(key, TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals("v1", response.getBody()); } public void testHotRodPutEmbeddedRestGet() { final String key = "3"; // 1. Put with Hot Rod RemoteCache<Object, Object> remote = cacheFactory1.getHotRodCache(); assertEquals(null, remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); // 2. Get with Embedded Cache embeddedCache = cacheFactory2.getEmbeddedCache().getAdvancedCache(); assertEquals("v1", embeddedCache.get(key)); // 3. Get with REST RestResponse response = join(cacheFactory2.getRestCacheClient().get(key, TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals("v1", response.getBody()); } }
3,491
36.148936
103
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/SpyMemcachedMarshaller.java
package org.infinispan.it.endpoints; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.marshall.AbstractMarshaller; import net.spy.memcached.CachedData; import net.spy.memcached.transcoders.SerializingTranscoder; import net.spy.memcached.transcoders.Transcoder; public class SpyMemcachedMarshaller extends AbstractMarshaller { private final Transcoder<Object> transcoder = new SerializingTranscoder(); @Override protected ByteBuffer objectToBuffer(Object o, int estimatedSize) { CachedData encoded = transcoder.encode(o); return ByteBufferImpl.create(encoded.getData()); } @Override public Object objectFromByteBuffer(byte[] buf, int offset, int length) { return transcoder.decode(new CachedData(0, buf, length)); } @Override public boolean isMarshallable(Object o) { try { transcoder.encode(o); return true; } catch (Throwable t) { return false; } } @Override public MediaType mediaType() { return MediaType.fromString("application/x-memcached"); } }
1,200
26.295455
77
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EmbeddedRestHotRodWithStringTest.java
package org.infinispan.it.endpoints; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "it.endpoints.EmbeddedRestHotRodWithStringTest") public class EmbeddedRestHotRodWithStringTest extends AbstractInfinispanTest { EndpointsCacheFactory<String, Object> cacheFactory; @BeforeClass protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<String, Object>().withCacheName("testCache") .withMarshaller(new UTF8StringMarshaller()).withCacheMode(CacheMode.LOCAL).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } public void testRestPutStringHotRodGet() { final String key = "1"; // 1. Put text content with REST RestEntity value = RestEntity.create(MediaType.TEXT_PLAIN, "<hey>ho</hey>"); RestResponse response = join(cacheFactory.getRestCacheClient().put(key, value)); assertEquals(204, response.getStatus()); // 3. Get with Hot Rod assertEquals("<hey>ho</hey>", cacheFactory.getHotRodCache().get(key)); final String newKey = "2"; final String newValue = "<let's>go</let's>"; //4. Put text content with Hot Rod RemoteCache<String, Object> hotRodCache = cacheFactory.getHotRodCache(); hotRodCache.put(newKey, newValue); //5. Read with rest response = join(cacheFactory.getRestCacheClient().get(newKey)); assertEquals(200, response.getStatus()); assertEquals(newValue, response.getBody()); } }
2,135
35.827586
99
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/CustomMemcachedHotRodTest.java
package org.infinispan.it.endpoints; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.Arrays; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests Hot Rod and Memcached interoperability, using a different client to SpyMemcached, * and Hot Rod. * * @author Galder Zamarreño * @since 5.3 */ @Test(groups = "functional", testName = "it.interop.CustomMemcachedHotRodTest") public class CustomMemcachedHotRodTest extends AbstractInfinispanTest { final static String CACHE_NAME = "memcachedCache"; EndpointsCacheFactory<String, String> cacheFactory; @BeforeClass protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<String, String>().withCacheName(CACHE_NAME) .withMarshaller(new UTF8StringMarshaller()).withCacheMode(CacheMode.LOCAL).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } public void testHotRodPutMemcachedGet() throws IOException { final String key = "1"; // 1. Put with Hot Rod RemoteCache<String, String> remote = cacheFactory.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); // 2. Read with Memcached MemcachedClient memcached = new MemcachedClient("localhost", cacheFactory.getMemcachedPort()); try { assertEquals("v1".getBytes(), memcached.getBytes(key)); } finally { memcached.close(); } } public void testMemcachedPutGet() throws IOException { final String key = "1"; MemcachedClient memcached = new MemcachedClient("localhost", cacheFactory.getMemcachedPort()); try { memcached.set(key, "v1"); assertEquals("v1", memcached.get(key)); } finally { memcached.close(); } } /** * Alternative Memcached client to SpyMemcached. * * @author Martin Gencur */ static class MemcachedClient { private static final int DEFAULT_TIMEOUT = 10000; private static final String DEFAULT_ENCODING = "UTF-8"; private String encoding; private Socket socket; private PrintWriter out; private InputStream input; public MemcachedClient(String host, int port) throws IOException { this(DEFAULT_ENCODING, host, port, DEFAULT_TIMEOUT); } public MemcachedClient(String enc, String host, int port, int timeout) throws IOException { encoding = enc; socket = new Socket(host, port); socket.setSoTimeout(timeout); out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), encoding)); input = socket.getInputStream(); } public String get(String key) throws IOException { byte[] data = getBytes(key); return (data == null) ? null : new String(data, encoding); } public byte[] getBytes(String key) throws IOException { writeln("get " + key); flush(); String valueStr = readln(); if (valueStr.startsWith("VALUE")) { String[] value = valueStr.split(" "); assertEquals(key, value[1]); int size = new Integer(value[3]); byte[] ret = read(size); assertEquals('\r', read()); assertEquals('\n', read()); assertEquals("END", readln()); return ret; } else { return null; } } public void set(String key, String value) throws IOException { writeln("set " + key + " 0 0 " + value.getBytes(encoding).length); writeln(value); flush(); assertEquals("STORED", readln()); } private byte[] read(int len) throws IOException { try { byte[] ret = new byte[len]; input.read(ret, 0, len); return ret; } catch (SocketTimeoutException ste) { return null; } } private byte read() throws IOException { try { return (byte) input.read(); } catch (SocketTimeoutException ste) { return -1; } } private String readln() throws IOException { byte[] buf = new byte[512]; int maxlen = 512; int read = 0; buf[read] = read(); while (buf[read] != '\n') { read++; if (read == maxlen) { maxlen += 512; buf = Arrays.copyOf(buf, maxlen); } buf[read] = read(); } if (read == 0) { return ""; } if (buf[read - 1] == '\r') { read--; } buf = Arrays.copyOf(buf, read); return new String(buf, encoding); } private void writeln(String str) { out.print(str + "\r\n"); } private void flush() { out.flush(); } public void close() throws IOException { socket.close(); } } }
5,607
28.515789
98
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/BaseJsonTest.java
package org.infinispan.it.endpoints; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.startHotRodServer; import static org.infinispan.rest.JSONConstants.TYPE; import static org.infinispan.server.core.test.ServerTestingUtil.findFreePort; import static org.infinispan.test.TestingUtil.killCacheManagers; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.Assert.assertEquals; import java.nio.charset.StandardCharsets; import java.util.List; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.dsl.Query; import org.infinispan.rest.RestServer; import org.infinispan.rest.configuration.RestServerConfigurationBuilder; import org.infinispan.server.core.DummyServerManagement; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Base class for Json reading/writing/querying across multiple endpoints. * * @since 9.2 */ @Test(groups = "functional") public abstract class BaseJsonTest extends AbstractInfinispanTest { RestServer restServer; RestClient restClient; private EmbeddedCacheManager cacheManager; private RemoteCacheManager remoteCacheManager; private RemoteCache<String, CryptoCurrency> remoteCache; private static final String CACHE_NAME = "indexed"; HotRodServer hotRodServer; private RestCacheClient restCacheClient; abstract ConfigurationBuilder getIndexCacheConfiguration(); abstract RemoteCacheManager createRemoteCacheManager() throws Exception; @BeforeClass protected void setup() throws Exception { cacheManager = TestCacheManagerFactory.createServerModeCacheManager(EndpointITSCI.INSTANCE, new ConfigurationBuilder()); cacheManager.getClassWhiteList().addRegexps(".*"); cacheManager.defineConfiguration(CACHE_NAME, getIndexCacheConfiguration().build()); RestServerConfigurationBuilder builder = new RestServerConfigurationBuilder(); int restPort = findFreePort(); builder.port(restPort); restServer = new RestServer(); restServer.setServerManagement(new DummyServerManagement(), true); restServer.start(builder.build(), cacheManager); restClient = RestClient.forConfiguration(new RestClientConfigurationBuilder().addServer().host(restServer.getHost()).port(restServer.getPort()).build()); restCacheClient = restClient.cache(CACHE_NAME); hotRodServer = startHotRodServer(cacheManager); remoteCacheManager = createRemoteCacheManager(); remoteCache = remoteCacheManager.getCache(CACHE_NAME); } protected String getEntityName() { return EndpointITSCI.getFQN(CryptoCurrency.class); } protected String getJsonType() { return getEntityName(); } private void writeCurrencyViaJson(String key, String description, int rank) { Json currency = Json.object(); currency.set(TYPE, getJsonType()); currency.set("description", description); currency.set("rank", rank); RestEntity value = RestEntity.create(MediaType.APPLICATION_JSON, currency.toString()); RestResponse response = join(restCacheClient.put(key, value)); assertEquals(response.getStatus(), 204); } private CryptoCurrency readCurrencyViaJson(String key) { RestResponse response = join(restCacheClient.get(key, MediaType.APPLICATION_JSON_TYPE)); String json = response.getBody(); Json jsonNode = Json.read(json); Json description = jsonNode.at("description"); Json rank = jsonNode.at("rank"); return new CryptoCurrency(description.asString(), rank.asInteger()); } @Test public void testRestOnly() { writeCurrencyViaJson("DASH", "Dash", 7); writeCurrencyViaJson("IOTA", "Iota", 8); writeCurrencyViaJson("XMR", "Monero", 9); CryptoCurrency xmr = readCurrencyViaJson("XMR"); assertEquals(xmr.getRank(), Integer.valueOf(9)); assertEquals(xmr.getDescription(), "Monero"); } @Test public void testHotRodInteroperability() { remoteCache.clear(); // Put object via Hot Rod remoteCache.put("BTC", new CryptoCurrency("Bitcoin", 1)); remoteCache.put("ETH", new CryptoCurrency("Ethereum", 2)); remoteCache.put("XRP", new CryptoCurrency("Ripple", 3)); remoteCache.put("CAT", new CryptoCurrency("Catcoin", 618)); assertEquals(remoteCache.get("CAT").getDescription(), "Catcoin"); assertEquals(remoteCache.size(), 4); Query<CryptoCurrency> query = Search.getQueryFactory(remoteCache).create("FROM " + getEntityName() + " c where c.rank < 10"); List<CryptoCurrency> highRankCoins = query.execute().list(); assertEquals(highRankCoins.size(), 3); // Read as Json CryptoCurrency btc = readCurrencyViaJson("BTC"); assertEquals(btc.getDescription(), "Bitcoin"); assertEquals(btc.getRank(), Integer.valueOf(1)); // Write as Json writeCurrencyViaJson("LTC", "Litecoin", 4); // Assert inserted entity is searchable query = Search.getQueryFactory(remoteCache).create("FROM " + getEntityName() + " c where c.description = 'Litecoin'"); CryptoCurrency litecoin = query.execute().list().iterator().next(); assertEquals(litecoin.getDescription(), "Litecoin"); assertEquals(litecoin.getRank(), Integer.valueOf(4)); // Read as JSON from the Hot Rod client Object jsonResult = remoteCache.withDataFormat(DataFormat.builder().valueType(MediaType.APPLICATION_JSON).build()).get("LTC"); Json jsonNode = Json.read(new String((byte[]) jsonResult, StandardCharsets.UTF_8)); assertEquals(jsonNode.at("description").asString(), "Litecoin"); } @AfterClass protected void teardown() { Util.close(restClient); remoteCacheManager.stop(); if (restServer != null) { try { restServer.stop(); } catch (Exception ignored) { } } killCacheManagers(cacheManager); cacheManager = null; killServers(hotRodServer); hotRodServer = null; } }
7,022
38.234637
159
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EmbeddedRestHotRodTest.java
package org.infinispan.it.endpoints; import static java.util.Collections.singletonMap; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.rest.JSONConstants.TYPE; import static org.infinispan.rest.ResponseHeader.CONTENT_TYPE_HEADER; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertArrayEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.rest.ResponseHeader; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test embedded caches, Hot Rod, and REST endpoints. * * @author Galder Zamarreño * @since 5.3 */ @Test(groups = "functional", testName = "it.endpoints.EmbeddedRestHotRodTest") public class EmbeddedRestHotRodTest extends AbstractInfinispanTest { private static final DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); EndpointsCacheFactory<String, Object> cacheFactory; @BeforeClass protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<String, Object>().withCacheMode(CacheMode.LOCAL) .withContextInitializer(EndpointITSCI.INSTANCE).build(); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); cacheFactory.addRegexAllowList("org.infinispan.*Person"); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } public void testRestPutEmbeddedHotRodGet() { final String key = "1"; // 1. Put with REST RestCacheClient restCacheClient = cacheFactory.getRestCacheClient(); CompletionStage<RestResponse> response = restCacheClient.put(key, RestEntity.create(TEXT_PLAIN, "<hey>ho</hey>")); assertEquals(204, join(response).getStatus()); // 2. Get with Embedded assertEquals("<hey>ho</hey>", cacheFactory.getEmbeddedCache().get(key)); // 3. Get with Hot Rod assertEquals("<hey>ho</hey>", cacheFactory.getHotRodCache().get(key)); } public void testEmbeddedPutRestHotRodGet() { final String key = "2"; // 1. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key, "v1")); // 2. Get with Hot Rod assertEquals("v1", cacheFactory.getHotRodCache().get(key)); // 3. Get with REST RestResponse response = join(cacheFactory.getRestCacheClient().get(key, TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals("v1", response.getBody()); } public void testHotRodPutEmbeddedRestGet() { final String key = "3"; // 1. Put with Hot Rod RemoteCache<String, Object> remote = cacheFactory.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1")); // 2. Get with Embedded assertEquals("v1", cacheFactory.getEmbeddedCache().get(key)); // 3. Get with REST RestResponse response = join(cacheFactory.getRestCacheClient().get(key, TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals("v1", response.getBody()); } public void testCustomObjectHotRodPutEmbeddedRestGet() throws Exception { final String key = "4"; Person p = new Person("Martin"); // 1. Put with Hot Rod RemoteCache<String, Object> remote = cacheFactory.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, p)); // 2. Get with Embedded assertEquals(p, cacheFactory.getEmbeddedCache().get(key)); // 3. Get with REST RestResponse response = join(cacheFactory.getRestCacheClient().get(key, APPLICATION_SERIALIZED_OBJECT_TYPE)); assertEquals(200, response.getStatus()); // REST finds the Java POJO in-memory and returns the Java serialized version assertEquals(p, new ObjectInputStream(response.getBodyAsStream()).readObject()); } public void testCustomObjectEmbeddedPutHotRodRestGet() throws Exception { final String key = "5"; Person p = new Person("Galder"); // 1. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key, p)); // 2. Get with Hot Rod assertEquals(p, cacheFactory.getHotRodCache().get(key)); // 3. Get with REST RestResponse response = join(cacheFactory.getRestCacheClient() .get(key, "application/x-java-serialized-object, application/json;q=0.3")); assertEquals(200, response.getStatus()); // REST finds the Java POJO in-memory and returns the Java serialized version assertEquals(p, new ObjectInputStream(response.getBodyAsStream()).readObject()); } public void testCustomObjectEmbeddedPutRestGetAcceptJSONAndXML() { final String key = "6"; final Person p = new Person("Anna"); // 1. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key, p)); // 2. Get with REST (accept application/json) RestResponse response = join(cacheFactory.getRestCacheClient().get(key, APPLICATION_JSON_TYPE)); String body = response.getBody(); assertEquals(200, response.getStatus()); assertEquals(asJson(p), body); // 3. Get with REST (accept application/xml) response = join(cacheFactory.getRestCacheClient().get(key, APPLICATION_XML_TYPE)); assertEquals(200, response.getStatus()); assertTrue(response.getBody().contains("<name>Anna</name>")); } public void testCustomObjectHotRodPutRestGetAcceptJSONAndXML() { final String key = "7"; final Person p = new Person("Jakub"); // 1. Put with HotRod RemoteCache<String, Object> remote = cacheFactory.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key, p)); // 2. Get with REST (accept application/json) RestResponse response = join(cacheFactory.getRestCacheClient().get(key, APPLICATION_JSON_TYPE)); assertEquals(200, response.getStatus()); assertEquals(asJson(p), response.getBody()); // 3. Get with REST (accept application/xml) response = join(cacheFactory.getRestCacheClient().get(key, APPLICATION_XML_TYPE)); assertEquals(200, response.getStatus()); assertTrue(response.getBody().contains("<name>Jakub</name>")); } public void testCustomObjectRestPutHotRodEmbeddedGet() throws Exception { final String key = "77"; Person p = new Person("Iker"); // 1. Put with Rest RestCacheClient restClient = cacheFactory.getRestCacheClient(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(bout)) { oos.writeObject(p); } RestEntity value = RestEntity.create(APPLICATION_SERIALIZED_OBJECT, new ByteArrayInputStream(bout.toByteArray())); join(restClient.put(key, value)); // 2. Get with Hot Rod RemoteCache<String, Object> remote = cacheFactory.getHotRodCache(); assertEquals(p, remote.get(key)); // 3. Get with Embedded assertEquals(p, cacheFactory.getEmbeddedCache().getAdvancedCache().get(key)); } public void testHotRodEmbeddedPutRestHeadExpiry() throws Exception { final String key1 = "8"; final String key2 = "9"; // 1. Put with HotRod assertNull(cacheFactory.getHotRodCache().put(key1, "v1", 5, TimeUnit.SECONDS)); // 2. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key2, "v2", 5, TimeUnit.SECONDS)); // 3. HEAD with REST key1 RestResponse response = join(cacheFactory.getRestCacheClient().head(key1)); assertEquals(200, response.getStatus()); String expires = response.getHeader(ResponseHeader.EXPIRES_HEADER.getValue()); assertNotNull(expires); assertTrue(dateFormat.parse(expires).after(new GregorianCalendar(2013, Calendar.JANUARY, 1).getTime())); // 4. HEAD with REST key2 response = join(cacheFactory.getRestCacheClient().head(key2)); assertEquals(200, response.getStatus()); expires = response.getHeader(ResponseHeader.EXPIRES_HEADER.getValue()); assertNotNull(expires); } public void testHotRodEmbeddedPutRestGetExpiry() throws Exception { final String key = "10"; final String key2 = "11"; // 1. Put with HotRod assertNull(cacheFactory.getHotRodCache().put(key, "v1", 5, TimeUnit.SECONDS)); // 2. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key2, "v2", 5, TimeUnit.SECONDS)); // 3. Get with REST key RestResponse response = join(cacheFactory.getRestCacheClient().get(key)); assertEquals(200, response.getStatus()); assertDate(response, "Expires"); // 4. Get with REST key2 response = join(cacheFactory.getRestCacheClient().get(key2)); assertEquals(200, response.getStatus()); assertDate(response, "Expires"); } public void testHotRodEmbeddedPutRestGetLastModified() throws Exception { final String key = "12"; final String key2 = "13"; // 1. Put with HotRod assertNull(cacheFactory.getHotRodCache().put(key, "v1", 5, TimeUnit.SECONDS)); // 2. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key2, "v2", 5, TimeUnit.SECONDS)); // 3. Get with REST key RestResponse response = join(cacheFactory.getRestCacheClient().get(key)); assertEquals(200, response.getStatus()); assertDate(response, "Last-Modified"); // 4. Get with REST key2 response = join(cacheFactory.getRestCacheClient().get(key2)); assertEquals(200, response.getStatus()); assertDate(response, "Last-Modified"); } private static void assertDate(RestResponse response, String header) throws Exception { String dateHeader = response.getHeader(header); assertNotNull(dateHeader); Date parsedDate = dateFormat.parse(dateHeader); assertTrue("Parsed date is before this code was written: " + parsedDate, parsedDate.after(new GregorianCalendar(2013, Calendar.JANUARY, 1).getTime())); } public void testByteArrayHotRodEmbeddedPutRestGet() { final String key1 = "14"; final String key2 = "15"; // 1. Put with Hot Rod RemoteCache<String, Object> remote = cacheFactory.getHotRodCache(); assertNull(remote.withFlags(Flag.FORCE_RETURN_VALUE).put(key1, "v1".getBytes())); // 2. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key2, "v2".getBytes())); // 3. Get with REST key1 RestResponse response = join(cacheFactory.getRestCacheClient().get(key1, TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals(TEXT_PLAIN_TYPE, response.getHeader(CONTENT_TYPE_HEADER.getValue())); assertArrayEquals("v1".getBytes(), response.getBodyAsByteArray()); // 4. Get with REST key2 response = join(cacheFactory.getRestCacheClient().get(key2, TEXT_PLAIN_TYPE)); assertEquals(200, response.getStatus()); assertEquals(TEXT_PLAIN_TYPE, response.getHeader(CONTENT_TYPE_HEADER.getValue())); assertArrayEquals("v2".getBytes(), response.getBodyAsByteArray()); } public void testHotRodEmbeddedPutRestGetWrongAccept() { final String key1 = "16"; final String key2 = "17"; // 1. Put with HotRod assertNull(cacheFactory.getHotRodCache().put(key1, "v1")); // 2. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key2, "v2")); // 3. GET with REST key1 RestResponse response = join(cacheFactory.getRestCacheClient().get(key1, "unknown-media-type")); assertEquals(406, response.getStatus()); // 4. GET with REST key2 response = join(cacheFactory.getRestCacheClient().get(key2, "unknown-media-type")); assertEquals(406, response.getStatus()); } public void testHotRodEmbeddedPutRestGetCacheControlHeader() { final String key1 = "18"; final String key2 = "19"; // 1. Put with HotRod assertNull(cacheFactory.getHotRodCache().put(key1, "v1", 7, TimeUnit.SECONDS)); // 2. Put with Embedded assertNull(cacheFactory.getEmbeddedCache().put(key2, "v2", 7, TimeUnit.SECONDS)); // 3. GET with REST key1, long min-fresh Map<String, String> headers = singletonMap("Cache-Control", "min-fresh=20"); RestResponse response = join(cacheFactory.getRestCacheClient().get(key1, headers)); assertEquals(404, response.getStatus()); // 4. GET with REST key2, long min-fresh response = join(cacheFactory.getRestCacheClient().get(key2, headers)); assertEquals(404, response.getStatus()); // 5. GET with REST key1, short min-fresh headers = new HashMap<>(); headers.put("Accept", TEXT_PLAIN_TYPE); headers.put("Cache-Control", "min-fresh=3"); response = join(cacheFactory.getRestCacheClient().get(key1, headers)); assertEquals(200, response.getStatus()); assertNotNull(response.getHeader("Cache-Control")); assertTrue(response.getHeader("Cache-Control").contains("max-age")); assertEquals("v1", response.getBody()); // 6. GET with REST key2, short min-fresh response = join(cacheFactory.getRestCacheClient().get(key2, headers)); assertEquals(200, response.getStatus()); assertTrue(response.getHeader("Cache-Control").contains("max-age")); assertEquals("v2", response.getBody()); } private String asJson(Person p) { Json person = Json.object(); person.set(TYPE, p.getClass().getName()); person.set("name", p.name); return person.toString(); } /** * The class needs a getter for the attribute "name" so that it can be converted to JSON format * internally by the REST server. */ static class Person implements Serializable { @ProtoField(number = 1) final String name; @ProtoFactory Person(String name) { this.name = name; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return name.equals(person.name); } @Override public int hashCode() { return name.hashCode(); } } }
16,026
37.526442
120
java
null
infinispan-main/integrationtests/endpoints-interop-it/src/test/java/org/infinispan/it/endpoints/EmbeddedHotRodBulkTest.java
package org.infinispan.it.endpoints; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Set; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.api.BasicCache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test embedded caches and Hot Rod endpoints for operations that retrieve data in bulk, * i.e. keySet, entrySet...etc. * * @author Jiří Holuša * @since 6.0 */ @Test(groups = "functional", testName = "it.endpoints.EmbeddedHotRodBulkTest") public class EmbeddedHotRodBulkTest extends AbstractInfinispanTest { EndpointsCacheFactory<Integer, Integer> cacheFactory; @BeforeClass protected void setup() throws Exception { cacheFactory = new EndpointsCacheFactory.Builder<Integer, Integer>().withCacheMode(CacheMode.LOCAL).build(); } @AfterClass protected void teardown() { EndpointsCacheFactory.killCacheFactories(cacheFactory); } private void populateCacheManager(BasicCache cache) { for (int i = 0; i < 100; i++) { cache.put(i, i); } } public void testEmbeddedPutHotRodKeySet() { Cache<Integer, Integer> embedded = cacheFactory.getEmbeddedCache(); RemoteCache<Integer, Integer> remote = cacheFactory.getHotRodCache(); populateCacheManager(embedded); Set<Integer> keySet = remote.keySet(); assertEquals(100, keySet.size()); for (int i = 0; i < 100; i++) { assertTrue(keySet.contains(i)); } } public void testHotRodPutEmbeddedKeySet() { Cache<Integer, Integer> embedded = cacheFactory.getEmbeddedCache(); RemoteCache<Integer, Integer> remote = cacheFactory.getHotRodCache(); populateCacheManager(remote); Set<Integer> keySet = embedded.keySet(); assertEquals(100, keySet.size()); for (int i = 0; i < 100; i++) { assertTrue(keySet.contains(i)); } } }
2,153
28.108108
114
java