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/core/src/main/java/org/infinispan/factories/package-info.java
|
/**
* Factories are internal components used to create other components based on a cache's
* configuration. This package also contains the ComponentRegistry classes, a light injection
* framework used to build and inject components based on what is needed.
*/
package org.infinispan.factories;
| 299
| 41.857143
| 94
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/AbstractComponentFactory.java
|
package org.infinispan.factories;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Factory that creates components used internally within Infinispan, and also wires dependencies into the components.
* <p/>
* The {@link InternalCacheFactory} is a special subclass of this, which bootstraps the construction of other
* components. When this class is loaded, it maintains a static list of known default factories for known components,
* which it then delegates to, when actually performing the construction.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @see Inject
* @see ComponentRegistry
* @since 4.0
*/
@Scope(Scopes.GLOBAL)
public abstract class AbstractComponentFactory extends AnyScopeComponentFactory {
}
| 871
| 35.333333
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/TransactionManagerFactory.java
|
package org.infinispan.factories;
import jakarta.transaction.TransactionManager;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.tx.lookup.TransactionManagerLookup;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.transaction.tm.BatchModeTransactionManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Uses a number of mechanisms to retrieve a transaction manager.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Galder Zamarreño
* @since 4.0
*/
@DefaultFactoryFor(classes = {TransactionManager.class})
public class TransactionManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
private static final Log log = LogFactory.getLog(TransactionManagerFactory.class);
@Override
public Object construct(String componentName) {
if (!configuration.transaction().transactionMode().isTransactional()) {
return null;
}
// See if we had a TransactionManager injected into our config
TransactionManager transactionManager = null;
TransactionManagerLookup lookup = configuration.transaction().transactionManagerLookup();
try {
if (lookup != null) {
componentRegistry.wireDependencies(lookup, false);
transactionManager = lookup.getTransactionManager();
}
} catch (Exception e) {
log.couldNotInstantiateTransactionManager(e);
}
if (transactionManager == null && configuration.invocationBatching().enabled()) {
log.usingBatchModeTransactionManager();
transactionManager = BatchModeTransactionManager.getInstance();
}
if (transactionManager == null) {
throw new CacheException("This is transactional cache but no transaction manager could be found. " +
"Configure the transaction manager lookup properly.");
}
return transactionManager;
}
}
| 2,055
| 35.714286
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/LockManagerFactory.java
|
package org.infinispan.factories;
import static org.infinispan.util.logging.Log.CONTAINER;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.concurrent.locks.PendingLockManager;
import org.infinispan.util.concurrent.locks.impl.DefaultLockManager;
import org.infinispan.util.concurrent.locks.impl.DefaultPendingLockManager;
import org.infinispan.util.concurrent.locks.impl.NoOpPendingLockManager;
/**
* Factory class that creates instances of {@link LockManager}.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
@DefaultFactoryFor(classes = {LockManager.class, PendingLockManager.class} )
public class LockManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (PendingLockManager.class.getName().equals(componentName)) {
return configuration.clustering().cacheMode().isClustered() ?
new DefaultPendingLockManager() :
NoOpPendingLockManager.getInstance();
} else if (LockManager.class.getName().equals(componentName)) {
return new DefaultLockManager();
}
throw CONTAINER.factoryCannotConstructComponent(componentName);
}
}
| 1,361
| 40.272727
| 111
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/StateTransferComponentFactory.java
|
package org.infinispan.factories;
import static org.infinispan.util.logging.Log.CONTAINER;
import org.infinispan.conflict.ConflictManager;
import org.infinispan.conflict.impl.DefaultConflictManager;
import org.infinispan.conflict.impl.InternalConflictManager;
import org.infinispan.conflict.impl.StateReceiver;
import org.infinispan.conflict.impl.StateReceiverImpl;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.statetransfer.StateConsumer;
import org.infinispan.statetransfer.StateConsumerImpl;
import org.infinispan.statetransfer.StateProvider;
import org.infinispan.statetransfer.StateProviderImpl;
import org.infinispan.statetransfer.StateTransferManager;
import org.infinispan.statetransfer.StateTransferManagerImpl;
/**
* Constructs {@link org.infinispan.statetransfer.StateTransferManager},
* {@link org.infinispan.statetransfer.StateConsumer}
* and {@link org.infinispan.statetransfer.StateProvider} instances.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Dan Berindei <dan@infinispan.org>
* @author anistor@redhat.com
* @since 4.0
*/
@DefaultFactoryFor(classes = {StateTransferManager.class, StateConsumer.class, StateProvider.class, StateReceiver.class,
ConflictManager.class, InternalConflictManager.class})
public class StateTransferComponentFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (!configuration.clustering().cacheMode().isClustered())
return null;
if (componentName.equals(StateTransferManager.class.getName())) {
return new StateTransferManagerImpl();
} else if (componentName.equals(StateProvider.class.getName())) {
return new StateProviderImpl();
} else if (componentName.equals(StateConsumer.class.getName())) {
return new StateConsumerImpl();
} else if (componentName.equals(StateReceiver.class.getName())) {
return new StateReceiverImpl<>();
} else if (componentName.equals(ConflictManager.class.getName()) || componentName.equals(InternalConflictManager.class.getName())) {
return new DefaultConflictManager<>();
}
throw CONTAINER.factoryCannotConstructComponent(componentName);
}
}
| 2,337
| 44.843137
| 138
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/SecurityActions.java
|
package org.infinispan.factories;
import java.lang.reflect.Field;
import java.util.Map.Entry;
import java.util.Properties;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* SecurityActions for the org.infinispan.factories package.
* <p>
* Do not move. Do not change class and method visibility to avoid being called from other
* {@link java.security.CodeSource}s, thus granting privilege escalation to external code.
*
* @author Tristan Tarrant
* @since 7.0
*/
final class SecurityActions {
private static final Log log = LogFactory.getLog(SecurityActions.class);
private static Field findFieldRecursively(Class<?> c, String fieldName) {
Field f = null;
try {
f = c.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
if (!c.equals(Object.class)) f = findFieldRecursively(c.getSuperclass(), fieldName);
}
return f;
}
static void setValue(Object instance, String fieldName, Object value) {
try {
final Field f = findFieldRecursively(instance.getClass(), fieldName);
if (f == null) {
throw new NoSuchMethodException("Cannot find field " + fieldName + " on " + instance.getClass() + " or superclasses");
}
f.setAccessible(true);
f.set(instance, value);
} catch (Exception e) {
log.unableToSetValue(e);
}
}
static void applyProperties(Object o, Properties p) {
for (Entry<Object, Object> entry : p.entrySet()) {
setValue(o, (String) entry.getKey(), entry.getValue());
}
}
}
| 1,614
| 30.057692
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/InboundInvocationHandlerFactory.java
|
package org.infinispan.factories;
import org.infinispan.configuration.cache.Configurations;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.remoting.inboundhandler.NonTxPerCacheInboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.TrianglePerCacheInboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.TxPerCacheInboundInvocationHandler;
/**
* Factory class that creates instances of {@link org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler}.
*
* @author Pedro Ruivo
* @since 7.1
*/
@DefaultFactoryFor(classes = PerCacheInboundInvocationHandler.class)
public class InboundInvocationHandlerFactory extends AbstractNamedCacheComponentFactory implements
AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (!configuration.clustering().cacheMode().isClustered()) {
return null;
} else if (configuration.transaction().transactionMode().isTransactional()) {
return new TxPerCacheInboundInvocationHandler();
} else {
if (configuration.clustering().cacheMode().isDistributed() && Configurations.isEmbeddedMode(globalConfiguration)) {
return new TrianglePerCacheInboundInvocationHandler();
} else {
return new NonTxPerCacheInboundInvocationHandler();
}
}
}
}
| 1,475
| 41.171429
| 124
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/EmptyConstructorFactory.java
|
package org.infinispan.factories;
import static org.infinispan.util.logging.Log.CONTAINER;
import org.infinispan.commands.RemoteCommandsFactory;
import org.infinispan.commons.time.TimeService;
import org.infinispan.container.versioning.RankCalculator;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.globalstate.GlobalConfigurationManager;
import org.infinispan.globalstate.GlobalStateManager;
import org.infinispan.globalstate.impl.GlobalConfigurationManagerImpl;
import org.infinispan.globalstate.impl.GlobalStateManagerImpl;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistryImpl;
import org.infinispan.remoting.inboundhandler.GlobalInboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.InboundInvocationHandler;
import org.infinispan.security.PrincipalRoleMapper;
import org.infinispan.security.RolePermissionMapper;
import org.infinispan.topology.PersistentUUIDManager;
import org.infinispan.topology.PersistentUUIDManagerImpl;
import org.infinispan.util.EmbeddedTimeService;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.BlockingManagerImpl;
import org.infinispan.util.concurrent.DataOperationOrderer;
import org.infinispan.util.concurrent.NonBlockingManager;
import org.infinispan.util.concurrent.NonBlockingManagerImpl;
import org.infinispan.util.logging.events.EventLogManager;
import org.infinispan.util.logging.events.EventLoggerNotifier;
import org.infinispan.util.logging.events.impl.EventLogManagerImpl;
import org.infinispan.util.logging.events.impl.EventLoggerNotifierImpl;
/**
* Factory for building global-scope components which have default empty constructors
*
* @author Manik Surtani
* @author <a href="mailto:galder.zamarreno@jboss.com">Galder Zamarreno</a>
* @since 4.0
*/
@DefaultFactoryFor(classes = {
EventLogManager.class,
InboundInvocationHandler.class, PersistentUUIDManager.class,
RemoteCommandsFactory.class, TimeService.class, DataOperationOrderer.class,
GlobalStateManager.class, GlobalConfigurationManager.class,
SerializationContextRegistry.class, BlockingManager.class, NonBlockingManager.class,
RankCalculator.class, EventLoggerNotifier.class, PrincipalRoleMapper.class, RolePermissionMapper.class
})
@Scope(Scopes.GLOBAL)
public class EmptyConstructorFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (componentName.equals(InboundInvocationHandler.class.getName()))
return new GlobalInboundInvocationHandler();
else if (componentName.equals(RemoteCommandsFactory.class.getName()))
return new RemoteCommandsFactory();
else if (componentName.equals(TimeService.class.getName()))
return new EmbeddedTimeService();
else if (componentName.equals(EventLogManager.class.getName()))
return new EventLogManagerImpl();
else if (componentName.equals(PersistentUUIDManager.class.getName()))
return new PersistentUUIDManagerImpl();
else if (componentName.equals(GlobalStateManager.class.getName()))
return new GlobalStateManagerImpl();
else if (componentName.equals(GlobalConfigurationManager.class.getName()))
return new GlobalConfigurationManagerImpl();
else if (componentName.equals(DataOperationOrderer.class.getName()))
return new DataOperationOrderer();
else if (componentName.equals(SerializationContextRegistry.class.getName()))
return new SerializationContextRegistryImpl();
else if (componentName.equals(BlockingManager.class.getName()))
return new BlockingManagerImpl();
else if (componentName.equals(NonBlockingManager.class.getName()))
return new NonBlockingManagerImpl();
else if (componentName.equals(RankCalculator.class.getName()))
return new RankCalculator();
else if (componentName.equals(EventLoggerNotifier.class.getName()))
return new EventLoggerNotifierImpl();
else if (componentName.equals(PrincipalRoleMapper.class.getName()))
return globalConfiguration.security().authorization().principalRoleMapper();
else if (componentName.equals(RolePermissionMapper.class.getName()))
return globalConfiguration.security().authorization().rolePermissionMapper();
throw CONTAINER.factoryCannotConstructComponent(componentName);
}
}
| 4,644
| 51.784091
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/LockContainerFactory.java
|
package org.infinispan.factories;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.util.concurrent.locks.impl.LockContainer;
import org.infinispan.util.concurrent.locks.impl.PerKeyLockContainer;
import org.infinispan.util.concurrent.locks.impl.StripedLockContainer;
/**
* Factory class that creates instances of {@link LockContainer}.
*
* @author Pedro Ruivo
* @since 7.0
*/
@DefaultFactoryFor(classes = LockContainer.class)
public class LockContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@SuppressWarnings("unchecked")
@Override
public Object construct(String componentName) {
return configuration.locking().useLockStriping() ?
new StripedLockContainer(configuration.locking().concurrencyLevel()) :
new PerKeyLockContainer();
}
}
| 869
| 33.8
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/RpcManagerFactory.java
|
package org.infinispan.factories;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.rpc.RpcManagerImpl;
/**
* A factory for the RpcManager
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
@DefaultFactoryFor(classes = RpcManager.class)
public class RpcManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (!configuration.clustering().cacheMode().isClustered())
return null;
// only do this if we have a transport configured!
if (!globalConfiguration.isClustered())
throw new CacheConfigurationException("Transport should be configured in order to use clustered caches");
return new RpcManagerImpl();
}
}
| 966
| 31.233333
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/VersionGeneratorFactory.java
|
package org.infinispan.factories;
import org.infinispan.configuration.cache.Configurations;
import org.infinispan.container.versioning.NumericVersionGenerator;
import org.infinispan.container.versioning.SimpleClusteredVersionGenerator;
import org.infinispan.container.versioning.VersionGenerator;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Version generator component factory. Version generators are used for situations where version or ids are needed, e.g.
* data versioning, transaction recovery, or hotrod/memcached support.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 5.1
*/
@DefaultFactoryFor(classes = VersionGenerator.class, names = {KnownComponentNames.TRANSACTION_VERSION_GENERATOR, KnownComponentNames.HOT_ROD_VERSION_GENERATOR})
@Scope(Scopes.NAMED_CACHE)
public class VersionGeneratorFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (KnownComponentNames.TRANSACTION_VERSION_GENERATOR.equals(componentName)) {
return new NumericVersionGenerator();
} else if (KnownComponentNames.HOT_ROD_VERSION_GENERATOR.equals(componentName)) {
//Note: HotRod cannot use the same version generator as Optimistic Transaction.
//the SimpleClusteredVersionGenerator#generateNew() always generates version=1. Not useful to detect conflicts.
return new NumericVersionGenerator();
} else if (Configurations.isTxVersioned(configuration)) {
return configuration.clustering().cacheMode().isClustered() ?
new SimpleClusteredVersionGenerator() :
new NumericVersionGenerator();
} else {
return new NumericVersionGenerator();
}
}
}
| 1,886
| 47.384615
| 160
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/XSiteEntryMergePolicyFactory.java
|
package org.infinispan.factories;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.xsite.spi.XSiteEntryMergePolicy;
/**
* A factory for {@link XSiteEntryMergePolicy}.
*
* @author Pedro Ruivo
* @since 12.0
*/
@DefaultFactoryFor(classes = XSiteEntryMergePolicy.class)
public class XSiteEntryMergePolicyFactory extends AbstractNamedCacheComponentFactory implements
AutoInstantiableFactory {
@Override
public Object construct(String name) {
assert name.equals(XSiteEntryMergePolicy.class.getName());
return configuration.sites().mergePolicy();
}
}
| 615
| 27
| 95
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/AbstractNamedCacheComponentFactory.java
|
package org.infinispan.factories;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* A component factory for creating components scoped per-cache.
*
* @author Manik Surtani
* @since 4.0
*/
@Scope(Scopes.NAMED_CACHE)
public abstract class AbstractNamedCacheComponentFactory extends AnyScopeComponentFactory {
@Inject protected Configuration configuration;
@Deprecated
@Inject protected ComponentRegistry componentRegistry;
@Inject protected BasicComponentRegistry basicComponentRegistry;
}
| 726
| 32.045455
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/ComponentFactory.java
|
package org.infinispan.factories;
import org.infinispan.factories.impl.ComponentAlias;
/**
* Factory for Infinispan components.
*
* <p>Implementations should usually be annotated with {@link org.infinispan.factories.annotations.DefaultFactoryFor}
* and {@link org.infinispan.factories.scopes.Scope} (the factory must have the same scope as the components it creates).</p>
*
* @since 9.4
*/
public interface ComponentFactory {
/**
* @return Either a component instance or a {@link ComponentAlias} pointing to another component.
*/
Object construct(String componentName);
}
| 595
| 30.368421
| 125
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/SizeCalculatorFactory.java
|
package org.infinispan.factories;
import org.infinispan.configuration.cache.MemoryConfiguration;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.container.impl.KeyValueMetadataSizeCalculator;
import org.infinispan.container.entries.CacheEntrySizeCalculator;
import org.infinispan.container.entries.PrimitiveEntrySizeCalculator;
import org.infinispan.container.offheap.OffHeapEntryFactory;
import org.infinispan.eviction.EvictionType;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.impl.ComponentAlias;
import org.infinispan.marshall.core.WrappedByteArraySizeCalculator;
/**
* Factory for creating size calculator used to estimate size of objects
* @author wburns
* @since 9.0
*/
@DefaultFactoryFor(classes = KeyValueMetadataSizeCalculator.class)
public class SizeCalculatorFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
MemoryConfiguration memory = configuration.memory();
if (memory.evictionStrategy().isEnabled() && memory.evictionType() == EvictionType.MEMORY) {
StorageType type = memory.storageType();
switch (type) {
case BINARY:
return CacheEntrySingleton.INSTANCE;
case OFF_HEAP:
return ComponentAlias.of(OffHeapEntryFactory.class);
case OBJECT:
/**
* We can't have object based when eviction is memory based. The
* {@link org.infinispan.configuration.cache.MemoryConfigurationBuilder#validate()} should handle
* checking for this.
*/
default:
throw new UnsupportedOperationException();
}
} else {
return (KeyValueMetadataSizeCalculator) (k, v, m, im) -> 1;
}
}
static class CacheEntrySingleton {
static final CacheEntrySizeCalculator INSTANCE = new CacheEntrySizeCalculator<>(new WrappedByteArraySizeCalculator<>(
new PrimitiveEntrySizeCalculator()));
}
}
| 2,113
| 41.28
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/InterceptorChainFactory.java
|
package org.infinispan.factories;
import java.util.List;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.Configurations;
import org.infinispan.configuration.cache.CustomInterceptorsConfiguration;
import org.infinispan.configuration.cache.InterceptorConfiguration;
import org.infinispan.configuration.cache.StoreConfiguration;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.interceptors.AsyncInterceptor;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.EmptyAsyncInterceptorChain;
import org.infinispan.interceptors.distribution.L1LastChanceInterceptor;
import org.infinispan.interceptors.distribution.L1NonTxInterceptor;
import org.infinispan.interceptors.distribution.L1TxInterceptor;
import org.infinispan.interceptors.distribution.NonTxDistributionInterceptor;
import org.infinispan.interceptors.distribution.TriangleDistributionInterceptor;
import org.infinispan.interceptors.distribution.TxDistributionInterceptor;
import org.infinispan.interceptors.distribution.VersionedDistributionInterceptor;
import org.infinispan.interceptors.impl.AsyncInterceptorChainImpl;
import org.infinispan.interceptors.impl.BatchingInterceptor;
import org.infinispan.interceptors.impl.CacheLoaderInterceptor;
import org.infinispan.interceptors.impl.CacheMgmtInterceptor;
import org.infinispan.interceptors.impl.CacheWriterInterceptor;
import org.infinispan.interceptors.impl.CallInterceptor;
import org.infinispan.interceptors.impl.ClusteredCacheLoaderInterceptor;
import org.infinispan.interceptors.impl.DistCacheWriterInterceptor;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.interceptors.impl.InvalidationInterceptor;
import org.infinispan.interceptors.impl.InvocationContextInterceptor;
import org.infinispan.interceptors.impl.IsMarshallableInterceptor;
import org.infinispan.interceptors.impl.NonTxIracLocalSiteInterceptor;
import org.infinispan.interceptors.impl.NonTxIracRemoteSiteInterceptor;
import org.infinispan.interceptors.impl.NotificationInterceptor;
import org.infinispan.interceptors.impl.OptimisticTxIracLocalSiteInterceptor;
import org.infinispan.interceptors.impl.PassivationCacheLoaderInterceptor;
import org.infinispan.interceptors.impl.PassivationClusteredCacheLoaderInterceptor;
import org.infinispan.interceptors.impl.PassivationWriterInterceptor;
import org.infinispan.interceptors.impl.PessimisticTxIracLocalInterceptor;
import org.infinispan.interceptors.impl.TransactionalExceptionEvictionInterceptor;
import org.infinispan.interceptors.impl.TransactionalStoreInterceptor;
import org.infinispan.interceptors.impl.TxInterceptor;
import org.infinispan.interceptors.impl.VersionInterceptor;
import org.infinispan.interceptors.impl.VersionedEntryWrappingInterceptor;
import org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor;
import org.infinispan.interceptors.locking.OptimisticLockingInterceptor;
import org.infinispan.interceptors.locking.PessimisticLockingInterceptor;
import org.infinispan.interceptors.xsite.NonTransactionalBackupInterceptor;
import org.infinispan.interceptors.xsite.OptimisticBackupInterceptor;
import org.infinispan.interceptors.xsite.PessimisticBackupInterceptor;
import org.infinispan.partitionhandling.PartitionHandling;
import org.infinispan.partitionhandling.impl.PartitionHandlingInterceptor;
import org.infinispan.statetransfer.StateTransferInterceptor;
import org.infinispan.statetransfer.TransactionSynchronizerInterceptor;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Factory class that builds an interceptor chain based on cache configuration.
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
* @author Mircea.Markus@jboss.com
* @author Marko Luksa
* @author Pedro Ruivo
* @since 4.0
*/
@DefaultFactoryFor(classes = {AsyncInterceptorChain.class})
public class InterceptorChainFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
private static final Log log = LogFactory.getLog(InterceptorChainFactory.class);
private AsyncInterceptor createInterceptor(AsyncInterceptor interceptor,
Class<? extends AsyncInterceptor> interceptorType) {
ComponentRef<? extends AsyncInterceptor> chainedInterceptor = basicComponentRegistry.getComponent(interceptorType);
if (chainedInterceptor != null) {
return chainedInterceptor.wired();
}
// TODO Dan: could use wireDependencies, as dependencies on interceptors won't trigger a call to the chain factory anyway
register(interceptorType, interceptor);
return interceptor;
}
private void register(Class<? extends AsyncInterceptor> clazz, AsyncInterceptor chainedInterceptor) {
try {
basicComponentRegistry.registerComponent(clazz.getName(), chainedInterceptor, true);
basicComponentRegistry.addDynamicDependency(AsyncInterceptorChain.class.getName(), clazz.getName());
} catch (RuntimeException e) {
log.unableToCreateInterceptor(clazz, e);
throw e;
}
}
private AsyncInterceptorChain buildInterceptorChain() {
TransactionMode transactionMode = configuration.transaction().transactionMode();
boolean needsVersionAwareComponents = Configurations.isTxVersioned(configuration);
AsyncInterceptorChain interceptorChain = new AsyncInterceptorChainImpl();
boolean invocationBatching = configuration.invocationBatching().enabled();
CacheMode cacheMode = configuration.clustering().cacheMode();
// load the icInterceptor first
if (invocationBatching) {
interceptorChain.appendInterceptor(createInterceptor(new BatchingInterceptor(), BatchingInterceptor.class), false);
}
interceptorChain.appendInterceptor(createInterceptor(new InvocationContextInterceptor(), InvocationContextInterceptor.class), false);
if (!configuration.transaction().transactionMode().isTransactional()) {
interceptorChain.appendInterceptor(createInterceptor(new VersionInterceptor(), VersionInterceptor.class), false);
}
// add marshallable check interceptor for situations where we want to figure out before marshalling
if (hasAsyncStore())
interceptorChain.appendInterceptor(createInterceptor(new IsMarshallableInterceptor(), IsMarshallableInterceptor.class), false);
// load the cache management interceptor next
if (configuration.statistics().available()) {
interceptorChain.appendInterceptor(createInterceptor(new CacheMgmtInterceptor(), CacheMgmtInterceptor.class), false);
}
// the state transfer interceptor sets the topology id and retries on topology changes
// so it's necessary even if there is no state transfer
// the only exception is non-tx invalidation mode, which ignores lock owners
if (cacheMode.needsStateTransfer() || cacheMode.isInvalidation() && transactionMode.isTransactional()) {
interceptorChain.appendInterceptor(createInterceptor(new StateTransferInterceptor(), StateTransferInterceptor.class), false);
}
if (cacheMode.needsStateTransfer()) {
if (transactionMode.isTransactional()) {
interceptorChain.appendInterceptor(createInterceptor(new TransactionSynchronizerInterceptor(), TransactionSynchronizerInterceptor.class), false);
}
if (configuration.clustering().partitionHandling().whenSplit() != PartitionHandling.ALLOW_READ_WRITES) {
interceptorChain.appendInterceptor(createInterceptor(new PartitionHandlingInterceptor(), PartitionHandlingInterceptor.class), false);
}
}
// load the tx interceptor
if (transactionMode.isTransactional())
interceptorChain.appendInterceptor(createInterceptor(new TxInterceptor<>(), TxInterceptor.class), false);
if (transactionMode.isTransactional()) {
if (configuration.transaction().lockingMode() == LockingMode.PESSIMISTIC) {
interceptorChain.appendInterceptor(createInterceptor(new PessimisticLockingInterceptor(), PessimisticLockingInterceptor.class), false);
} else {
interceptorChain.appendInterceptor(createInterceptor(new OptimisticLockingInterceptor(), OptimisticLockingInterceptor.class), false);
}
} else {
interceptorChain.appendInterceptor(createInterceptor(new NonTransactionalLockingInterceptor(), NonTransactionalLockingInterceptor.class), false);
}
// NotificationInterceptor is used only for Prepare/Commit/Rollback notifications
// This needs to be after locking interceptor to guarantee that locks are still held when raising notifications
if (transactionMode.isTransactional() && configuration.transaction().notifications()) {
interceptorChain.appendInterceptor(createInterceptor(new NotificationInterceptor(), NotificationInterceptor.class), false);
}
if (configuration.sites().hasBackups()) {
if (transactionMode == TransactionMode.TRANSACTIONAL) {
if (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC) {
interceptorChain.appendInterceptor(createInterceptor(new OptimisticBackupInterceptor(), OptimisticBackupInterceptor.class), false);
} else {
interceptorChain.appendInterceptor(createInterceptor(new PessimisticBackupInterceptor(), PessimisticBackupInterceptor.class), false);
}
} else {
interceptorChain.appendInterceptor(createInterceptor(new NonTransactionalBackupInterceptor(), NonTransactionalBackupInterceptor.class), false);
}
}
// This needs to be added after the locking interceptor (for tx caches) but before the wrapping interceptor.
if (configuration.clustering().l1().enabled()) {
interceptorChain.appendInterceptor(createInterceptor(new L1LastChanceInterceptor(), L1LastChanceInterceptor.class), false);
}
if (needsVersionAwareComponents) {
interceptorChain.appendInterceptor(createInterceptor(new VersionedEntryWrappingInterceptor(), VersionedEntryWrappingInterceptor.class), false);
} else {
interceptorChain.appendInterceptor(createInterceptor(new EntryWrappingInterceptor(), EntryWrappingInterceptor.class), false);
}
// Has to be after entry wrapping interceptor so it can properly see context values even when removed
if (transactionMode.isTransactional()) {
if (configuration.memory().evictionStrategy().isExceptionBased()) {
interceptorChain.appendInterceptor(createInterceptor(new TransactionalExceptionEvictionInterceptor(),
TransactionalExceptionEvictionInterceptor.class), false);
}
}
if (configuration.persistence().usingStores()) {
addPersistenceInterceptors(interceptorChain, configuration, configuration.persistence().stores());
}
if (configuration.clustering().l1().enabled()) {
if (transactionMode.isTransactional()) {
interceptorChain.appendInterceptor(createInterceptor(new L1TxInterceptor(), L1TxInterceptor.class), false);
}
else {
interceptorChain.appendInterceptor(createInterceptor(new L1NonTxInterceptor(), L1NonTxInterceptor.class), false);
}
}
if (configuration.sites().hasAsyncEnabledBackups() && cacheMode.isClustered()) {
if (transactionMode == TransactionMode.TRANSACTIONAL) {
if (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC) {
interceptorChain.appendInterceptor(createInterceptor(new OptimisticTxIracLocalSiteInterceptor(), OptimisticTxIracLocalSiteInterceptor.class), false);
} else {
interceptorChain.appendInterceptor(createInterceptor(new PessimisticTxIracLocalInterceptor(), PessimisticTxIracLocalInterceptor.class), false);
}
} else {
interceptorChain.appendInterceptor(createInterceptor(new NonTxIracLocalSiteInterceptor(), NonTxIracLocalSiteInterceptor.class), false);
}
}
switch (cacheMode) {
case INVALIDATION_SYNC:
case INVALIDATION_ASYNC:
interceptorChain.appendInterceptor(createInterceptor(new InvalidationInterceptor(), InvalidationInterceptor.class), false);
break;
case DIST_SYNC:
case REPL_SYNC:
if (needsVersionAwareComponents) {
interceptorChain.appendInterceptor(createInterceptor(new VersionedDistributionInterceptor(), VersionedDistributionInterceptor.class), false);
break;
}
case DIST_ASYNC:
case REPL_ASYNC:
if (transactionMode.isTransactional()) {
interceptorChain.appendInterceptor(createInterceptor(new TxDistributionInterceptor(), TxDistributionInterceptor.class), false);
} else {
if (cacheMode.isDistributed() && Configurations.isEmbeddedMode(globalConfiguration)) {
interceptorChain.appendInterceptor(createInterceptor(new TriangleDistributionInterceptor(), TriangleDistributionInterceptor.class), false);
} else {
interceptorChain.appendInterceptor(createInterceptor(new NonTxDistributionInterceptor(), NonTxDistributionInterceptor.class), false);
}
}
break;
case LOCAL:
//Nothing...
}
if (cacheMode.isClustered()) {
//local caches not involved in Cross Site Replication
interceptorChain.appendInterceptor(
createInterceptor(new NonTxIracRemoteSiteInterceptor(needsVersionAwareComponents), NonTxIracRemoteSiteInterceptor.class), false);
}
AsyncInterceptor callInterceptor = createInterceptor(new CallInterceptor(), CallInterceptor.class);
interceptorChain.appendInterceptor(callInterceptor, false);
log.trace("Finished building default interceptor chain.");
buildCustomInterceptors(interceptorChain, configuration.customInterceptors());
return interceptorChain;
}
private Class<? extends AsyncInterceptor> addInterceptor(AsyncInterceptorChain interceptorChain, AsyncInterceptor interceptor,
Class<? extends AsyncInterceptor> interceptorClass, Class<? extends AsyncInterceptor> after) {
if (interceptorChain.containsInterceptorType(interceptorClass, true)) {
return after;
}
AsyncInterceptor newInterceptor = createInterceptor(interceptor, interceptorClass);
boolean added = interceptorChain.addInterceptorAfter(newInterceptor, after);
return added ? newInterceptor.getClass() : after;
}
/**
* Adds all the interceptors related to persistence to the stack.
*
* @param interceptorChain The chain
* @param cacheConfiguration The configuration of the cache that owns the interceptor
* @param stores A list of {@link StoreConfiguration} possibly not present in the cacheConfiguration
*/
public void addPersistenceInterceptors(AsyncInterceptorChain interceptorChain, Configuration cacheConfiguration, List<StoreConfiguration> stores) {
TransactionMode transactionMode = cacheConfiguration.transaction().transactionMode();
CacheMode cacheMode = cacheConfiguration.clustering().cacheMode();
EntryWrappingInterceptor ewi = interceptorChain.findInterceptorExtending(EntryWrappingInterceptor.class);
if (ewi == null) {
throw new CacheException("Cannot find instance of EntryWrappingInterceptor in the interceptor chain");
}
Class<? extends AsyncInterceptor> lastAdded = ewi.getClass();
if (cacheConfiguration.persistence().passivation()) {
if (cacheMode.isClustered()) {
lastAdded = addInterceptor(interceptorChain, new PassivationClusteredCacheLoaderInterceptor<>(), CacheLoaderInterceptor.class, lastAdded);
} else {
lastAdded = addInterceptor(interceptorChain, new PassivationCacheLoaderInterceptor<>(), CacheLoaderInterceptor.class, lastAdded);
}
addInterceptor(interceptorChain, new PassivationWriterInterceptor(), PassivationWriterInterceptor.class, lastAdded);
} else {
if (cacheMode.isClustered()) {
lastAdded = addInterceptor(interceptorChain, new ClusteredCacheLoaderInterceptor<>(), CacheLoaderInterceptor.class, lastAdded);
} else {
lastAdded = addInterceptor(interceptorChain, new CacheLoaderInterceptor<>(), CacheLoaderInterceptor.class, lastAdded);
}
boolean transactionalStore = cacheConfiguration.persistence().stores().stream().anyMatch(StoreConfiguration::transactional) ||
stores.stream().anyMatch(StoreConfiguration::transactional);
if (transactionalStore && transactionMode.isTransactional())
lastAdded = addInterceptor(interceptorChain, new TransactionalStoreInterceptor(), TransactionalStoreInterceptor.class, lastAdded);
switch (cacheMode) {
case DIST_SYNC:
case DIST_ASYNC:
case REPL_SYNC:
case REPL_ASYNC:
addInterceptor(interceptorChain, new DistCacheWriterInterceptor(), DistCacheWriterInterceptor.class, lastAdded);
break;
default:
addInterceptor(interceptorChain, new CacheWriterInterceptor(), CacheWriterInterceptor.class, lastAdded);
break;
}
}
}
private void buildCustomInterceptors(AsyncInterceptorChain interceptorChain, CustomInterceptorsConfiguration customInterceptors) {
for (InterceptorConfiguration config : customInterceptors.interceptors()) {
if (interceptorChain.containsInterceptorType(config.asyncInterceptor().getClass())) continue;
AsyncInterceptor customInterceptor = config.asyncInterceptor();
SecurityActions.applyProperties(customInterceptor, config.properties());
register(customInterceptor.getClass(), customInterceptor);
if (config.first())
interceptorChain.addInterceptor(customInterceptor, 0);
else if (config.last())
interceptorChain.addInterceptorBefore(customInterceptor, CallInterceptor.class);
else if (config.index() >= 0)
interceptorChain.addInterceptor(customInterceptor, config.index());
else if (config.after() != null) {
boolean added = interceptorChain.addInterceptorAfter(customInterceptor, config.after());
if (!added) {
throw new CacheConfigurationException("Cannot add after class: " + config.after()
+ " as no such interceptor exists in the default chain");
}
} else if (config.before() != null) {
boolean added = interceptorChain.addInterceptorBefore(customInterceptor, config.before());
if (!added) {
throw new CacheConfigurationException("Cannot add before class: " + config.before()
+ " as no such interceptor exists in the default chain");
}
} else if (config.position() == InterceptorConfiguration.Position.OTHER_THAN_FIRST_OR_LAST) {
interceptorChain.addInterceptor(customInterceptor, 1);
}
}
}
private boolean hasAsyncStore() {
List<StoreConfiguration> loaderConfigs = configuration.persistence().stores();
for (StoreConfiguration loaderConfig : loaderConfigs) {
if (loaderConfig.async().enabled())
return true;
}
return false;
}
@Override
public Object construct(String componentName) {
try {
if (configuration.simpleCache())
return EmptyAsyncInterceptorChain.INSTANCE;
return buildInterceptorChain();
} catch (CacheException ce) {
throw ce;
} catch (Exception e) {
throw new CacheConfigurationException("Unable to build interceptor chain", e);
}
}
/**
* @deprecated Since 9.4, not used.
*/
@Deprecated
public static InterceptorChainFactory getInstance(ComponentRegistry componentRegistry, Configuration configuration) {
InterceptorChainFactory icf = new InterceptorChainFactory();
icf.componentRegistry = componentRegistry;
icf.configuration = configuration;
return icf;
}
}
| 20,868
| 52.373402
| 164
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/NamedComponentFactory.java
|
package org.infinispan.factories;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.util.ReflectionUtil;
/**
* A specialized type of component factory that knows how to create named components, identified with the {@link
* org.infinispan.factories.annotations.ComponentName} annotation on the classes requested in {@link
* org.infinispan.factories.annotations.Inject} annotated methods.
*
* @author Manik Surtani
* @since 4.0
* @deprecated Since 9.4, please implement {@link AbstractComponentFactory#construct(String)} directly.
*/
@Deprecated
public abstract class NamedComponentFactory extends AbstractComponentFactory {
@Override
public Object construct(String componentName) {
Class<?> componentType;
try {
componentType = ReflectionUtil.getClassForName(componentName, globalComponentRegistry.getClassLoader());
} catch (ClassNotFoundException e) {
throw new CacheConfigurationException(e);
}
return construct(componentType, componentName);
}
/**
* Constructs a component.
*
* @param componentType type of component
* @return a component
*/
public abstract <T> T construct(Class<T> componentType, String componentName);
}
| 1,260
| 33.081081
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/TransactionTableFactory.java
|
package org.infinispan.factories;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.impl.ComponentAlias;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.XaTransactionTable;
import org.infinispan.transaction.xa.recovery.RecoveryAwareTransactionTable;
/**
* Factory for {@link org.infinispan.transaction.impl.TransactionTable} objects.
*
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
@DefaultFactoryFor(classes = {TransactionTable.class, org.infinispan.transaction.TransactionTable.class})
@SuppressWarnings("unused")
public class TransactionTableFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (componentName.equals(TransactionTable.class.getName())) {
return ComponentAlias.of(org.infinispan.transaction.TransactionTable.class);
}
if (!configuration.transaction().transactionMode().isTransactional())
return null;
if (configuration.invocationBatching().enabled())
return new TransactionTable();
if (!configuration.transaction().useSynchronization()) {
if (configuration.transaction().recovery().enabled()) {
return new RecoveryAwareTransactionTable();
} else {
return new XaTransactionTable();
}
} else {
return new TransactionTable();
}
}
}
| 1,487
| 34.428571
| 116
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/EncoderRegistryFactory.java
|
package org.infinispan.factories;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.BinaryTranscoder;
import org.infinispan.commons.dataconversion.ByteArrayWrapper;
import org.infinispan.commons.dataconversion.DefaultTranscoder;
import org.infinispan.commons.dataconversion.GlobalMarshallerEncoder;
import org.infinispan.commons.dataconversion.IdentityEncoder;
import org.infinispan.commons.dataconversion.IdentityWrapper;
import org.infinispan.commons.dataconversion.JavaSerializationEncoder;
import org.infinispan.commons.dataconversion.TranscoderMarshallerAdapter;
import org.infinispan.commons.dataconversion.UTF8Encoder;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.encoding.ProtostreamTranscoder;
import org.infinispan.encoding.impl.JavaSerializationTranscoder;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.marshall.core.EncoderRegistryImpl;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
/**
* Factory for {@link EncoderRegistryImpl} objects.
*
* @since 9.1
*/
@DefaultFactoryFor(classes = {EncoderRegistry.class})
public class EncoderRegistryFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
// Must not start the global marshaller or it will be too late for modules to register their externalizers
@Inject @ComponentName(KnownComponentNames.INTERNAL_MARSHALLER)
ComponentRef<StreamingMarshaller> globalMarshaller;
@Inject @ComponentName(KnownComponentNames.USER_MARSHALLER)
Marshaller userMarshaller;
@Inject EmbeddedCacheManager embeddedCacheManager;
@Inject SerializationContextRegistry ctxRegistry;
@Override
public Object construct(String componentName) {
ClassLoader classLoader = globalConfiguration.classLoader();
EncoderRegistryImpl encoderRegistry = new EncoderRegistryImpl();
ClassAllowList classAllowList = embeddedCacheManager.getClassAllowList();
encoderRegistry.registerEncoder(IdentityEncoder.INSTANCE);
encoderRegistry.registerEncoder(UTF8Encoder.INSTANCE);
encoderRegistry.registerEncoder(new JavaSerializationEncoder(classAllowList));
encoderRegistry.registerEncoder(new GlobalMarshallerEncoder(globalMarshaller.wired()));
// Default and binary transcoder use the user marshaller to convert data to/from a byte array
encoderRegistry.registerTranscoder(new DefaultTranscoder(userMarshaller));
encoderRegistry.registerTranscoder(new BinaryTranscoder(userMarshaller));
// Core transcoders are always available
encoderRegistry.registerTranscoder(new ProtostreamTranscoder(ctxRegistry, classLoader));
encoderRegistry.registerTranscoder(new JavaSerializationTranscoder(classAllowList));
// Wraps the GlobalMarshaller so that it can be used as a transcoder
// Keeps application/x-infinispan-marshalling available for backwards compatibility
encoderRegistry.registerTranscoder(new TranscoderMarshallerAdapter(globalMarshaller.wired()));
// Make the user marshaller's media type available as well
// As custom marshaller modules like Kryo and Protostuff do not define their own transcoder
encoderRegistry.registerTranscoder(new TranscoderMarshallerAdapter(userMarshaller));
encoderRegistry.registerWrapper(ByteArrayWrapper.INSTANCE);
encoderRegistry.registerWrapper(IdentityWrapper.INSTANCE);
return encoderRegistry;
}
}
| 3,822
| 52.097222
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/EmptyConstructorNamedCacheFactory.java
|
package org.infinispan.factories;
import static org.infinispan.util.logging.Log.CONTAINER;
import org.infinispan.batch.BatchContainer;
import org.infinispan.cache.impl.CacheConfigurationMBean;
import org.infinispan.cache.impl.InvocationHelper;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.CommandsFactoryImpl;
import org.infinispan.commons.io.ByteBufferFactory;
import org.infinispan.commons.io.ByteBufferFactoryImpl;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.container.offheap.OffHeapEntryFactory;
import org.infinispan.container.offheap.OffHeapEntryFactoryImpl;
import org.infinispan.container.offheap.OffHeapMemoryAllocator;
import org.infinispan.container.offheap.UnpooledOffHeapMemoryAllocator;
import org.infinispan.container.versioning.irac.DefaultIracVersionGenerator;
import org.infinispan.container.versioning.irac.IracVersionGenerator;
import org.infinispan.container.versioning.irac.NoOpIracVersionGenerator;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.NonTransactionalInvocationContextFactory;
import org.infinispan.context.impl.TransactionalInvocationContextFactory;
import org.infinispan.distribution.L1Manager;
import org.infinispan.distribution.RemoteValueRetrievedListener;
import org.infinispan.distribution.TriangleOrderManager;
import org.infinispan.distribution.impl.L1ManagerImpl;
import org.infinispan.encoding.impl.StorageConfigurationManager;
import org.infinispan.eviction.EvictionManager;
import org.infinispan.eviction.impl.ActivationManager;
import org.infinispan.eviction.impl.ActivationManagerImpl;
import org.infinispan.eviction.impl.EvictionManagerImpl;
import org.infinispan.eviction.impl.PassivationManager;
import org.infinispan.eviction.impl.PassivationManagerImpl;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.impl.ComponentAlias;
import org.infinispan.functional.impl.FunctionalNotifier;
import org.infinispan.functional.impl.FunctionalNotifierImpl;
import org.infinispan.marshall.persistence.impl.MarshalledEntryFactoryImpl;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.notifications.cachelistener.CacheNotifierImpl;
import org.infinispan.notifications.cachelistener.cluster.ClusterCacheNotifier;
import org.infinispan.persistence.manager.PassivationPersistenceManager;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.persistence.manager.PersistenceManagerImpl;
import org.infinispan.persistence.manager.PreloadManager;
import org.infinispan.persistence.spi.MarshallableEntryFactory;
import org.infinispan.reactive.publisher.impl.PublisherHandler;
import org.infinispan.statetransfer.CommitManager;
import org.infinispan.statetransfer.StateTransferLock;
import org.infinispan.statetransfer.StateTransferLockImpl;
import org.infinispan.transaction.impl.ClusteredTransactionOriginatorChecker;
import org.infinispan.transaction.impl.TransactionCoordinator;
import org.infinispan.transaction.impl.TransactionOriginatorChecker;
import org.infinispan.transaction.xa.TransactionFactory;
import org.infinispan.transaction.xa.recovery.RecoveryAdminOperations;
import org.infinispan.util.concurrent.CommandAckCollector;
import org.infinispan.xsite.BackupReceiver;
import org.infinispan.xsite.BackupSender;
import org.infinispan.xsite.BackupSenderImpl;
import org.infinispan.xsite.ClusteredCacheBackupReceiver;
import org.infinispan.xsite.NoOpBackupSender;
import org.infinispan.xsite.metrics.DefaultXSiteMetricsCollector;
import org.infinispan.xsite.metrics.NoOpXSiteMetricsCollector;
import org.infinispan.xsite.metrics.XSiteMetricsCollector;
import org.infinispan.xsite.statetransfer.NoOpXSiteStateProvider;
import org.infinispan.xsite.statetransfer.NoOpXSiteStateTransferManager;
import org.infinispan.xsite.statetransfer.XSiteStateConsumer;
import org.infinispan.xsite.statetransfer.XSiteStateConsumerImpl;
import org.infinispan.xsite.statetransfer.XSiteStateProvider;
import org.infinispan.xsite.statetransfer.XSiteStateProviderImpl;
import org.infinispan.xsite.statetransfer.XSiteStateTransferManager;
import org.infinispan.xsite.statetransfer.XSiteStateTransferManagerImpl;
import org.infinispan.xsite.status.DefaultTakeOfflineManager;
import org.infinispan.xsite.status.NoOpTakeOfflineManager;
import org.infinispan.xsite.status.TakeOfflineManager;
/**
* Simple factory that just uses reflection and an empty constructor of the component type.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Pedro Ruivo
* @since 4.0
*/
@DefaultFactoryFor(classes = {CacheNotifier.class, CacheConfigurationMBean.class, ClusterCacheNotifier.class, CommandsFactory.class,
PersistenceManager.class, PassivationManager.class, ActivationManager.class,
PreloadManager.class, BatchContainer.class, EvictionManager.class,
TransactionCoordinator.class, RecoveryAdminOperations.class, StateTransferLock.class,
L1Manager.class, TransactionFactory.class, BackupSender.class,
ByteBufferFactory.class, MarshallableEntryFactory.class,
RemoteValueRetrievedListener.class, InvocationContextFactory.class, CommitManager.class,
XSiteStateTransferManager.class, XSiteStateConsumer.class, XSiteStateProvider.class,
FunctionalNotifier.class, CommandAckCollector.class, TriangleOrderManager.class,
TransactionOriginatorChecker.class, OffHeapEntryFactory.class, OffHeapMemoryAllocator.class,
PublisherHandler.class, InvocationHelper.class, TakeOfflineManager.class,
IracVersionGenerator.class, BackupReceiver.class, StorageConfigurationManager.class,
XSiteMetricsCollector.class
})
public class EmptyConstructorNamedCacheFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
boolean isTransactional = configuration.transaction().transactionMode().isTransactional();
if (componentName.equals(InvocationContextFactory.class.getName())) {
return isTransactional ? new TransactionalInvocationContextFactory()
: new NonTransactionalInvocationContextFactory();
} else if (componentName.equals(CacheNotifier.class.getName())) {
return new CacheNotifierImpl<>();
} else if (componentName.equals(CacheConfigurationMBean.class.getName())) {
return new CacheConfigurationMBean();
} else if (componentName.equals(CommandsFactory.class.getName())) {
return new CommandsFactoryImpl();
} else if (componentName.equals(PersistenceManager.class.getName())) {
PersistenceManagerImpl persistenceManager = new PersistenceManagerImpl();
if (configuration.persistence().passivation()) {
return new PassivationPersistenceManager(persistenceManager);
}
return persistenceManager;
} else if (componentName.equals(PassivationManager.class.getName())) {
return new PassivationManagerImpl();
} else if (componentName.equals(ActivationManager.class.getName())) {
return new ActivationManagerImpl();
} else if (componentName.equals(PreloadManager.class.getName())) {
return new PreloadManager();
} else if (componentName.equals(BatchContainer.class.getName())) {
return new BatchContainer();
} else if (componentName.equals(TransactionCoordinator.class.getName())) {
return new TransactionCoordinator();
} else if (componentName.equals(RecoveryAdminOperations.class.getName())) {
return new RecoveryAdminOperations();
} else if (componentName.equals(StateTransferLock.class.getName())) {
return new StateTransferLockImpl();
} else if (componentName.equals(EvictionManager.class.getName())) {
return new EvictionManagerImpl<>();
} else if (componentName.equals(L1Manager.class.getName())) {
return new L1ManagerImpl();
} else if (componentName.equals(TransactionFactory.class.getName())) {
return new TransactionFactory();
} else if (componentName.equals(BackupSender.class.getName())) {
return configuration.sites().hasSyncEnabledBackups() ?
new BackupSenderImpl() :
NoOpBackupSender.getInstance();
} else if (componentName.equals(ByteBufferFactory.class.getName())) {
return new ByteBufferFactoryImpl();
} else if (componentName.equals(MarshallableEntryFactory.class.getName())) {
return new MarshalledEntryFactoryImpl();
} else if (componentName.equals(CommitManager.class.getName())) {
return new CommitManager();
} else if (componentName.equals(XSiteStateTransferManager.class.getName())) {
return configuration.sites().hasBackups() ? new XSiteStateTransferManagerImpl(configuration)
: new NoOpXSiteStateTransferManager();
} else if (componentName.equals(XSiteStateConsumer.class.getName())) {
return new XSiteStateConsumerImpl(configuration);
} else if (componentName.equals(XSiteStateProvider.class.getName())) {
return configuration.sites().hasBackups() ? new XSiteStateProviderImpl(configuration)
: NoOpXSiteStateProvider.getInstance();
} else if (componentName.equals(FunctionalNotifier.class.getName())) {
return new FunctionalNotifierImpl<>();
} else if (componentName.equals(CommandAckCollector.class.getName())) {
if (configuration.clustering().cacheMode().isClustered()) {
return new CommandAckCollector();
} else {
return null;
}
} else if (componentName.equals(TriangleOrderManager.class.getName())) {
if (configuration.clustering().cacheMode().isClustered()) {
return new TriangleOrderManager(configuration.clustering().hash().numSegments());
} else {
return null;
}
} else if (componentName.equals(TransactionOriginatorChecker.class.getName())) {
return configuration.clustering().cacheMode() == CacheMode.LOCAL ?
TransactionOriginatorChecker.LOCAL :
new ClusteredTransactionOriginatorChecker();
} else if (componentName.equals(OffHeapEntryFactory.class.getName())) {
return new OffHeapEntryFactoryImpl();
} else if (componentName.equals(OffHeapMemoryAllocator.class.getName())) {
return new UnpooledOffHeapMemoryAllocator();
} else if (componentName.equals(ClusterCacheNotifier.class.getName())) {
return ComponentAlias.of(CacheNotifier.class);
} else if (componentName.equals(RemoteValueRetrievedListener.class.getName())) {
// L1Manager is currently only listener for remotely retrieved values
return ComponentAlias.of(L1Manager.class);
} else if (componentName.equals(PublisherHandler.class.getName())) {
return new PublisherHandler();
} else if (componentName.equals(InvocationHelper.class.getName())) {
return new InvocationHelper();
} else if (componentName.equals(TakeOfflineManager.class.getName())) {
return configuration.sites().hasBackups() ?
new DefaultTakeOfflineManager(componentRegistry.getCacheName()) :
NoOpTakeOfflineManager.getInstance();
} else if (componentName.equals(IracVersionGenerator.class.getName())) {
return configuration.sites().hasAsyncEnabledBackups() ?
new DefaultIracVersionGenerator(configuration.clustering().hash().numSegments()) :
NoOpIracVersionGenerator.getInstance();
} else if (componentName.equals(BackupReceiver.class.getName())) {
return configuration.clustering().cacheMode().isClustered() ?
new ClusteredCacheBackupReceiver(componentRegistry.getCacheName()) :
null;
} else if (componentName.equals(StorageConfigurationManager.class.getName())) {
return new StorageConfigurationManager();
} else if (componentName.equals(XSiteMetricsCollector.class.getName())) {
return configuration.sites().hasBackups() ?
new DefaultXSiteMetricsCollector(configuration) :
NoOpXSiteMetricsCollector.getInstance();
}
throw CONTAINER.factoryCannotConstructComponent(componentName);
}
}
| 12,782
| 59.582938
| 132
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/AbstractComponentRegistry.java
|
package org.infinispan.factories;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.api.Lifecycle;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.impl.BasicComponentRegistryImpl;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.ModuleRepository;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
/**
* A registry where components which have been created are stored. Components are stored as singletons, registered
* under a specific name.
* <p/>
* Components can be retrieved from the registry using {@link #getComponent(Class)}.
* <p/>
* Components can be registered using {@link #registerComponent(Object, Class)}, which will cause any dependencies to be
* wired in as well. Components that need to be created as a result of wiring will be done using {@link
* #getOrCreateComponent(Class)}, which will look up the default factory for the component type (factories annotated
* with the appropriate {@link DefaultFactoryFor} annotation.
* <p/>
* Default factories are treated as components too and will need to be wired before being used.
* <p/>
* The registry can exist in one of several states, as defined by the {@link org.infinispan.lifecycle.ComponentStatus}
* enumeration. In terms of the cache, state changes in the following manner: <ul> <li>INSTANTIATED - when first
* constructed</li> <li>CONSTRUCTED - when created using the DefaultCacheFactory</li> <li>STARTED - when {@link
* org.infinispan.Cache#start()} is called</li> <li>STOPPED - when {@link org.infinispan.Cache#stop()} is called</li>
* </ul>
* <p/>
* Cache configuration can only be changed and will only be re-injected if the cache is not in the {@link
* org.infinispan.lifecycle.ComponentStatus#RUNNING} state.
*
* Thread Safety: instances of {@link GlobalComponentRegistry} can be concurrently updated so all
* the write operations are serialized through class intrinsic lock.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
* @deprecated Since 9.4, please use {@link BasicComponentRegistry} instead.
*/
@Deprecated
public abstract class AbstractComponentRegistry implements Lifecycle {
final ModuleRepository moduleRepository;
final BasicComponentRegistry basicComponentRegistry;
protected volatile ComponentStatus state = ComponentStatus.INSTANTIATED;
AbstractComponentRegistry(ModuleRepository moduleRepository,
boolean isGlobal, BasicComponentRegistry nextBasicComponentRegistry) {
this.moduleRepository = moduleRepository;
this.basicComponentRegistry = new BasicComponentRegistryImpl(moduleRepository, isGlobal, nextBasicComponentRegistry);
}
/**
* Retrieves the state of the registry
*
* @return state of the registry
*/
public ComponentStatus getStatus() {
return state;
}
protected abstract ClassLoader getClassLoader();
protected abstract Log getLog();
/**
* Wires an object instance with dependencies annotated with the {@link Inject} annotation, creating more components
* as needed based on the Configuration passed in if these additional components don't exist in the {@link
* ComponentRegistry}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such
* as Commands.
*
* @param target object to wire
* @throws CacheConfigurationException if there is a problem wiring the instance
*/
public void wireDependencies(Object target) throws CacheConfigurationException {
basicComponentRegistry.wireDependencies(target, true);
}
/**
* Wires an object instance with dependencies annotated with the {@link Inject} annotation, creating more components
* as needed based on the Configuration passed in if these additional components don't exist in the {@link
* ComponentRegistry}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such
* as Commands.
*
* @param target object to wire
* @param startDependencies whether to start injected components (if not already started)
* @throws CacheConfigurationException if there is a problem wiring the instance
*/
public void wireDependencies(Object target, boolean startDependencies) throws CacheConfigurationException {
basicComponentRegistry.wireDependencies(target, startDependencies);
}
/**
* Registers a component in the registry under the given type, and injects any dependencies needed.
*
* Note: Until 9.4, if a component of this type already existed, it was overwritten.
*
* @param component component to register
* @param type type of component
* @throws org.infinispan.commons.CacheConfigurationException If a component is already registered with that
* name, or if a dependency cannot be resolved
*/
public final void registerComponent(Object component, Class<?> type) {
registerComponent(component, type.getName(), type.equals(component.getClass()));
}
public final void registerComponent(Object component, String name) {
registerComponent(component, name, name.equals(component.getClass().getName()));
}
public final void registerComponent(Object component, String name, boolean nameIsFQCN) {
registerComponentInternal(component, name, nameIsFQCN);
}
protected final void registerNonVolatileComponent(Object component, String name) {
registerComponentInternal(component, name, false);
}
protected void registerComponentInternal(Object component, String name, boolean nameIsFQCN) {
ComponentRef<Object> ref = basicComponentRegistry.registerComponent(name, component, true);
if (state == ComponentStatus.INITIALIZING || state == ComponentStatus.RUNNING) {
// Force the component to start if the registry is already running
ref.running();
}
}
/**
* Retrieves a component if one exists, and if not, attempts to find a factory capable of constructing the component
* (factories annotated with the {@link DefaultFactoryFor} annotation that is capable of creating the component
* class).
* <p/>
* If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on
* methods on the component type annotated with {@link Inject}.
* <p/>
* Summing it up, component retrieval happens in the following order:<br /> 1. Look for a component that has already
* been created and registered. 2. Look for an appropriate component that exists in the {@link Configuration} that
* may be injected from an external system. 3. Look for a class definition passed in to the {@link Configuration} -
* such as an EvictionPolicy implementation 4. Attempt to create it by looking for an appropriate factory (annotated
* with {@link DefaultFactoryFor})
* <p/>
*
* @param componentClass type of component to be retrieved. Should not be null.
* @return a fully wired component instance, or null if one cannot be found or constructed.
* @throws CacheConfigurationException if there is a problem with constructing or wiring the instance.
*/
protected <T> T getOrCreateComponent(Class<T> componentClass) {
return getComponent(componentClass, componentClass.getName());
}
protected <T> T getOrCreateComponent(Class<T> componentClass, String name) {
return getComponent(componentClass, name);
}
protected <T> T getOrCreateComponent(Class<T> componentClass, String name, boolean nameIsFQCN) {
return getComponent(componentClass, name);
}
/**
* Retrieves a component of a specified type from the registry, or null if it cannot be found.
*
* @param type type to find
* @return component, or null
*/
public <T> T getComponent(Class<T> type) {
String className = type.getName();
return getComponent(type, className);
}
@SuppressWarnings("unchecked")
public <T> T getComponent(String componentClassName) {
return (T) getComponent(componentClassName, componentClassName, true);
}
@SuppressWarnings("unchecked")
public <T> T getComponent(String componentClassName, String name) {
return (T) getComponent(componentClassName, name, false);
}
public <T> T getComponent(Class<T> componentClass, String name) {
ComponentRef<T> component = basicComponentRegistry.getComponent(name, componentClass);
return component != null ? component.wired() : null;
}
@SuppressWarnings("unchecked")
public <T> T getComponent(String componentClassName, String name, boolean nameIsFQCN) {
return (T) getComponent(Object.class, name);
}
public <T> Optional<T> getOptionalComponent(Class<T> type) {
return Optional.ofNullable(getComponent(type));
}
/**
* @deprecated Since 9.4, not used
*/
protected ClassLoader registerDefaultClassLoader(ClassLoader loader) {
ClassLoader loaderToUse = loader == null ? getClass().getClassLoader() : loader;
registerComponent(loaderToUse, ClassLoader.class);
return loaderToUse;
}
/**
* Rewires components. Used to rewire components in the CR if a cache has been stopped (moved to state TERMINATED),
* which would (almost) empty the registry of components. Rewiring will re-inject all dependencies so that the cache
* can be started again.
* <p/>
*/
public void rewire() {
basicComponentRegistry.rewire();
}
// ------------------------------ START: Publicly available lifecycle methods -----------------------------
// These methods perform a check for appropriate transition and then delegate to similarly named internal methods.
/**
* This starts the components in the registry, connecting to channels, starting service threads, etc. If the component is
* not in the {@link org.infinispan.lifecycle.ComponentStatus#INITIALIZING} state, it will be initialized first.
*/
@Override
public void start() {
synchronized (this) {
try {
while (state == ComponentStatus.INITIALIZING) {
wait();
}
if (state != ComponentStatus.INSTANTIATED) {
return;
}
state = ComponentStatus.INITIALIZING;
} catch (InterruptedException e) {
throw new CacheException("Interrupted waiting for the component registry to start");
}
}
try {
preStart();
internalStart();
CompletionStage<Void> cs = delayStart();
if (cs == null || CompletionStages.isCompletedSuccessfully(cs)) {
updateStatusRunning();
postStart();
} else {
cs.whenComplete((ignore, t) -> {
if (t != null) {
componentFailed(t);
} else {
updateStatusRunning();
postStart();
}
});
}
} catch (Throwable t) {
componentFailed(t);
}
}
private synchronized void updateStatusRunning() {
if (state == ComponentStatus.INITIALIZING) {
state = ComponentStatus.RUNNING;
notifyAll();
}
}
private void componentFailed(Throwable t) {
synchronized (this) {
state = ComponentStatus.FAILED;
notifyAll();
}
Log.CONFIG.startFailure(getName(), t);
try {
stop();
} catch (Throwable t1) {
t.addSuppressed(t1);
}
handleLifecycleTransitionFailure(t);
}
protected abstract String getName();
protected abstract void preStart();
protected abstract void postStart();
abstract protected CompletionStage<Void> delayStart();
/**
* Stops the component and sets its status to {@link org.infinispan.lifecycle.ComponentStatus#TERMINATED} once it
* is done. If the component is not in the {@link org.infinispan.lifecycle.ComponentStatus#RUNNING} state, this is a
* no-op.
*/
@Override
public final void stop() {
// Trying to stop() from FAILED is valid, but may not work
boolean failed;
synchronized (this) {
try {
while (state == ComponentStatus.STOPPING) {
wait();
}
if (!state.stopAllowed()) {
getLog().debugf("Ignoring call to stop() as current state is %s", state);
return;
}
failed = state == ComponentStatus.FAILED;
state = ComponentStatus.STOPPING;
} catch (InterruptedException e) {
throw new CacheException("Interrupted waiting for the component registry to stop");
}
}
preStop();
try {
internalStop();
postStop();
} catch (Throwable t) {
if (failed) {
getLog().failedToCallStopAfterFailure(t);
} else {
handleLifecycleTransitionFailure(t);
}
} finally {
synchronized (this) {
state = ComponentStatus.TERMINATED;
notifyAll();
}
}
}
protected abstract void postStop();
protected abstract void preStop();
/**
* Sets the cacheStatus to FAILED and re-throws the problem as one of the declared types. Converts any
* non-RuntimeException Exception to CacheException.
*
* @param t throwable thrown during failure
*/
private void handleLifecycleTransitionFailure(Throwable t) {
if (t.getCause() != null && t.getCause() instanceof CacheConfigurationException)
throw (CacheConfigurationException) t.getCause();
else if (t.getCause() != null && t.getCause() instanceof InvocationTargetException && t.getCause().getCause() != null && t.getCause().getCause() instanceof CacheConfigurationException)
throw (CacheConfigurationException) t.getCause().getCause();
else if (t instanceof CacheException)
throw (CacheException) t;
else if (t instanceof RuntimeException)
throw (RuntimeException) t;
else if (t instanceof Error)
throw (Error) t;
else
throw new CacheException(t);
}
private void internalStart() throws CacheException, IllegalArgumentException {
// Start all the components. The order doesn't matter, as starting one component starts its dependencies as well
Collection<ComponentRef<?>> components = basicComponentRegistry.getRegisteredComponents();
for (ComponentRef<?> component : components) {
component.running();
}
addShutdownHook();
}
protected void addShutdownHook() {
// no op. Override if needed.
}
protected void removeShutdownHook() {
// no op. Override if needed.
}
/**
* Actual stop
*/
private void internalStop() {
removeShutdownHook();
basicComponentRegistry.stop();
}
public abstract TimeService getTimeService();
}
| 15,533
| 37.450495
| 190
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/ExpirationManagerFactory.java
|
package org.infinispan.factories;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.expiration.impl.ClusterExpirationManager;
import org.infinispan.expiration.impl.ExpirationManagerImpl;
import org.infinispan.expiration.impl.InternalExpirationManager;
import org.infinispan.expiration.impl.TxClusterExpirationManager;
import org.infinispan.factories.annotations.DefaultFactoryFor;
/**
* Constructs the expiration manager
*
* @author William Burns
* @since 8.0
*/
@DefaultFactoryFor(classes = InternalExpirationManager.class)
public class ExpirationManagerFactory extends AbstractNamedCacheComponentFactory implements
AutoInstantiableFactory {
@Override
@SuppressWarnings("unchecked")
public Object construct(String componentName) {
CacheMode cacheMode = configuration.clustering().cacheMode();
if (cacheMode.needsStateTransfer()) {
if (configuration.transaction().transactionMode().isTransactional()) {
return new TxClusterExpirationManager<>();
}
return new ClusterExpirationManager<>();
} else {
return new ExpirationManagerImpl<>();
}
}
}
| 1,168
| 33.382353
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/PartitionHandlingManagerFactory.java
|
package org.infinispan.factories;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.partitionhandling.PartitionHandling;
import org.infinispan.partitionhandling.impl.AvailablePartitionHandlingManager;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.partitionhandling.impl.PartitionHandlingManagerImpl;
/**
* @author Dan Berindei
* @since 7.0
*/
@DefaultFactoryFor(classes = PartitionHandlingManager.class)
public class PartitionHandlingManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
if (configuration.clustering().partitionHandling().whenSplit() != PartitionHandling.ALLOW_READ_WRITES) {
if (configuration.clustering().cacheMode().isDistributed() ||
configuration.clustering().cacheMode().isReplicated()) {
return new PartitionHandlingManagerImpl(configuration);
}
}
return AvailablePartitionHandlingManager.getInstance();
}
}
| 1,092
| 38.035714
| 124
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/DistributionManagerFactory.java
|
package org.infinispan.factories;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.impl.DistributionManagerImpl;
import org.infinispan.factories.annotations.DefaultFactoryFor;
@DefaultFactoryFor(classes = DistributionManager.class)
public class DistributionManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
@SuppressWarnings("unchecked")
public Object construct(String componentName) {
if (configuration.clustering().cacheMode().isClustered())
return new DistributionManagerImpl();
else
return null;
}
}
| 645
| 34.888889
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/ComponentRegistry.java
|
package org.infinispan.factories;
import java.util.concurrent.CompletionStage;
import org.infinispan.AdvancedCache;
import org.infinispan.cache.impl.CacheConfigurationMBean;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.conflict.impl.InternalConflictManager;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.container.impl.InternalEntryFactory;
import org.infinispan.container.versioning.NumericVersionGenerator;
import org.infinispan.container.versioning.VersionGenerator;
import org.infinispan.container.versioning.irac.IracTombstoneManager;
import org.infinispan.container.versioning.irac.IracVersionGenerator;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.SurvivesRestarts;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.impl.ComponentAccessor;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.lifecycle.ModuleLifecycle;
import org.infinispan.marshall.persistence.PersistenceMarshaller;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.notifications.cachelistener.cluster.ClusterCacheNotifier;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.persistence.manager.PreloadManager;
import org.infinispan.reactive.publisher.impl.ClusterPublisherManager;
import org.infinispan.reactive.publisher.impl.LocalPublisherManager;
import org.infinispan.reactive.publisher.impl.PublisherHandler;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler;
import org.infinispan.remoting.responses.ResponseGenerator;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.statetransfer.StateTransferLock;
import org.infinispan.statetransfer.StateTransferManager;
import org.infinispan.stats.ClusterCacheStats;
import org.infinispan.topology.LocalTopologyManager;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CommandAckCollector;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.BackupReceiver;
import org.infinispan.xsite.BackupSender;
import org.infinispan.xsite.irac.IracManager;
import org.infinispan.xsite.statetransfer.XSiteStateTransferManager;
import org.infinispan.xsite.status.TakeOfflineManager;
/**
* Named cache specific components
*
* @author Manik Surtani
* @since 4.0
*/
@Scope(Scopes.NAMED_CACHE)
@SurvivesRestarts
public class ComponentRegistry extends AbstractComponentRegistry {
private static final Log log = LogFactory.getLog(ComponentRegistry.class);
private final String cacheName;
private final ByteString cacheByteString;
private final Configuration configuration;
private final GlobalComponentRegistry globalComponents;
@Inject CacheManagerNotifier cacheManagerNotifier;
// All modules must be initialized before the first cache starts
@SuppressWarnings("unused")
@Inject GlobalComponentRegistry.ModuleInitializer moduleInitializer;
//Cached fields:
private ComponentRef<AdvancedCache> cache;
private ComponentRef<AsyncInterceptorChain> asyncInterceptorChain;
private ComponentRef<BackupReceiver> backupReceiver;
private ComponentRef<BackupSender> backupSender;
private ComponentRef<BlockingManager> blockingManager;
private ComponentRef<ClusterPublisherManager> clusterPublisherManager;
private ComponentRef<ClusterPublisherManager> localClusterPublisherManager;
private ComponentRef<CacheNotifier> cacheNotifier;
private ComponentRef<ClusterCacheNotifier> clusterCacheNotifier;
private ComponentRef<CommandAckCollector> commandAckCollector;
private ComponentRef<CommandsFactory> commandsFactory;
private ComponentRef<InternalConflictManager> conflictManager;
private ComponentRef<DistributionManager> distributionManager;
private ComponentRef<InternalDataContainer> internalDataContainer;
private ComponentRef<InternalEntryFactory> internalEntryFactory;
private ComponentRef<InvocationContextFactory> invocationContextFactory;
private ComponentRef<IracManager> iracManager;
private ComponentRef<IracVersionGenerator> iracVersionGenerator;
private ComponentRef<IracTombstoneManager> iracTombstoneCleaner;
private ComponentRef<LocalPublisherManager> localPublisherManager;
private ComponentRef<LockManager> lockManager;
private ComponentRef<PerCacheInboundInvocationHandler> inboundInvocationHandler;
private ComponentRef<PersistenceMarshaller> persistenceMarshaller;
private ComponentRef<PublisherHandler> publisherHandler;
private ComponentRef<RecoveryManager> recoveryManager;
private ComponentRef<ResponseGenerator> responseGenerator;
private ComponentRef<RpcManager> rpcManager;
private ComponentRef<StateTransferLock> stateTransferLock;
private ComponentRef<StateTransferManager> stateTransferManager;
private ComponentRef<StreamingMarshaller> internalMarshaller;
private ComponentRef<TakeOfflineManager> takeOfflineManager;
private ComponentRef<TransactionTable> transactionTable;
private ComponentRef<VersionGenerator> versionGenerator;
private ComponentRef<XSiteStateTransferManager> xSiteStateTransferManager;
private ComponentRef<InternalCacheRegistry> icr;
// Global, but we don't cache components at global scope
private TimeService timeService;
/**
* Creates an instance of the component registry. The configuration passed in is automatically registered.
*
* @param configuration configuration with which this is created
* @param cache cache
* @param globalComponents Shared Component Registry to delegate to
*/
public ComponentRegistry(String cacheName, Configuration configuration, AdvancedCache<?, ?> cache,
GlobalComponentRegistry globalComponents, ClassLoader defaultClassLoader) {
super(globalComponents.moduleRepository,
false, globalComponents.getComponent(BasicComponentRegistry.class));
if (cacheName == null) throw new CacheConfigurationException("Cache name cannot be null!");
try {
this.cacheName = cacheName;
this.cacheByteString = ByteString.fromString(cacheName);
this.configuration = configuration;
this.globalComponents = globalComponents;
basicComponentRegistry.registerComponent(KnownComponentNames.CACHE_NAME, cacheName, false);
basicComponentRegistry.registerComponent(ComponentRegistry.class, this, false);
basicComponentRegistry.registerComponent(Configuration.class, configuration, false);
bootstrapComponents();
} catch (Exception e) {
throw new CacheException("Unable to construct a ComponentRegistry!", e);
}
}
@Override
protected ClassLoader getClassLoader() {
return globalComponents.getClassLoader();
}
@Override
protected Log getLog() {
return log;
}
@Override
public final <T> T getComponent(String componentTypeName, String name, boolean nameIsFQCN) {
Class<T> componentType = Util.loadClass(componentTypeName, getClassLoader());
ComponentRef<T> component = basicComponentRegistry.getComponent(name, componentType);
return component != null ? component.running() : null;
}
public final <T> T getLocalComponent(String componentTypeName, String name, boolean nameIsFQCN) {
Class<T> componentType = Util.loadClass(componentTypeName, getClassLoader());
ComponentRef<T> componentRef = basicComponentRegistry.getComponent(name, componentType);
if (componentRef == null || componentRef.wired() == null)
return null;
Class<?> componentClass = componentRef.wired().getClass();
ComponentAccessor<Object> metadata = moduleRepository.getComponentAccessor(componentClass.getName());
if (metadata != null && metadata.isGlobalScope())
return null;
return componentRef.running();
}
public final <T> T getLocalComponent(Class<T> componentType) {
String componentTypeName = componentType.getName();
return getLocalComponent(componentTypeName, componentTypeName, true);
}
public final GlobalComponentRegistry getGlobalComponentRegistry() {
return globalComponents;
}
@Override
protected final <T> T getOrCreateComponent(Class<T> componentClass, String name, boolean nameIsFQCN) {
ComponentRef<T> component = basicComponentRegistry.getComponent(name, componentClass);
return component != null ? component.running() : null;
}
@Override
public void start() {
// Override AbstractComponentRegistry.start() to allow restarting caches from JMX
// If FAILED, stop the existing components and transition to TERMINATED
if (state.needToDestroyFailedCache()) {
stop();
}
// If TERMINATED, rewire non-volatile components and transition to INSTANTIATED
if (state.needToInitializeBeforeStart()) {
state = ComponentStatus.INSTANTIATED;
// TODO Dan: Investigate either re-creating volatile dependencies of non-volatile components automatically
// in BasicComponentRegistry.start() or removing @SurvivesRestarts altogether.
rewire();
}
super.start();
}
/**
* The {@link ComponentRegistry} may delay the start after a cluster shutdown. The component waits for
* the installation of the previous stable topology to start.
*
* Caches that do not need state transfer or are private do not need to delay the start.
*/
@Override
protected CompletionStage<Void> delayStart() {
if (icr == null || icr.wired().isInternalCache(cacheName)) return null;
synchronized (this) {
LocalTopologyManager ltm;
if (state == ComponentStatus.INITIALIZING && (ltm = globalComponents.getLocalTopologyManager()) != null) {
return ltm.stableTopologyCompletion(cacheName);
}
}
return null;
}
@Override
protected String getName() {
return "Cache " + cacheName;
}
@Override
protected void preStart() {
// set this up *before* starting the components since some components - specifically state transfer -
// needs to be able to locate this registry via the InboundInvocationHandler
cacheComponents();
this.globalComponents.registerNamedComponentRegistry(this, cacheName);
notifyCacheStarting(configuration);
}
@Override
protected void postStart() {
CompletionStages.join(cacheManagerNotifier.notifyCacheStarted(cacheName));
}
private void notifyCacheStarting(Configuration configuration) {
for (ModuleLifecycle l : globalComponents.moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheStarting()", l);
}
l.cacheStarting(this, configuration, cacheName);
}
}
@Override
protected void preStop() {
// TODO Dan: This should be done by StateTransferManager after sending the leave request
globalComponents.unregisterNamedComponentRegistry(cacheName);
for (ModuleLifecycle l : globalComponents.moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheStopping()", l);
}
try {
l.cacheStopping(this, cacheName);
} catch (Throwable t) {
log.moduleStopError(l.getClass().getName() + ":" + cacheName, t);
}
}
}
@Override
protected void postStop() {
for (ModuleLifecycle l : globalComponents.moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheStopped()", l);
}
try {
l.cacheStopped(this, cacheName);
} catch (Throwable t) {
log.moduleStopError(l.getClass().getName() + ":" + cacheName, t);
}
}
CompletionStages.join(cacheManagerNotifier.notifyCacheStopped(cacheName));
}
@Override
public void rewire() {
super.rewire();
cacheComponents();
}
@Override
public TimeService getTimeService() {
return timeService;
}
public String getCacheName() {
return cacheName;
}
@Deprecated
public StreamingMarshaller getCacheMarshaller() {
return internalMarshaller.wired();
}
/**
* Caching shortcut for #getComponent(StreamingMarshaller.class, INTERNAL_MARSHALLER);
*/
public StreamingMarshaller getInternalMarshaller() {
return internalMarshaller.wired();
}
/**
* Caching shortcut for #getComponent(PersistenceMarshaller.class, PERSISTENCE_MARSHALLER);
*/
public PersistenceMarshaller getPersistenceMarshaller() {
return persistenceMarshaller.wired();
}
/**
* Caching shortcut for #getComponent(StateTransferManager.class);
*/
public StateTransferManager getStateTransferManager() {
return stateTransferManager.wired();
}
/**
* Caching shortcut for #getComponent(DistributionManager.class);
*/
public DistributionManager getDistributionManager() {
return distributionManager == null ? null : distributionManager.wired();
}
/**
* Caching shortcut for #getComponent(ResponseGenerator.class);
*/
public ResponseGenerator getResponseGenerator() {
return responseGenerator.wired();
}
/**
* Caching shortcut for #getLocalComponent(CommandsFactory.class);
*/
public CommandsFactory getCommandsFactory() {
return commandsFactory.wired();
}
/**
* Caching shortcut for #getComponent(StateTransferManager.class);
*/
public StateTransferLock getStateTransferLock() {
return stateTransferLock.wired();
}
/**
* Caching shortcut for #getLocalComponent(VersionGenerator.class)
*/
public VersionGenerator getVersionGenerator() {
return versionGenerator == null ? null : versionGenerator.wired();
}
/**
* Caching shortcut for #getComponent(PerCacheInboundInvocationHandler.class);
*/
public PerCacheInboundInvocationHandler getPerCacheInboundInvocationHandler() {
return inboundInvocationHandler.wired();
}
/**
* This is a good place to register components that don't have any dependency.
*/
protected void bootstrapComponents() {
}
/**
* Invoked last after all services are wired
*/
public void cacheComponents() {
asyncInterceptorChain = basicComponentRegistry.getComponent(AsyncInterceptorChain.class);
backupReceiver = basicComponentRegistry.lazyGetComponent(BackupReceiver.class); //can we avoid instantiate BackupReceiver is not needed?
backupSender = basicComponentRegistry.getComponent(BackupSender.class);
blockingManager = basicComponentRegistry.getComponent(BlockingManager.class);
clusterPublisherManager = basicComponentRegistry.getComponent(ClusterPublisherManager.class);
localClusterPublisherManager = basicComponentRegistry.getComponent(PublisherManagerFactory.LOCAL_CLUSTER_PUBLISHER, ClusterPublisherManager.class);
takeOfflineManager = basicComponentRegistry.getComponent(TakeOfflineManager.class);
cache = basicComponentRegistry.getComponent(AdvancedCache.class);
cacheNotifier = basicComponentRegistry.getComponent(CacheNotifier.class);
conflictManager = basicComponentRegistry.getComponent(InternalConflictManager.class);
commandsFactory = basicComponentRegistry.getComponent(CommandsFactory.class);
clusterCacheNotifier = basicComponentRegistry.getComponent(ClusterCacheNotifier.class);
commandAckCollector = basicComponentRegistry.getComponent(CommandAckCollector.class);
distributionManager = basicComponentRegistry.getComponent(DistributionManager.class);
inboundInvocationHandler = basicComponentRegistry.getComponent(PerCacheInboundInvocationHandler.class);
internalDataContainer = basicComponentRegistry.getComponent(InternalDataContainer.class);
internalEntryFactory = basicComponentRegistry.getComponent(InternalEntryFactory.class);
internalMarshaller = basicComponentRegistry.getComponent(KnownComponentNames.INTERNAL_MARSHALLER, StreamingMarshaller.class);
invocationContextFactory = basicComponentRegistry.getComponent(InvocationContextFactory.class);
iracManager = basicComponentRegistry.getComponent(IracManager.class);
iracVersionGenerator = basicComponentRegistry.getComponent(IracVersionGenerator.class);
iracTombstoneCleaner = basicComponentRegistry.getComponent(IracTombstoneManager.class);
localPublisherManager = basicComponentRegistry.getComponent(LocalPublisherManager.class);
lockManager = basicComponentRegistry.getComponent(LockManager.class);
persistenceMarshaller = basicComponentRegistry.getComponent(KnownComponentNames.PERSISTENCE_MARSHALLER, PersistenceMarshaller.class);
publisherHandler = basicComponentRegistry.getComponent(PublisherHandler.class);
recoveryManager = basicComponentRegistry.getComponent(RecoveryManager.class);
responseGenerator = basicComponentRegistry.getComponent(ResponseGenerator.class);
rpcManager = basicComponentRegistry.getComponent(RpcManager.class);
stateTransferLock = basicComponentRegistry.getComponent(StateTransferLock.class);
stateTransferManager = basicComponentRegistry.getComponent(StateTransferManager.class);
transactionTable = basicComponentRegistry.getComponent(org.infinispan.transaction.impl.TransactionTable.class);
versionGenerator = basicComponentRegistry.getComponent(VersionGenerator.class);
xSiteStateTransferManager = basicComponentRegistry.getComponent(XSiteStateTransferManager.class);
icr = basicComponentRegistry.getComponent(InternalCacheRegistry.class);
timeService = basicComponentRegistry.getComponent(TimeService.class).running();
// Initialize components that don't have any strong references from the cache
basicComponentRegistry.getComponent(ClusterCacheStats.class);
basicComponentRegistry.getComponent(CacheConfigurationMBean.class);
basicComponentRegistry.getComponent(InternalConflictManager.class);
basicComponentRegistry.getComponent(PreloadManager.class);
}
public final TransactionTable getTransactionTable() {
return transactionTable.wired();
}
public final ComponentRef<TransactionTable> getTransactionTableRef() {
return transactionTable;
}
public final synchronized void registerVersionGenerator(NumericVersionGenerator newVersionGenerator) {
registerComponent(newVersionGenerator, VersionGenerator.class);
versionGenerator = basicComponentRegistry.getComponent(VersionGenerator.class);
}
public ComponentRef<AdvancedCache> getCache() {
return cache;
}
public ComponentRef<AsyncInterceptorChain> getInterceptorChain() {
return asyncInterceptorChain;
}
public ComponentRef<BackupSender> getBackupSender() {
return backupSender;
}
public ComponentRef<BlockingManager> getBlockingManager() {
return blockingManager;
}
public ComponentRef<ClusterPublisherManager> getClusterPublisherManager() {
return clusterPublisherManager;
}
public ComponentRef<ClusterPublisherManager> getLocalClusterPublisherManager() {
return localClusterPublisherManager;
}
public ComponentRef<TakeOfflineManager> getTakeOfflineManager() {
return takeOfflineManager;
}
public ComponentRef<IracManager> getIracManager() {
return iracManager;
}
public ComponentRef<IracVersionGenerator> getIracVersionGenerator() {
return iracVersionGenerator;
}
public ComponentRef<IracTombstoneManager> getIracTombstoneManager() {
return iracTombstoneCleaner;
}
public ByteString getCacheByteString() {
return cacheByteString;
}
public ComponentRef<CacheNotifier> getCacheNotifier() {
return cacheNotifier;
}
public Configuration getConfiguration() {
return configuration;
}
public ComponentRef<InternalConflictManager> getConflictManager() {
return conflictManager;
}
public ComponentRef<ClusterCacheNotifier> getClusterCacheNotifier() {
return clusterCacheNotifier;
}
public ComponentRef<CommandAckCollector> getCommandAckCollector() {
return commandAckCollector;
}
public ComponentRef<InternalDataContainer> getInternalDataContainer() {
return internalDataContainer;
}
public ComponentRef<InternalEntryFactory> getInternalEntryFactory() {
return internalEntryFactory;
}
public ComponentRef<InvocationContextFactory> getInvocationContextFactory() {
return invocationContextFactory;
}
public ComponentRef<LocalPublisherManager> getLocalPublisherManager() {
return localPublisherManager;
}
public ComponentRef<PublisherHandler> getPublisherHandler() {
return publisherHandler;
}
public ComponentRef<LockManager> getLockManager() {
return lockManager;
}
public ComponentRef<RecoveryManager> getRecoveryManager() {
return recoveryManager;
}
public ComponentRef<RpcManager> getRpcManager() {
return rpcManager;
}
public ComponentRef<XSiteStateTransferManager> getXSiteStateTransferManager() {
return xSiteStateTransferManager;
}
public ComponentRef<BackupReceiver> getBackupReceiver() {
return backupReceiver;
}
}
| 22,433
| 39.204301
| 153
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/GlobalComponentRegistry.java
|
package org.infinispan.factories;
import static org.infinispan.stats.impl.LocalContainerStatsImpl.LOCAL_CONTAINER_STATS;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.management.MBeanServerFactory;
import org.infinispan.commands.module.ModuleCommandFactory;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.Version;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.ShutdownHookBehavior;
import org.infinispan.conflict.EntryMergePolicyFactoryRegistry;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.annotations.SurvivesRestarts;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.globalstate.GlobalConfigurationManager;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.lifecycle.ModuleLifecycle;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.manager.ModuleRepository;
import org.infinispan.metrics.impl.CacheManagerMetricsRegistration;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifierImpl;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.registry.impl.InternalCacheRegistryImpl;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.stats.ClusterContainerStats;
import org.infinispan.topology.ClusterTopologyManager;
import org.infinispan.topology.LocalTopologyManager;
import org.infinispan.util.ByteString;
import org.infinispan.util.ModuleProperties;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.util.logging.events.EventLogManager;
import org.infinispan.xsite.GlobalXSiteAdminOperations;
import net.jcip.annotations.ThreadSafe;
/**
* A global component registry where shared components are stored.
*
* @author Manik Surtani
* @since 4.0
*/
@Scope(Scopes.GLOBAL)
@SurvivesRestarts
@ThreadSafe
public class GlobalComponentRegistry extends AbstractComponentRegistry {
private static final Log log = LogFactory.getLog(GlobalComponentRegistry.class);
private static final AtomicBoolean versionLogged = new AtomicBoolean(false);
/**
* Hook to shut down the cache when the JVM exits.
*/
private Thread shutdownHook;
/**
* A flag that the shutdown hook sets before calling cache.stop(). Allows stop() to identify if it has been called
* from a shutdown hook.
*/
private boolean invokedFromShutdownHook;
private final GlobalConfiguration globalConfiguration;
private final EmbeddedCacheManager cacheManager;
/**
* Tracking set of created caches in order to make it easy to remove a cache on remote nodes.
*/
private final Set<String> createdCaches;
private final ModuleProperties moduleProperties = new ModuleProperties();
final Collection<ModuleLifecycle> moduleLifecycles;
private final ConcurrentMap<ByteString, ComponentRegistry> namedComponents = new ConcurrentHashMap<>(4);
protected final ClassLoader classLoader;
// Cached fields
ComponentRef<ClusterTopologyManager> clusterTopologyManager;
ComponentRef<LocalTopologyManager> localTopologyManager;
/**
* Creates an instance of the component registry. The configuration passed in is automatically registered.
*
* @param configuration configuration with which this is created
* @param configurationManager
*/
public GlobalComponentRegistry(GlobalConfiguration configuration,
EmbeddedCacheManager cacheManager,
Set<String> createdCaches, ModuleRepository moduleRepository,
ConfigurationManager configurationManager) {
super(moduleRepository, true, null);
ClassLoader configuredClassLoader = configuration.classLoader();
moduleLifecycles = moduleRepository.getModuleLifecycles();
classLoader = configuredClassLoader;
try {
// this order is important ...
globalConfiguration = configuration;
registerComponent(this, GlobalComponentRegistry.class);
registerComponent(configuration, GlobalConfiguration.class);
registerComponent(cacheManager, EmbeddedCacheManager.class);
basicComponentRegistry.registerComponent(ConfigurationManager.class.getName(), configurationManager, true);
basicComponentRegistry.registerComponent(CacheManagerJmxRegistration.class.getName(), new CacheManagerJmxRegistration(), true);
basicComponentRegistry.registerComponent(CacheManagerMetricsRegistration.class.getName(), new CacheManagerMetricsRegistration(), true);
basicComponentRegistry.registerComponent(CacheManagerNotifier.class.getName(), new CacheManagerNotifierImpl(), true);
basicComponentRegistry.registerComponent(InternalCacheRegistry.class.getName(), new InternalCacheRegistryImpl(), true);
basicComponentRegistry.registerComponent(EntryMergePolicyFactoryRegistry.class.getName(), new EntryMergePolicyFactoryRegistry(), true);
basicComponentRegistry.registerComponent(GlobalXSiteAdminOperations.class.getName(), new GlobalXSiteAdminOperations(), true);
moduleProperties.loadModuleCommandHandlers(configuredClassLoader);
Map<Byte, ModuleCommandFactory> factories = moduleProperties.moduleCommandFactories();
if (factories != null && !factories.isEmpty()) {
registerNonVolatileComponent(factories, KnownComponentNames.MODULE_COMMAND_FACTORIES);
} else {
registerNonVolatileComponent(Collections.emptyMap(), KnownComponentNames.MODULE_COMMAND_FACTORIES);
}
// Allow caches to depend only on module initialization instead of the entire GCR
basicComponentRegistry.registerComponent(ModuleInitializer.class, new ModuleInitializer(), true);
this.createdCaches = createdCaches;
this.cacheManager = cacheManager;
// Initialize components that do not have strong references from the cache manager
basicComponentRegistry.getComponent(EventLogManager.class);
basicComponentRegistry.getComponent(Transport.class);
basicComponentRegistry.getComponent(ClusterContainerStats.class);
basicComponentRegistry.getComponent(LOCAL_CONTAINER_STATS, ClusterContainerStats.class);
basicComponentRegistry.getComponent(GlobalConfigurationManager.class);
basicComponentRegistry.getComponent(CacheManagerJmxRegistration.class);
basicComponentRegistry.getComponent(CacheManagerMetricsRegistration.class);
basicComponentRegistry.getComponent(KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR, ScheduledExecutorService.class);
cacheComponents();
} catch (Exception e) {
throw new CacheException("Unable to construct a GlobalComponentRegistry!", e);
}
}
private void cacheComponents() {
localTopologyManager = basicComponentRegistry.getComponent(LocalTopologyManager.class);
clusterTopologyManager = basicComponentRegistry.getComponent(ClusterTopologyManager.class);
}
@Override
protected ClassLoader getClassLoader() {
return classLoader;
}
@Override
protected Log getLog() {
return log;
}
@Override
protected synchronized void removeShutdownHook() {
// if this is called from a source other than the shutdown hook, de-register the shutdown hook.
if (!invokedFromShutdownHook && shutdownHook != null) Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
@Override
public TimeService getTimeService() {
return getOrCreateComponent(TimeService.class);
}
public <T extends ModuleLifecycle> T getModuleLifecycle(Class<T> type) {
for (ModuleLifecycle module : moduleLifecycles) {
if (type.isInstance(module)) {
return (T) module;
}
}
return null;
}
/**
* This method returns true if there is an mbean server running
* <p>
* NOTE: This method is here for Quarkus (due to mbean usage) - so do not remove without modifying Quarkus as well
* @return true if any mbean server is running
*/
private boolean isMBeanServerRunning() {
return !MBeanServerFactory.findMBeanServer(null).isEmpty();
}
@Override
protected synchronized void addShutdownHook() {
ShutdownHookBehavior shutdownHookBehavior = globalConfiguration.shutdown().hookBehavior();
boolean registerShutdownHook = (shutdownHookBehavior == ShutdownHookBehavior.DEFAULT && !isMBeanServerRunning())
|| shutdownHookBehavior == ShutdownHookBehavior.REGISTER;
if (registerShutdownHook) {
log.tracef("Registering a shutdown hook. Configured behavior = %s", shutdownHookBehavior);
shutdownHook = new Thread(() -> {
try {
invokedFromShutdownHook = true;
cacheManager.stop();
} finally {
invokedFromShutdownHook = false;
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
} else {
log.tracef("Not registering a shutdown hook. Configured behavior = %s", shutdownHookBehavior);
}
}
public final Collection<ComponentRegistry> getNamedComponentRegistries() {
return new ArrayList<>(namedComponents.values());
}
public final ComponentRegistry getNamedComponentRegistry(String name) {
//no need so sync this method as namedComponents is thread safe and correctly published (final)
return getNamedComponentRegistry(ByteString.fromString(name));
}
public final ComponentRegistry getNamedComponentRegistry(ByteString name) {
//no need so sync this method as namedComponents is thread safe and correctly published (final)
return namedComponents.get(name);
}
public synchronized final void registerNamedComponentRegistry(ComponentRegistry componentRegistry, String name) {
namedComponents.put(ByteString.fromString(name), componentRegistry);
}
public synchronized final void unregisterNamedComponentRegistry(String name) {
namedComponents.remove(ByteString.fromString(name));
}
public synchronized final void rewireNamedRegistries() {
for (ComponentRegistry cr : namedComponents.values())
cr.rewire();
}
@Override
public void rewire() {
super.rewire();
cacheComponents();
}
@Override
protected String getName() {
return "DefaultCacheManager";
}
@Override
protected void preStart() {
basicComponentRegistry.getComponent(ModuleInitializer.class).running();
if (versionLogged.compareAndSet(false, true)) {
CONTAINER.version(Version.printVersion());
}
}
public void postStart() {
modulesManagerStarted();
}
@Override
protected CompletionStage<Void> delayStart() {
return null;
}
private void modulesManagerStarting() {
for (ModuleLifecycle l : moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheManagerStarting()", l);
}
l.cacheManagerStarting(this, globalConfiguration);
}
}
private void modulesManagerStarted() {
for (ModuleLifecycle l : moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheManagerStarted()", l);
}
l.cacheManagerStarted(this);
}
}
@Override
protected void preStop() {
modulesManagerStopping();
}
@Override
protected void postStop() {
// Do nothing, ModulesOuterLifecycle invokes modulesManagerStopped automatically
}
private void modulesManagerStopping() {
for (ModuleLifecycle l : moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheManagerStopping()", l);
}
try {
l.cacheManagerStopping(this);
} catch (Throwable t) {
CONTAINER.moduleStopError(l.getClass().getName(), t);
}
}
}
private void modulesManagerStopped() {
if (state == ComponentStatus.TERMINATED) {
for (ModuleLifecycle l : moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheManagerStopped()", l);
}
try {
l.cacheManagerStopped(this);
} catch (Throwable t) {
CONTAINER.moduleStopError(l.getClass().getName(), t);
}
}
}
}
public void notifyCacheStarted(String cacheName) {
ComponentRegistry cr = getNamedComponentRegistry(cacheName);
for (ModuleLifecycle l : moduleLifecycles) {
if (log.isTraceEnabled()) {
log.tracef("Invoking %s.cacheStarted()", l);
}
l.cacheStarted(cr, cacheName);
}
}
public final GlobalConfiguration getGlobalConfiguration() {
//this is final so no need to synchronise it
return globalConfiguration;
}
/**
* Removes a cache with the given name, returning true if the cache was removed.
*/
public synchronized boolean removeCache(String cacheName) {
return createdCaches.remove(cacheName);
}
@Deprecated
public ModuleProperties getModuleProperties() {
return moduleProperties;
}
public EmbeddedCacheManager getCacheManager() {
return cacheManager;
}
/**
* Module initialization happens in {@link ModuleLifecycle#cacheManagerStarting(GlobalComponentRegistry, GlobalConfiguration)}.
* This component helps guarantee that all modules are initialized before the first cache starts.
*/
@Scope(Scopes.GLOBAL)
public class ModuleInitializer {
@Start
void start() {
modulesManagerStarting();
}
@Stop
void stop() {
modulesManagerStopped();
}
}
public ClusterTopologyManager getClusterTopologyManager() {
return clusterTopologyManager.running();
}
public LocalTopologyManager getLocalTopologyManager() {
return localTopologyManager.running();
}
}
| 14,890
| 35.950372
| 144
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/AutoInstantiableFactory.java
|
package org.infinispan.factories;
/**
* Component factories that implement this interface can be instantiated automatically by component registries when
* looking up components. Typically, most component factories will implement this. One known exception is the {@link
* org.infinispan.factories.BootstrapFactory}.
* <p/>
* Anything implementing this interface should expose a public, no-arg constructor.
* <p/>
*
* @author Manik Surtani
* @since 4.0
*/
public interface AutoInstantiableFactory {
}
| 512
| 31.0625
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/MarshallerFactory.java
|
package org.infinispan.factories;
import org.infinispan.commons.marshall.ImmutableProtoStreamMarshaller;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.StreamAwareMarshaller;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.ComponentAlias;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.marshall.core.GlobalMarshaller;
import org.infinispan.marshall.core.impl.DelegatingUserMarshaller;
import org.infinispan.marshall.persistence.impl.PersistenceMarshallerImpl;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
/**
* MarshallerFactory.
*
* @author Galder Zamarreño
* @since 4.0
*/
@DefaultFactoryFor(
classes = {
Marshaller.class,
StreamingMarshaller.class,
StreamAwareMarshaller.class
},
names = {
KnownComponentNames.INTERNAL_MARSHALLER,
KnownComponentNames.PERSISTENCE_MARSHALLER,
KnownComponentNames.USER_MARSHALLER
}
)
public class MarshallerFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
@Inject
ComponentRef<SerializationContextRegistry> contextRegistry;
@Override
public Object construct(String componentName) {
if (componentName.equals(StreamingMarshaller.class.getName())) {
return ComponentAlias.of(KnownComponentNames.INTERNAL_MARSHALLER);
}
switch (componentName) {
case KnownComponentNames.PERSISTENCE_MARSHALLER:
return new PersistenceMarshallerImpl();
case KnownComponentNames.INTERNAL_MARSHALLER:
return new GlobalMarshaller();
case KnownComponentNames.USER_MARSHALLER:
Marshaller marshaller = globalConfiguration.serialization().marshaller();
if (marshaller != null) {
marshaller.initialize(globalComponentRegistry.getCacheManager().getClassAllowList());
} else {
marshaller = new ImmutableProtoStreamMarshaller(contextRegistry.wired().getUserCtx());
}
return new DelegatingUserMarshaller(marshaller);
default:
throw new IllegalArgumentException(String.format("Marshaller name '%s' not recognised", componentName));
}
}
}
| 2,448
| 37.265625
| 116
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/DataContainerFactory.java
|
package org.infinispan.factories;
import java.util.function.Supplier;
import org.infinispan.commons.marshall.WrappedBytes;
import org.infinispan.configuration.cache.ClusteringConfiguration;
import org.infinispan.configuration.cache.MemoryConfiguration;
import org.infinispan.container.DataContainer;
import org.infinispan.container.impl.BoundedSegmentedDataContainer;
import org.infinispan.container.impl.DefaultDataContainer;
import org.infinispan.container.impl.DefaultSegmentedDataContainer;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.container.impl.L1SegmentedDataContainer;
import org.infinispan.container.impl.PeekableTouchableContainerMap;
import org.infinispan.container.impl.PeekableTouchableMap;
import org.infinispan.container.offheap.BoundedOffHeapDataContainer;
import org.infinispan.container.offheap.OffHeapConcurrentMap;
import org.infinispan.container.offheap.OffHeapDataContainer;
import org.infinispan.container.offheap.OffHeapEntryFactory;
import org.infinispan.container.offheap.OffHeapMemoryAllocator;
import org.infinispan.container.offheap.SegmentedBoundedOffHeapDataContainer;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.factories.annotations.DefaultFactoryFor;
/**
* Constructs the data container
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Vladimir Blagojevic
* @since 4.0
*/
@DefaultFactoryFor(classes = InternalDataContainer.class)
public class DataContainerFactory extends AbstractNamedCacheComponentFactory implements
AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
ClusteringConfiguration clusteringConfiguration = configuration.clustering();
boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer();
int level = configuration.locking().concurrencyLevel();
MemoryConfiguration memoryConfiguration = configuration.memory();
boolean offHeap = memoryConfiguration.isOffHeap();
EvictionStrategy strategy = memoryConfiguration.whenFull();
//handle case when < 0 value signifies unbounded container or when we are not removal based
if (strategy.isExceptionBased() || !strategy.isEnabled()) {
if (offHeap) {
if (shouldSegment) {
int segments = clusteringConfiguration.hash().numSegments();
Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier =
this::createAndStartOffHeapConcurrentMap;
if (clusteringConfiguration.l1().enabled()) {
return new L1SegmentedDataContainer<>(mapSupplier, segments);
}
return new DefaultSegmentedDataContainer<>(mapSupplier, segments);
} else {
return new OffHeapDataContainer();
}
} else if (shouldSegment) {
Supplier<PeekableTouchableMap<Object, Object>> mapSupplier =
PeekableTouchableContainerMap::new;
int segments = clusteringConfiguration.hash().numSegments();
if (clusteringConfiguration.l1().enabled()) {
return new L1SegmentedDataContainer<>(mapSupplier, segments);
}
return new DefaultSegmentedDataContainer<>(mapSupplier, segments);
} else {
return DefaultDataContainer.unBoundedDataContainer(level);
}
}
boolean sizeInBytes = memoryConfiguration.maxSize() != null;
long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount();
DataContainer<?, ?> dataContainer;
if (offHeap) {
if (shouldSegment) {
int segments = clusteringConfiguration.hash().numSegments();
dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize,
memoryConfiguration.evictionType());
} else {
dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType());
}
} else if (shouldSegment) {
int segments = clusteringConfiguration.hash().numSegments();
dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize,
memoryConfiguration.evictionType());
} else {
dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize,
memoryConfiguration.evictionType());
}
if (sizeInBytes) {
memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE)
.addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes()));
} else {
memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT)
.addListener((newSize, old) -> dataContainer.resize(newSize.get()));
}
return dataContainer;
}
/* visible for testing */
OffHeapConcurrentMap createAndStartOffHeapConcurrentMap() {
OffHeapEntryFactory entryFactory = componentRegistry.getOrCreateComponent(OffHeapEntryFactory.class);
OffHeapMemoryAllocator memoryAllocator = componentRegistry.getOrCreateComponent(OffHeapMemoryAllocator.class);
return new OffHeapConcurrentMap(memoryAllocator, entryFactory, null);
}
}
| 5,348
| 47.189189
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/KnownComponentNames.java
|
package org.infinispan.factories;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commons.executors.BlockingThreadPoolExecutorFactory;
import org.infinispan.commons.util.ProcessorInfo;
/**
* Holder for known named component names. To be used with {@link org.infinispan.factories.annotations.ComponentName}
* annotation.
*
* @author Manik Surtani
* @since 4.0
*/
public class KnownComponentNames {
public static final String CACHE_NAME = "cacheName";
public static final String ASYNC_NOTIFICATION_EXECUTOR = "org.infinispan.executors.notification";
public static final String EXPIRATION_SCHEDULED_EXECUTOR = "org.infinispan.executors.expiration";
public static final String NON_BLOCKING_EXECUTOR = "org.infinispan.executors.non-blocking";
public static final String BLOCKING_EXECUTOR = "org.infinispan.executors.blocking";
public static final String TIMEOUT_SCHEDULE_EXECUTOR = "org.infinispan.executors.timeout";
public static final String MODULE_COMMAND_FACTORIES ="org.infinispan.modules.command.factories";
public static final String CLASS_LOADER = "java.lang.ClassLoader";
public static final String TRANSACTION_VERSION_GENERATOR = "org.infinispan.transaction.versionGenerator";
public static final String HOT_ROD_VERSION_GENERATOR = "org.infinispan.server.hotrod.versionGenerator";
public static final String CACHE_DEPENDENCY_GRAPH = "org.infinispan.CacheDependencyGraph";
public static final String INTERNAL_MARSHALLER = "org.infinispan.marshaller.internal";
public static final String PERSISTENCE_MARSHALLER = "org.infinispan.marshaller.persistence";
public static final String USER_MARSHALLER = "org.infinispan.marshaller.user";
private static final Map<String, Integer> DEFAULT_THREAD_COUNT = new HashMap<>(7);
private static final Map<String, Integer> DEFAULT_QUEUE_SIZE = new HashMap<>(7);
private static final Map<String, Integer> DEFAULT_THREAD_PRIORITY = new HashMap<>(8);
static {
DEFAULT_THREAD_COUNT.put(ASYNC_NOTIFICATION_EXECUTOR, 1);
DEFAULT_THREAD_COUNT.put(EXPIRATION_SCHEDULED_EXECUTOR, 1);
DEFAULT_THREAD_COUNT.put(NON_BLOCKING_EXECUTOR, ProcessorInfo.availableProcessors() * 2);
DEFAULT_THREAD_COUNT.put(BLOCKING_EXECUTOR, 150);
DEFAULT_QUEUE_SIZE.put(ASYNC_NOTIFICATION_EXECUTOR, 1_000);
DEFAULT_QUEUE_SIZE.put(EXPIRATION_SCHEDULED_EXECUTOR, 0);
DEFAULT_QUEUE_SIZE.put(NON_BLOCKING_EXECUTOR, 1_000);
DEFAULT_QUEUE_SIZE.put(BLOCKING_EXECUTOR, 5_000);
DEFAULT_THREAD_PRIORITY.put(ASYNC_NOTIFICATION_EXECUTOR, Thread.NORM_PRIORITY);
DEFAULT_THREAD_PRIORITY.put(EXPIRATION_SCHEDULED_EXECUTOR, Thread.NORM_PRIORITY);
DEFAULT_THREAD_PRIORITY.put(TIMEOUT_SCHEDULE_EXECUTOR, Thread.NORM_PRIORITY);
DEFAULT_THREAD_PRIORITY.put(NON_BLOCKING_EXECUTOR, Thread.NORM_PRIORITY);
DEFAULT_THREAD_PRIORITY.put(BLOCKING_EXECUTOR, Thread.NORM_PRIORITY);
}
public static int getDefaultThreads(String componentName) {
return DEFAULT_THREAD_COUNT.get(componentName);
}
public static int getDefaultThreadPrio(String componentName) {
return DEFAULT_THREAD_PRIORITY.get(componentName);
}
public static int getDefaultQueueSize(String componentName) {
return DEFAULT_QUEUE_SIZE.get(componentName);
}
public static int getDefaultMinThreads(String componentName) {
if (getDefaultQueueSize(componentName) == 0) {
return 1;
} else {
return getDefaultThreads(componentName);
}
}
public static long getDefaultKeepaliveMillis() {
return BlockingThreadPoolExecutorFactory.DEFAULT_KEEP_ALIVE_MILLIS;
}
public static String shortened(String cn) {
int dotIndex = cn.lastIndexOf(".");
int dotIndexPlusOne = dotIndex + 1;
String cname = cn;
if (dotIndexPlusOne == cn.length())
cname = shortened(cn.substring(0, cn.length() - 1));
else {
if (dotIndex > -1 && cn.length() > dotIndexPlusOne) {
cname = cn.substring(dotIndexPlusOne);
}
cname += "-thread";
}
return cname;
}
}
| 4,124
| 41.525773
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/RecoveryManagerFactory.java
|
package org.infinispan.factories;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.RecoveryConfiguration;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.xa.recovery.RecoveryAwareRemoteTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryInfoKey;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.transaction.xa.recovery.RecoveryManagerImpl;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Factory for RecoveryManager.
*
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
@DefaultFactoryFor(classes = {RecoveryManager.class})
public class RecoveryManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
private static final Log log = LogFactory.getLog(RecoveryManagerFactory.class);
private static final long DEFAULT_EXPIRY = TimeUnit.HOURS.toMillis(6);
@Override
public Object construct(String name) {
if (configuration.transaction().recovery().enabled()) {
String recoveryCacheName = configuration.transaction().recovery().recoveryInfoCacheName();
log.tracef("Using recovery cache name %s", recoveryCacheName);
EmbeddedCacheManager cm = componentRegistry.getGlobalComponentRegistry().getComponent(EmbeddedCacheManager.class);
boolean useDefaultCache = recoveryCacheName.equals(RecoveryConfiguration.DEFAULT_RECOVERY_INFO_CACHE);
//if use a defined cache
if (!useDefaultCache) {
// check to see that the cache is defined
if (!cm.getCacheConfigurationNames().contains(recoveryCacheName)) {
throw new CacheConfigurationException("Recovery cache (" + recoveryCacheName + ") does not exist!!");
}
} else {
InternalCacheRegistry internalCacheRegistry = componentRegistry.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class);
internalCacheRegistry.registerInternalCache(recoveryCacheName, getDefaultRecoveryCacheConfig());
}
return (RecoveryManager) buildRecoveryManager(componentRegistry.getCacheName(),
recoveryCacheName, cm, useDefaultCache);
} else {
return null;
}
}
private Configuration getDefaultRecoveryCacheConfig() {
ConfigurationBuilder builder = new ConfigurationBuilder();
//the recovery cache should not participate in main cache's transactions, especially because removals
// from this cache are executed in the context of a finalised transaction and cause issues.
builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
builder.clustering().cacheMode(CacheMode.LOCAL);
builder.expiration().lifespan(DEFAULT_EXPIRY);
builder.transaction().recovery().disable();
return builder.build();
}
private RecoveryManager buildRecoveryManager(String cacheName, String recoveryCacheName, EmbeddedCacheManager cm, boolean isDefault) {
log.tracef("About to obtain a reference to the recovery cache: %s", recoveryCacheName);
Cache<?, ?> recoveryCache = cm.getCache(recoveryCacheName);
if (recoveryCache.getCacheConfiguration().transaction().transactionMode().isTransactional()) {
//see comment in getDefaultRecoveryCacheConfig
throw new CacheConfigurationException("The recovery cache shouldn't be transactional.");
}
log.tracef("Obtained a reference to the recovery cache: %s", recoveryCacheName);
return new RecoveryManagerImpl((ConcurrentMap<RecoveryInfoKey, RecoveryAwareRemoteTransaction>) recoveryCache, cacheName);
}
}
| 4,174
| 49.301205
| 147
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/AnyScopeComponentFactory.java
|
package org.infinispan.factories;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.util.ReflectionUtil;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
@Scope(Scopes.NONE)
public class AnyScopeComponentFactory implements ComponentFactory {
protected static final Log log = LogFactory.getLog(AbstractComponentFactory.class);
@Inject protected GlobalComponentRegistry globalComponentRegistry;
@Inject protected GlobalConfiguration globalConfiguration;
@Override
public Object construct(String name) {
Class<?> componentType;
try {
componentType = ReflectionUtil.getClassForName(name, globalComponentRegistry.getClassLoader());
} catch (ClassNotFoundException e) {
throw new CacheConfigurationException(e);
}
return construct(componentType);
}
/**
* Constructs a component.
*
* @param componentType type of component
* @return a component
* @deprecated Since 9.4, please override {@link ComponentFactory#construct(String)} instead.
*/
@Deprecated
public <T> T construct(Class<T> componentType) {
throw new UnsupportedOperationException();
}
}
| 1,440
| 34.146341
| 104
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/TransactionSynchronizationRegistryFactory.java
|
package org.infinispan.factories;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.transaction.lookup.TransactionSynchronizationRegistryLookup;
/**
* Factory for the TransactionSynchronizationRegistry
*
* @author Stuart Douglas
*/
@DefaultFactoryFor(classes = {TransactionSynchronizationRegistry.class})
public class TransactionSynchronizationRegistryFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
// See if we had a TransactionSynchronizationRegistry injected into our config
TransactionSynchronizationRegistryLookup lookup = configuration.transaction().transactionSynchronizationRegistryLookup();
try {
if (lookup != null) {
return lookup.getTransactionSynchronizationRegistry();
}
}
catch (Exception e) {
throw new CacheConfigurationException("failed obtaining TransactionSynchronizationRegistry", e);
}
return null;
}
}
| 1,180
| 34.787879
| 134
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/NamedExecutorsFactory.java
|
package org.infinispan.factories;
import static org.infinispan.factories.KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.BLOCKING_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.EXPIRATION_SCHEDULED_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.NON_BLOCKING_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.getDefaultThreadPrio;
import static org.infinispan.factories.KnownComponentNames.shortened;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.executors.ScheduledThreadPoolExecutorFactory;
import org.infinispan.commons.executors.ThreadPoolExecutorFactory;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.ThreadPoolConfiguration;
import org.infinispan.executors.LazyInitializingBlockingTaskAwareExecutorService;
import org.infinispan.executors.LazyInitializingScheduledExecutorService;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.threads.BlockingThreadFactory;
import org.infinispan.factories.threads.CoreExecutorFactory;
import org.infinispan.factories.threads.DefaultThreadFactory;
import org.infinispan.factories.threads.NonBlockingThreadFactory;
/**
* A factory that specifically knows how to create named executors.
*
* @author Manik Surtani
* @author Pedro Ruivo
* @since 4.0
*/
@DefaultFactoryFor(names = {ASYNC_NOTIFICATION_EXECUTOR, BLOCKING_EXECUTOR, NON_BLOCKING_EXECUTOR,
EXPIRATION_SCHEDULED_EXECUTOR, TIMEOUT_SCHEDULE_EXECUTOR})
public class NamedExecutorsFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
try {
// Construction happens only on startup of either CacheManager, or Cache, so
// using synchronized protection does not have a great impact on app performance.
if (componentName.equals(ASYNC_NOTIFICATION_EXECUTOR)) {
return createExecutorService(
globalConfiguration.listenerThreadPool(),
ASYNC_NOTIFICATION_EXECUTOR,
ExecutorServiceType.DEFAULT);
} else if (componentName.equals(BLOCKING_EXECUTOR)) {
return createExecutorService(
globalConfiguration.blockingThreadPool(),
BLOCKING_EXECUTOR,
ExecutorServiceType.BLOCKING);
} else if (componentName.equals(EXPIRATION_SCHEDULED_EXECUTOR)) {
return createExecutorService(
globalConfiguration.expirationThreadPool(),
EXPIRATION_SCHEDULED_EXECUTOR,
ExecutorServiceType.SCHEDULED);
} else if (componentName.equals(NON_BLOCKING_EXECUTOR)) {
return createExecutorService(
globalConfiguration.nonBlockingThreadPool(),
NON_BLOCKING_EXECUTOR, ExecutorServiceType.NON_BLOCKING);
} else if (componentName.endsWith(TIMEOUT_SCHEDULE_EXECUTOR)) {
return createExecutorService(null, TIMEOUT_SCHEDULE_EXECUTOR, ExecutorServiceType.SCHEDULED);
} else {
throw new CacheConfigurationException("Unknown named executor " + componentName);
}
} catch (CacheConfigurationException ce) {
throw ce;
} catch (Exception e) {
throw new CacheConfigurationException("Unable to instantiate ExecutorFactory for named component " + componentName, e);
}
}
@SuppressWarnings("unchecked")
private <T extends ExecutorService> T createExecutorService(ThreadPoolConfiguration threadPoolConfiguration,
String componentName, ExecutorServiceType type) {
ThreadFactory threadFactory;
ThreadPoolExecutorFactory executorFactory;
if (threadPoolConfiguration != null) {
threadFactory = threadPoolConfiguration.threadFactory() != null
? threadPoolConfiguration.threadFactory()
: createThreadFactoryWithDefaults(globalConfiguration, componentName, type);
ThreadPoolExecutorFactory threadPoolFactory = threadPoolConfiguration.threadPoolFactory();
if (threadPoolFactory != null) {
executorFactory = threadPoolConfiguration.threadPoolFactory();
if (type == ExecutorServiceType.NON_BLOCKING && !executorFactory.createsNonBlockingThreads()) {
throw log.threadPoolFactoryIsBlocking(threadPoolConfiguration.name(), componentName);
}
} else {
executorFactory = createThreadPoolFactoryWithDefaults(componentName, type);
}
} else {
threadFactory = createThreadFactoryWithDefaults(globalConfiguration, componentName, type);
executorFactory = createThreadPoolFactoryWithDefaults(componentName, type);
}
switch (type) {
case SCHEDULED:
return (T) new LazyInitializingScheduledExecutorService(executorFactory, threadFactory);
default:
globalConfiguration.transport().nodeName();
return (T) new LazyInitializingBlockingTaskAwareExecutorService(executorFactory, threadFactory,
globalComponentRegistry.getTimeService());
}
}
private ThreadFactory createThreadFactoryWithDefaults(GlobalConfiguration globalCfg, final String componentName,
ExecutorServiceType type) {
switch (type) {
case BLOCKING:
return new BlockingThreadFactory("ISPN-blocking-thread-group", getDefaultThreadPrio(componentName),
DefaultThreadFactory.DEFAULT_PATTERN, globalCfg.transport().nodeName(), shortened(componentName));
case NON_BLOCKING:
return new NonBlockingThreadFactory("ISPN-non-blocking-thread-group", getDefaultThreadPrio(componentName),
DefaultThreadFactory.DEFAULT_PATTERN, globalCfg.transport().nodeName(), shortened(componentName));
default:
// Use defaults
return new DefaultThreadFactory(null, getDefaultThreadPrio(componentName), DefaultThreadFactory.DEFAULT_PATTERN,
globalCfg.transport().nodeName(), shortened(componentName));
}
}
private ThreadPoolExecutorFactory createThreadPoolFactoryWithDefaults(
final String componentName, ExecutorServiceType type) {
switch (type) {
case SCHEDULED:
return ScheduledThreadPoolExecutorFactory.create();
default:
int defaultQueueSize = KnownComponentNames.getDefaultQueueSize(componentName);
int defaultMaxThreads = KnownComponentNames.getDefaultThreads(componentName);
return CoreExecutorFactory.executorFactory(defaultMaxThreads, defaultQueueSize,
type == ExecutorServiceType.NON_BLOCKING);
}
}
private enum ExecutorServiceType {
DEFAULT,
SCHEDULED,
// This type of pool means that it can run blocking operations, should not run CPU based operations if possible
BLOCKING,
// This type of pool means that nothing should ever be executed upon it that may block
NON_BLOCKING,
;
}
}
| 7,636
| 50.952381
| 128
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/ClusteringDependentLogicFactory.java
|
package org.infinispan.factories;
import static org.infinispan.util.logging.Log.CONTAINER;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
@DefaultFactoryFor(classes = ClusteringDependentLogic.class)
public class ClusteringDependentLogicFactory extends AbstractNamedCacheComponentFactory implements
AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
CacheMode cacheMode = configuration.clustering().cacheMode();
ClusteringDependentLogic cdl;
if (!cacheMode.isClustered()) {
cdl = new ClusteringDependentLogic.LocalLogic();
} else if (cacheMode.isInvalidation()) {
cdl = new ClusteringDependentLogic.InvalidationLogic();
} else if (cacheMode.isReplicated()) {
cdl = new ClusteringDependentLogic.ReplicationLogic();
} else if (cacheMode.isDistributed()){
cdl = new ClusteringDependentLogic.DistributionLogic();
} else {
throw CONTAINER.factoryCannotConstructComponent(componentName);
}
return cdl;
}
}
| 1,187
| 38.6
| 98
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/PublisherManagerFactory.java
|
package org.infinispan.factories;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.impl.ComponentAlias;
import org.infinispan.partitionhandling.PartitionHandling;
import org.infinispan.reactive.publisher.impl.ClusterPublisherManager;
import org.infinispan.reactive.publisher.impl.ClusterPublisherManagerImpl;
import org.infinispan.reactive.publisher.impl.LocalClusterPublisherManagerImpl;
import org.infinispan.reactive.publisher.impl.LocalPublisherManager;
import org.infinispan.reactive.publisher.impl.LocalPublisherManagerImpl;
import org.infinispan.reactive.publisher.impl.PartitionAwareClusterPublisherManager;
/**
* Factory that allows creation of a {@link LocalPublisherManager} or {@link ClusterPublisherManager} based on the provided
* configuration.
*
* @author wburns
* @since 10.0
*/
@DefaultFactoryFor(classes = {LocalPublisherManager.class, ClusterPublisherManager.class}, names = PublisherManagerFactory.LOCAL_CLUSTER_PUBLISHER)
public class PublisherManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
public static final String LOCAL_CLUSTER_PUBLISHER = "NoClusterPublisherManager";
@Override
public Object construct(String componentName) {
if (componentName.equals(LOCAL_CLUSTER_PUBLISHER)) {
return new LocalClusterPublisherManagerImpl<>();
}
if (componentName.equals(LocalPublisherManager.class.getName())) {
return new LocalPublisherManagerImpl<>();
}
CacheMode cacheMode = configuration.clustering().cacheMode();
if (cacheMode.needsStateTransfer() && componentName.equals(ClusterPublisherManager.class.getName())) {
if (configuration.clustering().partitionHandling().whenSplit() == PartitionHandling.DENY_READ_WRITES) {
return new PartitionAwareClusterPublisherManager<>();
}
return new ClusterPublisherManagerImpl<>();
}
return ComponentAlias.of(LOCAL_CLUSTER_PUBLISHER);
}
}
| 2,066
| 48.214286
| 147
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/ResponseGeneratorFactory.java
|
package org.infinispan.factories;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.remoting.responses.DefaultResponseGenerator;
import org.infinispan.remoting.responses.ResponseGenerator;
/**
* Creates a ResponseGenerator
*
* @author Manik Surtani
* @since 4.0
*/
@DefaultFactoryFor(classes = ResponseGenerator.class)
public class ResponseGeneratorFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
return new DefaultResponseGenerator();
}
}
| 595
| 28.8
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/IracComponentFactory.java
|
package org.infinispan.factories;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.infinispan.configuration.cache.BackupConfiguration;
import org.infinispan.configuration.cache.BackupFailurePolicy;
import org.infinispan.container.versioning.irac.DefaultIracTombstoneManager;
import org.infinispan.container.versioning.irac.IracTombstoneManager;
import org.infinispan.container.versioning.irac.NoOpIracTombstoneManager;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.irac.DefaultIracManager;
import org.infinispan.xsite.irac.IracManager;
import org.infinispan.xsite.irac.IracXSiteBackup;
import org.infinispan.xsite.irac.NoOpIracManager;
import net.jcip.annotations.GuardedBy;
@DefaultFactoryFor(classes = {
IracManager.class,
IracTombstoneManager.class
})
public class IracComponentFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory {
@Inject Transport transport;
@GuardedBy("this")
private List<IracXSiteBackup> asyncBackups;
@Override
public Object construct(String name) {
if (name.equals(IracTombstoneManager.class.getName())) {
List<IracXSiteBackup> backups = getAsyncBackups();
return backups.isEmpty() ?
NoOpIracTombstoneManager.getInstance() :
new DefaultIracTombstoneManager(configuration, backups);
} else if (name.equals(IracManager.class.getName())) {
List<IracXSiteBackup> backups = getAsyncBackups();
return backups.isEmpty() ?
NoOpIracManager.INSTANCE :
new DefaultIracManager(configuration, backups);
}
throw CONTAINER.factoryCannotConstructComponent(name);
}
private synchronized List<IracXSiteBackup> getAsyncBackups() {
if (asyncBackups != null) {
return asyncBackups;
}
if (transport == null) {
return asyncBackups = Collections.emptyList();
}
// -1 since incrementAndGet is used!
AtomicInteger index = new AtomicInteger(-1);
asyncBackups = configuration.sites().asyncBackupsStream()
.filter(this::isRemoteSite) // filter local site
.map(c -> create(c, index)) //convert to sync
.collect(Collectors.toList());
if (log.isTraceEnabled()) {
String b = asyncBackups.stream().map(XSiteBackup::getSiteName).collect(Collectors.joining(", "));
log.tracef("Async remote sites found: %s", b);
}
if (!asyncBackups.isEmpty()) {
transport.checkCrossSiteAvailable();
}
return asyncBackups;
}
private boolean isRemoteSite(BackupConfiguration config) {
return !config.site().equals(transport.localSiteName());
}
private IracXSiteBackup create(BackupConfiguration config, AtomicInteger index) {
return new IracXSiteBackup(config.site(),
true,
config.replicationTimeout(),
config.backupFailurePolicy() == BackupFailurePolicy.WARN,
(short) index.incrementAndGet());
}
}
| 3,473
| 38.477273
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/AbstractThreadPoolExecutorFactory.java
|
package org.infinispan.factories.threads;
import java.util.concurrent.ExecutorService;
import org.infinispan.commons.executors.ThreadPoolExecutorFactory;
/**
* Abstract {@link ThreadPoolExecutorFactory} that contains commons variables for configuring a thread pool
* @author wburns
*/
public abstract class AbstractThreadPoolExecutorFactory<T extends ExecutorService> implements ThreadPoolExecutorFactory<T> {
protected final int maxThreads;
protected final int coreThreads;
protected final int queueLength;
protected final long keepAlive;
protected AbstractThreadPoolExecutorFactory(int maxThreads, int coreThreads, int queueLength, long keepAlive) {
this.maxThreads = maxThreads;
this.coreThreads = coreThreads;
this.queueLength = queueLength;
this.keepAlive = keepAlive;
}
public int maxThreads() {
return maxThreads;
}
public int coreThreads() {
return coreThreads;
}
public int queueLength() {
return queueLength;
}
public long keepAlive() {
return keepAlive;
}
}
| 1,070
| 25.775
| 124
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/CoreExecutorFactory.java
|
package org.infinispan.factories.threads;
import java.util.concurrent.ExecutorService;
import org.infinispan.commons.executors.ThreadPoolExecutorFactory;
/**
* Static factory class for producing executor factories in the core module
* @author wburns
*/
public class CoreExecutorFactory {
private CoreExecutorFactory() { }
public static ThreadPoolExecutorFactory<? extends ExecutorService> executorFactory(int maxThreads, int coreThreads,
int queueLength, long keepAlive, boolean nonBlocking) {
if (nonBlocking) {
return new NonBlockingThreadPoolExecutorFactory(maxThreads, coreThreads, queueLength, keepAlive);
}
return new EnhancedQueueExecutorFactory(maxThreads, coreThreads, queueLength, keepAlive);
}
public static ThreadPoolExecutorFactory<? extends ExecutorService> executorFactory(int maxThreads, int queueLength,
boolean nonBlocking) {
if (nonBlocking) {
return NonBlockingThreadPoolExecutorFactory.create(maxThreads, queueLength);
}
return EnhancedQueueExecutorFactory.create(maxThreads, queueLength);
}
}
| 1,110
| 36.033333
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/NonBlockingThreadPoolExecutorFactory.java
|
package org.infinispan.factories.threads;
import static org.infinispan.commons.logging.Log.CONFIG;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.executors.NonBlockingResource;
import org.infinispan.commons.util.concurrent.NonBlockingRejectedExecutionHandler;
/**
* Executor Factory used for non blocking executors which utilizes {@link ThreadPoolExecutor} internally.
* @author wburns
*/
public class NonBlockingThreadPoolExecutorFactory extends AbstractThreadPoolExecutorFactory<ExecutorService> {
public static final int DEFAULT_KEEP_ALIVE_MILLIS = 60000;
protected NonBlockingThreadPoolExecutorFactory(int maxThreads, int coreThreads, int queueLength, long keepAlive) {
super(maxThreads, coreThreads, queueLength, keepAlive);
}
@Override
public boolean createsNonBlockingThreads() {
return true;
}
@Override
public ExecutorService createExecutor(ThreadFactory threadFactory) {
BlockingQueue<Runnable> queue = queueLength == 0 ? new SynchronousQueue<>() : new LinkedBlockingQueue<>(queueLength);
if (!(threadFactory instanceof NonBlockingResource)) {
throw new IllegalStateException("Executor factory configured to be non blocking and received a thread" +
" factory that can create blocking threads!");
}
return new ThreadPoolExecutor(coreThreads, maxThreads, keepAlive,
TimeUnit.MILLISECONDS, queue, threadFactory,
NonBlockingRejectedExecutionHandler.getInstance());
}
@Override
public void validate() {
if (coreThreads < 0)
throw CONFIG.illegalValueThreadPoolParameter("core threads", ">= 0");
if (maxThreads <= 0)
throw CONFIG.illegalValueThreadPoolParameter("max threads", "> 0");
if (maxThreads < coreThreads)
throw CONFIG.illegalValueThreadPoolParameter(
"max threads and core threads", "max threads >= core threads");
if (keepAlive < 0)
throw CONFIG.illegalValueThreadPoolParameter("keep alive time", ">= 0");
if (queueLength < 0)
throw CONFIG.illegalValueThreadPoolParameter("work queue length", ">= 0");
}
@Override
public String toString() {
return "BlockingThreadPoolExecutorFactory{" +
"maxThreads=" + maxThreads +
", coreThreads=" + coreThreads +
", queueLength=" + queueLength +
", keepAlive=" + keepAlive +
'}';
}
public static NonBlockingThreadPoolExecutorFactory create(int maxThreads, int queueSize) {
int coreThreads = queueSize == 0 ? 1 : maxThreads;
return new NonBlockingThreadPoolExecutorFactory(maxThreads, coreThreads, queueSize, DEFAULT_KEEP_ALIVE_MILLIS);
}
}
| 3,008
| 36.148148
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/BlockingThreadFactory.java
|
package org.infinispan.factories.threads;
import org.infinispan.commons.executors.BlockingResource;
public class BlockingThreadFactory extends DefaultThreadFactory implements BlockingResource {
public BlockingThreadFactory(String threadGroupName, int initialPriority, String threadNamePattern,
String node, String component) {
super(new ISPNBlockingThreadGroup(threadGroupName), initialPriority, threadNamePattern, node, component);
}
public BlockingThreadFactory(String name, String threadGroupName, int initialPriority,
String threadNamePattern, String node, String component) {
super(name, new ISPNBlockingThreadGroup(threadGroupName), initialPriority, threadNamePattern, node, component);
}
public static final class ISPNBlockingThreadGroup extends ThreadGroup implements BlockingResource {
public ISPNBlockingThreadGroup(String name) {
super(name);
}
}
}
| 933
| 41.454545
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/NonBlockingThreadFactory.java
|
package org.infinispan.factories.threads;
import org.infinispan.commons.executors.NonBlockingResource;
public class NonBlockingThreadFactory extends DefaultThreadFactory implements NonBlockingResource {
public NonBlockingThreadFactory(String threadGroupName, int initialPriority, String threadNamePattern,
String node, String component) {
super(new ISPNNonBlockingThreadGroup(threadGroupName), initialPriority, threadNamePattern, node, component);
}
public NonBlockingThreadFactory(String name, String threadGroupName, int initialPriority,
String threadNamePattern, String node, String component) {
super(name, new ISPNNonBlockingThreadGroup(threadGroupName), initialPriority, threadNamePattern, node, component);
}
public static final class ISPNNonBlockingThreadGroup extends ThreadGroup implements NonBlockingResource {
public ISPNNonBlockingThreadGroup(String name) {
super(name);
}
}
}
| 1,029
| 45.818182
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/EnhancedQueueExecutorFactory.java
|
package org.infinispan.factories.threads;
import static org.infinispan.commons.logging.Log.CONFIG;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.executors.NonBlockingResource;
import org.infinispan.commons.util.concurrent.BlockingRejectedExecutionHandler;
import org.jboss.threads.EnhancedQueueExecutor;
import org.jboss.threads.management.ManageableThreadPoolExecutorService;
/**
* Executor Factory used for blocking executors which utilizes {@link EnhancedQueueExecutor} internally.
* @author wburns
*/
public class EnhancedQueueExecutorFactory extends AbstractThreadPoolExecutorFactory<ManageableThreadPoolExecutorService> {
protected EnhancedQueueExecutorFactory(int maxThreads, int coreThreads, int queueLength, long keepAlive) {
super(maxThreads, coreThreads, queueLength, keepAlive);
}
public static EnhancedQueueExecutorFactory create(int maxThreads, int queueSize) {
int coreThreads = queueSize == 0 ? 1 : maxThreads;
return new EnhancedQueueExecutorFactory(maxThreads, coreThreads, queueSize,
NonBlockingThreadPoolExecutorFactory.DEFAULT_KEEP_ALIVE_MILLIS);
}
@Override
public ManageableThreadPoolExecutorService createExecutor(ThreadFactory factory) {
if (factory instanceof NonBlockingResource) {
throw new IllegalStateException("Executor factory configured to be blocking and received a thread" +
" factory that creates non-blocking threads!");
}
EnhancedQueueExecutor.Builder builder = new EnhancedQueueExecutor.Builder();
builder.setThreadFactory(factory);
builder.setCorePoolSize(coreThreads);
builder.setMaximumPoolSize(maxThreads);
builder.setGrowthResistance(0.0f);
builder.setMaximumQueueSize(queueLength);
builder.setKeepAliveTime(keepAlive, TimeUnit.MILLISECONDS);
EnhancedQueueExecutor enhancedQueueExecutor = builder.build();
enhancedQueueExecutor.setHandoffExecutor(task ->
BlockingRejectedExecutionHandler.getInstance().rejectedExecution(task, enhancedQueueExecutor));
return enhancedQueueExecutor;
}
@Override
public void validate() {
if (coreThreads < 0)
throw CONFIG.illegalValueThreadPoolParameter("core threads", ">= 0");
if (maxThreads <= 0)
throw CONFIG.illegalValueThreadPoolParameter("max threads", "> 0");
if (maxThreads < coreThreads)
throw CONFIG.illegalValueThreadPoolParameter(
"max threads and core threads", "max threads >= core threads");
if (keepAlive < 0)
throw CONFIG.illegalValueThreadPoolParameter("keep alive time", ">= 0");
if (queueLength < 0)
throw CONFIG.illegalValueThreadPoolParameter("work queue length", ">= 0");
}
}
| 2,809
| 40.940299
| 122
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/ThreadNameInfo.java
|
package org.infinispan.factories.threads;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Galder Zamarreño
*/
public class ThreadNameInfo {
private final long globalThreadSequenceNum;
private final long perFactoryThreadSequenceNum;
private final long factorySequenceNum;
private final String node;
private final String component;
ThreadNameInfo(long globalThreadSequenceNum, long perFactoryThreadSequenceNum,
long factorySequenceNum, String node, String component) {
this.globalThreadSequenceNum = globalThreadSequenceNum;
this.perFactoryThreadSequenceNum = perFactoryThreadSequenceNum;
this.factorySequenceNum = factorySequenceNum;
this.node = node;
this.component = component;
}
private static final Pattern searchPattern = Pattern.compile("([^%]+)|%.");
/**
* Format the thread name string.
* <ul>
* <li>{@code %%} - emit a percent sign</li>
* <li>{@code %t} - emit the per-factory thread sequence number</li>
* <li>{@code %g} - emit the global thread sequence number</li>
* <li>{@code %f} - emit the factory sequence number</li>
* <li>{@code %p} - emit the {@code ":"}-separated thread group path</li>
* <li>{@code %i} - emit the thread ID</li>
* <li>{@code %G} - emit the thread group name</li>
* <li>{@code %n} - emit the node name</li>
* <li>{@code %c} - emit the component name</li>
* </ul>
*
* @param thread the thread
* @param formatString the format string
* @return the thread name string
*/
public String format(Thread thread, String formatString) {
final StringBuilder builder = new StringBuilder(formatString.length() * 5);
final ThreadGroup group = thread.getThreadGroup();
final Matcher matcher = searchPattern.matcher(formatString);
while (matcher.find()) {
if (matcher.group(1) != null) {
builder.append(matcher.group());
} else {
switch (matcher.group().charAt(1)) {
case '%': builder.append('%'); break;
case 't': builder.append(perFactoryThreadSequenceNum); break;
case 'g': builder.append(globalThreadSequenceNum); break;
case 'f': builder.append(factorySequenceNum); break;
case 'p': if (group != null) appendGroupPath(group, builder); break;
case 'i': builder.append(thread.getId()); break;
case 'G': if (group != null) builder.append(group.getName()); break;
case 'n': if (node != null) builder.append(node); break;
case 'c': if (component != null) builder.append(component); break;
}
}
}
return builder.toString();
}
private static void appendGroupPath(ThreadGroup group, StringBuilder builder) {
final ThreadGroup parent = group.getParent();
if (parent != null) {
appendGroupPath(parent, builder);
builder.append(':');
}
builder.append(group.getName());
}
}
| 3,048
| 37.1125
| 83
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/threads/DefaultThreadFactory.java
|
package org.infinispan.factories.threads;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import org.infinispan.commons.jdkspecific.ThreadCreator;
/**
* Thread factory based on JBoss Thread's JBossThreadFactory.
*
* @author Galder Zamarreño
* @since 7.0
*/
public class DefaultThreadFactory implements ThreadFactory {
public static final String DEFAULT_PATTERN = "%c-%n-p%f-t%t";
private final String name;
private final ThreadGroup threadGroup;
private final int initialPriority;
private final String threadNamePattern;
private final AtomicLong factoryThreadIndexSequence = new AtomicLong(1L);
private final long factoryIndex;
private static final AtomicLong globalThreadIndexSequence = new AtomicLong(1L);
private static final AtomicLong factoryIndexSequence = new AtomicLong(1L);
private String node;
private String component;
private ClassLoader classLoader;
/**
* Construct a new instance. The access control context of the calling thread will be the one used to create
* new threads if a security manager is installed.
*
* @param threadGroup the thread group to assign threads to by default (may be {@code null})
* @param initialPriority the initial thread priority, or {@code null} to use the thread group's setting
* @param threadNamePattern the name pattern string
*/
public DefaultThreadFactory(ThreadGroup threadGroup, int initialPriority, String threadNamePattern,
String node, String component) {
this(null, threadGroup, initialPriority, threadNamePattern, node, component);
}
/**
* Construct a new instance. The access control context of the calling thread will be the one used to create
* new threads if a security manager is installed.
*
* @param name the name of this thread factory (may be {@code null})
* @param threadGroup the thread group to assign threads to by default (may be {@code null})
* @param initialPriority the initial thread priority, or {@code null} to use the thread group's setting
* @param threadNamePattern the name pattern string
*/
public DefaultThreadFactory(String name, ThreadGroup threadGroup, int initialPriority, String threadNamePattern,
String node, String component) {
this.classLoader = Thread.currentThread().getContextClassLoader();
this.name = name;
if (threadGroup == null) {
threadGroup = Thread.currentThread().getThreadGroup();
}
this.threadGroup = threadGroup;
this.initialPriority = initialPriority;
factoryIndex = factoryIndexSequence.getAndIncrement();
if (threadNamePattern == null) {
threadNamePattern = DefaultThreadFactory.DEFAULT_PATTERN;
}
this.threadNamePattern = threadNamePattern;
this.node = node;
this.component = component;
}
public String getName() {
return name;
}
public void setNode(String node) {
this.node = node;
}
public void setComponent(String component) {
this.component = component;
}
public String threadNamePattern() {
return threadNamePattern;
}
public ThreadGroup threadGroup() {
return threadGroup;
}
public int initialPriority() {
return initialPriority;
}
@Override
public Thread newThread(final Runnable target) {
return createThread(target);
}
private Thread createThread(final Runnable target) {
final ThreadNameInfo nameInfo = new ThreadNameInfo(globalThreadIndexSequence.getAndIncrement(),
factoryThreadIndexSequence.getAndIncrement(), factoryIndex, node, component);
Thread thread = actualThreadCreate(threadGroup, target);
thread.setName(nameInfo.format(thread, threadNamePattern));
thread.setPriority(initialPriority);
thread.setDaemon(true);
thread.setContextClassLoader(classLoader);
return thread;
}
private final Thread actualThreadCreate(ThreadGroup threadGroup, Runnable target) {
return ThreadCreator.createThread(threadGroup, target, true);
}
}
| 4,108
| 34.119658
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/Scopes.java
|
package org.infinispan.factories.impl;
/**
* Copy of {@link org.infinispan.factories.scopes.Scopes} to avoid a runtime dependency on the annotations module.
*
* @since 10.0
*/
public enum Scopes {
/**
* A single instance of the component is shared by all the caches.
*/
GLOBAL,
/**
* Every cache uses a separate instance of the component.
*/
NAMED_CACHE,
/**
* The component is not cached between requests, but a subclass may be either {@code GLOBAL} or {@code NAMED_CACHE}.
*/
NONE
}
| 534
| 21.291667
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/WireContext.java
|
package org.infinispan.factories.impl;
/**
* Used by {@link ComponentAccessor} implementations for retrieving a component based on name and class.
*
* @author Dan Berindei
* @since 10.0
*/
public class WireContext {
private final BasicComponentRegistryImpl registry;
/**
* Package-private
*/
WireContext(BasicComponentRegistryImpl registry) {
this.registry = registry;
}
public <T> T get(String componentName, Class<T> componentClass, boolean start) {
ComponentRef<T> componentRef = registry.getComponent0(componentName, componentClass, true);
if (componentRef == null) {
return registry.throwDependencyNotFound(componentName);
}
return start ? componentRef.running() : componentRef.wired();
}
public <T, U extends T> ComponentRef<T> getLazy(String componentName, Class<U> componentClass, boolean start) {
ComponentRef<T> componentRef = registry.getComponent0(componentName, componentClass, false);
if (componentRef == null) {
registry.throwDependencyNotFound(componentName);
}
return componentRef;
}
}
| 1,116
| 30.914286
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/ComponentAlias.java
|
package org.infinispan.factories.impl;
public final class ComponentAlias {
private final String componentName;
public static ComponentAlias of(Class<?> componentType) {
return of(componentType.getName());
}
public static ComponentAlias of(String componentName) {
return new ComponentAlias(componentName);
}
private ComponentAlias(String componentName) {
this.componentName = componentName;
}
public String getComponentName() {
return componentName;
}
@Override
public String toString() {
return "ComponentAlias(" + componentName + ')';
}
}
| 613
| 20.928571
| 60
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/ModuleMetadataBuilder.java
|
package org.infinispan.factories.impl;
import java.util.Collection;
import java.util.List;
import org.infinispan.lifecycle.ModuleLifecycle;
/**
* Module metadata. This interface is not intended to be implemented by handwritten code. Implementations are generated
* via annotation processing of InfinispanModule annotation and friends.
*
* @author Dan Berindei
* @since 10.0
*/
public interface ModuleMetadataBuilder {
interface ModuleBuilder {
void registerComponentAccessor(String componentClassName, List<String> factoryComponentNames, ComponentAccessor<?> accessor);
void registerMBeanMetadata(String componentClassName, MBeanMetadata mBeanMetadata);
String getFactoryName(String componentName);
}
String getModuleName();
Collection<String> getRequiredDependencies();
Collection<String> getOptionalDependencies();
ModuleLifecycle newModuleLifecycle();
void registerMetadata(ModuleBuilder builder);
}
| 960
| 25.694444
| 131
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/MBeanMetadata.java
|
package org.infinispan.factories.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedAttribute;
import org.infinispan.jmx.annotations.ManagedOperation;
/**
* JMX related component metadata, as expressed by {@link MBean}, {@link ManagedAttribute} and {@link ManagedOperation}
* annotations.
*
* @author Dan Berindei
* @since 10.0
*/
public final class MBeanMetadata {
private final String jmxObjectName;
private final String description;
private final String superMBeanClassName;
private final Collection<AttributeMetadata> attributes;
private final Collection<OperationMetadata> operations;
public static MBeanMetadata of(String objectName, String description, String superMBeanClassName,
Object... attributesAndOperations) {
List<AttributeMetadata> attributes = new ArrayList<>();
List<OperationMetadata> operations = new ArrayList<>();
for (Object attributeOrOperation : attributesAndOperations) {
if (attributeOrOperation instanceof AttributeMetadata) {
attributes.add((AttributeMetadata) attributeOrOperation);
} else if (attributeOrOperation instanceof OperationMetadata) {
operations.add((OperationMetadata) attributeOrOperation);
} else {
throw new IllegalArgumentException();
}
}
return new MBeanMetadata(objectName, description, superMBeanClassName, attributes, operations);
}
public MBeanMetadata(String jmxObjectName, String description, String superMBeanClassName,
Collection<AttributeMetadata> attributes, Collection<OperationMetadata> operations) {
this.jmxObjectName = jmxObjectName != null ? (jmxObjectName.trim().length() == 0 ? null : jmxObjectName) : jmxObjectName;
this.description = description;
this.superMBeanClassName = superMBeanClassName;
this.attributes = attributes;
this.operations = operations;
}
public String getJmxObjectName() {
return jmxObjectName;
}
public String getDescription() {
return description;
}
public String getSuperMBeanClassName() {
return superMBeanClassName;
}
public Collection<AttributeMetadata> getAttributes() {
return attributes;
}
public Collection<OperationMetadata> getOperations() {
return operations;
}
@Override
public String toString() {
return "MBeanMetadata{" +
"jmxObjectName='" + jmxObjectName + '\'' +
", description='" + description + '\'' +
", super=" + superMBeanClassName +
", attributes=" + attributes +
", operations=" + operations +
'}';
}
public static final class AttributeMetadata {
private final String name;
private final String description;
private final boolean writable;
private final boolean useSetter;
private final String type;
private final boolean is;
private final Function<?, ?> getterFunction; // optional
private final BiConsumer<?, ?> setterFunction; // optional
public AttributeMetadata(String name, String description, boolean writable, boolean useSetter, String type,
boolean is, Function<?, ?> getterFunction, BiConsumer<?, ?> setterFunction) {
this.name = name;
this.description = description;
this.writable = writable;
this.useSetter = useSetter;
this.type = type;
this.is = is;
this.getterFunction = getterFunction;
this.setterFunction = setterFunction;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public boolean isWritable() {
return writable;
}
public boolean isUseSetter() {
return useSetter;
}
public String getType() {
return type;
}
public boolean isIs() {
return is;
}
public Supplier<?> getter(Object instance) {
if (getterFunction == null) {
return null;
}
return () -> ((Function<Object, Object>) getterFunction).apply(instance);
}
public Consumer<?> setter(Object instance) {
if (setterFunction == null) {
return null;
}
return (v) -> ((BiConsumer<Object, Object>) setterFunction).accept(instance, v);
}
@Override
public String toString() {
return "AttributeMetadata{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", writable=" + writable +
", type='" + type + '\'' +
", is=" + is +
", getterFunction=" + getterFunction +
", setterFunction=" + setterFunction +
'}';
}
}
public static final class OperationMetadata {
private final String methodName;
private final String operationName;
private final String description;
private final String returnType;
private final OperationParameterMetadata[] methodParameters;
public OperationMetadata(String methodName, String operationName, String description, String returnType,
OperationParameterMetadata... methodParameters) {
this.methodName = methodName;
this.operationName = operationName.isEmpty() ? methodName : operationName;
this.description = description;
this.returnType = returnType;
this.methodParameters = methodParameters;
}
public String getDescription() {
return description;
}
public String getOperationName() {
return operationName;
}
public String getMethodName() {
return methodName;
}
public OperationParameterMetadata[] getMethodParameters() {
return methodParameters;
}
public String getReturnType() {
return returnType;
}
public String getSignature() {
StringBuilder signature = new StringBuilder();
signature.append(methodName).append('(');
if (methodParameters != null) {
boolean first = true;
for (OperationParameterMetadata param : methodParameters) {
if (first) {
first = false;
} else {
signature.append(',');
}
signature.append(param.getType());
}
}
signature.append(')');
return signature.toString();
}
@Override
public String toString() {
return "OperationMetadata{" +
"methodName='" + methodName + '\'' +
", returnType=" + returnType +
", methodParameters=" + (methodParameters == null ? null : Arrays.toString(methodParameters)) +
", description='" + description + '\'' +
'}';
}
}
public static final class OperationParameterMetadata {
private final String name;
private final String type;
private final String description;
public OperationParameterMetadata(String name, String type, String description) {
this.name = name;
this.type = type;
this.description = description;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "OperationParameter{name='" + name + "', type=" + type + ", description='" + description + "'}";
}
}
}
| 8,055
| 30.346304
| 127
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/BasicComponentRegistryImpl.java
|
package org.infinispan.factories.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.factories.ComponentFactory;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.ModuleRepository;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import net.jcip.annotations.GuardedBy;
/**
* @author Dan Berindei
* @since 8.2
*/
public class BasicComponentRegistryImpl implements BasicComponentRegistry {
private static final Log log = LogFactory.getLog(BasicComponentRegistryImpl.class);
private final ModuleRepository moduleRepository;
private final Scopes scope;
private final BasicComponentRegistry next;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
// The map and can be used without the lock, but changes to the wrapper state need the lock
private final ConcurrentMap<String, ComponentWrapper> components = new ConcurrentHashMap<>();
@GuardedBy("lock")
private final List<String> startedComponents = new ArrayList<>();
private final ConcurrentMap<Thread, ComponentPath> mutatorThreads;
// Needs to lock for updates but not for reads
private volatile ComponentStatus status;
private final WireContext lookup = new WireContext(this);
public BasicComponentRegistryImpl(ModuleRepository moduleRepository,
boolean isGlobal, BasicComponentRegistry next) {
this.moduleRepository = moduleRepository;
this.scope = isGlobal ? Scopes.GLOBAL : Scopes.NAMED_CACHE;
this.next = next;
this.status = ComponentStatus.RUNNING;
this.mutatorThreads = new ConcurrentHashMap<>();
// No way to look up the next scope's BasicComponentRegistry, but that's not a problem
registerComponent(BasicComponentRegistry.class, this, false);
}
@Override
public <T, U extends T> ComponentRef<T> getComponent(String name, Class<U> componentType) {
return getComponent0(name, componentType, true);
}
@Override
public <T> ComponentRef<T> lazyGetComponent(Class<T> componentType) {
return getComponent0(componentType.getName(), componentType, false);
}
@Override
public MBeanMetadata getMBeanMetadata(String className) {
MBeanMetadata metadata = moduleRepository.getMBeanMetadata(className);
if (metadata == null) {
return null;
}
// collect attributes and operations from supers (in reverse order to ensure proper overriding)
Map<String, MBeanMetadata.AttributeMetadata> attributes = new HashMap<>();
Map<String, MBeanMetadata.OperationMetadata> operations = new HashMap<>();
MBeanMetadata currentMetadata = metadata;
for (;;) {
for (MBeanMetadata.AttributeMetadata attribute : currentMetadata.getAttributes()) {
MBeanMetadata.AttributeMetadata existingAttr = attributes.put(attribute.getName(), attribute);
if (existingAttr != null) {
throw new IllegalStateException("Overriding/duplicate JMX attributes are not allowed. Attribute "
+ attribute.getName() + " already exists in a subclass of " + className);
}
}
for (MBeanMetadata.OperationMetadata operation : currentMetadata.getOperations()) {
MBeanMetadata.OperationMetadata existingOp = operations.put(operation.getSignature(), operation);
if (existingOp != null) {
throw new IllegalStateException("Overriding/duplicate JMX operations are not allowed. Operation "
+ operation.getSignature() + " already exists in a subclass of " + className);
}
}
className = currentMetadata.getSuperMBeanClassName();
if (className == null) {
break;
}
currentMetadata = moduleRepository.getMBeanMetadata(className);
if (currentMetadata == null) {
throw new IllegalStateException("Missing MBean metadata for class " + className);
}
}
return new MBeanMetadata(metadata.getJmxObjectName(), metadata.getDescription(), null,
attributes.values(), operations.values());
}
<T, U extends T> ComponentRef<T> getComponent0(String name, Class<U> componentType, boolean needInstance) {
ComponentWrapper wrapper = components.get(name);
if (wrapper != null && (wrapper.isAtLeast(WrapperState.WIRED) || !needInstance)) {
// The wrapper already exists, return it even if the instance was not wired or even created yet
return wrapper;
}
if (wrapper == null) {
// The wrapper doesn't yet exist in the current scope
// Try to find/construct the component in the next scope
if (next != null) {
ComponentRef<T> nextScopeRef = next.getComponent(name, componentType);
if (nextScopeRef != null) {
return nextScopeRef;
}
}
}
ComponentFactory factory = findFactory(name);
if (wrapper == null) {
if (factory == null) {
// Return null without registering a wrapper so the previous scope can have a go
// It's ok to return null if another thread is registering the component concurrently
return null;
}
// Create the wrapper in the current scope
wrapper = registerWrapper(name, true);
}
if (needInstance) {
if (factory != null) {
instantiateWrapper(wrapper, factory);
} else {
// If the wrapper exists but the factory is null, another thread must be registering the component,
// either manually or from tryAutoInstantiation
awaitWrapperState(wrapper, WrapperState.INSTANTIATED);
}
wireWrapper(wrapper);
}
return wrapper;
}
private ComponentWrapper registerWrapper(String name, boolean manageLifecycle) {
ComponentWrapper wrapper = new ComponentWrapper(this, name, manageLifecycle);
lock.lock();
try {
if (status != ComponentStatus.RUNNING) {
throw new IllegalLifecycleStateException("Cannot register components while the registry is not running");
}
ComponentWrapper existing = components.putIfAbsent(wrapper.name, wrapper);
return existing != null ? existing : wrapper;
} finally {
lock.unlock();
}
}
private void instantiateWrapper(ComponentWrapper wrapper, ComponentFactory factory) {
String name = wrapper.name;
if (!prepareWrapperChange(wrapper, WrapperState.EMPTY, WrapperState.INSTANTIATING)) {
// Someone else has started instantiating and wiring the component, wait for them to finish
awaitWrapperState(wrapper, WrapperState.INSTANTIATED);
return;
}
try {
// Also changes the status when successful
doInstantiateWrapper(wrapper, factory, name);
} catch (Throwable t) {
commitWrapperStateChange(wrapper, WrapperState.INSTANTIATING, WrapperState.FAILED);
throw t;
}
}
private void doInstantiateWrapper(ComponentWrapper wrapper, ComponentFactory factory, String name) {
Object instance;
try {
instance = factory.construct(name);
} catch (Throwable t) {
throw new RuntimeException(
"Failed to construct component " + name + ", path " + peekMutatorPath(), t);
}
if (instance instanceof ComponentAlias) {
// Create the target component and point this wrapper to it
ComponentAlias alias = (ComponentAlias) instance;
commitWrapperAliasChange(wrapper, alias, null, WrapperState.INSTANTIATING, WrapperState.INSTANTIATED);
} else {
ComponentAccessor<Object> accessor = getMetadataForComponent(instance);
commitWrapperInstanceChange(wrapper, instance, accessor, WrapperState.INSTANTIATING,
WrapperState.INSTANTIATED);
}
}
private void wireWrapper(ComponentWrapper wrapper) {
if (!prepareWrapperChange(wrapper, WrapperState.INSTANTIATED, WrapperState.WIRING)) {
// Someone else has started wiring the component, wait for them to finish
awaitWrapperState(wrapper, WrapperState.WIRED);
return;
}
try {
// Also changes the status when successful
doWireWrapper(wrapper);
} catch (Throwable t) {
commitWrapperStateChange(wrapper, WrapperState.WIRING, WrapperState.FAILED);
throw t;
}
}
private void doWireWrapper(ComponentWrapper wrapper) {
if (wrapper.instance instanceof ComponentAlias) {
ComponentAlias alias = (ComponentAlias) wrapper.instance;
String aliasTargetName = alias.getComponentName();
ComponentRef<Object> targetRef = getComponent(aliasTargetName, Object.class);
if (targetRef == null) {
throw new RuntimeException(
"Alias " + wrapper.name + " target component is missing: " + aliasTargetName);
}
targetRef.wired();
commitWrapperAliasChange(wrapper, alias, targetRef, WrapperState.WIRING, WrapperState.WIRED);
} else {
invokeInjection(wrapper.instance, wrapper.accessor, false);
WrapperState wiredState = wrapper.accessor != null ? WrapperState.WIRED : WrapperState.STARTED;
commitWrapperStateChange(wrapper, WrapperState.WIRING, wiredState);
}
}
@Override
public void wireDependencies(Object target, boolean startDependencies) {
String componentClassName = target.getClass().getName();
pushMutatorPath("wireDependencies", componentClassName);
try {
ComponentAccessor<Object> accessor = moduleRepository.getComponentAccessor(componentClassName);
invokeInjection(target, accessor, startDependencies);
} finally {
popMutatorPath();
}
}
private ComponentFactory findFactory(String name) {
String factoryName = moduleRepository.getFactoryName(name);
if (factoryName == null) {
// No designated factory, try auto instantiation as a last resort
return tryAutoInstantiation(name);
}
ComponentRef<ComponentFactory> factoryRef = getComponent(factoryName, ComponentFactory.class);
if (factoryRef != null) {
// Start the factory (and it's dependencies!) because some factories
// are responsible for stopping the components they create (e.g. NamedExecutorsFactory)
return factoryRef.running();
} else {
// The factory does not exist in this scope
return null;
}
}
private void commitWrapperStateChange(ComponentWrapper wrapper, WrapperState expectedState, WrapperState newState) {
commitWrapperChange(wrapper, wrapper.instance, wrapper.accessor, wrapper.aliasTarget, expectedState, newState);
}
private void commitWrapperInstanceChange(ComponentWrapper wrapper, Object instance,
ComponentAccessor<Object> accessor,
WrapperState expectedState, WrapperState newState) {
commitWrapperChange(wrapper, instance, accessor, null, expectedState, newState);
}
private void commitWrapperAliasChange(ComponentWrapper wrapper, ComponentAlias alias, ComponentRef<?> targetRef,
WrapperState expectedState, WrapperState newState) {
commitWrapperChange(wrapper, alias, null, targetRef, expectedState, newState);
}
private void commitWrapperChange(ComponentWrapper wrapper, Object instance, ComponentAccessor<Object> accessor,
ComponentRef<?> aliasTargetRef,
WrapperState expectedState, WrapperState newState) {
lock.lock();
try {
if (wrapper.state != expectedState) {
throw new IllegalLifecycleStateException(
"Component " + wrapper.name + " has wrong status: " + wrapper.state + ", expected: " + expectedState);
}
wrapper.instance = instance;
wrapper.accessor = accessor;
wrapper.aliasTarget = aliasTargetRef;
wrapper.state = newState;
popMutatorPath();
if (log.isTraceEnabled())
log.tracef("Changed status of " + wrapper.name + " to " + wrapper.state);
condition.signalAll();
} finally {
lock.unlock();
}
}
/**
* Factories that implement {@link org.infinispan.factories.AutoInstantiableFactory} can be instantiated
* without an additional factory.
*/
private ComponentFactory tryAutoInstantiation(String factoryName) {
ComponentAccessor<Object> accessor = moduleRepository.getComponentAccessor(factoryName);
if (accessor == null) {
return null;
}
if (accessor.getScopeOrdinal() != null && !accessor.getScopeOrdinal().equals(scope.ordinal())) {
// The accessor exists, but it has a different scope (null means any scope)
// Returning null allows the factory to be auto-instantiated in the proper scope
return null;
}
Object autoInstance = accessor.newInstance();
if (autoInstance == null) {
// Not auto-instantiable
return null;
}
return new ConstComponentFactory(autoInstance);
}
private void invokeInjection(Object target, ComponentAccessor<Object> accessor, boolean startDependencies) {
try {
if (accessor == null)
return;
accessor.wire(target, lookup, startDependencies);
String superComponentClassName = accessor.getSuperAccessorName();
if (superComponentClassName != null) {
ComponentAccessor<Object> superAccessor = moduleRepository.getComponentAccessor(superComponentClassName);
if (superAccessor == null) {
throw new RuntimeException("Component metadata not found for super class " +
superComponentClassName);
}
invokeInjection(target, superAccessor, startDependencies);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(
"Unable to inject dependencies for component class " + target.getClass().getName() + ", path " +
peekMutatorPath(), e);
}
}
<T> T throwDependencyNotFound(String componentName) {
throw new RuntimeException(
"Unable to construct dependency " + componentName + " in scope " + scope + " for " +
peekMutatorPath());
}
@Override
public <T> ComponentRef<T> registerComponent(String componentName, T instance, boolean manageLifecycle) {
ComponentAccessor<Object> accessor = getMetadataForComponent(instance);
// Try to register the wrapper, but it may have been created as a lazy dependency of another component already
ComponentWrapper wrapper = registerWrapper(componentName, manageLifecycle);
if (!prepareWrapperChange(wrapper, WrapperState.EMPTY, WrapperState.INSTANTIATING)) {
throw new RuntimeException("Component " + componentName + " is already registered");
}
commitWrapperInstanceChange(wrapper, instance, accessor, WrapperState.INSTANTIATING, WrapperState.INSTANTIATED);
wireWrapper(wrapper);
return wrapper;
}
private ComponentAccessor<Object> validateAccessor(ComponentAccessor<Object> accessor, Class<?> componentClass) {
// A missing scope declaration is interpreted as any scope
String className = componentClass.getName();
if (accessor != null && !accessor.getScopeOrdinal().equals(Scopes.NONE.ordinal()) &&
!accessor.getScopeOrdinal().equals(scope.ordinal())) {
throw new RuntimeException(
"Wrong registration scope " + scope + " for component class " + className);
}
// Special case for classes generated by Mockito
if (accessor == null && className.contains("$MockitoMock$")) {
Class<?> mockedClass = componentClass.getSuperclass();
return validateAccessor(moduleRepository.getComponentAccessor(mockedClass.getName()), mockedClass);
}
// TODO It would be nice to log an exception if the component is annotated yet doesn't have an accessor
// but that would require a runtime dependency on the component-annotations module.
return accessor;
}
private ComponentAccessor<Object> getMetadataForComponent(Object component) {
if (component == null)
return null;
Class<?> componentClass = component.getClass();
ComponentAccessor<Object> accessor = moduleRepository.getComponentAccessor(componentClass.getName());
return validateAccessor(accessor, componentClass);
}
@Override
public void registerAlias(String aliasName, String targetComponentName, Class<?> targetComponentType) {
ComponentWrapper wrapper = registerWrapper(aliasName, false);
if (!prepareWrapperChange(wrapper, WrapperState.EMPTY, WrapperState.INSTANTIATING)) {
throw new IllegalStateException("Cannot register alias " + aliasName + " with target " + targetComponentName +
" as the name is already registered");
}
commitWrapperAliasChange(wrapper, ComponentAlias.of(targetComponentName), null, WrapperState.INSTANTIATING,
WrapperState.INSTANTIATED);
}
@Override
public void addDynamicDependency(String ownerComponentName, String dependencyComponentName) {
ComponentRef<Object> ref = getComponent0(ownerComponentName, Object.class, false);
if (ref instanceof ComponentWrapper) {
ComponentWrapper wrapper = (ComponentWrapper) ref;
lock.lock();
try {
wrapper.addDynamicDependency(dependencyComponentName);
} finally {
lock.unlock();
}
}
}
@Override
public void replaceComponent(String componentName, Object newInstance, boolean manageLifecycle) {
lock.lock();
ComponentWrapper newWrapper = null;
try {
ComponentAccessor<Object> accessor = getMetadataForComponent(newInstance);
invokeInjection(newInstance, accessor, false);
newWrapper = new ComponentWrapper(this, componentName, manageLifecycle);
ComponentWrapper oldWrapper = components.put(componentName, newWrapper);
prepareWrapperChange(newWrapper, WrapperState.EMPTY, WrapperState.INSTANTIATING);
// If the component was already started, start the replacement as well
// but avoid logStartedComponent in order to preserve the stop order
boolean wantStarted = oldWrapper != null && oldWrapper.isRunning();
boolean canRunStart = manageLifecycle && accessor != null;
if (wantStarted && canRunStart) {
invokeStart(newInstance, accessor);
}
WrapperState state = (wantStarted || !canRunStart) ? WrapperState.STARTED : WrapperState.WIRED;
commitWrapperInstanceChange(newWrapper, newInstance, accessor, WrapperState.INSTANTIATING, state);
} catch (Throwable t) {
if (newWrapper != null) {
commitWrapperStateChange(newWrapper, WrapperState.INSTANTIATING, WrapperState.FAILED);
}
throw new RuntimeException("Unable to start replacement component " + newInstance, t);
} finally {
lock.unlock();
}
}
@Override
public void rewire() {
// Rewire is not supposed to be used in production, so we can keep the registry locked for the entire duration
lock.lock();
try {
if (status == ComponentStatus.TERMINATED) {
status = ComponentStatus.RUNNING;
}
for (ComponentWrapper wrapper : components.values()) {
if (wrapper.isAlias()) {
// Duplicates the code in doWireWrapper(), but without the state change
ComponentAlias alias = (ComponentAlias) wrapper.instance;
String aliasTargetName = alias.getComponentName();
ComponentRef<Object> targetRef = getComponent(aliasTargetName, Object.class);
if (targetRef == null) {
throw new RuntimeException(
"Alias " + wrapper.name + " target component is missing: " + aliasTargetName);
}
targetRef.wired();
wrapper.aliasTarget = targetRef;
} else {
invokeInjection(wrapper.instance, wrapper.accessor, false);
}
}
} finally {
lock.unlock();
}
}
@Override
public Collection<ComponentRef<?>> getRegisteredComponents() {
lock.lock();
try {
List<ComponentRef<?>> list = new ArrayList<>(components.size());
for (ComponentWrapper wrapper : components.values()) {
list.add(wrapper);
}
return list;
} finally {
lock.unlock();
}
}
@Override
public void stop() {
ArrayList<String> componentsToStop;
lock.lock();
try {
if (status != ComponentStatus.RUNNING) {
throw new IllegalStateException(
"Stopping is only allowed in the RUNNING state, current state is " + status + "!");
}
componentsToStop = new ArrayList<>(startedComponents);
status = ComponentStatus.STOPPING;
condition.signalAll();
} finally {
lock.unlock();
}
for (int i = componentsToStop.size() - 1; i >= 0; i--) {
ComponentWrapper wrapper = components.get(componentsToStop.get(i));
if (wrapper != null) {
stopWrapper(wrapper);
}
}
lock.lock();
try {
startedComponents.clear();
removeVolatileComponents();
status = ComponentStatus.TERMINATED;
condition.signalAll();
} finally {
lock.unlock();
}
}
@Override
public boolean hasComponentAccessor(String componentClassName) {
return moduleRepository.getComponentAccessor(componentClassName) != null;
}
@GuardedBy("lock")
private void removeVolatileComponents() {
for (Iterator<ComponentWrapper> it = components.values().iterator(); it.hasNext(); ) {
ComponentWrapper wrapper = it.next();
boolean survivesRestarts = wrapper.accessor != null && wrapper.accessor.getSurvivesRestarts();
if (wrapper.manageLifecycle && !survivesRestarts) {
if (log.isTraceEnabled())
log.tracef("Removing component %s in state %s", wrapper.name, wrapper.state);
it.remove();
} else {
if (wrapper.manageLifecycle && wrapper.state == WrapperState.STOPPED) {
wrapper.state = WrapperState.INSTANTIATED;
}
if (log.isTraceEnabled())
log.tracef("Keeping component %s in state %s", wrapper.name, wrapper.state);
}
}
}
private void startWrapper(ComponentWrapper wrapper) {
if (!prepareWrapperChange(wrapper, WrapperState.WIRED, WrapperState.STARTING)) {
// Someone else is starting the wrapper, wait for it to finish
awaitWrapperState(wrapper, WrapperState.STARTED);
return;
}
try {
doStartWrapper(wrapper);
commitWrapperStateChange(wrapper, WrapperState.STARTING, WrapperState.STARTED);
} catch (CacheException e) {
commitWrapperStateChange(wrapper, WrapperState.STARTING, WrapperState.FAILED);
throw e;
} catch (Throwable t) {
commitWrapperStateChange(wrapper, WrapperState.STARTING, WrapperState.FAILED);
throw Log.CONFIG.componentFailedToStart(wrapper.toString(), t);
}
}
private void doStartWrapper(ComponentWrapper wrapper) throws Exception {
if (wrapper.aliasTarget != null) {
wrapper.aliasTarget.running();
return;
}
if (wrapper.accessor == null) {
throw new IllegalStateException("Components without metadata should go directly to RUNNING state");
}
startDependencies(wrapper);
if (!wrapper.manageLifecycle) {
return;
}
// Try to stop the component even if it failed, otherwise each component would have to catch exceptions
logStartedComponent(wrapper);
invokeStart(wrapper.instance, wrapper.accessor);
}
private void invokeStart(Object instance, ComponentAccessor<Object> accessor) throws Exception {
// Invoke super first
if (accessor.getSuperAccessorName() != null) {
invokeStart(instance, moduleRepository.getComponentAccessor(accessor.getSuperAccessorName()));
}
accessor.start(instance);
}
private void logStartedComponent(ComponentWrapper wrapper) {
lock.lock();
try {
startedComponents.add(wrapper.getName());
} finally {
lock.unlock();
}
}
private void startDependencies(ComponentWrapper wrapper) {
ComponentAccessor<Object> accessor = wrapper.accessor;
while (true) {
for (String dependencyName : accessor.getEagerDependencies()) {
ComponentRef<Object> dependency = getComponent(dependencyName, Object.class);
if (dependency != null) {
dependency.running();
}
}
if (accessor.getSuperAccessorName() == null)
break;
accessor = moduleRepository.getComponentAccessor(accessor.getSuperAccessorName());
}
ComponentPath remainingDependencies = wrapper.dynamicDependencies;
while (remainingDependencies != null) {
String componentName = remainingDependencies.name;
ComponentRef<Object> dependency = getComponent(componentName, Object.class);
if (dependency != null) {
dependency.running();
}
remainingDependencies = remainingDependencies.next;
}
}
private void stopWrapper(ComponentWrapper wrapper) {
if (!prepareWrapperChange(wrapper, WrapperState.STARTED, WrapperState.STOPPING)
&& !prepareWrapperChange(wrapper, WrapperState.FAILED, WrapperState.STOPPING))
return;
try {
doStopWrapper(wrapper);
} catch (Throwable t) {
log.errorf(t, "Error stopping component %s", wrapper.name);
} finally {
commitWrapperStateChange(wrapper, WrapperState.STOPPING, WrapperState.STOPPED);
}
}
private void doStopWrapper(ComponentWrapper wrapper) throws Exception {
if (!wrapper.manageLifecycle || wrapper.accessor == null)
return;
invokeStop(wrapper.instance, wrapper.accessor);
}
private void invokeStop(Object instance, ComponentAccessor<Object> accessor) throws Exception {
accessor.stop(instance);
// Invoke super last
String superComponentClassName = accessor.getSuperAccessorName();
if (superComponentClassName != null) {
invokeStop(instance, moduleRepository.getComponentAccessor(superComponentClassName));
}
}
private boolean prepareWrapperChange(ComponentWrapper wrapper, WrapperState expectedState, WrapperState newState) {
lock.lock();
try {
if (status != ComponentStatus.RUNNING && newState.isBefore(WrapperState.STOPPING)) {
throw new IllegalLifecycleStateException(
"Cannot wire or start components while the registry is not running");
}
if (wrapper.state != expectedState) {
return false;
}
wrapper.state = newState;
String componentClassName = wrapper.instance != null ? wrapper.instance.getClass().getName() : null;
String name = pushMutatorPath(wrapper.name, componentClassName);
if (log.isTraceEnabled())
log.tracef("Changed status of " + name + " to " + wrapper.state);
return true;
} finally {
lock.unlock();
}
}
private void awaitWrapperState(ComponentWrapper wrapper, WrapperState expectedState) {
lock.lock();
try {
String name = wrapper.name;
if (wrapper.state == WrapperState.EMPTY) {
throw new RuntimeException(
"Component " + name + " is missing a strong (non-ComponentRef) reference: waiting to become " +
expectedState + " but it has not been instantiated yet");
}
if (wrapper.state.isBefore(expectedState)) {
ComponentPath currentComponentPath = peekMutatorPath();
if (currentComponentPath != null && currentComponentPath.contains(name)) {
String className = wrapper.instance != null ? wrapper.instance.getClass().getName() : null;
throw new RuntimeException(
"Dependency cycle detected, please use ComponentRef<T> to break the cycle in path " +
new ComponentPath(name, className, peekMutatorPath()));
}
}
while (status == ComponentStatus.RUNNING && wrapper.isBefore(expectedState)) {
try {
condition.await();
} catch (InterruptedException e) {
throw new IllegalLifecycleStateException(
"Interrupted while waiting for component " + name + " to start");
}
}
wrapper.expectState(expectedState, WrapperState.STOPPING);
} finally {
lock.unlock();
}
}
private String pushMutatorPath(String name, String className) {
ComponentPath currentPath = mutatorThreads.get(Thread.currentThread());
mutatorThreads.put(Thread.currentThread(), new ComponentPath(name, className, currentPath));
return name;
}
private void popMutatorPath() {
ComponentPath currentPath = mutatorThreads.get(Thread.currentThread());
if (currentPath.next != null) {
mutatorThreads.put(Thread.currentThread(), currentPath.next);
} else {
mutatorThreads.remove(Thread.currentThread());
}
}
private ComponentPath peekMutatorPath() {
return mutatorThreads.get(Thread.currentThread());
}
@Override
public String toString() {
return "BasicComponentRegistryImpl{scope=" + scope + ", size=" + components.size() + "}";
}
enum WrapperState {
// Most components go through all the states.
// Aliases and components without metadata (i.e. no dependencies and no start methods)
// skip the WIRED and STARTING states.
EMPTY, INSTANTIATING, INSTANTIATED, WIRING, WIRED, STARTING, STARTED, STOPPING, STOPPED, FAILED;
boolean isAtLeast(WrapperState other) {
return this.ordinal() >= other.ordinal();
}
boolean isBefore(WrapperState other) {
return this.ordinal() < other.ordinal();
}
}
static class ComponentWrapper implements ComponentRef {
private final BasicComponentRegistryImpl registry;
private final String name;
private final boolean manageLifecycle;
// These can be changed only from null to non-null, and can be safely read without locking
// Always valid
private volatile WrapperState state;
private volatile ComponentPath dynamicDependencies;
// Valid from INSTANTIATED state
private volatile Object instance;
private volatile ComponentAccessor<Object> accessor;
private volatile ComponentRef<?> aliasTarget;
ComponentWrapper(BasicComponentRegistryImpl registry, String name, boolean manageLifecycle) {
this.registry = registry;
this.name = name;
this.manageLifecycle = manageLifecycle;
this.state = WrapperState.EMPTY;
}
@Override
public Object running() {
if (!isRunning()) {
wire();
registry.startWrapper(this);
expectState(WrapperState.STARTED, WrapperState.STOPPING);
}
return aliasTarget != null ? aliasTarget.running() : instance;
}
@Override
public Object wired() {
if (!isWired()) {
wire();
}
return aliasTarget != null ? aliasTarget.wired() : instance;
}
public void wire() {
if (!isAtLeast(WrapperState.INSTANTIATED)) {
ComponentFactory factory = registry.findFactory(name);
registry.instantiateWrapper(this, factory);
}
registry.wireWrapper(this);
}
@Override
public boolean isRunning() {
return state == WrapperState.STARTED;
}
@Override
public boolean isWired() {
return isAtLeast(WrapperState.WIRED) && isBefore(WrapperState.STOPPING);
}
@Override
public boolean isAlias() {
return instance instanceof ComponentAlias;
}
@Override
public String getName() {
return name;
}
void expectState(WrapperState firstAllowedState, WrapperState firstDisallowedState) {
WrapperState localState = this.state;
if (localState.isBefore(firstAllowedState)) {
throw new IllegalLifecycleStateException("Component " + name + " is not yet " + firstAllowedState);
}
if (localState.isAtLeast(firstDisallowedState)) {
throw new IllegalLifecycleStateException("Component " + name + " is already " + localState);
}
}
boolean isAtLeast(WrapperState expectedState) {
return state.isAtLeast(expectedState);
}
boolean isBefore(WrapperState expectedState) {
return state.isBefore(expectedState);
}
@GuardedBy("BasicComponentRegistryImpl.lock")
void addDynamicDependency(String subComponentName) {
dynamicDependencies = new ComponentPath(subComponentName, null, dynamicDependencies);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ComponentWrapper{")
.append("name=")
.append(name);
if (aliasTarget != null) {
sb.append(", aliasTarget=").append(aliasTarget);
} else {
sb.append(", instance=").append(instance);
}
sb.append(", status=").append(state);
sb.append('}');
return sb.toString();
}
}
static class ComponentPath {
final String name;
final String className;
final ComponentPath next;
ComponentPath(String name, String className, ComponentPath next) {
this.name = name;
this.className = className;
this.next = next;
}
public boolean contains(String name) {
ComponentPath path = this;
while (path != null) {
if (path.name.equals(name)) {
return true;
}
path = path.next;
}
return false;
}
public String toString() {
StringBuilder sb = new StringBuilder();
boolean firstIteration = true;
ComponentPath path = this;
while (path != null) {
if (firstIteration) {
firstIteration = false;
} else {
sb.append("\n << ");
}
sb.append(path.name);
if (path.className != null) {
sb.append(" (a ").append(path.className).append(")");
}
path = path.next;
}
return sb.toString();
}
}
private static class ConstComponentFactory implements ComponentFactory {
private final Object autoInstance;
public ConstComponentFactory(Object autoInstance) {
this.autoInstance = autoInstance;
}
@Override
public Object construct(String componentName) {
return autoInstance;
}
}
}
| 36,376
| 37.412883
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/BasicComponentRegistry.java
|
package org.infinispan.factories.impl;
import java.util.Collection;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.util.Experimental;
import org.infinispan.factories.annotations.Inject;
/**
* Basic dependency injection container.
*
* <p>Components are identified by a component name {@code String}, which is usually the fully-qualified name
* of a class or interface.
* Components may have aliases, e.g. the cache is visible both as {@code org.infinispan.Cache} and as
* {@code org.infinispan.AdvancedCache}. </p>
*
* <p>Components can either be registered explicitly with {@link #registerComponent(String, Object, boolean)},
* or constructed by a factory and registered implicitly when another component depends on them.</p>
*
* <p>During registration (either explicit or implicit), fields and and methods annotated with {@link Inject}
* are injected with other components.
* The name of the dependency is usually the fully-qualified name of the field or parameter type,
* but it can be overridden with the {@link org.infinispan.factories.annotations.ComponentName} annotation.</p>
*
* <p>A factory is a component implementing {@link org.infinispan.factories.ComponentFactory} and annotated with
* {@link org.infinispan.factories.annotations.DefaultFactoryFor}.
* A factory must have the same scope as the components it creates.
* A factory implementing {@link org.infinispan.factories.AutoInstantiableFactory} does not have to be registered
* explicitly, the registry will be create and register it on demand.</p>
*
* <p> Each registry has a scope, and {@link org.infinispan.factories.scopes.Scopes#NAMED_CACHE}-scoped registries
* delegate to a {@link org.infinispan.factories.scopes.Scopes#GLOBAL} registry.
* {@link #registerComponent(String, Object, boolean)} will throw a
* {@linkplain org.infinispan.commons.CacheConfigurationException} if the component has a
* {@link org.infinispan.factories.scopes.Scope} annotation withe a different scope.
* Implicitly created dependencies are automatically registered in the right scope based on their
* {@link org.infinispan.factories.scopes.Scope} annotation.</p>
*
* <p>Dependency cycles are not allowed. Declaring the dependency field of type {@link ComponentRef},
* breaks the cycle by allowing the registry to inject/start the dependency lazily.</p>
*
* <p>Components are not started by default.
* Methods annotated with {@link org.infinispan.factories.annotations.Start} are invoked only on
* {@link ComponentRef#running()}.</p>
*
* <p>During shutdown, registration of new components is not allowed.
* The registry stops all the components in the reverse order of their start, by invoking all the methods annotated
* with {@link org.infinispan.factories.annotations.Stop}.</p>
*
* @author Dan Berindei
* @since 9.4
*/
public interface BasicComponentRegistry {
/**
* Looks up a running component named {@code name} in the registry, or registers it if necessary.
*
* <p>If another thread is registering the component, wait for the other thread to finish.</p>
*
* <p>The component is wired (dependencies are injected) during registration.
* Use {@link ComponentRef#running()} to start the component.</p>
*
* @param name The component name.
* @param componentType The expected component type, not used to identify the component.
*/
<T, U extends T> ComponentRef<T> getComponent(String name, Class<U> componentType);
/**
* Looks up a running component named {@code name} in the registry, or registers it if necessary.
*
* @implSpec Equivalent to {@code getComponent(componentType.getName(), componentType)}.
*/
default <T> ComponentRef<T> getComponent(Class<T> componentType) {
return getComponent(componentType.getName(), componentType);
}
/**
* Register a component named {@code componentName}.
*
* <p>If the component has dependencies, look them up using {@link #getComponent(String, Class)}
* and inject them.</p>
*
* @param componentName The component name.
* @param instance The component instance.
* @param manageLifecycle {@code false} if the registry should ignore methods annotated with
* {@linkplain org.infinispan.factories.annotations.Start} and {@linkplain org.infinispan.factories.annotations.Stop}
*
* @throws IllegalLifecycleStateException If the registry is stopping/stopped
* @throws org.infinispan.commons.CacheConfigurationException If a component/alias is already registered with that
* name, or if a dependency cannot be resolved
*/
<T> ComponentRef<T> registerComponent(String componentName, T instance, boolean manageLifecycle);
/**
* Register a component named {@code componentType.getName()}.
*
* @implSpec Equivalent to {@code registerComponent(componentType.getName(), instance, manageLifecycle)}
*/
default <T> ComponentRef<T> registerComponent(Class<?> componentType, T instance, boolean manageLifecycle) {
return registerComponent(componentType.getName(), instance, manageLifecycle);
}
/**
* Register an alias to another component.
*
* <p>Components that depend on the alias will behave as if they depended on the original component directly.</p>
*
* @throws IllegalLifecycleStateException If the registry is stopping/stopped
* @throws org.infinispan.commons.CacheConfigurationException If a component/alias is already registered with that
* name
*/
void registerAlias(String aliasName, String targetComponentName, Class<?> targetComponentType);
/**
* Look up the dependencies of {@code target} as if it were a component, and inject them.
*
* <p>Behaves as if every dependency was resolved with {@code getComponent(String, Class)}.</p>
*
* @param target An instance of a class with {@link Inject} annotations.
* @param startDependencies If {@code true}, start the dependencies before injecting them.
*
* @throws IllegalLifecycleStateException If the registry is stopping/stopped
* @throws org.infinispan.commons.CacheConfigurationException If a dependency cannot be resolved
*/
void wireDependencies(Object target, boolean startDependencies);
/**
* Add a dynamic dependency between two components.
*
* @param ownerComponentName The dependent component's name.
* @param dependencyComponentName The component depended on.
*
* <p>Note: doesn't have any effect if the owner component is already started.
* The stop order is determined exclusively by the start order.</p>
*/
void addDynamicDependency(String ownerComponentName, String dependencyComponentName);
/**
* Replace an existing component.
*
* For testing purposes only, NOT THREAD-SAFE.
*
* <p>Dependencies will be injected, and the start/stop methods will run if {@code manageLifecycle} is {@code true}.
* The new component is stopped exactly when the replaced component would have been stopped,
* IGNORING DEPENDENCY CHANGES.
* Need to call {@link #rewire()} to inject the new component in all the components that depend on it.
* If the component is global, need to call {@link #rewire()} on all the cache component registries as well.</p>
*
* @throws IllegalLifecycleStateException If the registry is stopping/stopped
*/
@Experimental
void replaceComponent(String componentName, Object newInstance, boolean manageLifecycle);
/**
* Rewire all the injections after a component was replaced with {@link #replaceComponent(String, Object, boolean)}.
*
* For testing purposes only.
*/
@Experimental
void rewire();
/**
* Run {@code consumer} for each registered component in the current scope.
*/
@Experimental
Collection<ComponentRef<?>> getRegisteredComponents();
/**
* @return The MBean metadata for class {@code className}
*/
@Experimental
MBeanMetadata getMBeanMetadata(String className);
/**
* Check if a component accessor has been registered for class {@code componentClassName}
*/
@Experimental
boolean hasComponentAccessor(String componentClassName);
/**
* Stop the registry and all the components that have been started.
*
* <p>Components cannot be instantiated or started after this.</p>
*/
void stop();
/**
* Looks up a component named {@code name} in the registry, or registers it if necessary.
*
* The component isn't instantiated neither running. Invoke {@link ComponentRef#running()} to instantiate and start it.
*
* @param componentType The expected component type, not used to identify the component.
*/
@Experimental
<T> ComponentRef<T> lazyGetComponent(Class<T> componentType);
}
| 8,833
| 44.071429
| 122
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/ComponentRef.java
|
package org.infinispan.factories.impl;
import org.infinispan.commons.IllegalLifecycleStateException;
/**
* Reference to a component.
*
* TODO Dan: Investigate locking the component so that dependencies cannot stop while used through a weak dependency.
* Not sure how useful it would be, since most references to components are in classes that are not registered
* components themselves.
*
* @author Dan Berindei
* @since 9.4
*/
public interface ComponentRef<T> {
/**
* @return the running component instance
* @throws IllegalLifecycleStateException if the component is not running
*/
T running();
/**
* @return the wired component instance, which may or may not be running.
*/
T wired();
/**
* @return {@code true} if all of the component's start methods have run and none of its stop methods started running
*/
boolean isRunning();
boolean isWired();
boolean isAlias();
String getName();
}
| 963
| 23.717949
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/ComponentAccessor.java
|
package org.infinispan.factories.impl;
import java.util.List;
/**
* Component lifecycle management
*
* @since 10.0
* @author Dan Berindei
*/
public class ComponentAccessor<T> {
private final String className;
// Some modules will not have access to the Scopes enum at runtime
private final Integer scopeOrdinal;
private final boolean survivesRestarts;
private final String superAccessorName;
private final List<String> eagerDependencies;
public ComponentAccessor(String className, Integer scopeOrdinal, boolean survivesRestarts,
String superAccessorName, List<String> eagerDependencies) {
this.className = className;
this.scopeOrdinal = scopeOrdinal;
this.survivesRestarts = survivesRestarts;
this.superAccessorName = superAccessorName;
this.eagerDependencies = eagerDependencies;
}
final Integer getScopeOrdinal() {
return scopeOrdinal;
}
final boolean getSurvivesRestarts() {
return survivesRestarts;
}
/**
* Return name of the first class with component annotations going up in the inheritance hierarchy.
*/
final String getSuperAccessorName() {
return superAccessorName;
}
final List<String> getEagerDependencies() {
return eagerDependencies;
}
protected T newInstance() {
return null;
}
protected void wire(T instance, WireContext context, boolean start) {
// Do nothing
}
protected void start(T instance) throws Exception {
// Do nothing
}
protected void stop(T instance) throws Exception {
// Do nothing
}
@Override
public String toString() {
return "ComponentAccessor(" + className + ")";
}
/**
* Temporary, for ComponentRegistry.getLocalComponent
*/
public boolean isGlobalScope() {
return scopeOrdinal == Scopes.GLOBAL.ordinal();
}
}
| 1,889
| 24.2
| 102
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/factories/impl/DynamicModuleMetadataProvider.java
|
package org.infinispan.factories.impl;
import org.infinispan.configuration.global.GlobalConfiguration;
/**
* Modules implementing {@link org.infinispan.lifecycle.ModuleLifecycle} might need additional control over the created
* components. They can hook into the module metadata building process during startup by implementing this interface
* which allows them to register additional component metadata dynamically.
* <p>
* This interface is currently experimental, it does not constitute a public API and is only used for internal testing
* purposes.
*
* @author anistor@redhat.com
* @since 10.0
*/
public interface DynamicModuleMetadataProvider {
/**
* Use the provided builder to add additional component metadata. Use the GlobalConfiguration to access configuration,
* global or per-module (see GlobalConfiguration.module)
*
* @param moduleBuilder
* @param globalConfiguration
*/
void registerDynamicMetadata(ModuleMetadataBuilder.ModuleBuilder moduleBuilder, GlobalConfiguration globalConfiguration);
}
| 1,052
| 38
| 124
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/package-info.java
|
/**
* Contexts contain information of a specific invocation on the cache, such as its origins, scope
* (transactional or non-transactional), as well as invocation-specific flags.
*
* @api.public
*/
package org.infinispan.context;
| 235
| 28.5
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/InvocationContextFactory.java
|
package org.infinispan.context;
import jakarta.transaction.Transaction;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.context.impl.ClearInvocationContext;
import org.infinispan.context.impl.LocalTxInvocationContext;
import org.infinispan.context.impl.NonTxInvocationContext;
import org.infinispan.context.impl.RemoteTxInvocationContext;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.transport.Address;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.RemoteTransaction;
/**
* Factory for {@link InvocationContext} objects.
*
* @author Manik Surtani (manik AT infinispan DOT org)
* @author Mircea.Markus@jboss.com
* @author Dan Berindei
* @since 7.0
*/
@Scope(Scopes.NAMED_CACHE)
public interface InvocationContextFactory {
/**
* To be used when building InvocationContext with {@link #createInvocationContext(boolean, int)} as an indicator
* of the fact that the size of the keys to be accessed in the context is not known.
*/
int UNBOUNDED = -1;
/**
* If we are in a tx scope this will return an {@link org.infinispan.context.impl.TxInvocationContext}. Otherwise it
* will return an {@link org.infinispan.context.impl.NonTxInvocationContext}. Either way, both context will be marked
* as local, i.e. {@link org.infinispan.context.InvocationContext#isOriginLocal()} will be true.
*/
InvocationContext createInvocationContext(boolean isWrite, int keyCount);
/**
* Creates an invocation context
*/
InvocationContext createInvocationContext(Transaction tx, boolean implicitTransaction);
/**
* Will create an {@link org.infinispan.context.impl.NonTxInvocationContext} with the {@link
* org.infinispan.context.impl.NonTxInvocationContext#isOriginLocal()} returning true.
*/
NonTxInvocationContext createNonTxInvocationContext();
/**
* Will create an {@link org.infinispan.context.impl.NonTxInvocationContext} with the {@link
* org.infinispan.context.impl.NonTxInvocationContext#isOriginLocal()} returning true.
*/
InvocationContext createSingleKeyNonTxInvocationContext();
/**
* Will create an {@link ClearInvocationContext} with the {@link
* ClearInvocationContext#isOriginLocal()} returning true.
*/
InvocationContext createClearNonTxInvocationContext();
/**
* Returns a {@link org.infinispan.context.impl.LocalTxInvocationContext}.
*/
LocalTxInvocationContext createTxInvocationContext(LocalTransaction localTransaction);
/**
* Returns an {@link org.infinispan.context.impl.RemoteTxInvocationContext}.
*
* @param tx remote transaction
* @param origin the origin of the command, or null if local
*/
RemoteTxInvocationContext createRemoteTxInvocationContext(RemoteTransaction tx, Address origin);
/**
* Returns an {@link org.infinispan.context.impl.NonTxInvocationContext} whose {@link
* org.infinispan.context.impl.NonTxInvocationContext#isOriginLocal()} flag will be true.
*
* @param origin the origin of the command, or null if local
*/
InvocationContext createRemoteInvocationContext(Address origin);
/**
* As {@link #createRemoteInvocationContext(org.infinispan.remoting.transport.Address)},
* but returning the flags to the context from the Command if any Flag was set.
*
* @param cacheCommand the remote command
* @param origin the origin of the command, or null if local
*/
InvocationContext createRemoteInvocationContextForCommand(VisitableCommand cacheCommand, Address origin);
}
| 3,665
| 38.847826
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/InvocationContext.java
|
package org.infinispan.context;
import java.util.Collection;
import java.util.Set;
import org.infinispan.remoting.transport.Address;
/**
* A context that contains information pertaining to a given invocation. These contexts typically have the lifespan of
* a single invocation.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public interface InvocationContext extends EntryLookup, Cloneable {
/**
* Returns true if the call was originated locally, false if it is the result of a remote rpc.
*/
boolean isOriginLocal();
/**
* @return the origin of the command, or null if the command originated locally
*/
Address getOrigin();
/**
* Returns true if this call is performed in the context of an transaction, false otherwise.
*/
boolean isInTxScope();
/**
* Returns the in behalf of which locks will be acquired.
*/
Object getLockOwner();
/**
* Sets the object to be used by lock owner.
*/
void setLockOwner(Object lockOwner);
/**
* Clones the invocation context.
*
* @return A cloned instance of this invocation context instance
*/
InvocationContext clone();
/**
* Returns the set of keys that are locked for writing.
*/
Set<Object> getLockedKeys();
void clearLockedKeys();
/**
* Tracks the given key as locked by this invocation context.
*/
void addLockedKey(Object key);
default void addLockedKeys(Collection<?> keys) {
for (Object key : keys) {
addLockedKey(key);
}
}
/**
* Returns true if the lock being tested is already held in the current scope, false otherwise.
*
* @param key lock to test
*/
boolean hasLockedKey(Object key);
/**
* @deprecated Since 11, to be removed in 14 with no replacement
*/
boolean isEntryRemovedInContext(Object key);
}
| 1,943
| 23.3
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/Flag.java
|
package org.infinispan.context;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.marshall.core.Ids;
/**
* Available flags, which may be set on a per-invocation basis. These are
* provided using the {@link AdvancedCache} interface, using some of the
* overloaded methods that allow passing in of a variable number of Flags.
*
* When making modifications to these enum, do not change the order of
* enumerations, so always append any new enumerations after the last one.
* Finally, enumerations should not be removed.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
*/
public enum Flag {
/**
* Overrides the {@link org.infinispan.configuration.cache.LockingConfiguration#lockAcquisitionTimeout(long)} configuration setting by ensuring lock
* managers use a 0-millisecond lock acquisition timeout. Useful if you only want to acquire a lock on an entry
* <i>if and only if</i> the lock is uncontended.
*/
ZERO_LOCK_ACQUISITION_TIMEOUT,
/**
* Forces LOCAL mode operation, even if the cache is configured to use a clustered mode like replication,
* invalidation or distribution. Applying this flag will suppress any RPC messages otherwise associated with this
* invocation. Write operations mat not acquire the entry locks. In distributed mode, the modifications performed
* during an operation in a non-owner node are going to L1, if it is enabled, otherwise the operation is a no-op in
* that node.
*/
CACHE_MODE_LOCAL,
/**
* Bypasses lock acquisition for this invocation altogether. A potentially dangerous flag, as it can lead to
* inconsistent data: a Lock is needed to make sure the same value is written to each node replica; a lock
* is also needed to guarantee that several writes on the same key are not applied out of order to an async CacheLoader
* storage engine.
* So this flag is useful only as an optimization when the same key is written once and never again, or as
* an unsafe optimisation if the period between writes on the same key is large enough to make a race condition
* never happen in practice. If this is unclear, avoid it.
*/
SKIP_LOCKING,
/**
* Forces a write lock, even if the invocation is a read operation. Useful when reading an entry to later update it
* within the same transaction, and is analogous in behavior and use case to a <tt>select ... for update ... </tt>
* SQL statement.
*/
FORCE_WRITE_LOCK,
/**
* Forces asynchronous network calls where possible, even if otherwise configured to use synchronous network calls.
* Only applicable to non-local, clustered caches.
*/
FORCE_ASYNCHRONOUS,
/**
* Forces synchronous network calls where possible, even if otherwise configured to use asynchronous network calls.
* Only applicable to non-local, clustered caches.
*/
FORCE_SYNCHRONOUS,
/**
* Skips storing an entry to any configured {@link org.infinispan.persistence.spi.CacheLoader}s.
*/
SKIP_CACHE_STORE,
/**
* Skips loading an entry from any configured {@link org.infinispan.persistence.spi.CacheLoader}s.
* Useful for example to perform a {@link Cache#put(Object, Object)} operation while not interested
* in the return value (i.e. the previous value of the key).
* <br>
* Note that the loader will be skipped even if that changes the meaning of the operation, e.g. for
* conditional write operations. If that is not intended,
* you should use {@link #IGNORE_RETURN_VALUES} instead.
*/
SKIP_CACHE_LOAD,
/**
* <p>Swallows any exceptions, logging them instead at a low log level. Will prevent a failing operation from
* affecting any ongoing JTA transactions as well.</p>
* <p>This Flag will not be replicated to remote nodes, but it will still protect the invoker from remote exceptions.</p>
* <p>When using this flag with Optimistic caches, lock acquisition happen in the prepare phase at which
* point this flag will be ignored in order to ensure that Infinispan reports the correct exception
* back to the transaction manager. This is done for safety reasons to avoid inconsistent cache contents.</p>
*/
FAIL_SILENTLY,
/**
* When used with <b>distributed</b> cache mode, will prevent retrieving a remote value either when
* executing a {@link Cache#get(Object)} or {@link Cache#containsKey(Object)},
* or to return the overwritten value for {@link Cache#put(Object, Object)} or {@link Cache#remove(Object)}.
* This would render return values for most operations unusable, in exchange for the performance gains of
* reducing remote calls.
* <br>
* Note that the remote lookup will be skipped even if that changes the meaning of the operation, e.g. for
* conditional write operations. If that is not intended,
* you should use {@link #IGNORE_RETURN_VALUES} instead.
*/
SKIP_REMOTE_LOOKUP,
/**
* Used by the Query module only, it will prevent the indexes to be updated as a result of the current operations.
*/
SKIP_INDEXING,
/**
* Flags the invocation as a {@link Cache#putForExternalRead(Object, Object)}
* call, as opposed to a regular {@link Cache#put(Object, Object)}. This
* flag was created purely for internal Infinispan usage, and should not be
* used by clients calling into Infinispan.
*/
PUT_FOR_EXTERNAL_READ,
/**
* Flags the invocation as a put operation done internally by the state transfer.
* This flag was created purely for internal Infinispan usage, and should not be
* used by clients calling into Infinispan.
*
* Note for internal users: PUT_FOR_STATE_TRANSFER only applies to state transfer-specific actions,
* in order to avoid loading the previous value one should add the IGNORE_RETURN_VALUES flag explicitly.
*/
PUT_FOR_STATE_TRANSFER,
/**
* Flags the invocation as a put operation done internally by the cross-site state transfer. This flag was created
* purely for internal Infinispan usage, and should not be used by clients calling into Infinispan.
*/
PUT_FOR_X_SITE_STATE_TRANSFER,
/**
* If this flag is enabled, if a cache store is shared, then storage to the store is skipped.
*/
SKIP_SHARED_CACHE_STORE,
/**
* Ignore current consistent hash and read from data container/commit the change no matter what (if the flag is set).
*/
SKIP_OWNERSHIP_CHECK,
/**
* Signals that a write operation's return value will be ignored, so reading
* the existing value from a store or from a remote node is not necessary.
*
* Typical operations whose return value might be ignored include
* {@link java.util.Map#put(Object, Object)} whose return value indicates
* previous value. So, a user might decide to the put something in the
* cache but might not be interested in the return value.
*
* This flag is ignored for operations that need the existing value to execute
* correctly, e.g. {@link Cache#get(Object)},
* conditional remove ({@link Cache#remove(Object, Object)}),
* and replace with an expected value ({@link Cache#replace(Object, Object, Object)}).
*
* That means it is safe to use {@code IGNORE_RETURN_VALUES} for all the operations on a cache,
* unlike {@link Flag#SKIP_REMOTE_LOOKUP} and {@link Flag#SKIP_CACHE_LOAD}.
*/
IGNORE_RETURN_VALUES,
/**
* If cross-site replication is enabled, this would skip the replication to any remote site.
*/
SKIP_XSITE_BACKUP,
/**
* This flag skips listener notifications as a result of a cache operation.
* For example, if this flag is passed as a result of a {@link Cache#get(Object)}
* call, no callbacks will be made on listeners annotated with
* {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited}.
*/
SKIP_LISTENER_NOTIFICATION,
/**
* This flag skips statistics updates as a result of a cache operation.
* For example, if this flag is passed as a result of a {@link Cache#get(Object)}
* call, no cache hits or cache miss counters will be updated.
*/
SKIP_STATISTICS,
/**
* Flag to identify cache operations coming from the Hot Rod server.
* @deprecated Since 10.0, not in use.
*/
@Deprecated
OPERATION_HOTROD,
/**
* Flag to identify cache operations coming from the Memcached server.
* @deprecated Since 10.0, not in use.
*/
@Deprecated
OPERATION_MEMCACHED,
/**
* Any time a new indexed entry is inserted, a delete statement is issued on the indexes
* to remove previous values. This delete statement is executed even if there is no known
* entry having the same key. Enable this flag when you know for sure there is no existing
* entry in the index for improved performance.
* For example, this is useful for speeding up import of new data in an empty cache
* having an empty index.
*/
SKIP_INDEX_CLEANUP,
/**
* If a write operation encounters a retry due to a topology change this flag should be used to tell the new owner
* that such a thing happened. This flag was created purely for internal Infinispan usage, and should not be
* used by clients calling into Infinispan.
*/
COMMAND_RETRY,
/**
* Flag to identity that data is being written as part of a Rolling Upgrade.
*/
ROLLING_UPGRADE,
/**
* Flag to identify that this iteration is done on a remote node and thus no additional wrappings are required
* @deprecated Since 14.0, no longer does anything. Will be removed in 17.0.
*/
@Deprecated
REMOTE_ITERATION,
/**
* Flag that can be used to skip any size optimizations - forcing iteration of entries to count. User shouldn't
* normally need to use this flag. This is helpful if there are concerns that can cause just a simple size invocation
* from being consistent (eg. on-going transaction with modifications).
*/
SKIP_SIZE_OPTIMIZATION,
/**
* Flag that is used by keySet, entrySet and values methods so that they do not return transactional values. Normally
* an end user would not need to do this.
*/
IGNORE_TRANSACTION,
/**
* Signals a {@link org.infinispan.commands.write.WriteCommand} as an update from a remote site (async).
* <p>
* Internal use
*/
IRAC_UPDATE,
/**
* Signals a {@link org.infinispan.commands.write.WriteCommand} as state transfer from remote site.
* <p>
* Internal use
*/
IRAC_STATE,
/**
* Flag to designate that this operation was performed on behalf of another that already has the lock for the given
* key.
*/
ALREADY_HAS_LOCK,
/**
* Signals that a {@link org.infinispan.commands.write.WriteCommand} was sent from the primary as a backup operation.
* Some things do not need to be checked in this case.
*/
BACKUP_WRITE,
/**
* Signals that a state transfer is in course. This is primarily used to identify how to load data from cache stores
* during the state transfer.
*/
STATE_TRANSFER_PROGRESS,
;
private static final Flag[] CACHED_VALUES = values();
private static Flag valueOf(int ordinal) {
return CACHED_VALUES[ordinal];
}
public static class Externalizer extends AbstractExternalizer<Flag> {
@Override
public Integer getId() {
return Ids.FLAG;
}
@Override
public Set<Class<? extends Flag>> getTypeClasses() {
return Collections.singleton(Flag.class);
}
@Override
public void writeObject(ObjectOutput output, Flag flag) throws IOException {
MarshallUtil.marshallEnum(flag, output);
}
@Override
public Flag readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return MarshallUtil.unmarshallEnum(input, Flag::valueOf);
}
}
}
| 12,212
| 39.71
| 151
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/EntryLookup.java
|
package org.infinispan.context;
import java.util.Collection;
import java.util.Map;
import java.util.function.BiConsumer;
import org.infinispan.container.entries.CacheEntry;
import org.reactivestreams.Publisher;
/**
* Interface that can look up MVCC wrapped entries.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public interface EntryLookup {
/**
* Retrieves an entry from the collection of looked up entries in the current scope.
* <p/>
*
* @param key key to look up
* @return an entry, or null if it cannot be found.
*/
CacheEntry lookupEntry(Object key);
/**
* Retrieves a map of entries looked up within the current scope.
* <p/>
* Note: The key inside the {@linkplain CacheEntry} may be {@code null} if the key does not exist in the cache.
*
* @return a map of looked up entries.
*/
Map<Object, CacheEntry> getLookedUpEntries();
/**
* Returns a Publisher that when subscribed to provide all values that have a value in the given context.
*
* @param <K> key type provided from user
* @param <V> value type provided from user
* @return
*/
<K, V> Publisher<CacheEntry<K, V>> publisher();
/**
* Execute an action for each value in the context.
* <p>
* Entries that do not have a value (because the key was removed, or it doesn't exist in the cache).
*
* @since 9.3
*/
default void forEachValue(BiConsumer<Object, CacheEntry> action) {
forEachEntry((key, entry) -> {
if (!entry.isRemoved() && !entry.isNull()) {
action.accept(key, entry);
}
});
}
/**
* Execute an action for each entry in the context.
*
* Includes invalid entries, which have a {@code null} value and may also report a {@code null} key.
*
* @since 9.3
*/
default void forEachEntry(BiConsumer<Object, CacheEntry> action) {
getLookedUpEntries().forEach(action);
}
/**
* @return The number of entries wrapped in the context, including invalid entries.
*/
default int lookedUpEntriesCount() {
return getLookedUpEntries().size();
}
/**
* Puts an entry in the registry of looked up entries in the current scope.
* <p/>
*
* @param key key to store
* @param e entry to store
*/
void putLookedUpEntry(Object key, CacheEntry e);
void removeLookedUpEntry(Object key);
default void removeLookedUpEntries(Collection<?> keys) {
for (Object key : keys) {
removeLookedUpEntry(key);
}
}
}
| 2,595
| 26.617021
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/NonTransactionalInvocationContextFactory.java
|
package org.infinispan.context.impl;
import jakarta.transaction.Transaction;
import org.infinispan.context.InvocationContext;
import org.infinispan.factories.annotations.SurvivesRestarts;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.transport.Address;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.RemoteTransaction;
/**
* Invocation Context container to be used for non-transactional caches.
*
* @author Mircea Markus
*/
@Scope(Scopes.NAMED_CACHE)
@SurvivesRestarts
public class NonTransactionalInvocationContextFactory extends AbstractInvocationContextFactory {
@Override
public InvocationContext createInvocationContext(boolean isWrite, int keyCount) {
if (keyCount == 1) {
return new SingleKeyNonTxInvocationContext(null);
} else if (keyCount > 0) {
return new NonTxInvocationContext(keyCount, null);
}
return createInvocationContext(null, false);
}
@Override
public InvocationContext createInvocationContext(Transaction tx, boolean implicitTransaction) {
return createNonTxInvocationContext();
}
@Override
public NonTxInvocationContext createNonTxInvocationContext() {
return new NonTxInvocationContext(null);
}
@Override
public InvocationContext createSingleKeyNonTxInvocationContext() {
return new SingleKeyNonTxInvocationContext(null);
}
@Override
public NonTxInvocationContext createRemoteInvocationContext(Address origin) {
return new NonTxInvocationContext(origin);
}
@Override
public LocalTxInvocationContext createTxInvocationContext(LocalTransaction localTransaction) {
throw exception();
}
@Override
public RemoteTxInvocationContext createRemoteTxInvocationContext(
RemoteTransaction tx, Address origin) {
throw exception();
}
private IllegalStateException exception() {
return new IllegalStateException("This is a non-transactional cache - why need to build a transactional context for it!");
}
}
| 2,119
| 30.641791
| 128
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/package-info.java
|
/**
* This package contains different context implementations, selected dynamically based on the type of invocation.
*/
package org.infinispan.context.impl;
| 159
| 31
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/AbstractTxInvocationContext.java
|
package org.infinispan.context.impl;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.transaction.impl.AbstractCacheTransaction;
import org.infinispan.transaction.xa.GlobalTransaction;
/**
* Support class for {@link org.infinispan.context.impl.TxInvocationContext}.
*
* @author Mircea.Markus@jboss.com
* @author Galder Zamarreño
* @author Pedro Ruivo
* @since 4.0
*/
public abstract class AbstractTxInvocationContext<T extends AbstractCacheTransaction> extends AbstractInvocationContext
implements TxInvocationContext<T> {
private final T cacheTransaction;
private Object lockOwnerOverride;
protected AbstractTxInvocationContext(T cacheTransaction, Address origin) {
super(origin);
if (cacheTransaction == null) {
throw new NullPointerException("CacheTransaction cannot be null");
}
this.cacheTransaction = cacheTransaction;
}
@Override
public Object getLockOwner() {
if (lockOwnerOverride != null) {
return lockOwnerOverride;
}
//not final because the test suite overwrite it...
return cacheTransaction.getGlobalTransaction();
}
@Override
public void setLockOwner(Object lockOwner) {
lockOwnerOverride = lockOwner;
}
@Override
public final Set<Object> getLockedKeys() {
return cacheTransaction.getLockedKeys();
}
@Override
public final void addLockedKey(Object key) {
cacheTransaction.registerLockedKey(key);
}
@Override
public final GlobalTransaction getGlobalTransaction() {
return cacheTransaction.getGlobalTransaction();
}
@Override
public final boolean hasModifications() {
return cacheTransaction.hasModifications();
}
@Override
public final List<WriteCommand> getModifications() {
return cacheTransaction.getModifications();
}
@Override
public final CacheEntry lookupEntry(Object key) {
return cacheTransaction.lookupEntry(key);
}
@Override
public final Map<Object, CacheEntry> getLookedUpEntries() {
return cacheTransaction.getLookedUpEntries();
}
@Override
public final Set<Object> getAffectedKeys() {
return cacheTransaction.getAffectedKeys();
}
@Override
public final void addAllAffectedKeys(Collection<?> keys) {
if (keys != null && !keys.isEmpty()) {
cacheTransaction.addAllAffectedKeys(keys);
}
}
@Override
public final void addAffectedKey(Object key) {
cacheTransaction.addAffectedKey(key);
}
@Override
public final void putLookedUpEntry(Object key, CacheEntry e) {
cacheTransaction.putLookedUpEntry(key, e);
}
@Override
public final void removeLookedUpEntry(Object key) {
cacheTransaction.removeLookedUpEntry(key);
}
@Override
public final boolean isInTxScope() {
return true;
}
@Override
public final void clearLockedKeys() {
cacheTransaction.clearLockedKeys();
}
@Override
public final T getCacheTransaction() {
return cacheTransaction;
}
}
| 3,259
| 24.669291
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/TxInvocationContext.java
|
package org.infinispan.context.impl;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import jakarta.transaction.Transaction;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.transaction.impl.AbstractCacheTransaction;
import org.infinispan.transaction.xa.GlobalTransaction;
/**
* Interface defining additional functionality for invocation contexts that propagate within a transaction's scope.
*
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public interface TxInvocationContext<T extends AbstractCacheTransaction> extends InvocationContext {
/**
* Checks if there are modifications performed within the tx's scope. Any modifications having Flag.CACHE_MODE_LOCAL are ignored.
*/
boolean hasModifications();
/**
* Returns the set of keys that are affected by this transaction. Used to generate appropriate recipient groups
* for cluster-wide prepare and commit calls.
*/
Set<Object> getAffectedKeys();
/**
* Returns the id of the transaction associated with the current call.
*/
GlobalTransaction getGlobalTransaction();
/**
* Returns the modifications performed in the scope of the current transaction. Any modifications having Flag.CACHE_MODE_LOCAL are ignored.
* The returned list can be null.
*/
List<WriteCommand> getModifications();
/**
* Returns the tx associated with the current thread. This method MUST be guarded with a call to {@link
* #isOriginLocal()}, as {@link javax.transaction.Transaction} are not propagated from the node where tx was
* started.
* @throws IllegalStateException if the call is performed from a {@link #isOriginLocal()}==false context.
*/
Transaction getTransaction();
/**
* Registers a new participant with the transaction.
*/
void addAllAffectedKeys(Collection<?> keys);
void addAffectedKey(Object key);
/**
*
* @return true if the current transaction is in a valid state to perform operations on (i.e.,RUNNING or PREPARING)
* or false otherwise.
*/
boolean isTransactionValid();
boolean isImplicitTransaction();
T getCacheTransaction();
}
| 2,232
| 30.9
| 142
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/ClearInvocationContext.java
|
package org.infinispan.context.impl;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.entries.ClearCacheEntry;
import org.infinispan.remoting.transport.Address;
/**
* Implementation of {@link org.infinispan.context.InvocationContext} used by the {@link
* org.infinispan.commands.write.ClearCommand}.
*
* @author Pedro Ruivo
* @since 7.2
*/
public class ClearInvocationContext extends AbstractInvocationContext implements Cloneable {
private static final Map<Object, CacheEntry> LOOKUP_ENTRIES = Collections.singletonMap((Object) "_clear_", (CacheEntry) ClearCacheEntry.getInstance());
public ClearInvocationContext(Address origin) {
super(origin);
}
@Override
public boolean isInTxScope() {
return false;
}
@Override
public Object getLockOwner() {
return null; // clear does not acquire any locks
}
@Override
public void setLockOwner(Object lockOwner) {
/*no-op. clear does not acquire any locks*/
}
@Override
public ClearInvocationContext clone() {
return (ClearInvocationContext) super.clone();
}
@Override
public Set<Object> getLockedKeys() {
return Collections.emptySet();
}
@Override
public void clearLockedKeys() {
/*no-op*/
}
@Override
public void addLockedKey(Object key) {
/*no-op*/
}
@Override
public boolean hasLockedKey(Object key) {
//ClearCommand does not acquire locks
return false;
}
@Override
public boolean isEntryRemovedInContext(Object key) {
//clear remove all entries
return true;
}
@Override
public CacheEntry lookupEntry(Object key) {
return null;
}
@Override
public Map<Object, CacheEntry> getLookedUpEntries() {
return LOOKUP_ENTRIES;
}
@Override
public void putLookedUpEntry(Object key, CacheEntry e) {
/*no-op*/
}
@Override
public void removeLookedUpEntry(Object key) {
/*no-op*/
}
}
| 2,067
| 21.236559
| 154
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/NonTxInvocationContext.java
|
package org.infinispan.context.impl;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.remoting.transport.Address;
/**
* Context to be used for non transactional calls, both remote and local.
*
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class NonTxInvocationContext extends AbstractInvocationContext {
private static final int INITIAL_CAPACITY = 4;
private final Map<Object, CacheEntry> lookedUpEntries;
private Set<Object> lockedKeys;
private Object lockOwner;
public NonTxInvocationContext(int numEntries, Address origin) {
super(origin);
lookedUpEntries = new HashMap<>(numEntries);
}
public NonTxInvocationContext(Address origin) {
super(origin);
lookedUpEntries = new HashMap<>(INITIAL_CAPACITY);
}
@Override
public CacheEntry lookupEntry(Object k) {
return lookedUpEntries.get(k);
}
@Override
public void removeLookedUpEntry(Object key) {
lookedUpEntries.remove(key);
}
@Override
public void putLookedUpEntry(Object key, CacheEntry e) {
lookedUpEntries.put(key, e);
}
@Override
@SuppressWarnings("unchecked")
public Map<Object, CacheEntry> getLookedUpEntries() {
return (Map<Object, CacheEntry>)
(lookedUpEntries == null ?
Collections.emptyMap() : lookedUpEntries);
}
@Override
public void forEachEntry(BiConsumer<Object, CacheEntry> action) {
if (lookedUpEntries != null) {
lookedUpEntries.forEach(action);
}
}
@Override
public int lookedUpEntriesCount() {
return lookedUpEntries != null ? lookedUpEntries.size() : 0;
}
@Override
public boolean isInTxScope() {
return false;
}
@Override
public Object getLockOwner() {
return lockOwner;
}
@Override
public void setLockOwner(Object lockOwner) {
this.lockOwner = lockOwner;
}
@Override
public NonTxInvocationContext clone() {
NonTxInvocationContext dolly = (NonTxInvocationContext) super.clone();
dolly.lookedUpEntries.putAll(lookedUpEntries);
return dolly;
}
@Override
public void addLockedKey(Object key) {
if (lockedKeys == null)
lockedKeys = new HashSet<>(INITIAL_CAPACITY);
lockedKeys.add(key);
}
@Override
public Set<Object> getLockedKeys() {
return lockedKeys == null ? Collections.emptySet() : lockedKeys;
}
@Override
public void clearLockedKeys() {
lockedKeys = null;
}
}
| 2,683
| 22.752212
| 76
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/ImmutableContext.java
|
package org.infinispan.context.impl;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import org.infinispan.commons.CacheException;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.context.InvocationContext;
import org.infinispan.remoting.transport.Address;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
/**
* This context is a non-context for operations such as eviction which are not related
* to the method invocation which caused them.
*
* @author Sanne Grinovero <sanne@infinispan.org> (C) 2011 Red Hat Inc.
*/
public final class ImmutableContext implements InvocationContext {
public static final ImmutableContext INSTANCE = new ImmutableContext();
private ImmutableContext() {
//don't create multiple instances
}
@Override
public CacheEntry lookupEntry(Object key) {
throw newUnsupportedMethod();
}
@Override
public Map<Object, CacheEntry> getLookedUpEntries() {
return Collections.emptyMap();
}
@Override
public void putLookedUpEntry(Object key, CacheEntry e) {
throw newUnsupportedMethod();
}
@Override
public void removeLookedUpEntry(Object key) {
throw newUnsupportedMethod();
}
@Override
public boolean hasLockedKey(Object key) {
return false;
}
@Override
public boolean isOriginLocal() {
return true;
}
@Override
public Address getOrigin() {
return null;
}
@Override
public boolean isInTxScope() {
return false;
}
@Override
public Object getLockOwner() {
return null;
}
@Override
public void setLockOwner(Object lockOwner) {
throw newUnsupportedMethod();
}
@Override
public Set<Object> getLockedKeys() {
return Collections.emptySet();
}
@Override
public InvocationContext clone() {
return this;
}
/**
* @return an exception to state this context is read only
*/
private static CacheException newUnsupportedMethod() {
throw new UnsupportedOperationException();
}
@Override
public void addLockedKey(Object key) {
throw newUnsupportedMethod();
}
@Override
public void clearLockedKeys() {
throw newUnsupportedMethod();
}
@Override
public boolean isEntryRemovedInContext(Object key) {
return false;
}
@Override
public void forEachEntry(BiConsumer<Object, CacheEntry> action) { }
@Override
public void forEachValue(BiConsumer<Object, CacheEntry> action) { }
@Override
public <K, V> Publisher<CacheEntry<K, V>> publisher() {
return Flowable.empty();
}
}
| 2,709
| 21.03252
| 86
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/AbstractInvocationContext.java
|
package org.infinispan.context.impl;
import java.util.Collection;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.context.InvocationContext;
import org.infinispan.remoting.transport.Address;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
/**
* Common features of transaction and invocation contexts
*
* @author Manik Surtani
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public abstract class AbstractInvocationContext implements InvocationContext {
private final Address origin;
protected AbstractInvocationContext(Address origin) {
this.origin = origin;
}
@Override
public final Address getOrigin() {
return origin;
}
@Override
public boolean isOriginLocal() {
return origin == null;
}
@Override
public boolean hasLockedKey(Object key) {
return getLockedKeys().contains(key);
}
@Override
public boolean isEntryRemovedInContext(final Object key) {
CacheEntry ce = lookupEntry(key);
return ce != null && ce.isRemoved() && ce.isChanged();
}
@Override
public InvocationContext clone() {
try {
return (InvocationContext) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Impossible!", e);
}
}
@Override
public <K, V> Publisher<CacheEntry<K, V>> publisher() {
if (lookedUpEntriesCount() == 0) {
return Flowable.empty();
}
Collection<CacheEntry<K, V>> collection = (Collection) getLookedUpEntries().values();
return Flowable.fromIterable(collection)
.filter(ce -> !ce.isRemoved() && !ce.isNull());
}
}
| 1,697
| 24.727273
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/RemoteTxInvocationContext.java
|
package org.infinispan.context.impl;
import jakarta.transaction.Transaction;
import org.infinispan.transaction.impl.RemoteTransaction;
/**
* Context to be used for transaction that originated remotely.
*
* @author Mircea.Markus@jboss.com
* @author Galder Zamarreño
* @author Pedro Ruivo
* @since 4.0
*/
public class RemoteTxInvocationContext extends AbstractTxInvocationContext<RemoteTransaction> {
public RemoteTxInvocationContext(RemoteTransaction cacheTransaction) {
super(cacheTransaction, cacheTransaction.getGlobalTransaction().getAddress());
}
@Override
public final Transaction getTransaction() {
// this method is only valid for locally originated transactions!
return null;
}
@Override
public final boolean isTransactionValid() {
// this is always true since we are governed by the originator's transaction
return true;
}
@Override
public final boolean isImplicitTransaction() {
//has no meaning in remote transaction
return false;
}
@Override
public final boolean isOriginLocal() {
return false;
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RemoteTxInvocationContext)) return false;
RemoteTxInvocationContext that = (RemoteTxInvocationContext) o;
return getCacheTransaction().equals(that.getCacheTransaction());
}
@Override
public final int hashCode() {
return getCacheTransaction().hashCode();
}
}
| 1,519
| 25.666667
| 95
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/FlagBitSets.java
|
package org.infinispan.context.impl;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.context.Flag;
import org.infinispan.context.InvocationContext;
/**
* Pre-computed bitsets containing each flag.
*
* @author Dan Berindei
* @since 9.0
*/
public class FlagBitSets {
public static final long ZERO_LOCK_ACQUISITION_TIMEOUT = EnumUtil.bitSetOf(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT);
public static final long CACHE_MODE_LOCAL = EnumUtil.bitSetOf(Flag.CACHE_MODE_LOCAL);
public static final long SKIP_LOCKING = EnumUtil.bitSetOf(Flag.SKIP_LOCKING);
public static final long FORCE_WRITE_LOCK = EnumUtil.bitSetOf(Flag.FORCE_WRITE_LOCK);
public static final long FORCE_ASYNCHRONOUS = EnumUtil.bitSetOf(Flag.FORCE_ASYNCHRONOUS);
public static final long FORCE_SYNCHRONOUS = EnumUtil.bitSetOf(Flag.FORCE_SYNCHRONOUS);
public static final long SKIP_CACHE_STORE = EnumUtil.bitSetOf(Flag.SKIP_CACHE_STORE);
public static final long SKIP_CACHE_LOAD = EnumUtil.bitSetOf(Flag.SKIP_CACHE_LOAD);
public static final long FAIL_SILENTLY = EnumUtil.bitSetOf(Flag.FAIL_SILENTLY);
public static final long SKIP_REMOTE_LOOKUP = EnumUtil.bitSetOf(Flag.SKIP_REMOTE_LOOKUP);
public static final long SKIP_INDEXING = EnumUtil.bitSetOf(Flag.SKIP_INDEXING);
public static final long PUT_FOR_EXTERNAL_READ = EnumUtil.bitSetOf(Flag.PUT_FOR_EXTERNAL_READ);
public static final long PUT_FOR_STATE_TRANSFER = EnumUtil.bitSetOf(Flag.PUT_FOR_STATE_TRANSFER);
public static final long PUT_FOR_X_SITE_STATE_TRANSFER = EnumUtil.bitSetOf(Flag.PUT_FOR_X_SITE_STATE_TRANSFER);
public static final long SKIP_SHARED_CACHE_STORE = EnumUtil.bitSetOf(Flag.SKIP_SHARED_CACHE_STORE);
public static final long SKIP_OWNERSHIP_CHECK = EnumUtil.bitSetOf(Flag.SKIP_OWNERSHIP_CHECK);
public static final long IGNORE_RETURN_VALUES = EnumUtil.bitSetOf(Flag.IGNORE_RETURN_VALUES);
public static final long SKIP_XSITE_BACKUP = EnumUtil.bitSetOf(Flag.SKIP_XSITE_BACKUP);
public static final long SKIP_LISTENER_NOTIFICATION = EnumUtil.bitSetOf(Flag.SKIP_LISTENER_NOTIFICATION);
public static final long SKIP_STATISTICS = EnumUtil.bitSetOf(Flag.SKIP_STATISTICS);
@Deprecated
public static final long OPERATION_HOTROD = EnumUtil.bitSetOf(Flag.OPERATION_HOTROD);
@Deprecated
public static final long OPERATION_MEMCACHED = EnumUtil.bitSetOf(Flag.OPERATION_MEMCACHED);
public static final long SKIP_INDEX_CLEANUP = EnumUtil.bitSetOf(Flag.SKIP_INDEX_CLEANUP);
public static final long COMMAND_RETRY = EnumUtil.bitSetOf(Flag.COMMAND_RETRY);
public static final long ROLLING_UPGRADE = EnumUtil.bitSetOf(Flag.ROLLING_UPGRADE);
@Deprecated
public static final long REMOTE_ITERATION = EnumUtil.bitSetOf(Flag.REMOTE_ITERATION);
public static final long SKIP_SIZE_OPTIMIZATION = EnumUtil.bitSetOf(Flag.SKIP_SIZE_OPTIMIZATION);
public static final long IGNORE_TRANSACTION = EnumUtil.bitSetOf(Flag.IGNORE_TRANSACTION);
public static final long IRAC_UPDATE = EnumUtil.bitSetOf(Flag.IRAC_UPDATE);
public static final long IRAC_STATE = EnumUtil.bitSetOf(Flag.IRAC_STATE);
public static final long ALREADY_HAS_LOCK = EnumUtil.bitSetOf(Flag.ALREADY_HAS_LOCK);
public static final long BACKUP_WRITE = EnumUtil.bitSetOf(Flag.BACKUP_WRITE);
public static final long STATE_TRANSFER_PROGRESS = EnumUtil.bitSetOf(Flag.STATE_TRANSFER_PROGRESS);
/**
* Creates a copy of a Flag BitSet removing instances of FAIL_SILENTLY.
*/
public static long copyWithoutRemotableFlags(long flagsBitSet) {
return EnumUtil.diffBitSets(flagsBitSet, FAIL_SILENTLY);
}
public static Flag extractStateTransferFlag(InvocationContext ctx, FlagAffectedCommand command) {
if (command == null) {
//commit command
return ctx instanceof TxInvocationContext ?
((TxInvocationContext<?>) ctx).getCacheTransaction().getStateTransferFlag() :
null;
} else {
if (command.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER)) {
return Flag.PUT_FOR_STATE_TRANSFER;
} else if (command.hasAnyFlag(FlagBitSets.PUT_FOR_X_SITE_STATE_TRANSFER)) {
return Flag.PUT_FOR_X_SITE_STATE_TRANSFER;
}
}
return null;
}
}
| 4,308
| 56.453333
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/LocalTxInvocationContext.java
|
package org.infinispan.context.impl;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.remoting.transport.Address;
import org.infinispan.transaction.impl.LocalTransaction;
/**
* Invocation context to be used for locally originated transactions.
*
* @author Mircea.Markus@jboss.com
* @author Galder Zamarreño
* @author Pedro Ruivo
* @since 4.0
*/
public class LocalTxInvocationContext extends AbstractTxInvocationContext<LocalTransaction> {
public LocalTxInvocationContext(LocalTransaction localTransaction) {
super(localTransaction, null);
}
@Override
public final boolean isTransactionValid() {
Transaction t = getTransaction();
int status = -1;
if (t != null) {
try {
status = t.getStatus();
} catch (SystemException e) {
// no op
}
}
return status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARING;
}
@Override
public final boolean isImplicitTransaction() {
return getCacheTransaction().isImplicitTransaction();
}
@Override
public final boolean isOriginLocal() {
return true;
}
@Override
public final boolean hasLockedKey(Object key) {
return getCacheTransaction().ownsLock(key);
}
public final void remoteLocksAcquired(Collection<Address> nodes) {
getCacheTransaction().locksAcquired(nodes);
}
public final Collection<Address> getRemoteLocksAcquired() {
return getCacheTransaction().getRemoteLocksAcquired();
}
@Override
public final Transaction getTransaction() {
return getCacheTransaction().getTransaction();
}
/**
* @return {@code true} if there is an {@link IracMetadata} stored for {@code key}.
*/
public boolean hasIracMetadata(Object key) {
return getCacheTransaction().hasIracMetadata(key);
}
/**
* Stores the {@link IracMetadata} associated with {@code key}.
*
* @param key The key.
* @param metadata The {@link CompletionStage} that will be completed with {@link IracMetadata} to associate.
*/
public void storeIracMetadata(Object key, CompletionStage<IracMetadata> metadata) {
getCacheTransaction().storeIracMetadata(key, metadata);
}
/**
* @return The {@link IracMetadata} associated with {@code key}.
*/
public CompletionStage<IracMetadata> getIracMetadata(Object key) {
return getCacheTransaction().getIracMetadata(key);
}
}
| 2,664
| 27.351064
| 112
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/TransactionalInvocationContextFactory.java
|
package org.infinispan.context.impl;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.batch.BatchContainer;
import org.infinispan.commons.CacheException;
import org.infinispan.context.InvocationContext;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.transport.Address;
import org.infinispan.transaction.impl.LocalTransaction;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
/**
* Invocation context to be used for transactional caches.
*
* @author Mircea.Markus@jboss.com
*/
@Scope(Scopes.NAMED_CACHE)
public class TransactionalInvocationContextFactory extends AbstractInvocationContextFactory {
@Inject TransactionManager tm;
@Inject TransactionTable transactionTable;
@Inject BatchContainer batchContainer;
private boolean batchingEnabled;
@Start
public void start() {
this.batchingEnabled = config.invocationBatching().enabled();
}
@Override
public NonTxInvocationContext createNonTxInvocationContext() {
return newNonTxInvocationContext(null);
}
@Override
public InvocationContext createSingleKeyNonTxInvocationContext() {
return new SingleKeyNonTxInvocationContext(null);
}
@Override
public InvocationContext createInvocationContext(boolean isWrite, int keyCount) {
final Transaction runningTx = getRunningTx();
if (runningTx == null && !isWrite) {
if (keyCount == 1)
return createSingleKeyNonTxInvocationContext();
else
return newNonTxInvocationContext(null);
}
return createInvocationContext(runningTx, false);
}
@Override
public InvocationContext createInvocationContext(Transaction tx, boolean implicitTransaction) {
if (tx == null) {
throw new IllegalArgumentException("Cannot create a transactional context without a valid Transaction instance.");
}
LocalTransaction localTransaction = transactionTable.getOrCreateLocalTransaction(tx, implicitTransaction);
return new LocalTxInvocationContext(localTransaction);
}
@Override
public LocalTxInvocationContext createTxInvocationContext(LocalTransaction localTransaction) {
return new LocalTxInvocationContext(localTransaction);
}
@Override
public RemoteTxInvocationContext createRemoteTxInvocationContext(
RemoteTransaction tx, Address origin) {
RemoteTxInvocationContext ctx = new RemoteTxInvocationContext(tx);
return ctx;
}
@Override
public NonTxInvocationContext createRemoteInvocationContext(Address origin) {
return newNonTxInvocationContext(origin);
}
private Transaction getRunningTx() {
try {
Transaction transaction = null;
if (batchingEnabled) {
transaction = batchContainer.getBatchTransaction();
}
if (transaction == null) {
transaction = tm.getTransaction();
}
return transaction;
} catch (SystemException e) {
throw new CacheException(e);
}
}
protected final NonTxInvocationContext newNonTxInvocationContext(Address origin) {
NonTxInvocationContext ctx = new NonTxInvocationContext(origin);
return ctx;
}
}
| 3,512
| 32.141509
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/AbstractInvocationContextFactory.java
|
package org.infinispan.context.impl;
import org.infinispan.commands.DataCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.transport.Address;
/**
* Base class for InvocationContextFactory implementations.
*
* @author Mircea Markus
* @author Dan Berindei
*/
@Scope(Scopes.NAMED_CACHE)
public abstract class AbstractInvocationContextFactory implements InvocationContextFactory {
@Inject protected Configuration config;
@Override
public InvocationContext createRemoteInvocationContextForCommand(
VisitableCommand cacheCommand, Address origin) {
if (cacheCommand instanceof DataCommand && !(cacheCommand instanceof InvalidateCommand)) {
return new SingleKeyNonTxInvocationContext(origin);
} else if (cacheCommand instanceof PutMapCommand) {
return new NonTxInvocationContext(((PutMapCommand) cacheCommand).getMap().size(), origin);
} else if (cacheCommand instanceof ClearCommand) {
return createClearInvocationContext(origin);
} else {
return createRemoteInvocationContext(origin);
}
}
@Override
public final InvocationContext createClearNonTxInvocationContext() {
return createClearInvocationContext(null);
}
private ClearInvocationContext createClearInvocationContext(Address origin) {
ClearInvocationContext context = new ClearInvocationContext(origin);
return context;
}
}
| 1,909
| 36.45098
| 99
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/context/impl/SingleKeyNonTxInvocationContext.java
|
package org.infinispan.context.impl;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.context.InvocationContext;
import org.infinispan.remoting.transport.Address;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
/**
* @author Mircea Markus
* @author Sanne Grinovero
*/
public final class SingleKeyNonTxInvocationContext implements InvocationContext {
/**
* It is possible for the key to only be wrapped but not locked, e.g. when a get takes place.
*/
private boolean isLocked;
private Object key;
private CacheEntry cacheEntry;
//TODO move the Origin's address to the InvocationContextFactory when isOriginLocal=true -> all addresses are the same (Memory allocation cost)
//(verify if this is worth it by looking at object alignment - would need a different implementation as pointing to null wouldn't help)
private final Address origin;
private Object lockOwner;
public SingleKeyNonTxInvocationContext(final Address origin) {
this.origin = origin;
}
@Override
public boolean isOriginLocal() {
return origin == null;
}
@Override
public boolean isInTxScope() {
return false;
}
@Override
public Object getLockOwner() {
return lockOwner;
}
@Override
public void setLockOwner(Object lockOwner) {
this.lockOwner = lockOwner;
}
@Override
public InvocationContext clone() {
try {
return (InvocationContext) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Impossible!", e);
}
}
@Override
public Set<Object> getLockedKeys() {
return isLocked ? Collections.singleton(key) : Collections.emptySet();
}
@Override
public void clearLockedKeys() {
isLocked = false;
}
@Override
public void addLockedKey(final Object key) {
if (this.key == null) {
// Set the key here
this.key = key;
} else if (!isKeyEquals(key)) {
throw illegalStateException();
}
isLocked = true;
}
private IllegalStateException illegalStateException() {
return new IllegalStateException("This is a single key invocation context, using multiple keys shouldn't be possible");
}
@Override
public CacheEntry lookupEntry(final Object key) {
if (this.key != null && isKeyEquals(key))
return cacheEntry;
return null;
}
public boolean isKeyEquals(Object key) {
return this.key == key || this.key.equals(key);
}
@Override
public Map<Object, CacheEntry> getLookedUpEntries() {
return cacheEntry == null ? Collections.emptyMap() : Collections.singletonMap(key, cacheEntry);
}
@Override
public void forEachEntry(BiConsumer<Object, CacheEntry> action) {
if (cacheEntry != null) {
action.accept(key, cacheEntry);
}
}
@Override
public void forEachValue(BiConsumer<Object, CacheEntry> action) {
if (cacheEntry != null && !cacheEntry.isRemoved() && !cacheEntry.isNull()) {
action.accept(key, cacheEntry);
}
}
@Override
public <K, V> Publisher<CacheEntry<K, V>> publisher() {
if (cacheEntry != null && !cacheEntry.isRemoved() && !cacheEntry.isNull()) {
return Flowable.just(cacheEntry);
}
return Flowable.empty();
}
@Override
public int lookedUpEntriesCount() {
return cacheEntry != null ? 1 : 0;
}
@Override
public void putLookedUpEntry(final Object key, final CacheEntry e) {
if (this.key == null) {
// Set the key here
this.key = key;
} else if (!isKeyEquals(key)) {
throw illegalStateException();
}
this.cacheEntry = e;
}
@Override
public void removeLookedUpEntry(final Object key) {
if (this.key != null && isKeyEquals(key)) {
this.cacheEntry = null;
}
}
public Object getKey() {
return key;
}
public CacheEntry getCacheEntry() {
return cacheEntry;
}
@Override
public Address getOrigin() {
return origin;
}
@Override
public boolean hasLockedKey(final Object key) {
return isLocked && isKeyEquals(key);
}
@Override
public boolean isEntryRemovedInContext(final Object key) {
CacheEntry ce = lookupEntry(key);
return ce != null && ce.isRemoved() && ce.isChanged();
}
public void resetState() {
this.key = null;
this.cacheEntry = null;
this.isLocked = false;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("SingleKeyNonTxInvocationContext{");
sb.append("isLocked=").append(isLocked);
sb.append(", key=").append(key);
sb.append(", cacheEntry=").append(cacheEntry);
sb.append(", origin=").append(origin);
sb.append(", lockOwner=").append(lockOwner);
sb.append('}');
return sb.toString();
}
}
| 5,078
| 24.395
| 147
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/registry/package-info.java
|
/**
* The internal cache registry API
*
* @api.private
*/
package org.infinispan.registry;
| 95
| 12.714286
| 34
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/registry/InternalCacheRegistry.java
|
package org.infinispan.registry;
import java.util.EnumSet;
import java.util.Set;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* InternalCacheRegistry. Components which create caches for internal use should use this class to
* create/retrieve them
*
* @author Tristan Tarrant
* @since 7.2
*/
@Scope(Scopes.GLOBAL)
public interface InternalCacheRegistry {
void startInternalCaches();
enum Flag {
/**
* means that the cache must be declared only once
*/
EXCLUSIVE,
/**
* means that this cache is visible to users
*/
USER,
/**
* means that his cache requires security to be accessible remotely
*/
PROTECTED,
/**
* means the cache should be made persistent across restarts if global state persistence is enabled
*/
PERSISTENT,
/**
* means that this cache should be queryable
*/
QUERYABLE,
/**
* means that this cache will be global to all nodes when running in clustered mode
*/
GLOBAL
}
/**
* Registers an internal cache. The cache will be marked as private and volatile
*
* @param name
* The name of the cache
* @param configuration
* The configuration for the cache
*/
void registerInternalCache(String name, Configuration configuration);
/**
* Registers an internal cache with the specified flags.
*
* @param name
* The name of the cache
* @param configuration
* The configuration for the cache
* @param flags
* The flags which determine the behaviour of the cache. See {@link Flag}
*/
void registerInternalCache(String name, Configuration configuration, EnumSet<Flag> flags);
/**
* Unregisters an internal cache
* @param name The name of the cache
*/
void unregisterInternalCache(String name);
/**
* Returns whether the cache is internal, i.e. it has been registered using the
* {@link #registerInternalCache(String, Configuration)} method
*/
boolean isInternalCache(String name);
/**
* Returns whether the cache is private, i.e. it has been registered using the
* {@link #registerInternalCache(String, Configuration, EnumSet<Flag>)} method without the
* {@link Flag#USER} flag
*/
boolean isPrivateCache(String name);
/**
* Retrieves the names of all the internal caches
*/
Set<String> getInternalCacheNames();
/**
* Removes the private caches from the specified set of cache names
*/
void filterPrivateCaches(Set<String> names);
/**
* Returns whether a particular internal cache has a specific flag
*
* @param name the name of the internal cache
* @param flag the flag to check
* @return true if the internal cache has the flag, false otherwise
*/
boolean internalCacheHasFlag(String name, Flag flag);
}
| 3,040
| 27.157407
| 105
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/registry/impl/InternalCacheRegistryImpl.java
|
package org.infinispan.registry.impl;
import static org.infinispan.util.logging.Log.CONFIG;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.infinispan.Cache;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* InternalCacheRegistryImpl.
*
* @author Tristan Tarrant
* @since 7.2
*/
@Scope(Scopes.GLOBAL)
public class InternalCacheRegistryImpl implements InternalCacheRegistry {
private static final Log log = LogFactory.getLog(InternalCacheRegistryImpl.class);
@Inject EmbeddedCacheManager cacheManager;
@Inject CacheManagerJmxRegistration cacheManagerJmxRegistration;
@Inject ConfigurationManager configurationManager;
@Inject GlobalConfiguration globalConfiguration;
private final ConcurrentMap<String, EnumSet<Flag>> internalCaches = new ConcurrentHashMap<>();
private final Set<String> privateCaches = ConcurrentHashMap.newKeySet();
@Override
public void registerInternalCache(String name, Configuration configuration) {
registerInternalCache(name, configuration, EnumSet.noneOf(Flag.class));
}
// Synchronized to prevent users from registering the same configuration at the same time
@Override
public synchronized void registerInternalCache(String name, Configuration configuration, EnumSet<Flag> flags) {
log.debugf("Registering internal cache %s %s", name, flags);
boolean configPresent = configurationManager.getConfiguration(name, false) != null;
// check if it already has been defined. Currently we don't support existing user-defined configuration.
if ((flags.contains(Flag.EXCLUSIVE) || !internalCaches.containsKey(name)) && configPresent) {
throw CONFIG.existingConfigForInternalCache(name);
}
// Don't redefine
if (configPresent) {
return;
}
ConfigurationBuilder builder = new ConfigurationBuilder().read(configuration, Combine.DEFAULT);
builder.statistics().disable(); // Internal caches must not be included in stats counts
if (flags.contains(Flag.GLOBAL) && globalConfiguration.isClustered()) {
// TODO: choose a merge policy
builder.clustering()
.cacheMode(CacheMode.REPL_SYNC)
.stateTransfer().fetchInMemoryState(true).awaitInitialTransfer(true);
}
if (flags.contains(Flag.PERSISTENT)) {
if (globalConfiguration.globalState().enabled()) {
builder.persistence()
.availabilityInterval(-1)
.addSingleFileStore()
.location(globalConfiguration.globalState().persistentLocation())
// Internal caches don't need to be segmented
.segmented(false)
.purgeOnStartup(false)
.preload(true)
.fetchPersistentState(true);
} else {
CONFIG.warnUnableToPersistInternalCaches();
}
}
SecurityActions.defineConfiguration(cacheManager, name, builder.build());
internalCaches.put(name, flags);
if (!flags.contains(Flag.USER)) {
privateCaches.add(name);
}
}
@Override
public synchronized void unregisterInternalCache(String name) {
log.debugf("Unregistering internal cache %s", name);
if (isInternalCache(name)) {
Cache<Object, Object> cache = cacheManager.getCache(name, false);
if (cache != null) {
cache.stop();
}
internalCaches.remove(name);
privateCaches.remove(name);
SecurityActions.undefineConfiguration(cacheManager, name);
}
}
@Override
public boolean isInternalCache(String name) {
return internalCaches.containsKey(name);
}
@Override
public boolean isPrivateCache(String name) {
return privateCaches.contains(name);
}
@Override
public Set<String> getInternalCacheNames() {
return internalCaches.keySet();
}
@Override
public void filterPrivateCaches(Set<String> names) {
names.removeAll(privateCaches);
}
@Override
public boolean internalCacheHasFlag(String name, Flag flag) {
EnumSet<Flag> flags = internalCaches.get(name);
return flags != null && flags.contains(flag);
}
@Override
public void startInternalCaches() {
log.debugf("Starting internal caches: %s", internalCaches.keySet());
for (String cacheName : internalCaches.keySet()) {
SecurityActions.getCache(cacheManager, cacheName);
}
}
}
| 5,328
| 36.794326
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/TopologyAffectedCommand.java
|
package org.infinispan.commands;
/**
* Some of the commands sent over the wire can only be honored by the receiver if the topology of the cluster at
* delivery time is still 'compatible' with the topology in place at send time (eg. a 'get' command cannot execute
* on a node that is no longer owner after state transfer took place). These commands need to be tagged with
* the current topology id of the sender so the receiver can detect and handle topology mismatches.
*
* @author anistor@redhat.com
* @since 5.2
*/
public interface TopologyAffectedCommand extends ReplicableCommand {
int getTopologyId();
void setTopologyId(int topologyId);
}
| 662
| 35.833333
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/Visitor.java
|
package org.infinispan.commands;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.functional.ReadOnlyKeyCommand;
import org.infinispan.commands.functional.ReadOnlyManyCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.read.EntrySetCommand;
import org.infinispan.commands.read.GetAllCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.read.KeySetCommand;
import org.infinispan.commands.read.SizeCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.EvictCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.InvalidateL1Command;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.RemoveExpiredCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.expiration.impl.TouchCommand;
/**
* @author Mircea.Markus@jboss.com
* @author Galder Zamarreño
* @since 4.0
*/
public interface Visitor {
// write commands
Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable;
Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable;
Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable;
Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable;
Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable;
Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable;
Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable;
Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable;
default Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) throws Throwable {
return visitRemoveCommand(ctx, command);
}
Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) throws Throwable;
// read commands
Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable;
Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable;
Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable;
Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable;
Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable;
Object visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) throws Throwable;
// tx commands
Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable;
Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) throws Throwable;
Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable;
Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand invalidateCommand) throws Throwable;
Object visitInvalidateL1Command(InvocationContext ctx, InvalidateL1Command invalidateL1Command) throws Throwable;
// locking commands
Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable;
/**
* @deprecated since 11.0 will be removed in the next major version with no direct replacement. There is no reason
* that a unknown command should be passed through the interceptor chain.
*/
@Deprecated
Object visitUnknownCommand(InvocationContext ctx, VisitableCommand command) throws Throwable;
Object visitReadOnlyKeyCommand(InvocationContext ctx, ReadOnlyKeyCommand command) throws Throwable;
Object visitReadOnlyManyCommand(InvocationContext ctx, ReadOnlyManyCommand command) throws Throwable;
Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) throws Throwable;
Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) throws Throwable;
Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable;
Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) throws Throwable;
Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) throws Throwable;
Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) throws Throwable;
Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) throws Throwable;
Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) throws Throwable;
Object visitTouchCommand(InvocationContext ctx, TouchCommand command) throws Throwable;
}
| 6,046
| 46.242188
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/package-info.java
|
/**
* Commands that operate on the cache, either locally or remotely. This package contains the entire command object
* model including interfaces and abstract classes. Your starting point is probably {@link ReplicableCommand}, which
* represents a command that can be used in RPC calls.
* <p />
* A sub-interface, {@link VisitableCommand}, represents commands that can be visited using the <a href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a>.
* Most commands that relate to public {@link Cache} API methods tend to be {@link VisitableCommand}s, and hence the
* importance of this interface.
* <p />
* The {@link Visitor} interface is capable of visiting {@link VisitableCommand}s, and a useful abstract implementation
* of {@link Visitor} is {@link org.infinispan.interceptors.base.CommandInterceptor}, which allows you to create
* interceptors that intercept command invocations adding aspects of behavior to a given invocation.
*
* @author Manik Surtani
* @since 4.0
*/
package org.infinispan.commands;
| 1,046
| 57.166667
| 171
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/InitializableCommand.java
|
package org.infinispan.commands;
import org.infinispan.factories.ComponentRegistry;
/**
* An interface to be implemented by Commands which require an intialized state after deserialization.
*
* @author Ryan Emerson
* @since 10.0
* @deprecated since 11.0, please implement {@link ReplicableCommand#invokeAsync(ComponentRegistry)} instead
*/
@Deprecated
public interface InitializableCommand {
void init(ComponentRegistry componentRegistry, boolean isRemote);
}
| 473
| 25.333333
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/GlobalRpcCommand.java
|
package org.infinispan.commands;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.GlobalComponentRegistry;
/**
* Commands correspond to specific areas of functionality in the cluster, and can be replicated using the {@link
* org.infinispan.remoting.inboundhandler.GlobalInboundInvocationHandler}.
*
* Implementations of this interface must not rely on calls to {@link GlobalComponentRegistry#wireDependencies(Object)},
* as {@code @Inject} annotations on implementations will be ignored, components must be accessed via the
* {@link GlobalComponentRegistry} parameter of {@link #invokeAsync(GlobalComponentRegistry)}.
*
* @author Ryan Emerson
* @since 11.0
*/
public interface GlobalRpcCommand extends ReplicableCommand {
/**
* Invoke the command asynchronously.
*/
default CompletionStage<?> invokeAsync(GlobalComponentRegistry globalComponentRegistry) throws Throwable {
return invokeAsync();
}
}
| 963
| 36.076923
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/AbstractFlagAffectedCommand.java
|
package org.infinispan.commands;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.context.Flag;
/**
* Base class for those commands that can carry flags.
*
* @author Galder Zamarreño
* @since 5.1
*/
public abstract class AbstractFlagAffectedCommand implements FlagAffectedCommand {
private long flags = 0;
@Override
public long getFlagsBitSet() {
return flags;
}
@Override
public void setFlagsBitSet(long bitSet) {
this.flags = bitSet;
}
protected final boolean hasSameFlags(FlagAffectedCommand other) {
return this.flags == other.getFlagsBitSet();
}
protected final String printFlags() {
return EnumUtil.prettyPrintBitSet(flags, Flag.class);
}
}
| 734
| 20.617647
| 82
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/LocalCommand.java
|
package org.infinispan.commands;
/**
* This is a marker interface to indicate that such commands will never be replicated and hence will not return any
* valid command IDs.
*
* @author Manik Surtani
* @since 4.0
*/
public interface LocalCommand {
}
| 256
| 20.416667
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/AbstractTopologyAffectedCommand.java
|
package org.infinispan.commands;
/**
* Base class for commands that carry topology id.
*
* @author Galder Zamarreño
* @since 5.1
*/
public abstract class AbstractTopologyAffectedCommand extends AbstractFlagAffectedCommand implements TopologyAffectedCommand {
private int topologyId = -1;
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
}
| 479
| 19
| 126
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/DataCommand.java
|
package org.infinispan.commands;
/**
* Commands of this type manipulate data in the cache.
*
* @author Mircea.Markus@jboss.com
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public interface DataCommand extends VisitableCommand, TopologyAffectedCommand, FlagAffectedCommand, SegmentSpecificCommand {
Object getKey();
}
| 378
| 26.071429
| 125
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/CommandInvocationId.java
|
package org.infinispan.commands;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.remoting.transport.Address;
/**
* Represents an unique identified for non-transaction write commands.
* <p>
* It is used to lock the key for a specific command.
* <p>
* This class is final to prevent issues as it is usually not marshalled
* as polymorphic object but directly using {@link #writeTo(ObjectOutput, CommandInvocationId)}
* and {@link #readFrom(ObjectInput)}.
*
* @author Pedro Ruivo
* @since 8.0
*/
public final class CommandInvocationId {
public static final CommandInvocationId DUMMY_INVOCATION_ID = new CommandInvocationId(null, 0);
public static final AbstractExternalizer<CommandInvocationId> EXTERNALIZER = new Externalizer();
private static final AtomicLong nextId = new AtomicLong(0);
private final Address address;
private final long id;
private CommandInvocationId(Address address, long id) {
this.address = address;
this.id = id;
}
public static CommandInvocationId generateId(Address address) {
return new CommandInvocationId(address, nextId.getAndIncrement());
}
public static CommandInvocationId generateIdFrom(CommandInvocationId commandInvocationId) {
return new CommandInvocationId(commandInvocationId.address, nextId.getAndIncrement());
}
public static void writeTo(ObjectOutput output, CommandInvocationId commandInvocationId) throws IOException {
output.writeObject(commandInvocationId.address);
output.writeLong(commandInvocationId.id);
}
public static CommandInvocationId readFrom(ObjectInput input) throws ClassNotFoundException, IOException {
Address address = (Address) input.readObject();
long id = input.readLong();
return new CommandInvocationId(address, id);
}
public long getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CommandInvocationId that = (CommandInvocationId) o;
return id == that.id && Objects.equals(address, that.address);
}
public Address getAddress() {
return address;
}
@Override
public int hashCode() {
int result = address != null ? address.hashCode() : 0;
result = 31 * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public String toString() {
return "CommandInvocation:" + Objects.toString(address, "local") + ":" + id;
}
public static String show(CommandInvocationId id) {
return id == DUMMY_INVOCATION_ID ? "" : id.toString();
}
private static class Externalizer extends AbstractExternalizer<CommandInvocationId> {
@Override
public Set<Class<? extends CommandInvocationId>> getTypeClasses() {
return Collections.singleton(CommandInvocationId.class);
}
@Override
public Integer getId() {
return Ids.COMMAND_INVOCATION_ID;
}
@Override
public void writeObject(ObjectOutput output, CommandInvocationId object) throws IOException {
writeTo(output, object);
}
@Override
public CommandInvocationId readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return readFrom(input);
}
}
}
| 3,648
| 28.909836
| 112
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/CommandsFactory.java
|
package org.infinispan.commands;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.functional.Mutation;
import org.infinispan.commands.functional.ReadOnlyKeyCommand;
import org.infinispan.commands.functional.ReadOnlyManyCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.TxReadOnlyKeyCommand;
import org.infinispan.commands.functional.TxReadOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.irac.IracCleanupKeysCommand;
import org.infinispan.commands.irac.IracClearKeysCommand;
import org.infinispan.commands.irac.IracMetadataRequestCommand;
import org.infinispan.commands.irac.IracPutManyCommand;
import org.infinispan.commands.irac.IracRequestStateCommand;
import org.infinispan.commands.irac.IracStateResponseCommand;
import org.infinispan.commands.irac.IracTombstoneCleanupCommand;
import org.infinispan.commands.irac.IracTombstonePrimaryCheckCommand;
import org.infinispan.commands.irac.IracTombstoneRemoteSiteCheckCommand;
import org.infinispan.commands.irac.IracTombstoneStateResponseCommand;
import org.infinispan.commands.irac.IracTouchKeyCommand;
import org.infinispan.commands.irac.IracUpdateVersionCommand;
import org.infinispan.commands.read.EntrySetCommand;
import org.infinispan.commands.read.GetAllCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.read.KeySetCommand;
import org.infinispan.commands.read.SizeCommand;
import org.infinispan.commands.remote.CheckTransactionRpcCommand;
import org.infinispan.commands.remote.ClusteredGetAllCommand;
import org.infinispan.commands.remote.ClusteredGetCommand;
import org.infinispan.commands.remote.SingleRpcCommand;
import org.infinispan.commands.remote.recovery.CompleteTransactionCommand;
import org.infinispan.commands.remote.recovery.GetInDoubtTransactionsCommand;
import org.infinispan.commands.remote.recovery.GetInDoubtTxInfoCommand;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.statetransfer.ConflictResolutionStartCommand;
import org.infinispan.commands.statetransfer.StateResponseCommand;
import org.infinispan.commands.statetransfer.StateTransferCancelCommand;
import org.infinispan.commands.statetransfer.StateTransferGetListenersCommand;
import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.commands.triangle.BackupNoopCommand;
import org.infinispan.commands.triangle.MultiEntriesFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.MultiKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.PutMapBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.VersionedCommitCommand;
import org.infinispan.commands.tx.VersionedPrepareCommand;
import org.infinispan.commands.write.BackupAckCommand;
import org.infinispan.commands.write.BackupMultiKeyAckCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.EvictCommand;
import org.infinispan.commands.write.ExceptionAckCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.RemoveExpiredCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.IntSet;
import org.infinispan.configuration.cache.XSiteStateTransferMode;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.versioning.irac.IracEntryVersion;
import org.infinispan.container.versioning.irac.IracTombstoneInfo;
import org.infinispan.encoding.DataConversion;
import org.infinispan.expiration.impl.TouchCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.impl.Params;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.notifications.cachelistener.cluster.ClusterEvent;
import org.infinispan.notifications.cachelistener.cluster.MultiClusterEventCommand;
import org.infinispan.reactive.publisher.impl.DeliveryGuarantee;
import org.infinispan.reactive.publisher.impl.commands.batch.CancelPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.batch.InitialPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.batch.NextPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.reduction.ReductionPublisherRequestCommand;
import org.infinispan.remoting.transport.Address;
import org.infinispan.statetransfer.StateChunk;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.xsite.SingleXSiteRpcCommand;
import org.infinispan.xsite.commands.XSiteAmendOfflineStatusCommand;
import org.infinispan.xsite.commands.XSiteAutoTransferStatusCommand;
import org.infinispan.xsite.commands.XSiteBringOnlineCommand;
import org.infinispan.xsite.commands.XSiteOfflineStatusCommand;
import org.infinispan.xsite.commands.XSiteSetStateTransferModeCommand;
import org.infinispan.xsite.commands.XSiteStateTransferCancelSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferClearStatusCommand;
import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferFinishSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferRestartSendingCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStatusRequestCommand;
import org.infinispan.xsite.commands.XSiteStatusCommand;
import org.infinispan.xsite.commands.XSiteTakeOfflineCommand;
import org.infinispan.xsite.irac.IracManagerKeyInfo;
import org.infinispan.xsite.statetransfer.XSiteState;
import org.infinispan.xsite.statetransfer.XSiteStatePushCommand;
import org.reactivestreams.Publisher;
/**
* A factory to build commands, initializing and injecting dependencies accordingly. Commands built for a specific,
* named cache instance cannot be reused on a different cache instance since most commands contain the cache name it was
* built for along with references to other named-cache scoped components.
* <p>
* Commands returned by the various build*Command methods should be initialised sufficiently for local execution via the
* interceptor chain, with no calls to {@link #initializeReplicableCommand(ReplicableCommand, boolean)} required.
* However, for remote execution, it's assumed that a command will be initialized via {@link
* #initializeReplicableCommand(ReplicableCommand, boolean)} before being invoked.
* <p>
* Note, {@link InitializableCommand} implementations should not rely on access to the {@link
* org.infinispan.factories.ComponentRegistry} in their constructors for local execution initialization as this leads to
* duplicated code. Instead implementations of this interface should call {@link InitializableCommand#init(ComponentRegistry,
* boolean)} before returning the created command.
*
* @author Manik Surtani
* @author Mircea.Markus@jboss.com
* @author Galder Zamarreño
* @since 4.0
*/
@Scope(Scopes.NAMED_CACHE)
public interface CommandsFactory {
/**
* Builds a PutKeyValueCommand
* @param key key to put
* @param value value to put
* @param segment the segment of the given key
* @param metadata metadata of entry
* @param flagsBitSet Command flags provided by cache
* @return a PutKeyValueCommand
*/
default PutKeyValueCommand buildPutKeyValueCommand(Object key, Object value, int segment, Metadata metadata, long flagsBitSet) {
return buildPutKeyValueCommand(key, value, segment, metadata, flagsBitSet, false);
}
PutKeyValueCommand buildPutKeyValueCommand(Object key, Object value, int segment, Metadata metadata,
long flagsBitSet, boolean returnEntry);
/**
* Builds a RemoveCommand
* @param key key to remove
* @param value value to check for ina conditional remove, or null for an unconditional remove.
* @param segment the segment of the given key
* @param flagsBitSet Command flags provided by cache
* @return a RemoveCommand
*/
default RemoveCommand buildRemoveCommand(Object key, Object value, int segment, long flagsBitSet) {
return buildRemoveCommand(key, value, segment, flagsBitSet, false);
}
RemoveCommand buildRemoveCommand(Object key, Object value, int segment, long flagsBitSet, boolean returnEntry);
/**
* Builds an InvalidateCommand
* @param flagsBitSet Command flags provided by cache
* @param keys keys to invalidate
* @return an InvalidateCommand
*/
InvalidateCommand buildInvalidateCommand(long flagsBitSet, Object... keys);
/**
* Builds an InvalidateFromL1Command
*
* @param flagsBitSet Command flags provided by cache
* @param keys keys to invalidate
* @return an InvalidateFromL1Command
*/
InvalidateCommand buildInvalidateFromL1Command(long flagsBitSet, Collection<Object> keys);
/**
* @see #buildInvalidateFromL1Command(long, Collection)
*/
InvalidateCommand buildInvalidateFromL1Command(Address origin, long flagsBitSet, Collection<Object> keys);
/**
* Builds an expired remove command that is used to remove only a specific entry when it expires via lifespan
* @param key the key of the expired entry
* @param value the value of the entry when it was expired
* @param segment the segment of the given key
* @param lifespan the lifespan that expired from the command
* @param flagsBitSet Command flags provided by cache
* @return a RemovedExpiredCommand
*/
RemoveExpiredCommand buildRemoveExpiredCommand(Object key, Object value, int segment, Long lifespan, long flagsBitSet);
/**
* Builds an expired remove command that is used to remove only a specific entry when it expires via maxIdle
* @param key the key of the expired entry
* @param value the value of the entry when it was expired
* @param segment the segment of the given key
* @param flagsBitSet Command flags provided by cache
* @return a RemovedExpiredCommand
*/
RemoveExpiredCommand buildRemoveExpiredCommand(Object key, Object value, int segment, long flagsBitSet);
/**
* Builds a ReplaceCommand
* @param key key to replace
* @param oldValue existing value to check for if conditional, null if unconditional.
* @param newValue value to replace with
* @param segment the segment of the given key
* @param metadata metadata of entry
* @param flagsBitSet Command flags provided by cache
* @return a ReplaceCommand
*/
default ReplaceCommand buildReplaceCommand(Object key, Object oldValue, Object newValue, int segment, Metadata metadata,
long flagsBitSet) {
return buildReplaceCommand(key, oldValue, newValue, segment, metadata, flagsBitSet, false);
}
/**
* Builds a ReplaceCommand
*
* @param key key to replace
* @param oldValue existing value to check for if conditional, null if unconditional.
* @param newValue value to replace with
* @param segment the segment of the given key
* @param metadata metadata of entry
* @param flagsBitSet Command flags provided by cache
* @param returnEntry true if the {@link CacheEntry} is the command response, otherwise returns previous value.
* @return a ReplaceCommand
*/
ReplaceCommand buildReplaceCommand(Object key, Object oldValue, Object newValue, int segment, Metadata metadata,
long flagsBitSet, boolean returnEntry);
/**
* Builds a ComputeCommand
* @param key key to compute if this key is absent
* @param mappingFunction BiFunction for the key and the value
* @param computeIfPresent flag to apply as computeIfPresent mode
* @param segment the segment of the given key
* @param metadata metadata of entry
* @param flagsBitSet Command flags provided by cache
* @return a ComputeCommand
*/
ComputeCommand buildComputeCommand(Object key, BiFunction mappingFunction, boolean computeIfPresent, int segment,
Metadata metadata, long flagsBitSet);
/**
* Builds a ComputeIfAbsentCommand
* @param key key to compute if this key is absent
* @param mappingFunction mappingFunction for the key
* @param segment the segment of the given key
* @param metadata metadata of entry
* @param flagsBitSet Command flags provided by cache
* @return a ComputeCommand
*/
ComputeIfAbsentCommand buildComputeIfAbsentCommand(Object key, Function mappingFunction, int segment,
Metadata metadata, long flagsBitSet);
/**
* Builds a SizeCommand
* @param flagsBitSet Command flags provided by cache
* @return a SizeCommand
*/
SizeCommand buildSizeCommand(IntSet segments, long flagsBitSet);
/**
* Builds a GetKeyValueCommand
* @param key key to get
* @param segment the segment of the given key
* @param flagsBitSet Command flags provided by cache
* @return a GetKeyValueCommand
*/
GetKeyValueCommand buildGetKeyValueCommand(Object key, int segment, long flagsBitSet);
/**
* Builds a GetCacheEntryCommand
* @param key key to get
* @param segment the segment for the key
* @param flagsBitSet Command flags provided by cache
* @return a GetCacheEntryCommand
*/
GetCacheEntryCommand buildGetCacheEntryCommand(Object key, int segment, long flagsBitSet);
/**
* Builds a GetAllCommand
* @param keys keys to get
* @param flagsBitSet Command flags provided by cache
* @param returnEntries boolean indicating whether entire cache entries are
* returned, otherwise return just the value parts
* @return a GetKeyValueCommand
*/
GetAllCommand buildGetAllCommand(Collection<?> keys, long flagsBitSet, boolean returnEntries);
/**
* Builds a KeySetCommand
* @param flagsBitSet Command flags provided by cache
* @return a KeySetCommand
*/
KeySetCommand buildKeySetCommand(long flagsBitSet);
/**
* Builds a EntrySetCommand
* @param flagsBitSet Command flags provided by cache
* @return a EntrySetCommand
*/
EntrySetCommand buildEntrySetCommand(long flagsBitSet);
/**
* Builds a PutMapCommand
* @param map map containing key/value entries to put
* @param metadata metadata of entry
* @param flagsBitSet Command flags provided by cache
* @return a PutMapCommand
*/
PutMapCommand buildPutMapCommand(Map<?, ?> map, Metadata metadata, long flagsBitSet);
/**
* Builds a ClearCommand
* @param flagsBitSet Command flags provided by cache
* @return a ClearCommand
*/
ClearCommand buildClearCommand(long flagsBitSet);
/**
* Builds an EvictCommand
* @param key key to evict
* @param segment the segment for the key
* @param flagsBitSet Command flags provided by cache
* @return an EvictCommand
*/
EvictCommand buildEvictCommand(Object key, int segment, long flagsBitSet);
/**
* Builds a PrepareCommand
* @param gtx global transaction associated with the prepare
* @param modifications list of modifications
* @param onePhaseCommit is this a one-phase or two-phase transaction?
* @return a PrepareCommand
*/
PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhaseCommit);
/**
* Builds a VersionedPrepareCommand
*
* @param gtx global transaction associated with the prepare
* @param modifications list of modifications
* @param onePhase
* @return a VersionedPrepareCommand
*/
VersionedPrepareCommand buildVersionedPrepareCommand(GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhase);
/**
* Builds a CommitCommand
* @param gtx global transaction associated with the commit
* @return a CommitCommand
*/
CommitCommand buildCommitCommand(GlobalTransaction gtx);
/**
* Builds a VersionedCommitCommand
* @param gtx global transaction associated with the commit
* @return a VersionedCommitCommand
*/
VersionedCommitCommand buildVersionedCommitCommand(GlobalTransaction gtx);
/**
* Builds a RollbackCommand
* @param gtx global transaction associated with the rollback
* @return a RollbackCommand
*/
RollbackCommand buildRollbackCommand(GlobalTransaction gtx);
/**
* Initializes a {@link org.infinispan.commands.ReplicableCommand} read from a data stream with components specific
* to the target cache instance.
* <p/>
* Implementations should also be deep, in that if the command contains other commands, these should be recursed
* into.
* <p/>
*
* @param command command to initialize. Cannot be null.
* @param isRemote
* @deprecated since 11.0, please use {@link org.infinispan.commands.remote.CacheRpcCommand#invokeAsync(ComponentRegistry)}
* or {@link GlobalRpcCommand#invokeAsync(GlobalComponentRegistry)} instead.
* to access any components required at invocation time.
*/
@Deprecated
void initializeReplicableCommand(ReplicableCommand command, boolean isRemote);
/**
* Builds a SingleRpcCommand "envelope" containing a single ReplicableCommand
* @param call ReplicableCommand to include in the envelope
* @return a SingleRpcCommand
* @deprecated since 11.0 use {@link #buildSingleRpcCommand(VisitableCommand)} instead.
*/
@Deprecated
default SingleRpcCommand buildSingleRpcCommand(ReplicableCommand call) {
return buildSingleRpcCommand((VisitableCommand) call);
}
/**
* Builds a SingleRpcCommand "envelope" containing a single ReplicableCommand
* @param command VisitableCommand to include in the envelope
* @return a SingleRpcCommand
*/
SingleRpcCommand buildSingleRpcCommand(VisitableCommand command);
/**
* Builds a ClusteredGetCommand, which is a remote lookup command
* @param key key to look up
* @param segment the segment for the key or null if it should be computed on the remote node
* @param flagsBitSet Command flags provided by cache
* @return a ClusteredGetCommand
*/
ClusteredGetCommand buildClusteredGetCommand(Object key, Integer segment, long flagsBitSet);
/**
* Builds a ClusteredGetAllCommand, which is a remote lookup command
* @param keys key to look up
* @param flagsBitSet Command flags provided by cache
* @return a ClusteredGetAllCommand
*/
ClusteredGetAllCommand buildClusteredGetAllCommand(List<?> keys, long flagsBitSet, GlobalTransaction gtx);
/**
* Builds a LockControlCommand to control explicit remote locking
*
* @param keys keys to lock
* @param flagsBitSet Command flags provided by cache
* @param gtx
* @return a LockControlCommand
*/
LockControlCommand buildLockControlCommand(Collection<?> keys, long flagsBitSet, GlobalTransaction gtx);
/**
* Same as {@link #buildLockControlCommand(Collection, long, GlobalTransaction)}
* but for locking a single key vs a collection of keys.
*/
LockControlCommand buildLockControlCommand(Object key, long flagsBitSet, GlobalTransaction gtx);
LockControlCommand buildLockControlCommand(Collection<?> keys, long flagsBitSet);
ConflictResolutionStartCommand buildConflictResolutionStartCommand(int topologyId, IntSet segments);
StateTransferCancelCommand buildStateTransferCancelCommand(int topologyId, IntSet segments);
StateTransferGetListenersCommand buildStateTransferGetListenersCommand(int topologyId);
StateTransferGetTransactionsCommand buildStateTransferGetTransactionsCommand(int topologyId, IntSet segments);
StateTransferStartCommand buildStateTransferStartCommand(int topologyId, IntSet segments);
/**
* Builds a StateResponseCommand used for pushing cache entries to another node.
*/
StateResponseCommand buildStateResponseCommand(int viewId, Collection<StateChunk> stateChunks, boolean applyState);
/**
* Retrieves the cache name this CommandFactory is set up to construct commands for.
* @return the name of the cache this CommandFactory is set up to construct commands for.
*/
String getCacheName();
/**
* Builds a {@link org.infinispan.commands.remote.recovery.GetInDoubtTransactionsCommand}.
*/
GetInDoubtTransactionsCommand buildGetInDoubtTransactionsCommand();
/**
* Builds a {@link org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand}.
*/
TxCompletionNotificationCommand buildTxCompletionNotificationCommand(XidImpl xid, GlobalTransaction globalTransaction);
/**
* @see GetInDoubtTxInfoCommand
*/
GetInDoubtTxInfoCommand buildGetInDoubtTxInfoCommand();
/**
* Builds a CompleteTransactionCommand command.
* @param xid the xid identifying the transaction we want to complete.
* @param commit commit(true) or rollback(false)?
*/
CompleteTransactionCommand buildCompleteTransactionCommand(XidImpl xid, boolean commit);
/**
* @param internalId the internal id identifying the transaction to be removed.
* @see org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand
*/
TxCompletionNotificationCommand buildTxCompletionNotificationCommand(long internalId);
XSiteStateTransferCancelSendCommand buildXSiteStateTransferCancelSendCommand(String siteName);
XSiteStateTransferClearStatusCommand buildXSiteStateTransferClearStatusCommand();
XSiteStateTransferFinishReceiveCommand buildXSiteStateTransferFinishReceiveCommand(String siteName);
XSiteStateTransferFinishSendCommand buildXSiteStateTransferFinishSendCommand(String siteName, boolean statusOk);
XSiteStateTransferRestartSendingCommand buildXSiteStateTransferRestartSendingCommand(String siteName, int topologyId);
XSiteStateTransferStartReceiveCommand buildXSiteStateTransferStartReceiveCommand();
XSiteStateTransferStartSendCommand buildXSiteStateTransferStartSendCommand(String siteName, int topologyId);
XSiteStateTransferStatusRequestCommand buildXSiteStateTransferStatusRequestCommand();
XSiteAmendOfflineStatusCommand buildXSiteAmendOfflineStatusCommand(String siteName, Integer afterFailures, Long minTimeToWait);
XSiteBringOnlineCommand buildXSiteBringOnlineCommand(String siteName);
XSiteOfflineStatusCommand buildXSiteOfflineStatusCommand(String siteName);
XSiteStatusCommand buildXSiteStatusCommand();
XSiteTakeOfflineCommand buildXSiteTakeOfflineCommand(String siteName);
/**
* Builds XSiteStatePushCommand used to transfer a single chunk of data between sites.
*
* @param chunk the data chunk
* @param timeoutMillis timeout in milliseconds, for the retries in the receiver site.
* @return the XSiteStatePushCommand created
*/
XSiteStatePushCommand buildXSiteStatePushCommand(XSiteState[] chunk, long timeoutMillis);
/**
* Builds SingleRpcCommand used to perform {@link org.infinispan.commands.VisitableCommand} on the backup site,
* @param command the visitable command.
* @return the SingleXSiteRpcCommand created
*/
SingleXSiteRpcCommand buildSingleXSiteRpcCommand(VisitableCommand command);
<K, V, R> ReadOnlyKeyCommand<K, V, R> buildReadOnlyKeyCommand(Object key, Function<ReadEntryView<K, V>, R> f,
int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, R> ReadOnlyManyCommand<K, V, R> buildReadOnlyManyCommand(Collection<?> keys, Function<ReadEntryView<K, V>, R> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V> WriteOnlyKeyCommand<K, V> buildWriteOnlyKeyCommand(
Object key, Consumer<WriteEntryView<K, V>> f, int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, T, R> ReadWriteKeyValueCommand<K, V, T, R> buildReadWriteKeyValueCommand(
Object key, Object argument, BiFunction<T, ReadWriteEntryView<K, V>, R> f, int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, R> ReadWriteKeyCommand<K, V, R> buildReadWriteKeyCommand(
Object key, Function<ReadWriteEntryView<K, V>, R> f, int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, T> WriteOnlyManyEntriesCommand<K, V, T> buildWriteOnlyManyEntriesCommand(
Map<?, ?> arguments, BiConsumer<T, WriteEntryView<K, V>> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, T> WriteOnlyKeyValueCommand<K, V, T> buildWriteOnlyKeyValueCommand(Object key, Object argument,
BiConsumer<T, WriteEntryView<K, V>> f, int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V> WriteOnlyManyCommand<K, V> buildWriteOnlyManyCommand(Collection<?> keys, Consumer<WriteEntryView<K, V>> f,
Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, R> ReadWriteManyCommand<K, V, R> buildReadWriteManyCommand(Collection<?> keys, Function<ReadWriteEntryView<K, V>, R> f,
Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, T, R> ReadWriteManyEntriesCommand<K, V, T, R> buildReadWriteManyEntriesCommand(Map<?, ?> entries, BiFunction<T, ReadWriteEntryView<K, V>, R> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion);
<K, V, R> TxReadOnlyKeyCommand<K, V, R> buildTxReadOnlyKeyCommand(Object key, Function<ReadEntryView<K, V>, R> f,
List<Mutation<K, V, ?>> mutations, int segment,
Params params, DataConversion keyDataConversion,
DataConversion valueDataConversion);
<K, V, R> TxReadOnlyManyCommand<K, V, R> buildTxReadOnlyManyCommand(Collection<?> keys, List<List<Mutation<K,V,?>>> mutations,
Params params, DataConversion keyDataConversion,
DataConversion valueDataConversion);
BackupAckCommand buildBackupAckCommand(long id, int topologyId);
BackupMultiKeyAckCommand buildBackupMultiKeyAckCommand(long id, int segment, int topologyId);
ExceptionAckCommand buildExceptionAckCommand(long id, Throwable throwable, int topologyId);
SingleKeyBackupWriteCommand buildSingleKeyBackupWriteCommand();
SingleKeyFunctionalBackupWriteCommand buildSingleKeyFunctionalBackupWriteCommand();
PutMapBackupWriteCommand buildPutMapBackupWriteCommand();
MultiEntriesFunctionalBackupWriteCommand buildMultiEntriesFunctionalBackupWriteCommand();
MultiKeyFunctionalBackupWriteCommand buildMultiKeyFunctionalBackupWriteCommand();
BackupNoopCommand buildBackupNoopCommand();
<K, R> ReductionPublisherRequestCommand<K> buildKeyReductionPublisherCommand(boolean parallelStream, DeliveryGuarantee deliveryGuarantee,
IntSet segments, Set<K> keys, Set<K> excludedKeys, long explicitFlags,
Function<? super Publisher<K>, ? extends CompletionStage<R>> transformer,
Function<? super Publisher<R>, ? extends CompletionStage<R>> finalizer);
<K, V, R> ReductionPublisherRequestCommand<K> buildEntryReductionPublisherCommand(boolean parallelStream, DeliveryGuarantee deliveryGuarantee,
IntSet segments, Set<K> keys, Set<K> excludedKeys, long explicitFlags,
Function<? super Publisher<CacheEntry<K, V>>, ? extends CompletionStage<R>> transformer,
Function<? super Publisher<R>, ? extends CompletionStage<R>> finalizer);
<K, I, R> InitialPublisherCommand<K, I, R> buildInitialPublisherCommand(String requestId, DeliveryGuarantee deliveryGuarantee,
int batchSize, IntSet segments, Set<K> keys, Set<K> excludedKeys, long explicitFlags, boolean entryStream,
boolean trackKeys, Function<? super Publisher<I>, ? extends Publisher<R>> transformer);
NextPublisherCommand buildNextPublisherCommand(String requestId);
CancelPublisherCommand buildCancelPublisherCommand(String requestId);
<K, V> MultiClusterEventCommand<K, V> buildMultiClusterEventCommand(Map<UUID, Collection<ClusterEvent<K, V>>> events);
CheckTransactionRpcCommand buildCheckTransactionRpcCommand(Collection<GlobalTransaction> globalTransactions);
TouchCommand buildTouchCommand(Object key, int segment, boolean touchEvenIfExpired, long flagBitSet);
IracClearKeysCommand buildIracClearKeysCommand();
IracCleanupKeysCommand buildIracCleanupKeyCommand(Collection<? extends IracManagerKeyInfo> state);
IracTombstoneCleanupCommand buildIracTombstoneCleanupCommand(int maxCapacity);
IracMetadataRequestCommand buildIracMetadataRequestCommand(int segment, IracEntryVersion versionSeen);
IracRequestStateCommand buildIracRequestStateCommand(IntSet segments);
IracStateResponseCommand buildIracStateResponseCommand(int capacity);
IracPutKeyValueCommand buildIracPutKeyValueCommand(Object key, int segment, Object value, Metadata metadata,
PrivateMetadata privateMetadata);
IracTouchKeyCommand buildIracTouchCommand(Object key);
IracUpdateVersionCommand buildIracUpdateVersionCommand(Map<Integer, IracEntryVersion> segmentsVersion);
XSiteAutoTransferStatusCommand buildXSiteAutoTransferStatusCommand(String site);
XSiteSetStateTransferModeCommand buildXSiteSetStateTransferModeCommand(String site, XSiteStateTransferMode mode);
IracTombstoneRemoteSiteCheckCommand buildIracTombstoneRemoteSiteCheckCommand(List<Object> keys);
IracTombstoneStateResponseCommand buildIracTombstoneStateResponseCommand(Collection<IracTombstoneInfo> state);
IracTombstonePrimaryCheckCommand buildIracTombstonePrimaryCheckCommand(Collection<IracTombstoneInfo> tombstones);
IracPutManyCommand buildIracPutManyCommand(int capacity);
}
| 32,423
| 47.25
| 239
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/FlagAffectedCommand.java
|
package org.infinispan.commands;
import java.util.Set;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.context.Flag;
import org.infinispan.context.impl.FlagBitSets;
/**
* Flags modify behavior of command such as whether or not to invoke certain commands remotely, check cache store etc.
*
* @author William Burns
* @author Sanne Grinovero
* @since 5.0
*/
public interface FlagAffectedCommand extends VisitableCommand {
/**
* @return The command flags - only valid to invoke after {@link #setFlags(java.util.Set)}. The set should
* not be modified directly, only via the {@link #setFlags(Set)}, {@link #addFlag(Flag)} and {@link
* #addFlags(Set)} methods.
*/
default Set<Flag> getFlags() {
return EnumUtil.enumSetOf(getFlagsBitSet(), Flag.class);
}
/**
* @return The command flags. Flags can be modified with {@link #setFlagsBitSet(long)}, {@link #addFlags(long)}
* and {@link #addFlags(Set)} methods.
*/
long getFlagsBitSet();
/**
* Set the flags, replacing any existing flags.
*
* @param flags The new flags.
* @deprecated Since 9.0, please use {@link #setFlagsBitSet(long)} instead.
*/
default void setFlags(Set<Flag> flags) {
setFlagsBitSet(EnumUtil.bitSetOf(flags));
}
/**
* Set the flags, replacing any existing flags.
*/
void setFlagsBitSet(long bitSet);
/**
* Add a single flag to the command.
*
* @param flag The flag to add.
*
* @deprecated Since 9.0, please use {@link #addFlags(long)} with a {@link FlagBitSets} constant instead.
*/
@Deprecated
default void addFlag(Flag flag) {
setFlagsBitSet(EnumUtil.setEnum(getFlagsBitSet(), flag));
}
/**
* Add a set of flags to the command.
*
* @param flags The flags to add.
*
* @deprecated Since 9.0, please use {@link #addFlags(long)} with a {@link FlagBitSets} constant instead.
*/
@Deprecated
default void addFlags(Set<Flag> flags) {
setFlagsBitSet(EnumUtil.setEnums(getFlagsBitSet(), flags));
}
/**
* Add a set of flags to the command.
*
* @param flagsBitSet The flags to add, usually a {@link FlagBitSets} constant (or combination thereof).
*/
default void addFlags(long flagsBitSet) {
setFlagsBitSet(EnumUtil.mergeBitSets(getFlagsBitSet(), flagsBitSet));
}
/**
* Check whether a particular flag is present in the command.
*
* @param flag to lookup in the command
* @return true if the flag is present
*
* @deprecated Since 9.0, please use {@link #hasAnyFlag(long)} with a {@link FlagBitSets} constant instead.
*/
@Deprecated
default boolean hasFlag(Flag flag) {
return EnumUtil.hasEnum(getFlagsBitSet(), flag);
}
/**
* Check whether any of the flags in the {@code flagsBitSet} parameter is present in the command.
*
* Should be used with the constants in {@link FlagBitSets}.
*/
default boolean hasAnyFlag(long flagsBitSet) {
return EnumUtil.containsAny(getFlagsBitSet(), flagsBitSet);
}
/**
* Check whether all of the flags in the {@code flagsBitSet} parameter are present in the command.
*
* Should be used with the constants in {@link FlagBitSets}.
*/
default boolean hasAllFlags(long flagBitSet) {
return EnumUtil.containsAll(getFlagsBitSet(), flagBitSet);
}
}
| 3,381
| 29.468468
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/RemoteCommandsFactory.java
|
package org.infinispan.commands;
import java.util.Map;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.functional.ReadOnlyKeyCommand;
import org.infinispan.commands.functional.ReadOnlyManyCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.TxReadOnlyKeyCommand;
import org.infinispan.commands.functional.TxReadOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.irac.IracCleanupKeysCommand;
import org.infinispan.commands.irac.IracClearKeysCommand;
import org.infinispan.commands.irac.IracMetadataRequestCommand;
import org.infinispan.commands.irac.IracPutManyCommand;
import org.infinispan.commands.irac.IracRequestStateCommand;
import org.infinispan.commands.irac.IracStateResponseCommand;
import org.infinispan.commands.irac.IracTombstoneCleanupCommand;
import org.infinispan.commands.irac.IracTombstonePrimaryCheckCommand;
import org.infinispan.commands.irac.IracTombstoneRemoteSiteCheckCommand;
import org.infinispan.commands.irac.IracTombstoneStateResponseCommand;
import org.infinispan.commands.irac.IracTouchKeyCommand;
import org.infinispan.commands.irac.IracUpdateVersionCommand;
import org.infinispan.commands.module.ModuleCommandFactory;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.read.SizeCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.remote.CheckTransactionRpcCommand;
import org.infinispan.commands.remote.ClusteredGetAllCommand;
import org.infinispan.commands.remote.ClusteredGetCommand;
import org.infinispan.commands.remote.SingleRpcCommand;
import org.infinispan.commands.remote.recovery.CompleteTransactionCommand;
import org.infinispan.commands.remote.recovery.GetInDoubtTransactionsCommand;
import org.infinispan.commands.remote.recovery.GetInDoubtTxInfoCommand;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.statetransfer.ConflictResolutionStartCommand;
import org.infinispan.commands.statetransfer.StateResponseCommand;
import org.infinispan.commands.statetransfer.StateTransferCancelCommand;
import org.infinispan.commands.statetransfer.StateTransferGetListenersCommand;
import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.commands.topology.CacheAvailabilityUpdateCommand;
import org.infinispan.commands.topology.CacheJoinCommand;
import org.infinispan.commands.topology.CacheLeaveCommand;
import org.infinispan.commands.topology.CacheShutdownCommand;
import org.infinispan.commands.topology.CacheShutdownRequestCommand;
import org.infinispan.commands.topology.CacheStatusRequestCommand;
import org.infinispan.commands.topology.RebalancePhaseConfirmCommand;
import org.infinispan.commands.topology.RebalancePolicyUpdateCommand;
import org.infinispan.commands.topology.RebalanceStartCommand;
import org.infinispan.commands.topology.RebalanceStatusRequestCommand;
import org.infinispan.commands.topology.TopologyUpdateCommand;
import org.infinispan.commands.topology.TopologyUpdateStableCommand;
import org.infinispan.commands.triangle.BackupNoopCommand;
import org.infinispan.commands.triangle.MultiEntriesFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.MultiKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.PutMapBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.VersionedCommitCommand;
import org.infinispan.commands.tx.VersionedPrepareCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.InvalidateL1Command;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.RemoveExpiredCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.expiration.impl.TouchCommand;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.manager.impl.ReplicableManagerFunctionCommand;
import org.infinispan.manager.impl.ReplicableRunnableCommand;
import org.infinispan.notifications.cachelistener.cluster.MultiClusterEventCommand;
import org.infinispan.reactive.publisher.impl.commands.batch.CancelPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.batch.InitialPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.batch.NextPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.reduction.ReductionPublisherRequestCommand;
import org.infinispan.topology.HeartBeatCommand;
import org.infinispan.util.ByteString;
import org.infinispan.xsite.SingleXSiteRpcCommand;
import org.infinispan.xsite.commands.XSiteAmendOfflineStatusCommand;
import org.infinispan.xsite.commands.XSiteAutoTransferStatusCommand;
import org.infinispan.xsite.commands.XSiteBringOnlineCommand;
import org.infinispan.xsite.commands.XSiteOfflineStatusCommand;
import org.infinispan.xsite.commands.XSiteSetStateTransferModeCommand;
import org.infinispan.xsite.commands.XSiteStateTransferCancelSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferClearStatusCommand;
import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferFinishSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferRestartSendingCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStatusRequestCommand;
import org.infinispan.xsite.commands.XSiteStatusCommand;
import org.infinispan.xsite.commands.XSiteTakeOfflineCommand;
import org.infinispan.xsite.commands.XSiteViewNotificationCommand;
import org.infinispan.xsite.statetransfer.XSiteStatePushCommand;
/**
* Specifically used to create un-initialized {@link org.infinispan.commands.ReplicableCommand}s from a byte stream.
* This is a {@link Scopes#GLOBAL} component and doesn't have knowledge of initializing a command by injecting
* cache-specific components into it.
*
* @author Manik Surtani
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
@Scope(Scopes.GLOBAL)
public class RemoteCommandsFactory {
@Inject EmbeddedCacheManager cacheManager;
@Inject GlobalComponentRegistry globalComponentRegistry;
@Inject @ComponentName(KnownComponentNames.MODULE_COMMAND_FACTORIES)
Map<Byte,ModuleCommandFactory> commandFactories;
/**
* Creates an un-initialized command. Un-initialized in the sense that parameters will be set, but any components
* specific to the cache in question will not be set.
*
* @param id id of the command
* @param type type of the command
* @return a replicable command
*/
public ReplicableCommand fromStream(byte id, byte type) {
ReplicableCommand command;
if (type == 0) {
switch (id) {
case PutKeyValueCommand.COMMAND_ID:
command = new PutKeyValueCommand();
break;
case PutMapCommand.COMMAND_ID:
command = new PutMapCommand();
break;
case RemoveCommand.COMMAND_ID:
command = new RemoveCommand();
break;
case ReplaceCommand.COMMAND_ID:
command = new ReplaceCommand();
break;
case ComputeCommand.COMMAND_ID:
command = new ComputeCommand();
break;
case ComputeIfAbsentCommand.COMMAND_ID:
command = new ComputeIfAbsentCommand();
break;
case GetKeyValueCommand.COMMAND_ID:
command = new GetKeyValueCommand();
break;
case ClearCommand.COMMAND_ID:
command = new ClearCommand();
break;
case InvalidateCommand.COMMAND_ID:
command = new InvalidateCommand();
break;
case InvalidateL1Command.COMMAND_ID:
command = new InvalidateL1Command();
break;
case GetCacheEntryCommand.COMMAND_ID:
command = new GetCacheEntryCommand();
break;
case ReadWriteKeyCommand.COMMAND_ID:
command = new ReadWriteKeyCommand<>();
break;
case ReadWriteKeyValueCommand.COMMAND_ID:
command = new ReadWriteKeyValueCommand<>();
break;
case ReadWriteManyCommand.COMMAND_ID:
command = new ReadWriteManyCommand<>();
break;
case ReadWriteManyEntriesCommand.COMMAND_ID:
command = new ReadWriteManyEntriesCommand<>();
break;
case WriteOnlyKeyCommand.COMMAND_ID:
command = new WriteOnlyKeyCommand<>();
break;
case WriteOnlyKeyValueCommand.COMMAND_ID:
command = new WriteOnlyKeyValueCommand<>();
break;
case WriteOnlyManyCommand.COMMAND_ID:
command = new WriteOnlyManyCommand<>();
break;
case WriteOnlyManyEntriesCommand.COMMAND_ID:
command = new WriteOnlyManyEntriesCommand<>();
break;
case RemoveExpiredCommand.COMMAND_ID:
command = new RemoveExpiredCommand();
break;
case ReplicableRunnableCommand.COMMAND_ID:
command = new ReplicableRunnableCommand();
break;
case ReplicableManagerFunctionCommand.COMMAND_ID:
command = new ReplicableManagerFunctionCommand();
break;
case ReadOnlyKeyCommand.COMMAND_ID:
command = new ReadOnlyKeyCommand();
break;
case ReadOnlyManyCommand.COMMAND_ID:
command = new ReadOnlyManyCommand<>();
break;
case TxReadOnlyKeyCommand.COMMAND_ID:
command = new TxReadOnlyKeyCommand<>();
break;
case TxReadOnlyManyCommand.COMMAND_ID:
command = new TxReadOnlyManyCommand<>();
break;
case HeartBeatCommand.COMMAND_ID:
command = HeartBeatCommand.INSTANCE;
break;
case CacheJoinCommand.COMMAND_ID:
command = new CacheJoinCommand();
break;
case CacheLeaveCommand.COMMAND_ID:
command = new CacheLeaveCommand();
break;
case RebalancePhaseConfirmCommand.COMMAND_ID:
command = new RebalancePhaseConfirmCommand();
break;
case RebalancePolicyUpdateCommand.COMMAND_ID:
command = new RebalancePolicyUpdateCommand();
break;
case RebalanceStartCommand.COMMAND_ID:
command = new RebalanceStartCommand();
break;
case RebalanceStatusRequestCommand.COMMAND_ID:
command = new RebalanceStatusRequestCommand();
break;
case CacheShutdownRequestCommand.COMMAND_ID:
command = new CacheShutdownRequestCommand();
break;
case CacheShutdownCommand.COMMAND_ID:
command = new CacheShutdownCommand();
break;
case TopologyUpdateCommand.COMMAND_ID:
command = new TopologyUpdateCommand();
break;
case CacheStatusRequestCommand.COMMAND_ID:
command = new CacheStatusRequestCommand();
break;
case TopologyUpdateStableCommand.COMMAND_ID:
command = new TopologyUpdateStableCommand();
break;
case CacheAvailabilityUpdateCommand.COMMAND_ID:
command = new CacheAvailabilityUpdateCommand();
break;
case IracPutKeyValueCommand.COMMAND_ID:
command = new IracPutKeyValueCommand();
break;
case TouchCommand.COMMAND_ID:
command = new TouchCommand();
break;
case XSiteViewNotificationCommand.COMMAND_ID:
command = new XSiteViewNotificationCommand();
break;
default:
throw new CacheException("Unknown command id " + id + "!");
}
} else {
ModuleCommandFactory mcf = commandFactories.get(id);
if (mcf != null)
return mcf.fromStream(id);
else
throw new CacheException("Unknown command id " + id + "!");
}
return command;
}
/**
* Resolve an {@link CacheRpcCommand} from the stream.
*
* @param id id of the command
* @param type type of command (whether internal or user defined)
* @param cacheName cache name at which this command is directed
* @return an instance of {@link CacheRpcCommand}
*/
public CacheRpcCommand fromStream(byte id, byte type, ByteString cacheName) {
CacheRpcCommand command;
if (type == 0) {
switch (id) {
case LockControlCommand.COMMAND_ID:
command = new LockControlCommand(cacheName);
break;
case PrepareCommand.COMMAND_ID:
command = new PrepareCommand(cacheName);
break;
case VersionedPrepareCommand.COMMAND_ID:
command = new VersionedPrepareCommand(cacheName);
break;
case CommitCommand.COMMAND_ID:
command = new CommitCommand(cacheName);
break;
case VersionedCommitCommand.COMMAND_ID:
command = new VersionedCommitCommand(cacheName);
break;
case RollbackCommand.COMMAND_ID:
command = new RollbackCommand(cacheName);
break;
case SingleRpcCommand.COMMAND_ID:
command = new SingleRpcCommand(cacheName);
break;
case ClusteredGetCommand.COMMAND_ID:
command = new ClusteredGetCommand(cacheName);
break;
case ConflictResolutionStartCommand.COMMAND_ID:
command = new ConflictResolutionStartCommand(cacheName);
break;
case StateTransferCancelCommand.COMMAND_ID:
command = new StateTransferCancelCommand(cacheName);
break;
case StateTransferStartCommand.COMMAND_ID:
command = new StateTransferStartCommand(cacheName);
break;
case StateTransferGetListenersCommand.COMMAND_ID:
command = new StateTransferGetListenersCommand(cacheName);
break;
case StateTransferGetTransactionsCommand.COMMAND_ID:
command = new StateTransferGetTransactionsCommand(cacheName);
break;
case StateResponseCommand.COMMAND_ID:
command = new StateResponseCommand(cacheName);
break;
case TxCompletionNotificationCommand.COMMAND_ID:
command = new TxCompletionNotificationCommand(cacheName);
break;
case GetInDoubtTransactionsCommand.COMMAND_ID:
command = new GetInDoubtTransactionsCommand(cacheName);
break;
case GetInDoubtTxInfoCommand.COMMAND_ID:
command = new GetInDoubtTxInfoCommand(cacheName);
break;
case CompleteTransactionCommand.COMMAND_ID:
command = new CompleteTransactionCommand(cacheName);
break;
case XSiteAmendOfflineStatusCommand.COMMAND_ID:
command = new XSiteAmendOfflineStatusCommand(cacheName);
break;
case XSiteBringOnlineCommand.COMMAND_ID:
command = new XSiteBringOnlineCommand(cacheName);
break;
case XSiteOfflineStatusCommand.COMMAND_ID:
command = new XSiteOfflineStatusCommand(cacheName);
break;
case XSiteStatusCommand.COMMAND_ID:
command = new XSiteStatusCommand(cacheName);
break;
case XSiteTakeOfflineCommand.COMMAND_ID:
command = new XSiteTakeOfflineCommand(cacheName);
break;
case XSiteStateTransferCancelSendCommand.COMMAND_ID:
command = new XSiteStateTransferCancelSendCommand(cacheName);
break;
case XSiteStateTransferClearStatusCommand.COMMAND_ID:
command = new XSiteStateTransferClearStatusCommand(cacheName);
break;
case XSiteStateTransferFinishReceiveCommand.COMMAND_ID:
command = new XSiteStateTransferFinishReceiveCommand(cacheName);
break;
case XSiteStateTransferFinishSendCommand.COMMAND_ID:
command = new XSiteStateTransferFinishSendCommand(cacheName);
break;
case XSiteStateTransferRestartSendingCommand.COMMAND_ID:
command = new XSiteStateTransferRestartSendingCommand(cacheName);
break;
case XSiteStateTransferStartReceiveCommand.COMMAND_ID:
command = new XSiteStateTransferStartReceiveCommand(cacheName);
break;
case XSiteStateTransferStartSendCommand.COMMAND_ID:
command = new XSiteStateTransferStartSendCommand(cacheName);
break;
case XSiteStateTransferStatusRequestCommand.COMMAND_ID:
command = new XSiteStateTransferStatusRequestCommand(cacheName);
break;
case XSiteStatePushCommand.COMMAND_ID:
command = new XSiteStatePushCommand(cacheName);
break;
case SingleXSiteRpcCommand.COMMAND_ID:
command = new SingleXSiteRpcCommand(cacheName);
break;
case ClusteredGetAllCommand.COMMAND_ID:
command = new ClusteredGetAllCommand(cacheName);
break;
case SingleKeyBackupWriteCommand.COMMAND_ID:
command = new SingleKeyBackupWriteCommand(cacheName);
break;
case SingleKeyFunctionalBackupWriteCommand.COMMAND_ID:
command = new SingleKeyFunctionalBackupWriteCommand(cacheName);
break;
case PutMapBackupWriteCommand.COMMAND_ID:
command = new PutMapBackupWriteCommand(cacheName);
break;
case MultiEntriesFunctionalBackupWriteCommand.COMMAND_ID:
command = new MultiEntriesFunctionalBackupWriteCommand(cacheName);
break;
case MultiKeyFunctionalBackupWriteCommand.COMMAND_ID:
command = new MultiKeyFunctionalBackupWriteCommand(cacheName);
break;
case BackupNoopCommand.COMMAND_ID:
command = new BackupNoopCommand(cacheName);
break;
case ReductionPublisherRequestCommand.COMMAND_ID:
command = new ReductionPublisherRequestCommand<>(cacheName);
break;
case MultiClusterEventCommand.COMMAND_ID:
command = new MultiClusterEventCommand<>(cacheName);
break;
case InitialPublisherCommand.COMMAND_ID:
command = new InitialPublisherCommand<>(cacheName);
break;
case NextPublisherCommand.COMMAND_ID:
command = new NextPublisherCommand(cacheName);
break;
case CancelPublisherCommand.COMMAND_ID:
command = new CancelPublisherCommand(cacheName);
break;
case CheckTransactionRpcCommand.COMMAND_ID:
command = new CheckTransactionRpcCommand(cacheName);
break;
case IracCleanupKeysCommand.COMMAND_ID:
command = new IracCleanupKeysCommand(cacheName);
break;
case IracMetadataRequestCommand.COMMAND_ID:
command = new IracMetadataRequestCommand(cacheName);
break;
case IracRequestStateCommand.COMMAND_ID:
command = new IracRequestStateCommand(cacheName);
break;
case IracStateResponseCommand.COMMAND_ID:
command = new IracStateResponseCommand(cacheName);
break;
case IracClearKeysCommand.COMMAND_ID:
command = new IracClearKeysCommand(cacheName);
break;
case IracTouchKeyCommand.COMMAND_ID:
command = new IracTouchKeyCommand(cacheName);
break;
case IracUpdateVersionCommand.COMMAND_ID:
command = new IracUpdateVersionCommand(cacheName);
break;
case XSiteAutoTransferStatusCommand.COMMAND_ID:
command = new XSiteAutoTransferStatusCommand(cacheName);
break;
case XSiteSetStateTransferModeCommand.COMMAND_ID:
command = new XSiteSetStateTransferModeCommand(cacheName);
break;
case IracTombstoneCleanupCommand.COMMAND_ID:
command = new IracTombstoneCleanupCommand(cacheName);
break;
case IracTombstoneRemoteSiteCheckCommand.COMMAND_ID:
command = new IracTombstoneRemoteSiteCheckCommand(cacheName);
break;
case IracTombstoneStateResponseCommand.COMMAND_ID:
command = new IracTombstoneStateResponseCommand(cacheName);
break;
case IracTombstonePrimaryCheckCommand.COMMAND_ID:
command = new IracTombstonePrimaryCheckCommand(cacheName);
break;
case IracPutManyCommand.COMMAND_ID:
command = new IracPutManyCommand(cacheName);
break;
case SizeCommand.COMMAND_ID:
command = new SizeCommand(cacheName);
break;
default:
throw new CacheException("Unknown command id " + id + "!");
}
} else {
ModuleCommandFactory mcf = commandFactories.get(id);
if (mcf != null)
return mcf.fromStream(id, cacheName);
else
throw new CacheException("Unknown command id " + id + "!");
}
return command;
}
}
| 24,030
| 47.547475
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/AbstractVisitor.java
|
package org.infinispan.commands;
import java.util.Collection;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.functional.ReadOnlyKeyCommand;
import org.infinispan.commands.functional.ReadOnlyManyCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.read.EntrySetCommand;
import org.infinispan.commands.read.GetAllCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.read.KeySetCommand;
import org.infinispan.commands.read.SizeCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.EvictCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.InvalidateL1Command;
import org.infinispan.commands.write.IracPutKeyValueCommand;
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.context.InvocationContext;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.expiration.impl.TouchCommand;
/**
* An abstract implementation of a Visitor that delegates all visit calls to a default handler which can be overridden.
*
* @author Mircea.Markus@jboss.com
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
*/
public abstract class AbstractVisitor implements Visitor {
// write commands
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
// read commands
@Override
public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) throws Throwable {
return handleDefault(ctx, command);
}
// tx commands
@Override
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand invalidateCommand) throws Throwable {
return handleDefault(ctx, invalidateCommand);
}
@Override
public Object visitInvalidateL1Command(InvocationContext ctx, InvalidateL1Command invalidateL1Command) throws Throwable {
return visitInvalidateCommand(ctx, invalidateL1Command);
}
/**
* A default handler for all commands visited. This is called for any visit method called, unless a visit command is
* appropriately overridden.
*
* @param ctx invocation context
* @param command command to handle
* @return return value
* @throws Throwable in the case of a problem
*/
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
return null;
}
/**
* Helper method to visit a collection of VisitableCommands.
*
* @param ctx Invocation context
* @param toVisit collection of commands to visit
* @throws Throwable in the event of problems
*/
public void visitCollection(InvocationContext ctx, Collection<? extends VisitableCommand> toVisit) throws Throwable {
for (VisitableCommand command : toVisit) {
command.acceptVisitor(ctx, this);
}
}
@Override
public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitUnknownCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitReadOnlyKeyCommand(InvocationContext ctx, ReadOnlyKeyCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitReadOnlyManyCommand(InvocationContext ctx, ReadOnlyManyCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
public Object visitTouchCommand(InvocationContext ctx, TouchCommand command) throws Throwable {
return handleDefault(ctx, command);
}
}
| 8,963
| 35.439024
| 128
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/MetadataAwareCommand.java
|
package org.infinispan.commands;
import org.infinispan.metadata.Metadata;
/**
* A command that contains metadata information.
*
* @author Galder Zamarreño
* @since 5.3
*/
public interface MetadataAwareCommand {
/**
* Get metadata of this command.
*
* @return an instance of Metadata
*/
Metadata getMetadata();
/**
* Sets metadata for this command.
*/
void setMetadata(Metadata metadata);
}
| 436
| 15.807692
| 48
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/ReplicableCommand.java
|
package org.infinispan.commands;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* The core of the command-based cache framework. Commands correspond to specific areas of functionality in the cache,
* and can be replicated using the {@link org.infinispan.remoting.rpc.RpcManager}
*
* @author Mircea.Markus@jboss.com
* @author Manik Surtani
* @since 4.0
*/
public interface ReplicableCommand {
/**
* Invoke the command asynchronously.
*
* @since 9.0
* @deprecated since 11.0, please use {@link org.infinispan.commands.remote.CacheRpcCommand#invokeAsync(ComponentRegistry)}
* or {@link GlobalRpcCommand#invokeAsync(GlobalComponentRegistry)} instead.
*/
@Deprecated
default CompletableFuture<Object> invokeAsync() throws Throwable {
return CompletableFuture.completedFuture(invoke());
}
/**
* Invoke the command synchronously.
*
* @since 9.0
* @deprecated since 11.0, please use {@link org.infinispan.commands.remote.CacheRpcCommand#invokeAsync(ComponentRegistry)}
* or {@link GlobalRpcCommand#invokeAsync(GlobalComponentRegistry)} instead.
*/
@Deprecated
default Object invoke() throws Throwable {
try {
return invokeAsync().join();
} catch (CompletionException e) {
throw CompletableFutures.extractException(e);
}
}
/**
* Used by marshallers to convert this command into an id for streaming.
*
* @return the method id of this command. This is compatible with pre-2.2.0 MethodCall ids.
*/
byte getCommandId();
/**
* If true, a return value will be provided when performed remotely. Otherwise, a remote {@link
* org.infinispan.remoting.responses.ResponseGenerator} may choose to simply return null to save on marshalling
* costs.
*
* @return true or false
*/
boolean isReturnValueExpected();
/**
* If true, a return value will be marshalled as a {@link org.infinispan.remoting.responses.SuccessfulResponse},
* otherwise it will be marshalled as a {@link org.infinispan.remoting.responses.UnsuccessfulResponse}.
*/
default boolean isSuccessful() {
return true;
}
/**
* If true, the command is processed asynchronously in a thread provided by an Infinispan thread pool. Otherwise,
* the command is processed directly in the JGroups thread.
* <p/>
* This feature allows to avoid keep a JGroups thread busy that can originate discard of messages and
* retransmissions. So, the commands that can block (waiting for some state, acquiring locks, etc.) should return
* true.
*
* @return {@code true} if the command can block/wait, {@code false} otherwise
* @deprecated since 11.0 - All commands will be required to be non blocking!
*/
@Deprecated
default boolean canBlock() {
return false;
}
default boolean logThrowable(Throwable t) {
return true;
}
/**
* Writes this instance to the {@link ObjectOutput}.
*
* @param output the stream.
* @throws IOException if an error occurred during the I/O.
*/
default void writeTo(ObjectOutput output) throws IOException {
// no-op
}
/**
* Reads this instance from the stream written by {@link #writeTo(ObjectOutput)}.
*
* @param input the stream to read.
* @throws IOException if an error occurred during the I/O.
* @throws ClassNotFoundException if it tries to load an undefined class.
*/
default void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
// no-op
}
/**
* Sets the sender's {@link Address}.
* <p>
* By default, it doesn't set anything. Implement this method if the sender's {@link Address} is needed.
*
* @param origin the sender's {@link Address}
*/
default void setOrigin(Address origin) {
//no-op by default
}
}
| 4,252
| 32.226563
| 126
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/SegmentSpecificCommand.java
|
package org.infinispan.commands;
import org.infinispan.commons.util.SegmentAwareKey;
import org.infinispan.distribution.ch.KeyPartitioner;
/**
* Interface to be implemented when the command can define a single segment for its operation. This is useful so that
* subsequent operations requiring a segment can retrieve it from the command and have it only computed once at creation
* time.
* <p>
* If a command implements this interface, the command <b>MUST</b> ensure that it is initialized properly to always
* return a number 0 or greater when invoking {@link #getSegment()}.
*
* @author wburns
* @since 9.3
*/
public interface SegmentSpecificCommand {
/**
* Returns the segment that this key maps to. This must always return a number 0 or larger.
*
* @return the segment of the key
*/
int getSegment();
/**
* Utility to extract the segment from a given command that may be a {@link SegmentSpecificCommand}. If the command
* is a {@link SegmentSpecificCommand}, it will immediately return the value from {@link #getSegment()}. Otherwise it
* will return the result from invoking {@link KeyPartitioner#getSegment(Object)} passing the provided key.
*
* @param command the command to extract the segment from
* @param key the key the segment belongs to
* @param keyPartitioner the partitioner to calculate the segment of the key
* @return the segment value to use.
*/
static int extractSegment(ReplicableCommand command, Object key, KeyPartitioner keyPartitioner) {
if (command instanceof SegmentSpecificCommand) {
return ((SegmentSpecificCommand) command).getSegment();
}
return keyPartitioner.getSegment(key);
}
/**
* Create an {@link SegmentAwareKey} instance with the key and its segment.
* <p>
* If the {@code command} implements {@link SegmentSpecificCommand}, it will return the segment from {@link
* #getSegment()} instead of computing it.
*
* @param command the command to extract the segment from
* @param key the key the segment belongs to
* @param keyPartitioner the partitioner to calculate the segment of the key
* @param <K> The key's type.
* @return The {@link SegmentAwareKey} instance.
*/
static <K> SegmentAwareKey<K> extractSegmentAwareKey(ReplicableCommand command, K key, KeyPartitioner keyPartitioner) {
int segment = command instanceof SegmentSpecificCommand ?
((SegmentSpecificCommand) command).getSegment() :
keyPartitioner.getSegment(key);
return new SegmentAwareKey<>(key, segment);
}
}
| 2,657
| 42.57377
| 122
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/CommandsFactoryImpl.java
|
package org.infinispan.commands;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import org.infinispan.Cache;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.functional.Mutation;
import org.infinispan.commands.functional.ReadOnlyKeyCommand;
import org.infinispan.commands.functional.ReadOnlyManyCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.TxReadOnlyKeyCommand;
import org.infinispan.commands.functional.TxReadOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.irac.IracCleanupKeysCommand;
import org.infinispan.commands.irac.IracClearKeysCommand;
import org.infinispan.commands.irac.IracMetadataRequestCommand;
import org.infinispan.commands.irac.IracPutManyCommand;
import org.infinispan.commands.irac.IracRequestStateCommand;
import org.infinispan.commands.irac.IracStateResponseCommand;
import org.infinispan.commands.irac.IracTombstoneCleanupCommand;
import org.infinispan.commands.irac.IracTombstonePrimaryCheckCommand;
import org.infinispan.commands.irac.IracTombstoneRemoteSiteCheckCommand;
import org.infinispan.commands.irac.IracTombstoneStateResponseCommand;
import org.infinispan.commands.irac.IracTouchKeyCommand;
import org.infinispan.commands.irac.IracUpdateVersionCommand;
import org.infinispan.commands.read.EntrySetCommand;
import org.infinispan.commands.read.GetAllCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.read.KeySetCommand;
import org.infinispan.commands.read.SizeCommand;
import org.infinispan.commands.remote.CheckTransactionRpcCommand;
import org.infinispan.commands.remote.ClusteredGetAllCommand;
import org.infinispan.commands.remote.ClusteredGetCommand;
import org.infinispan.commands.remote.SingleRpcCommand;
import org.infinispan.commands.remote.recovery.CompleteTransactionCommand;
import org.infinispan.commands.remote.recovery.GetInDoubtTransactionsCommand;
import org.infinispan.commands.remote.recovery.GetInDoubtTxInfoCommand;
import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand;
import org.infinispan.commands.statetransfer.ConflictResolutionStartCommand;
import org.infinispan.commands.statetransfer.StateResponseCommand;
import org.infinispan.commands.statetransfer.StateTransferCancelCommand;
import org.infinispan.commands.statetransfer.StateTransferGetListenersCommand;
import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.commands.triangle.BackupNoopCommand;
import org.infinispan.commands.triangle.MultiEntriesFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.MultiKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.triangle.PutMapBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyBackupWriteCommand;
import org.infinispan.commands.triangle.SingleKeyFunctionalBackupWriteCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.VersionedCommitCommand;
import org.infinispan.commands.tx.VersionedPrepareCommand;
import org.infinispan.commands.write.BackupAckCommand;
import org.infinispan.commands.write.BackupMultiKeyAckCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.EvictCommand;
import org.infinispan.commands.write.ExceptionAckCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.InvalidateL1Command;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.RemoveExpiredCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commands.write.ValueMatcher;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.LambdaExternalizer;
import org.infinispan.commons.marshall.SerializeFunctionWith;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.commons.util.IntSet;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.XSiteStateTransferMode;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.versioning.irac.IracEntryVersion;
import org.infinispan.container.versioning.irac.IracTombstoneInfo;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.encoding.DataConversion;
import org.infinispan.expiration.impl.TouchCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.functional.EntryView.ReadEntryView;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.impl.Params;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.core.GlobalMarshaller;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.notifications.cachelistener.cluster.ClusterEvent;
import org.infinispan.notifications.cachelistener.cluster.MultiClusterEventCommand;
import org.infinispan.reactive.publisher.impl.DeliveryGuarantee;
import org.infinispan.reactive.publisher.impl.commands.batch.CancelPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.batch.InitialPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.batch.NextPublisherCommand;
import org.infinispan.reactive.publisher.impl.commands.reduction.ReductionPublisherRequestCommand;
import org.infinispan.remoting.transport.Address;
import org.infinispan.statetransfer.StateChunk;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.SingleXSiteRpcCommand;
import org.infinispan.xsite.commands.XSiteAmendOfflineStatusCommand;
import org.infinispan.xsite.commands.XSiteAutoTransferStatusCommand;
import org.infinispan.xsite.commands.XSiteBringOnlineCommand;
import org.infinispan.xsite.commands.XSiteOfflineStatusCommand;
import org.infinispan.xsite.commands.XSiteSetStateTransferModeCommand;
import org.infinispan.xsite.commands.XSiteStateTransferCancelSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferClearStatusCommand;
import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferFinishSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferRestartSendingCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartReceiveCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStartSendCommand;
import org.infinispan.xsite.commands.XSiteStateTransferStatusRequestCommand;
import org.infinispan.xsite.commands.XSiteStatusCommand;
import org.infinispan.xsite.commands.XSiteTakeOfflineCommand;
import org.infinispan.xsite.irac.IracManagerKeyInfo;
import org.infinispan.xsite.statetransfer.XSiteState;
import org.infinispan.xsite.statetransfer.XSiteStatePushCommand;
import org.reactivestreams.Publisher;
/**
* @author Mircea.Markus@jboss.com
* @author Galder Zamarreño
* @author Sanne Grinovero <sanne@hibernate.org> (C) 2011 Red Hat Inc.
* @since 4.0
*/
@Scope(Scopes.NAMED_CACHE)
public class CommandsFactoryImpl implements CommandsFactory {
private static final Log log = LogFactory.getLog(CommandsFactoryImpl.class);
@Inject ClusteringDependentLogic clusteringDependentLogic;
@Inject Configuration configuration;
@Inject ComponentRef<Cache<Object, Object>> cache;
@Inject ComponentRegistry componentRegistry;
@Inject EmbeddedCacheManager cacheManager;
@Inject @ComponentName(KnownComponentNames.INTERNAL_MARSHALLER)
StreamingMarshaller marshaller;
private ByteString cacheName;
private boolean transactional;
@Start(priority = 1)
// needs to happen early on
public void start() {
cacheName = ByteString.fromString(cache.wired().getName());
this.transactional = configuration.transaction().transactionMode().isTransactional();
}
@Override
public PutKeyValueCommand buildPutKeyValueCommand(Object key, Object value, int segment, Metadata metadata,
long flagsBitSet, boolean returnEntry) {
boolean reallyTransactional = transactional && !EnumUtil.containsAny(flagsBitSet, FlagBitSets.PUT_FOR_EXTERNAL_READ);
return new PutKeyValueCommand(key, value, false, returnEntry, metadata, segment, flagsBitSet, generateUUID(reallyTransactional));
}
@Override
public RemoveCommand buildRemoveCommand(Object key, Object value, int segment, long flagsBitSet, boolean returnEntry) {
return new RemoveCommand(key, value, returnEntry, segment, flagsBitSet, generateUUID(transactional));
}
@Override
public InvalidateCommand buildInvalidateCommand(long flagsBitSet, Object... keys) {
// StateConsumerImpl always uses non-tx invalidation
return new InvalidateCommand(flagsBitSet, generateUUID(false), keys);
}
@Override
public InvalidateCommand buildInvalidateFromL1Command(long flagsBitSet, Collection<Object> keys) {
// StateConsumerImpl always uses non-tx invalidation
return new InvalidateL1Command(flagsBitSet, keys, generateUUID(transactional));
}
@Override
public InvalidateCommand buildInvalidateFromL1Command(Address origin, long flagsBitSet, Collection<Object> keys) {
// L1 invalidation is always non-transactional
return new InvalidateL1Command(origin, flagsBitSet, keys, generateUUID(false));
}
@Override
public RemoveExpiredCommand buildRemoveExpiredCommand(Object key, Object value, int segment, Long lifespan,
long flagsBitSet) {
return new RemoveExpiredCommand(key, value, lifespan, false, segment, flagsBitSet,
generateUUID(false));
}
@Override
public RemoveExpiredCommand buildRemoveExpiredCommand(Object key, Object value, int segment, long flagsBitSet) {
return new RemoveExpiredCommand(key, value, null, true, segment, flagsBitSet,
generateUUID(false));
}
@Override
public ReplaceCommand buildReplaceCommand(Object key, Object oldValue, Object newValue, int segment,
Metadata metadata, long flagsBitSet, boolean returnEntry) {
return new ReplaceCommand(key, oldValue, newValue, returnEntry, metadata, segment, flagsBitSet, generateUUID(transactional));
}
@Override
public ComputeCommand buildComputeCommand(Object key, BiFunction mappingFunction, boolean computeIfPresent, int segment, Metadata metadata, long flagsBitSet) {
return init(new ComputeCommand(key, mappingFunction, computeIfPresent, segment, flagsBitSet, generateUUID(transactional), metadata));
}
@Override
public ComputeIfAbsentCommand buildComputeIfAbsentCommand(Object key, Function mappingFunction, int segment, Metadata metadata, long flagsBitSet) {
return init(new ComputeIfAbsentCommand(key, mappingFunction, segment, flagsBitSet, generateUUID(transactional), metadata));
}
@Override
public SizeCommand buildSizeCommand(IntSet segments, long flagsBitSet) {
return new SizeCommand(cacheName, segments, flagsBitSet);
}
@Override
public KeySetCommand buildKeySetCommand(long flagsBitSet) {
return new KeySetCommand<>(flagsBitSet);
}
@Override
public EntrySetCommand buildEntrySetCommand(long flagsBitSet) {
return new EntrySetCommand<>(flagsBitSet);
}
@Override
public GetKeyValueCommand buildGetKeyValueCommand(Object key, int segment, long flagsBitSet) {
return new GetKeyValueCommand(key, segment, flagsBitSet);
}
@Override
public GetAllCommand buildGetAllCommand(Collection<?> keys, long flagsBitSet, boolean returnEntries) {
return new GetAllCommand(keys, flagsBitSet, returnEntries);
}
@Override
public PutMapCommand buildPutMapCommand(Map<?, ?> map, Metadata metadata, long flagsBitSet) {
return new PutMapCommand(map, metadata, flagsBitSet, generateUUID(transactional));
}
@Override
public ClearCommand buildClearCommand(long flagsBitSet) {
return new ClearCommand(flagsBitSet);
}
@Override
public EvictCommand buildEvictCommand(Object key, int segment, long flagsBitSet) {
return new EvictCommand(key, segment, flagsBitSet, generateUUID(transactional));
}
@Override
public PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhaseCommit) {
return new PrepareCommand(cacheName, gtx, modifications, onePhaseCommit);
}
@Override
public VersionedPrepareCommand buildVersionedPrepareCommand(GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhase) {
return new VersionedPrepareCommand(cacheName, gtx, modifications, onePhase);
}
@Override
public CommitCommand buildCommitCommand(GlobalTransaction gtx) {
return new CommitCommand(cacheName, gtx);
}
@Override
public VersionedCommitCommand buildVersionedCommitCommand(GlobalTransaction gtx) {
return new VersionedCommitCommand(cacheName, gtx);
}
@Override
public RollbackCommand buildRollbackCommand(GlobalTransaction gtx) {
return new RollbackCommand(cacheName, gtx);
}
@Override
public SingleRpcCommand buildSingleRpcCommand(VisitableCommand call) {
return new SingleRpcCommand(cacheName, call);
}
@Override
public ClusteredGetCommand buildClusteredGetCommand(Object key, Integer segment, long flagsBitSet) {
return new ClusteredGetCommand(key, cacheName, segment, flagsBitSet);
}
/**
* @param isRemote true if the command is deserialized and is executed remote.
*/
@Override
public void initializeReplicableCommand(ReplicableCommand c, boolean isRemote) {
if (c == null) return;
if (c instanceof InitializableCommand)
((InitializableCommand) c).init(componentRegistry, isRemote);
}
@SuppressWarnings("unchecked")
private <T> T init(VisitableCommand cmd) {
cmd.init(componentRegistry);
return (T) cmd;
}
@Override
public LockControlCommand buildLockControlCommand(Collection<?> keys, long flagsBitSet, GlobalTransaction gtx) {
return new LockControlCommand(keys, cacheName, flagsBitSet, gtx);
}
@Override
public LockControlCommand buildLockControlCommand(Object key, long flagsBitSet, GlobalTransaction gtx) {
return new LockControlCommand(key, cacheName, flagsBitSet, gtx);
}
@Override
public LockControlCommand buildLockControlCommand(Collection<?> keys, long flagsBitSet) {
return new LockControlCommand(keys, cacheName, flagsBitSet, null);
}
@Override
public ConflictResolutionStartCommand buildConflictResolutionStartCommand(int topologyId, IntSet segments) {
return new ConflictResolutionStartCommand(cacheName, topologyId, segments);
}
@Override
public StateTransferCancelCommand buildStateTransferCancelCommand(int topologyId, IntSet segments) {
return new StateTransferCancelCommand(cacheName, topologyId, segments);
}
@Override
public StateTransferGetListenersCommand buildStateTransferGetListenersCommand(int topologyId) {
return new StateTransferGetListenersCommand(cacheName, topologyId);
}
@Override
public StateTransferGetTransactionsCommand buildStateTransferGetTransactionsCommand(int topologyId, IntSet segments) {
return new StateTransferGetTransactionsCommand(cacheName, topologyId, segments);
}
@Override
public StateTransferStartCommand buildStateTransferStartCommand(int topologyId, IntSet segments) {
return new StateTransferStartCommand(cacheName, topologyId, segments);
}
@Override
public StateResponseCommand buildStateResponseCommand(int topologyId, Collection<StateChunk> stateChunks, boolean applyState) {
return new StateResponseCommand(cacheName, topologyId, stateChunks, applyState);
}
@Override
public String getCacheName() {
return cacheName.toString();
}
@Override
public GetInDoubtTransactionsCommand buildGetInDoubtTransactionsCommand() {
return new GetInDoubtTransactionsCommand(cacheName);
}
@Override
public TxCompletionNotificationCommand buildTxCompletionNotificationCommand(XidImpl xid, GlobalTransaction globalTransaction) {
return new TxCompletionNotificationCommand(xid, globalTransaction, cacheName);
}
@Override
public TxCompletionNotificationCommand buildTxCompletionNotificationCommand(long internalId) {
return new TxCompletionNotificationCommand(internalId, cacheName);
}
@Override
public GetInDoubtTxInfoCommand buildGetInDoubtTxInfoCommand() {
return new GetInDoubtTxInfoCommand(cacheName);
}
@Override
public CompleteTransactionCommand buildCompleteTransactionCommand(XidImpl xid, boolean commit) {
return new CompleteTransactionCommand(cacheName, xid, commit);
}
@Override
public XSiteStateTransferCancelSendCommand buildXSiteStateTransferCancelSendCommand(String siteName) {
return new XSiteStateTransferCancelSendCommand(cacheName, siteName);
}
@Override
public XSiteStateTransferClearStatusCommand buildXSiteStateTransferClearStatusCommand() {
return new XSiteStateTransferClearStatusCommand(cacheName);
}
@Override
public XSiteStateTransferFinishReceiveCommand buildXSiteStateTransferFinishReceiveCommand(String siteName) {
return new XSiteStateTransferFinishReceiveCommand(cacheName, siteName);
}
@Override
public XSiteStateTransferFinishSendCommand buildXSiteStateTransferFinishSendCommand(String siteName, boolean statusOk) {
return new XSiteStateTransferFinishSendCommand(cacheName, siteName, statusOk);
}
@Override
public XSiteStateTransferRestartSendingCommand buildXSiteStateTransferRestartSendingCommand(String siteName, int topologyId) {
return new XSiteStateTransferRestartSendingCommand(cacheName, siteName, topologyId);
}
@Override
public XSiteStateTransferStartReceiveCommand buildXSiteStateTransferStartReceiveCommand() {
return new XSiteStateTransferStartReceiveCommand(cacheName);
}
@Override
public XSiteStateTransferStartSendCommand buildXSiteStateTransferStartSendCommand(String siteName, int topologyId) {
return new XSiteStateTransferStartSendCommand(cacheName, siteName, topologyId);
}
@Override
public XSiteStateTransferStatusRequestCommand buildXSiteStateTransferStatusRequestCommand() {
return new XSiteStateTransferStatusRequestCommand(cacheName);
}
@Override
public XSiteAmendOfflineStatusCommand buildXSiteAmendOfflineStatusCommand(String siteName, Integer afterFailures, Long minTimeToWait) {
return new XSiteAmendOfflineStatusCommand(cacheName, siteName, afterFailures, minTimeToWait);
}
@Override
public XSiteBringOnlineCommand buildXSiteBringOnlineCommand(String siteName) {
return new XSiteBringOnlineCommand(cacheName, siteName);
}
@Override
public XSiteOfflineStatusCommand buildXSiteOfflineStatusCommand(String siteName) {
return new XSiteOfflineStatusCommand(cacheName, siteName);
}
@Override
public XSiteStatusCommand buildXSiteStatusCommand() {
return new XSiteStatusCommand(cacheName);
}
@Override
public XSiteTakeOfflineCommand buildXSiteTakeOfflineCommand(String siteName) {
return new XSiteTakeOfflineCommand(cacheName, siteName);
}
@Override
public XSiteStatePushCommand buildXSiteStatePushCommand(XSiteState[] chunk, long timeoutMillis) {
return new XSiteStatePushCommand(cacheName, chunk, timeoutMillis);
}
@Override
public SingleXSiteRpcCommand buildSingleXSiteRpcCommand(VisitableCommand command) {
return new SingleXSiteRpcCommand(cacheName, command);
}
@Override
public GetCacheEntryCommand buildGetCacheEntryCommand(Object key, int segment, long flagsBitSet) {
return new GetCacheEntryCommand(key, segment, flagsBitSet);
}
@Override
public ClusteredGetAllCommand buildClusteredGetAllCommand(List<?> keys, long flagsBitSet, GlobalTransaction gtx) {
return new ClusteredGetAllCommand(cacheName, keys, flagsBitSet, gtx);
}
private CommandInvocationId generateUUID(boolean tx) {
if (tx) {
return CommandInvocationId.DUMMY_INVOCATION_ID;
} else {
return CommandInvocationId.generateId(clusteringDependentLogic.getAddress());
}
}
@Override
public <K, V, R> ReadOnlyKeyCommand<K, V, R> buildReadOnlyKeyCommand(Object key, Function<ReadEntryView<K, V>, R> f,
int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new ReadOnlyKeyCommand<>(key, f, segment, params, keyDataConversion, valueDataConversion));
}
@Override
public <K, V, R> ReadOnlyManyCommand<K, V, R> buildReadOnlyManyCommand(Collection<?> keys, Function<ReadEntryView<K, V>, R> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new ReadOnlyManyCommand<>(keys, f, params, keyDataConversion, valueDataConversion));
}
@Override
public <K, V, T, R> ReadWriteKeyValueCommand<K, V, T, R> buildReadWriteKeyValueCommand(Object key, Object argument,
BiFunction<T, ReadWriteEntryView<K, V>, R> f, int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new ReadWriteKeyValueCommand<>(key, argument, f, segment, generateUUID(transactional), getValueMatcher(f),
params, keyDataConversion, valueDataConversion));
}
@Override
public <K, V, R> ReadWriteKeyCommand<K, V, R> buildReadWriteKeyCommand(Object key,
Function<ReadWriteEntryView<K, V>, R> f, int segment, Params params, DataConversion keyDataConversion,
DataConversion valueDataConversion) {
return init(new ReadWriteKeyCommand<>(key, f, segment, generateUUID(transactional), getValueMatcher(f), params, keyDataConversion, valueDataConversion));
}
@Override
public <K, V, R> ReadWriteManyCommand<K, V, R> buildReadWriteManyCommand(Collection<?> keys, Function<ReadWriteEntryView<K, V>, R> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new ReadWriteManyCommand<>(keys, f, params, generateUUID(transactional), keyDataConversion, valueDataConversion));
}
@Override
public <K, V, T, R> ReadWriteManyEntriesCommand<K, V, T, R> buildReadWriteManyEntriesCommand(Map<?, ?> entries, BiFunction<T, ReadWriteEntryView<K, V>, R> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new ReadWriteManyEntriesCommand<>(entries, f, params, generateUUID(transactional), keyDataConversion, valueDataConversion));
}
@Override
public <K, V> WriteOnlyKeyCommand<K, V> buildWriteOnlyKeyCommand(
Object key, Consumer<WriteEntryView<K, V>> f, int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new WriteOnlyKeyCommand<>(key, f, segment, generateUUID(transactional), getValueMatcher(f), params, keyDataConversion, valueDataConversion));
}
@Override
public <K, V, T> WriteOnlyKeyValueCommand<K, V, T> buildWriteOnlyKeyValueCommand(Object key, Object argument, BiConsumer<T, WriteEntryView<K, V>> f,
int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new WriteOnlyKeyValueCommand<>(key, argument, f, segment, generateUUID(transactional), getValueMatcher(f), params, keyDataConversion, valueDataConversion));
}
@Override
public <K, V> WriteOnlyManyCommand<K, V> buildWriteOnlyManyCommand(Collection<?> keys, Consumer<WriteEntryView<K, V>> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new WriteOnlyManyCommand<>(keys, f, params, generateUUID(transactional), keyDataConversion, valueDataConversion));
}
@Override
public <K, V, T> WriteOnlyManyEntriesCommand<K, V, T> buildWriteOnlyManyEntriesCommand(
Map<?, ?> arguments, BiConsumer<T, WriteEntryView<K, V>> f, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new WriteOnlyManyEntriesCommand<>(arguments, f, params, generateUUID(transactional), keyDataConversion, valueDataConversion));
}
@Override
public <K, V, R> TxReadOnlyKeyCommand<K, V, R> buildTxReadOnlyKeyCommand(Object key, Function<ReadEntryView<K, V>, R> f, List<Mutation<K, V, ?>> mutations, int segment, Params params, DataConversion keyDataConversion, DataConversion valueDataConversion) {
return init(new TxReadOnlyKeyCommand<>(key, f, mutations, segment, params, keyDataConversion, valueDataConversion));
}
@Override
public <K, V, R> TxReadOnlyManyCommand<K, V, R> buildTxReadOnlyManyCommand(Collection<?> keys, List<List<Mutation<K, V, ?>>> mutations,
Params params, DataConversion keyDataConversion,
DataConversion valueDataConversion) {
return init(new TxReadOnlyManyCommand<K, V, R>(keys, mutations, params, keyDataConversion, valueDataConversion));
}
@Override
public BackupAckCommand buildBackupAckCommand(long id, int topologyId) {
return new BackupAckCommand(cacheName, id, topologyId);
}
@Override
public BackupMultiKeyAckCommand buildBackupMultiKeyAckCommand(long id, int segment, int topologyId) {
return new BackupMultiKeyAckCommand(cacheName, id, segment, topologyId);
}
@Override
public ExceptionAckCommand buildExceptionAckCommand(long id, Throwable throwable, int topologyId) {
return new ExceptionAckCommand(cacheName, id, throwable, topologyId);
}
private ValueMatcher getValueMatcher(Object o) {
SerializeFunctionWith ann = o.getClass().getAnnotation(SerializeFunctionWith.class);
if (ann != null)
return ValueMatcher.valueOf(ann.valueMatcher().toString());
Externalizer ext = ((GlobalMarshaller) marshaller).findExternalizerFor(o);
if (ext instanceof LambdaExternalizer)
return ValueMatcher.valueOf(((LambdaExternalizer) ext).valueMatcher(o).toString());
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public SingleKeyBackupWriteCommand buildSingleKeyBackupWriteCommand() {
return new SingleKeyBackupWriteCommand(cacheName);
}
@Override
public SingleKeyFunctionalBackupWriteCommand buildSingleKeyFunctionalBackupWriteCommand() {
return new SingleKeyFunctionalBackupWriteCommand(cacheName);
}
@Override
public PutMapBackupWriteCommand buildPutMapBackupWriteCommand() {
return new PutMapBackupWriteCommand(cacheName);
}
@Override
public MultiEntriesFunctionalBackupWriteCommand buildMultiEntriesFunctionalBackupWriteCommand() {
return new MultiEntriesFunctionalBackupWriteCommand(cacheName);
}
@Override
public MultiKeyFunctionalBackupWriteCommand buildMultiKeyFunctionalBackupWriteCommand() {
return new MultiKeyFunctionalBackupWriteCommand(cacheName);
}
@Override
public BackupNoopCommand buildBackupNoopCommand() {
return new BackupNoopCommand(cacheName);
}
@Override
public <K, R> ReductionPublisherRequestCommand<K> buildKeyReductionPublisherCommand(boolean parallelStream,
DeliveryGuarantee deliveryGuarantee, IntSet segments, Set<K> keys, Set<K> excludedKeys, long explicitFlags,
Function<? super Publisher<K>, ? extends CompletionStage<R>> transformer,
Function<? super Publisher<R>, ? extends CompletionStage<R>> finalizer) {
return new ReductionPublisherRequestCommand<>(cacheName, parallelStream, deliveryGuarantee, segments, keys, excludedKeys,
explicitFlags, false, transformer, finalizer);
}
@Override
public <K, V, R> ReductionPublisherRequestCommand<K> buildEntryReductionPublisherCommand(boolean parallelStream,
DeliveryGuarantee deliveryGuarantee, IntSet segments, Set<K> keys, Set<K> excludedKeys, long explicitFlags,
Function<? super Publisher<CacheEntry<K, V>>, ? extends CompletionStage<R>> transformer,
Function<? super Publisher<R>, ? extends CompletionStage<R>> finalizer) {
return new ReductionPublisherRequestCommand<>(cacheName, parallelStream, deliveryGuarantee, segments, keys, excludedKeys,
explicitFlags, true, transformer, finalizer);
}
@Override
public <K, I, R> InitialPublisherCommand<K, I, R> buildInitialPublisherCommand(String requestId, DeliveryGuarantee deliveryGuarantee,
int batchSize, IntSet segments, Set<K> keys, Set<K> excludedKeys, long explicitFlags, boolean entryStream,
boolean trackKeys, Function<? super Publisher<I>, ? extends Publisher<R>> transformer) {
return new InitialPublisherCommand<>(cacheName, requestId, deliveryGuarantee, batchSize, segments, keys,
excludedKeys, explicitFlags, entryStream, trackKeys, transformer);
}
@Override
public NextPublisherCommand buildNextPublisherCommand(String requestId) {
return new NextPublisherCommand(cacheName, requestId);
}
@Override
public CancelPublisherCommand buildCancelPublisherCommand(String requestId) {
return new CancelPublisherCommand(cacheName, requestId);
}
@Override
public <K, V> MultiClusterEventCommand<K, V> buildMultiClusterEventCommand(Map<UUID, Collection<ClusterEvent<K, V>>> events) {
return new MultiClusterEventCommand<>(cacheName, events);
}
@Override
public CheckTransactionRpcCommand buildCheckTransactionRpcCommand(Collection<GlobalTransaction> globalTransactions) {
return new CheckTransactionRpcCommand(cacheName, globalTransactions);
}
@Override
public TouchCommand buildTouchCommand(Object key, int segment, boolean touchEvenIfExpired, long flagBitSet) {
return new TouchCommand(key, segment, flagBitSet, touchEvenIfExpired);
}
@Override
public IracClearKeysCommand buildIracClearKeysCommand() {
return new IracClearKeysCommand(cacheName);
}
@Override
public IracCleanupKeysCommand buildIracCleanupKeyCommand(Collection<? extends IracManagerKeyInfo> state) {
return new IracCleanupKeysCommand(cacheName, state);
}
@Override
public IracTombstoneCleanupCommand buildIracTombstoneCleanupCommand(int maxCapacity) {
return new IracTombstoneCleanupCommand(cacheName, maxCapacity);
}
@Override
public IracMetadataRequestCommand buildIracMetadataRequestCommand(int segment, IracEntryVersion versionSeen) {
return new IracMetadataRequestCommand(cacheName, segment, versionSeen);
}
@Override
public IracRequestStateCommand buildIracRequestStateCommand(IntSet segments) {
return new IracRequestStateCommand(cacheName, segments);
}
@Override
public IracStateResponseCommand buildIracStateResponseCommand(int capacity) {
return new IracStateResponseCommand(cacheName, capacity);
}
@Override
public IracPutKeyValueCommand buildIracPutKeyValueCommand(Object key, int segment, Object value, Metadata metadata,
PrivateMetadata privateMetadata) {
return new IracPutKeyValueCommand(key, segment, generateUUID(false), value, metadata, privateMetadata);
}
@Override
public IracTouchKeyCommand buildIracTouchCommand(Object key) {
return new IracTouchKeyCommand(cacheName, key);
}
@Override
public IracUpdateVersionCommand buildIracUpdateVersionCommand(Map<Integer, IracEntryVersion> segmentsVersion) {
return new IracUpdateVersionCommand(cacheName, segmentsVersion);
}
@Override
public XSiteAutoTransferStatusCommand buildXSiteAutoTransferStatusCommand(String site) {
return new XSiteAutoTransferStatusCommand(cacheName, site);
}
@Override
public XSiteSetStateTransferModeCommand buildXSiteSetStateTransferModeCommand(String site, XSiteStateTransferMode mode) {
return new XSiteSetStateTransferModeCommand(cacheName, site, mode);
}
@Override
public IracTombstoneRemoteSiteCheckCommand buildIracTombstoneRemoteSiteCheckCommand(List<Object> keys) {
return new IracTombstoneRemoteSiteCheckCommand(cacheName, keys);
}
@Override
public IracTombstoneStateResponseCommand buildIracTombstoneStateResponseCommand(Collection<IracTombstoneInfo> state) {
return new IracTombstoneStateResponseCommand(cacheName, state);
}
@Override
public IracTombstonePrimaryCheckCommand buildIracTombstonePrimaryCheckCommand(Collection<IracTombstoneInfo> tombstones) {
return new IracTombstonePrimaryCheckCommand(cacheName, tombstones);
}
@Override
public IracPutManyCommand buildIracPutManyCommand(int capacity) {
return new IracPutManyCommand(cacheName, capacity);
}
}
| 35,052
| 45.366402
| 258
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/VisitableCommand.java
|
package org.infinispan.commands;
import org.infinispan.context.InvocationContext;
import org.infinispan.factories.ComponentRegistry;
/**
* A type of command that can accept {@link Visitor}s, such as {@link org.infinispan.interceptors.DDAsyncInterceptor}.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public interface VisitableCommand extends ReplicableCommand {
default void init(ComponentRegistry registry) {
// no-op
}
/**
* Accept a visitor, and return the result of accepting this visitor.
*
* @param ctx invocation context
* @param visitor visitor to accept
* @return arbitrary return value
* @throws Throwable in the event of problems
*/
Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable;
/**
* @return Nodes on which the command needs to read the previous values of the keys it acts on.
* @throws UnsupportedOperationException if the distinction does not make any sense.
*/
LoadType loadType();
enum LoadType {
/**
* Never load previous value.
*/
DONT_LOAD,
/**
* In non-transactional cache, load previous value only on the primary owner.
* In transactional cache, the value is fetched to originator. Primary then does not have to
* load the value but for write-skew check.
*/
PRIMARY,
/**
* In non-transactional cache, load previous value on both primary and backups.
* In transactional cache, the value is both fetched to originator and all owners have to load
* it because it is needed to produce the new value.
*/
OWNER
}
}
| 1,707
| 30.62963
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/control/LockControlCommand.java
|
package org.infinispan.commands.control;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.tx.AbstractTransactionBoundaryCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.context.Flag;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.context.impl.RemoteTxInvocationContext;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.locks.TransactionalRemoteLockCommand;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* LockControlCommand is a command that enables distributed locking across infinispan nodes.
* <p/>
* For more details refer to: https://jira.jboss.org/jira/browse/ISPN-70 https://jira.jboss.org/jira/browse/ISPN-48
*
* @author Vladimir Blagojevic (<a href="mailto:vblagoje@redhat.com">vblagoje@redhat.com</a>)
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class LockControlCommand extends AbstractTransactionBoundaryCommand implements FlagAffectedCommand, TopologyAffectedCommand, TransactionalRemoteLockCommand {
private static final Log log = LogFactory.getLog(LockControlCommand.class);
public static final int COMMAND_ID = 3;
private List<Object> keys;
private boolean unlock = false;
private long flags = EnumUtil.EMPTY_BIT_SET;
private LockControlCommand() {
super(null); // For command id uniqueness test
}
public LockControlCommand(ByteString cacheName) {
super(cacheName);
}
public LockControlCommand(Collection<?> keys, ByteString cacheName, long flags, GlobalTransaction gtx) {
super(cacheName);
if (keys != null) {
//building defensive copies is here in order to support replaceKey operation
this.keys = new ArrayList<>(keys);
} else {
this.keys = Collections.emptyList();
}
this.flags = flags;
this.globalTx = gtx;
}
public LockControlCommand(Object key, ByteString cacheName, long flags, GlobalTransaction gtx) {
this(cacheName);
this.keys = new ArrayList<>(1);
this.keys.add(key);
this.flags = flags;
this.globalTx = gtx;
}
public void setGlobalTransaction(GlobalTransaction gtx) {
globalTx = gtx;
}
public Collection<Object> getKeys() {
return keys;
}
public boolean multipleKeys() {
return keys.size() > 1;
}
public Object getSingleKey() {
if (keys.size() == 0)
return null;
return keys.get(0);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitLockControlCommand((TxInvocationContext) ctx, this);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
globalTx.setRemote(true);
RemoteTxInvocationContext ctx = createContext(registry);
if (ctx == null) {
return CompletableFutures.completedNull();
}
return registry.getInterceptorChain().running().invokeAsync(ctx, this);
}
@Override
public RemoteTxInvocationContext createContext(ComponentRegistry componentRegistry) {
TransactionTable txTable = componentRegistry.getTransactionTableRef().running();
RemoteTransaction transaction = txTable.getRemoteTransaction(globalTx);
if (transaction == null) {
if (unlock) {
log.tracef("Unlock for missing transaction %s. Not doing anything.", globalTx);
return null;
}
//create a remote tx without any modifications (we do not know modifications ahead of time)
transaction = txTable.getOrCreateRemoteTransaction(globalTx, Collections.emptyList());
}
return componentRegistry.getInvocationContextFactory().running().createRemoteTxInvocationContext(transaction, getOrigin());
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output);
output.writeBoolean(unlock);
MarshallUtil.marshallCollection(keys, output);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(flags));
}
@Override
@SuppressWarnings("unchecked")
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
unlock = input.readBoolean();
keys = MarshallUtil.unmarshallCollection(input, ArrayList::new);
flags = input.readLong();
}
public boolean isUnlock() {
return unlock;
}
public void setUnlock(boolean unlock) {
this.unlock = unlock;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
LockControlCommand that = (LockControlCommand) o;
if (unlock != that.unlock) return false;
if (flags != that.flags) return false;
if (!keys.equals(that.keys)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + keys.hashCode();
result = 31 * result + (unlock ? 1 : 0);
result = 31 * result + (int) (flags ^ (flags >>> 32));
return result;
}
@Override
public String toString() {
return new StringBuilder()
.append("LockControlCommand{cache=").append(cacheName)
.append(", keys=").append(keys)
.append(", flags=").append(EnumUtil.prettyPrintBitSet(flags, Flag.class))
.append(", unlock=").append(unlock)
.append(", gtx=").append(globalTx)
.append("}")
.toString();
}
@Override
public long getFlagsBitSet() {
return flags;
}
@Override
public void setFlagsBitSet(long bitSet) {
this.flags = bitSet;
}
@Override
public Collection<?> getKeysToLock() {
return unlock ? Collections.emptyList() : Collections.unmodifiableCollection(keys);
}
@Override
public Object getKeyLockOwner() {
return globalTx;
}
@Override
public boolean hasZeroLockAcquisition() {
return hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
@Override
public boolean hasSkipLocking() {
return hasAnyFlag(FlagBitSets.SKIP_LOCKING); //is it possible??
}
}
| 7,166
| 30.572687
| 164
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracTombstoneCleanupCommand.java
|
package org.infinispan.commands.irac;
import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.container.versioning.irac.IracTombstoneInfo;
import org.infinispan.container.versioning.irac.IracTombstoneManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* A {@link CacheRpcCommand} to clean up tombstones for IRAC algorithm.
* <p>
* This command is sent from the primary owners to the backup owner with the tombstone to be removed. No response is
* expected from the backup owners.
*
* @since 14.0
*/
public class IracTombstoneCleanupCommand implements CacheRpcCommand {
public static final byte COMMAND_ID = 37;
private final ByteString cacheName;
private Collection<IracTombstoneInfo> tombstonesToRemove;
@SuppressWarnings("unused")
public IracTombstoneCleanupCommand() {
this(null, 1);
}
public IracTombstoneCleanupCommand(ByteString cacheName) {
this(cacheName, 1);
}
public IracTombstoneCleanupCommand(ByteString cacheName, int maxCapacity) {
this.cacheName = cacheName;
tombstonesToRemove = new HashSet<>(maxCapacity);
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public CompletionStage<Boolean> invokeAsync(ComponentRegistry registry) {
IracTombstoneManager tombstoneManager = registry.getIracTombstoneManager().running();
tombstonesToRemove.forEach(tombstoneManager::removeTombstone);
return CompletableFutures.completedNull();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
marshallCollection(tombstonesToRemove, output, IracTombstoneInfo::writeTo);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
tombstonesToRemove = unmarshallCollection(input, ArrayList::new, IracTombstoneInfo::readFrom);
}
@Override
public Address getOrigin() {
//not needed
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op
}
@Override
public String toString() {
return "IracTombstoneCleanupCommand{" +
"cacheName=" + cacheName +
", tombstone=" + tombstonesToRemove +
'}';
}
public void add(IracTombstoneInfo tombstone) {
tombstonesToRemove.add(tombstone);
}
public int size() {
return tombstonesToRemove.size();
}
public boolean isEmpty() {
return tombstonesToRemove.isEmpty();
}
public Collection<IracTombstoneInfo> getTombstonesToRemove() {
return tombstonesToRemove;
}
}
| 3,294
| 26.923729
| 116
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracTombstoneRemoteSiteCheckCommand.java
|
package org.infinispan.commands.irac;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PrimitiveIterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSets;
import org.infinispan.commons.util.Util;
import org.infinispan.distribution.DistributionInfo;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.rpc.RpcOptions;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ValidSingleResponseCollector;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.xsite.BackupReceiver;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.irac.IracManager;
/**
* A {@link XSiteReplicateCommand} to check tombstones for IRAC algorithm.
* <p>
* Periodically, the primary owner sends this command to the remote sites where they check if the tombstone for this key
* is still necessary.
*
* @since 14.0
*/
public class IracTombstoneRemoteSiteCheckCommand extends XSiteReplicateCommand<IntSet> {
public static final byte COMMAND_ID = 38;
private List<Object> keys;
@SuppressWarnings("unused")
public IracTombstoneRemoteSiteCheckCommand() {
super(COMMAND_ID, null);
}
public IracTombstoneRemoteSiteCheckCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public IracTombstoneRemoteSiteCheckCommand(ByteString cacheName, List<Object> keys) {
super(COMMAND_ID, cacheName);
this.keys = keys;
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public CompletionStage<IntSet> invokeAsync(ComponentRegistry registry) {
int numberOfKeys = keys.size();
IntSet toKeepIndexes = IntSets.mutableEmptySet(numberOfKeys);
LocalizedCacheTopology topology = registry.getDistributionManager().getCacheTopology();
IracManager iracManager = registry.getIracManager().running();
for (int index = 0; index < numberOfKeys; ++index) {
Object key = keys.get(index);
// if we are not the primary owner mark the tombstone to keep
// if we have a pending update to send, mark the tombstone to keep
if (!topology.getDistribution(key).isPrimary() || iracManager.containsKey(key)) {
toKeepIndexes.set(index);
}
}
return CompletableFuture.completedFuture(toKeepIndexes);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public CompletionStage<IntSet> performInLocalSite(ComponentRegistry registry, boolean preserveOrder) {
LocalizedCacheTopology topology = registry.getDistributionManager().getCacheTopology();
IracManager iracManager = registry.getIracManager().running();
RpcManager rpcManager = registry.getRpcManager().running();
RpcOptions rpcOptions = rpcManager.getSyncRpcOptions();
int numberOfKeys = keys.size();
Map<Address, IntSetResponseCollector> primaryOwnerKeys = new HashMap<>(rpcManager.getMembers().size());
IntSet toKeepIndexes = IntSets.concurrentSet(numberOfKeys);
for (int index = 0 ; index < numberOfKeys; ++index) {
Object key = keys.get(index);
DistributionInfo dInfo = topology.getDistribution(key);
if (dInfo.isPrimary()) {
if (iracManager.containsKey(key)) {
toKeepIndexes.set(index);
}
} else {
IntSetResponseCollector collector = primaryOwnerKeys.computeIfAbsent(dInfo.primary(), a -> new IntSetResponseCollector(numberOfKeys, toKeepIndexes));
collector.add(index, key);
}
}
if (primaryOwnerKeys.isEmpty()) {
return CompletableFuture.completedFuture(toKeepIndexes);
}
AggregateCompletionStage<IntSet> stage = CompletionStages.aggregateCompletionStage(toKeepIndexes);
for (Map.Entry<Address, IntSetResponseCollector> entry : primaryOwnerKeys.entrySet()) {
IracTombstoneRemoteSiteCheckCommand cmd = new IracTombstoneRemoteSiteCheckCommand(cacheName, entry.getValue().getKeys());
stage.dependsOn(rpcManager.invokeCommand(entry.getKey(), cmd, entry.getValue(), rpcOptions));
}
return stage.freeze();
}
@Override
public CompletionStage<IntSet> performInLocalSite(BackupReceiver receiver, boolean preserveOrder) {
throw new IllegalStateException("Should never be invoked!");
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallCollection(keys, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
keys = MarshallUtil.unmarshallCollection(input, ArrayList::new);
}
@Override
public Address getOrigin() {
//not needed
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op
}
@Override
public String toString() {
return "IracSiteTombstoneCheckCommand{" +
"cacheName=" + cacheName +
", keys=" + keys.stream().map(Util::toStr).collect(Collectors.joining(",")) +
'}';
}
private static class IntSetResponseCollector extends ValidSingleResponseCollector<Void> {
private final List<Object> keys;
private final int[] keyIndexes;
private final IntSet globalToKeepIndexes;
private int nextInsertPosition;
private IntSetResponseCollector(int maxCapacity, IntSet globalToKeepIndexes) {
keys = new ArrayList<>(maxCapacity);
keyIndexes = new int[maxCapacity];
this.globalToKeepIndexes = globalToKeepIndexes;
}
void add(int index, Object key) {
assert nextInsertPosition < keyIndexes.length;
keys.add(key);
keyIndexes[nextInsertPosition++] = index;
}
List<Object> getKeys() {
return keys;
}
@Override
protected Void withValidResponse(Address sender, ValidResponse response) {
Object rsp = response.getResponseValue();
assert rsp instanceof IntSet;
IntSet toKeep = (IntSet) rsp;
for (PrimitiveIterator.OfInt it = toKeep.iterator(); it.hasNext(); ) {
int localPosition = it.nextInt();
assert localPosition < keyIndexes.length;
globalToKeepIndexes.set(keyIndexes[localPosition]);
}
return null;
}
@Override
protected Void withException(Address sender, Exception exception) {
markAllToKeep();
return null;
}
@Override
protected Void targetNotFound(Address sender) {
markAllToKeep();
return null;
}
private void markAllToKeep() {
for (int index : keyIndexes) {
globalToKeepIndexes.set(index);
}
}
}
}
| 7,512
| 33.15
| 161
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.