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/interceptors/impl/MultiSubCommandInvoker.java
package org.infinispan.interceptors.impl; import java.util.Iterator; import org.infinispan.commands.VisitableCommand; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.BaseAsyncInterceptor; import org.infinispan.interceptors.InvocationSuccessFunction; /** * Invoke a sequence of sub-commands. * * @author Dan Berindei * @since 9.0 */ public class MultiSubCommandInvoker implements InvocationSuccessFunction<VisitableCommand> { private final BaseAsyncInterceptor interceptor; private final Object finalStage; private final Iterator<VisitableCommand> subCommands; private MultiSubCommandInvoker(BaseAsyncInterceptor interceptor, Object finalReturnValue, Iterator<VisitableCommand> subCommands) { this.interceptor = interceptor; this.finalStage = finalReturnValue; this.subCommands = subCommands; } /** * Call {@link BaseAsyncInterceptor#invokeNext(InvocationContext, VisitableCommand)} on a sequence of sub-commands. * <p> * Stop when one of the sub-commands throws an exception, and return an invocation stage with that exception. If all * the sub-commands are successful, return the {@code finalStage}. If {@code finalStage} has and exception, skip all * the sub-commands and just return the {@code finalStage}. */ public static Object invokeEach(InvocationContext ctx, Iterator<VisitableCommand> subCommands, BaseAsyncInterceptor interceptor, Object finalReturnValue) { if (!subCommands.hasNext()) return finalReturnValue; MultiSubCommandInvoker invoker = new MultiSubCommandInvoker(interceptor, finalReturnValue, subCommands); VisitableCommand newCommand = subCommands.next(); return interceptor.invokeNextThenApply(ctx, newCommand, invoker); } @Override public Object apply(InvocationContext rCtx, VisitableCommand rCommand, Object rv) throws Throwable { if (subCommands.hasNext()) { VisitableCommand newCommand = subCommands.next(); return interceptor.invokeNextThenApply(rCtx, newCommand, this); } else { return finalStage; } } }
2,203
39.072727
119
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/InvocationContextInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.commons.util.Util.toStr; import static org.infinispan.util.logging.Log.CONTAINER; import java.util.Collection; import java.util.Collections; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import org.infinispan.InvalidCacheUsageException; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.control.LockControlCommand; import org.infinispan.commands.tx.TransactionBoundaryCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.CacheException; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.interceptors.BaseAsyncInterceptor; import org.infinispan.interceptors.InvocationExceptionFunction; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.statetransfer.OutdatedTopologyException; import org.infinispan.topology.LocalTopologyManager; import org.infinispan.transaction.WriteSkewException; import org.infinispan.transaction.impl.AbstractCacheTransaction; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.util.UserRaisedFunctionalException; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * @author Mircea.Markus@jboss.com * @author Galder Zamarreño * @since 9.0 */ public class InvocationContextInterceptor extends BaseAsyncInterceptor { private static final Log log = LogFactory.getLog(InvocationContextInterceptor.class); @Inject ComponentRegistry componentRegistry; @Inject TransactionTable txTable; private volatile boolean shuttingDown = false; private final InvocationExceptionFunction<VisitableCommand> suppressExceptionsHandler = (rCtx, rCommand, throwable) -> { if (throwable instanceof InvalidCacheUsageException || throwable instanceof InterruptedException) { throw throwable; } if (throwable instanceof UserRaisedFunctionalException) { if (rCtx.isOriginLocal()) { throw throwable.getCause(); } else { throw throwable; } } else { rethrowException(rCtx, rCommand, throwable); } // Ignore the exception return rCommand instanceof LockControlCommand ? Boolean.FALSE : null; }; @Start(priority = 1) void setStartStatus() { shuttingDown = false; } @Stop(priority = 1) void setStopStatus() { shuttingDown = true; } @Override public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable { if (log.isTraceEnabled()) log.tracef("Invoked %s with command %s and InvocationContext [%s]", componentRegistry.getCacheName(), command, ctx); if (ctx == null) throw new IllegalStateException("Null context not allowed!!"); ComponentStatus status = componentRegistry.getStatus(); if (!status.allowInvocations()) { ignoreCommand(ctx, command, status); } return invokeNextAndExceptionally(ctx, command, suppressExceptionsHandler); } private void ignoreCommand(InvocationContext ctx, VisitableCommand command, ComponentStatus status) throws Exception { switch (status) { case FAILED: case TERMINATED: throw CONTAINER.cacheIsTerminated(getCacheNamePrefix(), status.toString()); case STOPPING: if (stoppingAndNotAllowed(status, ctx)) { throw CONTAINER.cacheIsStopping(getCacheNamePrefix()); } case INITIALIZING: LocalTopologyManager ltm = componentRegistry.getComponent(LocalTopologyManager.class); if (ltm != null) ltm.assertTopologyStable(componentRegistry.getCacheName()); default: // Allow the command to run } } private void rethrowException(InvocationContext ctx, VisitableCommand command, Throwable th) throws Throwable { // Only check for fail silently if there's a failure :) boolean suppressExceptions = (command instanceof FlagAffectedCommand) && ((FlagAffectedCommand) command).hasAnyFlag(FlagBitSets.FAIL_SILENTLY); // If we are shutting down there is every possibility that the invocation fails. suppressExceptions = suppressExceptions || shuttingDown; if (suppressExceptions) { if (shuttingDown) log.trace("Exception while executing code, but we're shutting down so failing silently.", th); else log.trace("Exception while executing code, failing silently...", th); } else { if (th instanceof WriteSkewException) { // We log this as DEBUG rather than ERROR - see ISPN-2076 log.debug("Exception executing call", th); } else if (th instanceof OutdatedTopologyException) { if (log.isTraceEnabled()) log.tracef("Topology changed, retrying command: %s", th); } else if (command.logThrowable(th)) { Collection<?> affectedKeys = extractWrittenKeys(ctx, command); log.executionError(command.getClass().getSimpleName(), getCacheNamePrefix(), toStr(affectedKeys), th); } else { log.trace("Unexpected exception encountered", th); } if (ctx.isInTxScope() && ctx.isOriginLocal()) { if (log.isTraceEnabled()) log.trace("Transaction marked for rollback as exception was received."); markTxForRollback(ctx); } if (ctx.isOriginLocal() && !(th instanceof CacheException)) { th = new CacheException(th); } throw th; } } private Collection<?> extractWrittenKeys(InvocationContext ctx, VisitableCommand command) { if (command instanceof WriteCommand) { return ((WriteCommand) command).getAffectedKeys(); } else if (command instanceof LockControlCommand) { return Collections.emptyList(); } else if (command instanceof TransactionBoundaryCommand) { return ((TxInvocationContext<AbstractCacheTransaction>) ctx).getAffectedKeys(); } return Collections.emptyList(); } private String getCacheNamePrefix() { String cacheName = componentRegistry.getCacheName(); return "Cache '" + cacheName + "'"; } /** * If the cache is STOPPING, non-transaction invocations, or transactional invocations for transaction others than * the ongoing ones, are no allowed. This method returns true if under this circumstances meet. Otherwise, it returns * false. */ private boolean stoppingAndNotAllowed(ComponentStatus status, InvocationContext ctx) throws Exception { return status.isStopping() && (!ctx.isInTxScope() || !isOngoingTransaction(ctx)); } private void markTxForRollback(InvocationContext ctx) throws Throwable { if (ctx.isOriginLocal() && ctx.isInTxScope()) { Transaction transaction = ((TxInvocationContext) ctx).getTransaction(); if (transaction != null && isValidRunningTx(transaction)) { transaction.setRollbackOnly(); } } } private boolean isValidRunningTx(Transaction tx) throws Exception { int status; try { status = tx.getStatus(); } catch (SystemException e) { throw new CacheException("Unexpected!", e); } return status == Status.STATUS_ACTIVE; } private boolean isOngoingTransaction(InvocationContext ctx) throws SystemException { if (!ctx.isInTxScope()) return false; if (ctx.isOriginLocal()) return txTable.containsLocalTx(((TxInvocationContext) ctx).getGlobalTransaction()); else return txTable.containRemoteTx(((TxInvocationContext) ctx).getGlobalTransaction()); } }
8,149
39.954774
125
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/AbstractIracLocalSiteInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.metadata.impl.PrivateMetadata.getBuilder; import static org.infinispan.util.IracUtils.setIracMetadata; import java.lang.invoke.MethodHandles; import java.util.Optional; import java.util.stream.Stream; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.SegmentSpecificCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.commands.write.RemoveExpiredCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.IracTombstoneManager; import org.infinispan.container.versioning.irac.IracVersionGenerator; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.LocalTxInvocationContext; import org.infinispan.context.impl.RemoteTxInvocationContext; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.factories.annotations.Inject; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.InvocationFinallyAction; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.util.CacheTopologyUtil; import org.infinispan.util.IracUtils; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.infinispan.util.logging.LogSupplier; /** * A {@link DDAsyncInterceptor} with common code for all the IRAC related interceptors. * * @author Pedro Ruivo * @since 11.0 */ public abstract class AbstractIracLocalSiteInterceptor extends DDAsyncInterceptor implements LogSupplier { protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @Inject ClusteringDependentLogic clusteringDependentLogic; @Inject IracVersionGenerator iracVersionGenerator; @Inject IracTombstoneManager iracTombstoneManager; @Inject KeyPartitioner keyPartitioner; private final InvocationFinallyAction<DataWriteCommand> afterWriteCommand = this::handleNonTxDataWriteCommand; @Override public final Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @Override public final boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public final Log getLog() { return log; } protected static boolean isNormalWriteCommand(WriteCommand command) { return !command.hasAnyFlag(FlagBitSets.IRAC_UPDATE); } protected static boolean isIracState(FlagAffectedCommand command) { return command.hasAnyFlag(FlagBitSets.IRAC_STATE); } static LocalTxInvocationContext asLocalTxInvocationContext(InvocationContext ctx) { assert ctx.isOriginLocal(); assert ctx.isInTxScope(); return (LocalTxInvocationContext) ctx; } static RemoteTxInvocationContext asRemoteTxInvocationContext(InvocationContext ctx) { assert !ctx.isOriginLocal(); assert ctx.isInTxScope(); return (RemoteTxInvocationContext) ctx; } static void updateCommandMetadata(Object key, WriteCommand command, IracMetadata iracMetadata) { PrivateMetadata interMetadata = getBuilder(command.getInternalMetadata(key)) .iracMetadata(iracMetadata) .build(); command.setInternalMetadata(key, interMetadata); } protected DistributionInfo getDistributionInfo(int segment) { return getCacheTopology().getSegmentDistribution(segment); } protected boolean isWriteOwner(StreamData data) { return getDistributionInfo(data.segment).isWriteOwner(); } protected boolean isPrimaryOwner(StreamData data) { return getDistributionInfo(data.segment).isPrimary(); } protected LocalizedCacheTopology getCacheTopology() { return clusteringDependentLogic.getCacheTopology(); } protected int getSegment(WriteCommand command, Object key) { return SegmentSpecificCommand.extractSegment(command, key, keyPartitioner); } protected void setMetadataToCacheEntry(CacheEntry<?, ?> entry, int segment, IracMetadata metadata) { if (entry.isEvicted()) { if (log.isTraceEnabled()) { log.tracef("[IRAC] Ignoring evict key: %s", entry.getKey()); } return; } setIracMetadata(entry, segment, metadata, iracTombstoneManager, this); } protected Stream<StreamData> streamKeysFromModifications(Stream<WriteCommand> modsStream) { return modsStream.filter(AbstractIracLocalSiteInterceptor::isNormalWriteCommand) .flatMap(this::streamKeysFromCommand); } protected Stream<StreamData> streamKeysFromCommand(WriteCommand command) { return command.getAffectedKeys().stream().map(key -> new StreamData(key, command, getSegment(command, key))); } protected boolean skipEntryCommit(InvocationContext ctx, WriteCommand command, Object key) { LocalizedCacheTopology cacheTopology = CacheTopologyUtil.checkTopology(command, getCacheTopology()); switch (cacheTopology.getSegmentDistribution(getSegment(command, key)).writeOwnership()) { case NON_OWNER: //not a write owner, we do nothing return true; case BACKUP: //if it is local, we do nothing. //the update happens in the remote context after the primary validated the write return ctx.isOriginLocal(); } return false; } protected Object visitNonTxDataWriteCommand(InvocationContext ctx, DataWriteCommand command) { final Object key = command.getKey(); if (isIracState(command)) { //all the state transfer/preload is done via put commands. setMetadataToCacheEntry(ctx.lookupEntry(key), command.getSegment(), command.getInternalMetadata(key).iracMetadata()); return invokeNext(ctx, command); } if (command.hasAnyFlag(FlagBitSets.IRAC_UPDATE)) { return invokeNext(ctx, command); } visitNonTxKey(ctx, key, command); return invokeNextAndFinally(ctx, command, afterWriteCommand); } /** * Visits the {@link WriteCommand} before executing it. * <p> * The primary owner generates a new {@link IracMetadata} and stores it in the {@link WriteCommand}. */ protected void visitNonTxKey(InvocationContext ctx, Object key, WriteCommand command) { LocalizedCacheTopology cacheTopology = CacheTopologyUtil.checkTopology(command, getCacheTopology()); int segment = getSegment(command, key); if (!cacheTopology.getSegmentDistribution(segment).isPrimary()) { return; } Optional<IracMetadata> entryMetadata = IracUtils.findIracMetadataFromCacheEntry(ctx.lookupEntry(key)); IracMetadata metadata; // RemoveExpired should lose to any other conflicting write if (command instanceof RemoveExpiredCommand) { metadata = entryMetadata.orElseGet(() -> iracVersionGenerator.generateMetadataWithCurrentVersion(segment)); } else { IracEntryVersion versionSeen = entryMetadata.map(IracMetadata::getVersion).orElse(null); metadata = iracVersionGenerator.generateNewMetadata(segment, versionSeen); } updateCommandMetadata(key, command, metadata); if (log.isTraceEnabled()) { log.tracef("[IRAC] New metadata for key '%s' is %s. Command=%s", key, metadata, command); } } /** * Visits th {@link WriteCommand} after executed and stores the {@link IracMetadata} if it was successful. */ @SuppressWarnings("unused") private void handleNonTxDataWriteCommand(InvocationContext ctx, DataWriteCommand command, Object rv, Throwable t) { final Object key = command.getKey(); if (!command.isSuccessful() || skipEntryCommit(ctx, command, key)) { return; } setMetadataToCacheEntry(ctx.lookupEntry(key), command.getSegment(), command.getInternalMetadata(key).iracMetadata()); } static class StreamData { final Object key; final WriteCommand command; final int segment; public StreamData(Object key, WriteCommand command, int segment) { this.key = key; this.command = command; this.segment = segment; } @Override public String toString() { return "StreamData{" + "key=" + key + ", command=" + command + ", segment=" + segment + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StreamData data = (StreamData) o; return segment == data.segment && key.equals(data.key); } @Override public int hashCode() { int result = key.hashCode(); result = 31 * result + segment; return result; } } }
9,323
37.213115
126
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/JmxStatsCommandInterceptor.java
package org.infinispan.interceptors.impl; import org.infinispan.factories.annotations.Start; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.jmx.JmxStatisticsExposer; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedAttribute; import org.infinispan.jmx.annotations.ManagedOperation; /** * Base class for all the interceptors exposing management statistics. * * @author Mircea.Markus@jboss.com * @since 9.0 */ @MBean public abstract class JmxStatsCommandInterceptor extends DDAsyncInterceptor implements JmxStatisticsExposer { private boolean statisticsEnabled = false; @Start public final void onStart() { setStatisticsEnabled(cacheConfiguration.statistics().enabled()); } /** * Returns whether an interceptor's statistics are being captured. * * @return true if statistics are captured */ @ManagedAttribute(description = "Enables or disables the gathering of statistics by this component", writable = true) @Override public boolean getStatisticsEnabled() { return statisticsEnabled; } /** * @param enabled whether gathering statistics for JMX are enabled. */ @Override public void setStatisticsEnabled(boolean enabled) { statisticsEnabled = enabled; } /** * Resets statistics gathered. Is a no-op, and should be overridden if it is to be meaningful. */ @ManagedOperation(displayName = "Reset Statistics", description = "Resets statistics gathered by this component") @Override public void resetStatistics() { } }
1,601
29.226415
120
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/NonTxIracLocalSiteInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.commands.SegmentSpecificCommand.extractSegment; 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.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.tx.RollbackCommand; import org.infinispan.commands.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.InvocationFinallyAction; import org.infinispan.metadata.impl.IracMetadata; /** * Interceptor used by IRAC for non transactional caches to handle the local site updates. * <p> * The primary owner job is to generate a new {@link IracMetadata} for the write and store in the {@link WriteCommand}. * If the command is successful, the {@link IracMetadata} is stored in the context entry. * <p> * The backup owners just handle the updates from the primary owner and extract the {@link IracMetadata} to stored in * the context entry. * * @author Pedro Ruivo * @since 11.0 */ public class NonTxIracLocalSiteInterceptor extends AbstractIracLocalSiteInterceptor { private final InvocationFinallyAction<WriteCommand> afterWriteCommand = this::handleWriteCommand; @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { return visitWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) { throw new UnsupportedOperationException(); } @SuppressWarnings("rawtypes") @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) { throw new UnsupportedOperationException(); } @SuppressWarnings("rawtypes") @Override public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) { throw new UnsupportedOperationException(); } @SuppressWarnings("rawtypes") @Override public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) { return visitWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) { return visitNonTxDataWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) { return visitWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) { return visitWriteCommand(ctx, command); } @SuppressWarnings("rawtypes") @Override public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) { return visitWriteCommand(ctx, command); } private Object visitWriteCommand(InvocationContext ctx, WriteCommand command) { if (command.hasAnyFlag(FlagBitSets.IRAC_UPDATE)) { return invokeNext(ctx, command); } for (Object key : command.getAffectedKeys()) { visitNonTxKey(ctx, key, command); } return invokeNextAndFinally(ctx, command, afterWriteCommand); } /** * Visits th {@link WriteCommand} after executed and stores the {@link IracMetadata} if it was successful. */ @SuppressWarnings("unused") private void handleWriteCommand(InvocationContext ctx, WriteCommand command, Object rv, Throwable t) { if (!command.isSuccessful()) { return; } for (Object key : command.getAffectedKeys()) { if (skipEntryCommit(ctx, command, key)) { continue; } setMetadataToCacheEntry(ctx.lookupEntry(key), extractSegment(command, key, keyPartitioner), command.getInternalMetadata(key).iracMetadata()); } } }
6,317
36.384615
150
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/CacheLoaderInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.BOTH; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.NOT_ASYNC; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.PRIVATE; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.SHARED; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Predicate; import org.infinispan.Cache; import org.infinispan.CacheSet; import org.infinispan.InternalCacheSet; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.SegmentSpecificCommand; import org.infinispan.commands.VisitableCommand; 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.read.AbstractDataCommand; 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.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; import org.infinispan.commands.write.IracPutKeyValueCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.MVCCEntry; import org.infinispan.container.impl.EntryFactory; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.distribution.group.impl.GroupManager; 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.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedAttribute; import org.infinispan.jmx.annotations.ManagedOperation; import org.infinispan.jmx.annotations.MeasurementType; import org.infinispan.jmx.annotations.Parameter; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.persistence.internal.PersistenceUtil; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.manager.PersistenceManager.StoreChangeListener; import org.infinispan.persistence.manager.PersistenceStatus; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.persistence.util.EntryLoader; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; /** * @since 9.0 */ @MBean(objectName = "CacheLoader", description = "Component that handles loading entries from a CacheStore into memory.") public class CacheLoaderInterceptor<K, V> extends JmxStatsCommandInterceptor implements EntryLoader<K, V>, StoreChangeListener { private static final Log log = LogFactory.getLog(CacheLoaderInterceptor.class); protected final AtomicLong cacheLoads = new AtomicLong(0); protected final AtomicLong cacheMisses = new AtomicLong(0); @Inject protected PersistenceManager persistenceManager; @Inject protected CacheNotifier notifier; @Inject protected EntryFactory entryFactory; @Inject TimeService timeService; @Inject InternalEntryFactory iceFactory; @Inject InternalDataContainer<K, V> dataContainer; @Inject GroupManager groupManager; @Inject ComponentRef<Cache<K, V>> cache; @Inject KeyPartitioner partitioner; @Inject @ComponentName(KnownComponentNames.NON_BLOCKING_EXECUTOR) protected ExecutorService nonBlockingExecutor; protected boolean activation; private volatile boolean usingStores; private final ConcurrentMap<Object, CompletionStage<InternalCacheEntry<K, V>>> pendingLoads = new ConcurrentHashMap<>(); @Start public void start() { this.activation = cacheConfiguration.persistence().passivation(); this.usingStores = cacheConfiguration.persistence().usingStores(); } @Override public void storeChanged(PersistenceStatus persistenceStatus) { usingStores = persistenceStatus.isEnabled(); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) { return visitManyDataCommand(ctx, command, command.getKeys()); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) { return visitDataCommand(ctx, command); } private Object visitManyDataCommand(InvocationContext ctx, FlagAffectedCommand command, Collection<?> keys) { AggregateCompletionStage<Void> stage = null; for (Object key : keys) { CompletionStage<?> innerStage = loadIfNeeded(ctx, key, command); if (innerStage != null && !CompletionStages.isCompletedSuccessfully(innerStage)) { if (stage == null) { stage = CompletionStages.aggregateCompletionStage(); } stage.dependsOn(innerStage); } } if (stage != null) { return asyncInvokeNext(ctx, command, stage.freeze()); } return invokeNext(ctx, command); } private Object visitDataCommand(InvocationContext ctx, AbstractDataCommand command) { Object key; CompletionStage<?> stage = null; if ((key = command.getKey()) != null) { stage = loadIfNeeded(ctx, key, command); } return asyncInvokeNext(ctx, command, stage); } @Override public Object visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, rCommand, rv) -> { if (hasSkipLoadFlag(rCommand)) { // Continue with the existing throwable/return value return rv; } CacheSet<CacheEntry<K, V>> entrySet = (CacheSet<CacheEntry<K, V>>) rv; return new WrappedEntrySet(entrySet, rCommand); }); } @Override public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, rCommand, rv) -> { if (hasSkipLoadFlag(rCommand)) { // Continue with the existing throwable/return value return rv; } CacheSet<K> keySet = (CacheSet<K>) rv; return new WrappedKeySet(keySet, rCommand); }); } @Override public Object visitReadOnlyKeyCommand(InvocationContext ctx, ReadOnlyKeyCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitReadOnlyManyCommand(InvocationContext ctx, ReadOnlyManyCommand command) { return visitManyDataCommand(ctx, command, command.getKeys()); } @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { return visitDataCommand(ctx, command); } @Override public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) { return visitDataCommand(ctx, command); } @Override public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) { return visitManyDataCommand(ctx, command, command.getAffectedKeys()); } @Override public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) throws Throwable { return visitManyDataCommand(ctx, command, command.getAffectedKeys()); } @Override public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) { CompletionStage<Long> sizeStage = trySizeOptimization(command); return asyncValue(sizeStage).thenApply(ctx, command, (rCtx, rCommand, rv) -> { if ((Long) rv == -1) { // Avoid any try to optimization down the stack. If we are here means that we are using stores, any other // optimization should be possible only if not using any store. rCommand.addFlags(FlagBitSets.SKIP_SIZE_OPTIMIZATION); return super.visitSizeCommand(rCtx, rCommand); } return rv; }); } private CompletionStage<Long> trySizeOptimization(SizeCommand command) { if (command.hasAnyFlag(FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_SIZE_OPTIMIZATION) || cacheConfiguration.persistence().passivation()) { return NonBlockingStore.SIZE_UNAVAILABLE_FUTURE; } // Get the size from any shared store that isn't async return persistenceManager.size(SHARED.and(NOT_ASYNC)) .thenCompose(v -> v >= 0 || !command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL) ? CompletableFuture.completedFuture(v) // For a local request get the size private not asynchronous store : persistenceManager.size(PRIVATE.and(NOT_ASYNC), command.getSegments())); } protected final boolean isConditional(WriteCommand cmd) { return cmd.isConditional(); } protected final boolean hasSkipLoadFlag(FlagAffectedCommand cmd) { return cmd.hasAnyFlag(FlagBitSets.SKIP_CACHE_LOAD); } protected boolean canLoad(Object key, int segment) { return true; } /** * Loads from the cache loader the entry for the given key. A found value is loaded into the current context. The * method returns whether the value was found or not, or even if the cache loader was checked. * @param ctx The current invocation's context * @param key The key for the entry to look up * @param cmd The command that was called that now wants to query the cache loader * @return null or a CompletionStage that when complete all listeners will be notified * @throws Throwable */ protected final CompletionStage<?> loadIfNeeded(final InvocationContext ctx, Object key, final FlagAffectedCommand cmd) { int segment = SegmentSpecificCommand.extractSegment(cmd, key, partitioner); if (skipLoad(ctx, key, segment, cmd)) { return null; } return loadInContext(ctx, key, segment, cmd); } /** * Attemps to load the given entry for a key from the persistence store. This method optimizes concurrent loads * of the same key so only the first is actually loaded. The additional loads will in turn complete when the * first completes, which provides minimal hits to the backing store(s). * @param ctx context for this invocation * @param key key to find the entry for * @param segment the segment of the key * @param cmd the command that initiated this load * @return a stage that when complete will have the entry loaded into the provided context */ protected CompletionStage<?> loadInContext(InvocationContext ctx, Object key, int segment, FlagAffectedCommand cmd) { CompletableFuture<InternalCacheEntry<K, V>> cf = new CompletableFuture<>(); CompletionStage<InternalCacheEntry<K, V>> otherCF = pendingLoads.putIfAbsent(key, cf); if (otherCF != null) { // Nothing to clean up, just put the entry from the other load in the context if (log.isTraceEnabled()) { log.tracef("Piggybacking on concurrent load for key %s", key); } // Resume on a different CPU thread so we don't have to wait until the other command completes return otherCF.thenAcceptAsync(entry -> putInContext(ctx, key, cmd, entry), nonBlockingExecutor); } try { CompletionStage<InternalCacheEntry<K, V>> result = loadAndStoreInDataContainer(ctx, key, segment, cmd); if (CompletionStages.isCompletedSuccessfully(result)) { finishLoadInContext(ctx, key, cmd, cf, CompletionStages.join(result), null); } else { result.whenComplete((value, throwable) -> finishLoadInContext(ctx, key, cmd, cf, value, throwable)); } } catch (Throwable t) { pendingLoads.remove(key); cf.completeExceptionally(t); } return cf; } private void finishLoadInContext(InvocationContext ctx, Object key, FlagAffectedCommand cmd, CompletableFuture<InternalCacheEntry<K, V>> cf, InternalCacheEntry<K, V> value, Throwable throwable) { // Make sure we clean up our pendingLoads properly and before completing any responses pendingLoads.remove(key); if (throwable != null) { cf.completeExceptionally(throwable); } else { putInContext(ctx, key, cmd, value); cf.complete(value); } } private void putInContext(InvocationContext ctx, Object key, FlagAffectedCommand cmd, InternalCacheEntry<K, V> entry) { if (entry != null) { entryFactory.wrapExternalEntry(ctx, key, entry, true, cmd instanceof WriteCommand); } CacheEntry contextEntry = ctx.lookupEntry(key); if (contextEntry instanceof MVCCEntry) { ((MVCCEntry) contextEntry).setLoaded(true); } } public CompletionStage<InternalCacheEntry<K, V>> loadAndStoreInDataContainer(InvocationContext ctx, Object key, int segment, FlagAffectedCommand cmd) { InternalCacheEntry<K, V> entry = dataContainer.peek(segment, key); boolean includeStores = true; if (entry != null) { if (!entry.canExpire() || !entry.isExpired(timeService.wallClockTime())) { return CompletableFuture.completedFuture(entry); } includeStores = false; } if (log.isTraceEnabled()) { log.tracef("Loading entry for key %s", key); } CompletionStage<InternalCacheEntry<K, V>> resultStage = persistenceManager.<K, V>loadFromAllStores(key, segment, ctx.isOriginLocal(), includeStores).thenApply(me -> { if (me != null) { InternalCacheEntry<K, V> ice = PersistenceUtil.convert(me, iceFactory); if (getStatisticsEnabled()) { cacheLoads.incrementAndGet(); } if (log.isTraceEnabled()) { log.tracef("Loaded entry: %s for key %s from store and attempting to insert into data container", ice, key); } DataContainer.ComputeAction<K, V> putIfAbsentOrExpired = (k, oldEntry, factory) -> { if (oldEntry != null && (!oldEntry.canExpire() || !oldEntry.isExpired(timeService.wallClockTime()))) { return oldEntry; } if (ice.canExpire()) { ice.touch(timeService.wallClockTime()); } return ice; }; dataContainer.compute(segment, (K) key, putIfAbsentOrExpired); return ice; } else { if (log.isTraceEnabled()) { log.tracef("Missed entry load for key %s from store", key); } if (getStatisticsEnabled()) { cacheMisses.incrementAndGet(); } return null; } }); if (notifier.hasListener(CacheEntryLoaded.class) || notifier.hasListener(CacheEntryActivated.class)) { return resultStage.thenCompose(ice -> { if (ice != null) { V value = ice.getValue(); CompletionStage<Void> notificationStage = sendNotification(key, value, true, ctx, cmd); notificationStage = notificationStage.thenCompose(v -> sendNotification(key, value, false, ctx, cmd)); return notificationStage.thenApply(ignore -> ice); } else { return CompletableFutures.completedNull(); } }); } return resultStage; } private boolean skipLoad(InvocationContext ctx, Object key, int segment, FlagAffectedCommand cmd) { CacheEntry e = ctx.lookupEntry(key); if (e == null) { if (log.isTraceEnabled()) { log.tracef("Skip load for command %s. Entry is not in the context.", cmd); } return true; } if (e.getValue() != null) { if (log.isTraceEnabled()) { log.tracef("Skip load for command %s. Entry %s (skipLookup=%s) has non-null value.", cmd, e, e.skipLookup()); } return true; } if (e.skipLookup()) { if (log.isTraceEnabled()) { log.tracef("Skip load for command %s. Entry %s (skipLookup=%s) is set to skip lookup.", cmd, e, e.skipLookup()); } return true; } if (!cmd.hasAnyFlag(FlagBitSets.SKIP_OWNERSHIP_CHECK) && !canLoad(key, segment)) { if (log.isTraceEnabled()) { log.tracef("Skip load for command %s. Cannot load the key.", cmd); } return true; } boolean skip; if (cmd instanceof WriteCommand) { skip = skipLoadForWriteCommand((WriteCommand) cmd, key, ctx); if (log.isTraceEnabled()) { log.tracef("Skip load for write command %s? %s", cmd, skip); } } else { //read command skip = hasSkipLoadFlag(cmd); if (log.isTraceEnabled()) { log.tracef("Skip load for command %s?. %s", cmd, skip); } } return skip; } protected boolean skipLoadForWriteCommand(WriteCommand cmd, Object key, InvocationContext ctx) { // TODO loading should be mandatory if there are listeners for previous values if (cmd.loadType() != VisitableCommand.LoadType.DONT_LOAD) { if (hasSkipLoadFlag(cmd)) { log.tracef("Skipping load for command that reads existing values %s", cmd); return true; } else { return false; } } return true; } protected CompletionStage<Void> sendNotification(Object key, Object value, boolean pre, InvocationContext ctx, FlagAffectedCommand cmd) { CompletionStage<Void> stage = notifier.notifyCacheEntryLoaded(key, value, pre, ctx, cmd); if (activation) { if (CompletionStages.isCompletedSuccessfully(stage)) { stage = notifier.notifyCacheEntryActivated(key, value, pre, ctx, cmd); } else { stage = CompletionStages.allOf(stage, notifier.notifyCacheEntryActivated(key, value, pre, ctx, cmd)); } } return stage; } @ManagedAttribute( description = "Number of entries loaded from cache store", displayName = "Number of cache store loads", measurementType = MeasurementType.TRENDSUP ) public long getCacheLoaderLoads() { return cacheLoads.get(); } @ManagedAttribute( description = "Number of entries that did not exist in cache store", displayName = "Number of cache store load misses", measurementType = MeasurementType.TRENDSUP ) public long getCacheLoaderMisses() { return cacheMisses.get(); } @Override public void resetStatistics() { cacheLoads.set(0); cacheMisses.set(0); } /** * This method returns a collection of cache loader types (fully qualified class names) that are configured and enabled. */ @ManagedAttribute( description = "Returns a collection of cache loader types which are configured and enabled", displayName = "Returns a collection of cache loader types which are configured and enabled") public Collection<String> getStores() { if (usingStores) { return persistenceManager.getStoresAsString(); } else { return Collections.emptySet(); } } /** * Disables a store of a given type. * * If the given type cannot be found, this is a no-op. If more than one store of the same type is configured, * all stores of the given type are disabled. * * @param storeType fully qualified class name of the cache loader type to disable */ @ManagedOperation( description = "Disable all stores of a given type, where type is a fully qualified class name of the cache loader to disable", displayName = "Disable all stores of a given type" ) public void disableStore(@Parameter(name = "storeType", description = "Fully qualified class name of a store implementation") String storeType) { persistenceManager.disableStore(storeType); } /** * Resolves how the operation should be performed. * If the command is for state transfer then we do not use shared stores, any other type of command can use * {@link org.infinispan.persistence.manager.PersistenceManager.AccessMode#BOTH}. * * @param command: The received command. * @return An access mode. */ private Predicate<? super StoreConfiguration> resolveStorePredicate(FlagAffectedCommand command) { if (command.hasAnyFlag(FlagBitSets.STATE_TRANSFER_PROGRESS)) { return PRIVATE; } return BOTH; } private class WrappedEntrySet extends InternalCacheSet<CacheEntry<K, V>> { protected final CacheSet<CacheEntry<K, V>> next; private final FlagAffectedCommand command; public WrappedEntrySet(CacheSet<CacheEntry<K, V>> next, FlagAffectedCommand command) { this.next = next; this.command = command; } @Override public Publisher<CacheEntry<K, V>> localPublisher(int segment) { Publisher<CacheEntry<K, V>> inMemorySource = next.localPublisher(segment); IntSet segments = IntSets.immutableSet(segment); return getCacheEntryPublisher(inMemorySource, segments); } @Override public Publisher<CacheEntry<K, V>> localPublisher(IntSet segments) { Publisher<CacheEntry<K, V>> inMemorySource = next.localPublisher(segments); return getCacheEntryPublisher(inMemorySource, segments); } private Publisher<CacheEntry<K, V>> getCacheEntryPublisher(Publisher<CacheEntry<K, V>> inMemorySource, IntSet segments) { Set<K> seenKeys = new HashSet<>(dataContainer.sizeIncludingExpired(segments)); Publisher<MarshallableEntry<K, V>> loaderSource = persistenceManager.publishEntries(segments, k -> !seenKeys.contains(k), true, true, resolveStorePredicate(command)); return Flowable.concat( Flowable.fromPublisher(inMemorySource) .doOnNext(ce -> seenKeys.add(ce.getKey())), Flowable.fromPublisher(loaderSource) .map(me -> PersistenceUtil.convert(me, iceFactory))); } } private class WrappedKeySet extends InternalCacheSet<K> { protected final CacheSet<K> next; private final FlagAffectedCommand command; public WrappedKeySet(CacheSet<K> next, FlagAffectedCommand command) { this.next = next; this.command = command; } @Override public Publisher<K> localPublisher(int segment) { Publisher<K> inMemorySource = next.localPublisher(segment); IntSet segments = IntSets.immutableSet(segment); return getKeyPublisher(inMemorySource, segments); } @Override public Publisher<K> localPublisher(IntSet segments) { Publisher<K> inMemorySource = next.localPublisher(segments); return getKeyPublisher(inMemorySource, segments); } private Publisher<K> getKeyPublisher(Publisher<K> inMemorySource, IntSet segments) { Set<K> seenKeys = new HashSet<>(dataContainer.sizeIncludingExpired(segments)); return Flowable.concat( Flowable.fromPublisher(inMemorySource) .doOnNext(seenKeys::add), persistenceManager.publishKeys(segments, k -> !seenKeys.contains(k), resolveStorePredicate(command))); } } }
26,864
40.458333
198
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/IsMarshallableInterceptor.java
package org.infinispan.interceptors.impl; import java.util.Map; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.functional.ReadWriteKeyCommand; import org.infinispan.commands.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; 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.commons.marshall.NotSerializableException; import org.infinispan.commons.marshall.StreamAwareMarshaller; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; 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.annotations.Stop; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.manager.PersistenceManager.StoreChangeListener; /** * Interceptor to verify whether parameters passed into cache are marshallables * or not. * * <p>This is handy when marshalling happens in a separate * thread and marshalling failures might be swallowed. * Currently, this only happens when we have an asynchronous store.</p> * * @author Galder Zamarreño * @since 9.0 */ public class IsMarshallableInterceptor extends DDAsyncInterceptor { @Inject @ComponentName(KnownComponentNames.PERSISTENCE_MARSHALLER) StreamAwareMarshaller marshaller; @Inject PersistenceManager persistenceManager; private volatile boolean usingAsyncStore; private StoreChangeListener storeChangeListener = pm -> usingAsyncStore = pm.usingAsyncStore(); @Start protected void start() { usingAsyncStore = cacheConfiguration.persistence().usingAsyncStore(); storeChangeListener = status -> usingAsyncStore = status.usingAsyncStore(); persistenceManager.addStoreListener(storeChangeListener); } @Stop protected void stop() { persistenceManager.removeStoreListener(storeChangeListener); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getValue()); } return invokeNext(ctx, command); } @Override public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); checkMarshallable(command.getValue()); checkMarshallable(command.getMetadata()); checkMarshallable(command.getInternalMetadata()); } return invokeNext(ctx, command); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getMap()); } return invokeNext(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); } return invokeNext(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getNewValue()); } return invokeNext(ctx, command); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); } return invokeNext(ctx, command); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); } return invokeNext(ctx, command); } @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); } return invokeNext(ctx, command); } private boolean isUsingAsyncStore(InvocationContext ctx, FlagAffectedCommand command) { return usingAsyncStore && ctx.isOriginLocal() && !command.hasAnyFlag(FlagBitSets.SKIP_CACHE_STORE); } private void checkMarshallable(Object o) throws NotSerializableException { boolean marshallable = false; try { marshallable = marshaller.isMarshallable(o); } catch (Exception e) { throwNotSerializable(o, e); } if (!marshallable) throwNotSerializable(o, null); } private void throwNotSerializable(Object o, Throwable t) { String msg = String.format( "Object of type %s expected to be marshallable", o.getClass()); if (t == null) throw new NotSerializableException(msg); else throw new NotSerializableException(msg, t); } private void checkMarshallable(Map<Object, Object> objs) throws NotSerializableException { for (Map.Entry<Object, Object> entry : objs.entrySet()) { checkMarshallable(entry.getKey()); checkMarshallable(entry.getValue()); } } }
5,720
34.981132
118
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/BaseRpcInterceptor.java
package org.infinispan.interceptors.impl; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.context.Flag; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.LocalTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.DistributionInfo; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.transaction.impl.LocalTransaction; import org.infinispan.util.logging.Log; /** * Acts as a base for all RPC calls * * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a> * @author Mircea.Markus@jboss.com * @since 9.0 */ public abstract class BaseRpcInterceptor extends DDAsyncInterceptor { @Inject protected RpcManager rpcManager; @Inject protected ComponentRegistry componentRegistry; protected boolean defaultSynchronous; protected abstract Log getLog(); @Start public void init() { defaultSynchronous = cacheConfiguration.clustering().cacheMode().isSynchronous(); } protected final boolean isSynchronous(FlagAffectedCommand command) { if (command.hasAnyFlag(FlagBitSets.FORCE_SYNCHRONOUS)) return true; else if (command.hasAnyFlag(FlagBitSets.FORCE_ASYNCHRONOUS)) return false; return defaultSynchronous; } protected final boolean isLocalModeForced(FlagAffectedCommand command) { return command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL); } protected boolean shouldInvokeRemoteTxCommand(TxInvocationContext ctx) { if (!ctx.isOriginLocal()) { return false; } // Skip the remote invocation if this is a state transfer transaction LocalTxInvocationContext localCtx = (LocalTxInvocationContext) ctx; if (localCtx.getCacheTransaction().getStateTransferFlag() == Flag.PUT_FOR_STATE_TRANSFER) { return false; } // just testing for empty modifications isn't enough - the Lock API may acquire locks on keys but won't // register a Modification. See ISPN-711. boolean shouldInvokeRemotely = ctx.hasModifications() || !localCtx.getRemoteLocksAcquired().isEmpty() || localCtx.getCacheTransaction().getTopologyId() != rpcManager.getTopologyId(); if (getLog().isTraceEnabled()) { getLog().tracef("Should invoke remotely? %b. hasModifications=%b, hasRemoteLocksAcquired=%b", shouldInvokeRemotely, ctx.hasModifications(), !localCtx.getRemoteLocksAcquired().isEmpty()); } return shouldInvokeRemotely; } protected static void transactionRemotelyPrepared(TxInvocationContext ctx) { if (ctx.isOriginLocal()) { ((LocalTransaction)ctx.getCacheTransaction()).markPrepareSent(); } } protected boolean shouldLoad(InvocationContext ctx, FlagAffectedCommand command, DistributionInfo info) { if (command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_REMOTE_LOOKUP)) return false; VisitableCommand.LoadType loadType = command.loadType(); switch (loadType) { case DONT_LOAD: return false; case OWNER: return info.isPrimary() || (info.isWriteOwner() && !ctx.isOriginLocal()); case PRIMARY: return info.isPrimary(); default: throw new IllegalStateException(); } } }
3,681
36.191919
110
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/EntryWrappingInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.commons.util.Util.toStr; import static org.infinispan.container.impl.EntryFactory.expirationCheckDelay; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.commands.AbstractVisitor; import org.infinispan.commands.DataCommand; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.functional.FunctionalCommand; 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.read.AbstractDataCommand; import org.infinispan.commands.read.GetAllCommand; import org.infinispan.commands.read.GetCacheEntryCommand; import org.infinispan.commands.read.GetKeyValueCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.AbstractDataWriteCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; import org.infinispan.commands.write.DataWriteCommand; 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.commands.write.WriteCommand; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.configuration.cache.Configurations; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.MVCCEntry; import org.infinispan.container.impl.EntryFactory; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.versioning.VersionGenerator; import org.infinispan.context.Flag; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.SingleKeyNonTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.distribution.group.impl.GroupManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.ExceptionSyncInvocationStage; import org.infinispan.interceptors.InvocationFinallyFunction; import org.infinispan.interceptors.InvocationSuccessFunction; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.remoting.responses.Response; import org.infinispan.remoting.transport.Address; import org.infinispan.statetransfer.OutdatedTopologyException; import org.infinispan.statetransfer.StateConsumer; import org.infinispan.statetransfer.StateTransferLock; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.impl.WriteSkewHelper; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.concurrent.IsolationLevel; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.infinispan.xsite.statetransfer.XSiteStateConsumer; /** * Interceptor in charge with wrapping entries and add them in caller's context. * * @see EntryFactory for overview of entry wrapping. * * @author Mircea Markus * @author Pedro Ruivo * @since 9.0 */ public class EntryWrappingInterceptor extends DDAsyncInterceptor { @Inject EntryFactory entryFactory; @Inject InternalDataContainer<Object, Object> dataContainer; @Inject protected ClusteringDependentLogic cdl; @Inject VersionGenerator versionGenerator; @Inject protected DistributionManager distributionManager; @Inject ComponentRef<StateConsumer> stateConsumer; @Inject StateTransferLock stateTransferLock; @Inject ComponentRef<XSiteStateConsumer> xSiteStateConsumer; @Inject GroupManager groupManager; @Inject CacheNotifier<Object, Object> notifier; @Inject KeyPartitioner keyPartitioner; private final EntryWrappingVisitor entryWrappingVisitor = new EntryWrappingVisitor(); private boolean isInvalidation; private boolean isSync; private boolean useRepeatableRead; private boolean isVersioned; private boolean isPessimistic; private static final Log log = LogFactory.getLog(EntryWrappingInterceptor.class); private static final long EVICT_FLAGS_BITSET = FlagBitSets.SKIP_OWNERSHIP_CHECK | FlagBitSets.CACHE_MODE_LOCAL; private void addVersionRead(InvocationContext rCtx, AbstractDataCommand dataCommand) { // The entry must be in the context CacheEntry cacheEntry = rCtx.lookupEntry(dataCommand.getKey()); cacheEntry.setSkipLookup(true); if (isVersioned && ((MVCCEntry) cacheEntry).isRead()) { WriteSkewHelper.addVersionRead((TxInvocationContext) rCtx, cacheEntry, dataCommand.getKey(), versionGenerator, log); } } private final InvocationSuccessFunction<AbstractDataCommand> dataReadReturnHandler = (rCtx, dataCommand, rv) -> { if (rCtx.isInTxScope() && useRepeatableRead) { // This invokes another method as this is only done with a specific configuration and we want to inline // the notifier below addVersionRead(rCtx, dataCommand); } // Entry visit notifications used to happen in the CallInterceptor // We do it at the end to avoid adding another try/finally block around the notifications if (rv != null && !(rv instanceof Response)) { Object value = dataCommand instanceof GetCacheEntryCommand ? ((CacheEntry) rv).getValue() : rv; CompletionStage<Void> stage = notifier.notifyCacheEntryVisited(dataCommand.getKey(), value, true, rCtx, dataCommand); // If stage is already complete, we can avoid allocating lambda below if (CompletionStages.isCompletedSuccessfully(stage)) { stage = notifier.notifyCacheEntryVisited(dataCommand.getKey(), value, false, rCtx, dataCommand); } else { // Make sure to fire the events serially stage = stage.thenCompose(v -> notifier.notifyCacheEntryVisited(dataCommand.getKey(), value, false, rCtx, dataCommand)); } return delayedValue(stage, rv); } return rv; }; private final InvocationSuccessFunction<VisitableCommand> commitEntriesSuccessHandler = (rCtx, rCommand, rv) -> delayedValue(commitContextEntries(rCtx, null), rv); private final InvocationFinallyFunction<CommitCommand> commitEntriesFinallyHandler = this::commitEntriesFinally; private final InvocationSuccessFunction<PrepareCommand> prepareHandler = this::prepareHandler; private final InvocationSuccessFunction<DataWriteCommand> applyAndFixVersion = this::applyAndFixVersion; private final InvocationSuccessFunction<WriteCommand> applyAndFixVersionForMany = this::applyAndFixVersionForMany; private final InvocationFinallyFunction<GetAllCommand> getAllHandleFunction = this::getAllHandle; @Start public void start() { isInvalidation = cacheConfiguration.clustering().cacheMode().isInvalidation(); isSync = cacheConfiguration.clustering().cacheMode().isSynchronous(); // isolation level makes no sense without transactions useRepeatableRead = cacheConfiguration.transaction().transactionMode().isTransactional() && cacheConfiguration.locking().isolationLevel() == IsolationLevel.REPEATABLE_READ; isVersioned = Configurations.isTxVersioned(cacheConfiguration); isPessimistic = cacheConfiguration.transaction().transactionMode().isTransactional() && cacheConfiguration.transaction().lockingMode() == LockingMode.PESSIMISTIC; } private boolean ignoreOwnership(FlagAffectedCommand command) { return distributionManager == null || command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_OWNERSHIP_CHECK); } protected boolean canRead(DataCommand command) { return distributionManager.getCacheTopology().isSegmentReadOwner(command.getSegment()); } protected boolean canReadKey(Object key) { return distributionManager.getCacheTopology().isReadOwner(key); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { return wrapEntriesForPrepareAndApply(ctx, command, prepareHandler); } private Object prepareHandler(InvocationContext ctx, PrepareCommand command, Object rv) { if (command.isOnePhaseCommit()) { return invokeNextThenApply(ctx, command, commitEntriesSuccessHandler); } else { return invokeNext(ctx, command); } } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { return invokeNextAndHandle(ctx, command, commitEntriesFinallyHandler); } @Override public final Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { return visitDataReadCommand(ctx, command); } @Override public final Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable { return visitDataReadCommand(ctx, command); } private Object visitDataReadCommand(InvocationContext ctx, AbstractDataCommand command) { final Object key = command.getKey(); CompletionStage<Void> stage = entryFactory.wrapEntryForReading(ctx, key, command.getSegment(), ignoreOwnership(command) || canRead(command), command.hasAnyFlag(FlagBitSets.ALREADY_HAS_LOCK) || (isPessimistic && command.hasAnyFlag(FlagBitSets.FORCE_WRITE_LOCK)), CompletableFutures.completedNull()); return makeStage(asyncInvokeNext(ctx, command, stage)).thenApply(ctx, command, dataReadReturnHandler); } @Override public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { boolean ignoreOwnership = ignoreOwnership(command); CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getKeys()) { currentStage = entryFactory.wrapEntryForReading(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), false, currentStage); } return makeStage(asyncInvokeNext(ctx, command, expirationCheckDelay(currentStage, initialStage))) .andHandle(ctx, command, getAllHandleFunction); } private Object getAllHandle(InvocationContext rCtx, GetAllCommand command, Object rv, Throwable t) { if (useRepeatableRead) { for (Object key : command.getKeys()) { CacheEntry cacheEntry = rCtx.lookupEntry(key); if (cacheEntry == null) { // Data was lost if (log.isTraceEnabled()) log.tracef(t, "Missing entry for " + key); } else { cacheEntry.setSkipLookup(true); } } } AggregateCompletionStage<Void> stage = CompletionStages.aggregateCompletionStage(); // Entry visit notifications used to happen in the CallInterceptor // instanceof check excludes the case when the command returns UnsuccessfulResponse if (t == null && rv instanceof Map) { boolean notify = !command.hasAnyFlag(FlagBitSets.SKIP_LISTENER_NOTIFICATION) && notifier.hasListener(CacheEntryVisited.class); log.tracef("Notifying getAll? %s; result %s", notify, rv); if (notify) { Map<Object, Object> map = (Map<Object, Object>) rv; for (Map.Entry<Object, Object> entry : map.entrySet()) { Object value = entry.getValue(); if (value != null) { Object finalValue = command.isReturnEntries() ? ((CacheEntry) value).getValue() : entry.getValue(); CompletionStage<Void> innerStage = notifier.notifyCacheEntryVisited(entry.getKey(), finalValue, true, rCtx, command); stage.dependsOn(innerStage.thenCompose(ig -> notifier.notifyCacheEntryVisited(entry.getKey(), finalValue, false, rCtx, command))); } } } } return delayedValue(stage.freeze(), rv, t); } @Override public final Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) { CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; if (command.getKeys() != null) { for (Object key : command.getKeys()) { // TODO: move this to distribution interceptors? // we need to try to wrap the entry to get it removed // for the removal itself, wrapping null would suffice, but listeners need previous value currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), true, false, currentStage); } } return setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(ctx, command, expirationCheckDelay(currentStage, initialStage)); } @Override public final Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, rCommand, rv) -> { // If we are committing a ClearCommand now then no keys should be written by state transfer from // now on until current rebalance ends. if (stateConsumer.running() != null) { stateConsumer.running().stopApplyingState(rCommand.getTopologyId()); } if (xSiteStateConsumer.running() != null) { xSiteStateConsumer.running().endStateTransfer(null); } CompletionStage<Void> stage = null; if (!rCtx.isInTxScope()) { stage = applyChanges(rCtx, rCommand); } if (log.isTraceEnabled()) log.tracef("The return value is %s", rv); return delayedValue(stage, rv); }); } @Override public Object visitInvalidateL1Command(InvocationContext ctx, InvalidateL1Command command) { CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getKeys()) { // TODO: move to distribution interceptors? // we need to try to wrap the entry to get it removed // for the removal itself, wrapping null would suffice, but listeners need previous value currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), false, false, currentStage); if (log.isTraceEnabled()) log.tracef("Entry to be removed: %s", toStr(key)); } return setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(ctx, command, expirationCheckDelay(currentStage, initialStage)); } @Override public final Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public final Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) { boolean isOwner = ignoreOwnership(command) || canRead(command); entryFactory.wrapEntryForWritingSkipExpiration(ctx, command.getKey(), command.getSegment(), isOwner); return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, CompletableFutures.completedNull()); } protected CompletionStage<Void> wrapEntryIfNeeded(InvocationContext ctx, AbstractDataWriteCommand command) { if (command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { removeFromContextOnRetry(ctx, command.getKey()); } // Non-owners should not wrap entries (unless L1 is enabled) boolean isOwner = ignoreOwnership(command) || canRead(command); if (command.hasAnyFlag(FlagBitSets.BACKUP_WRITE)) { // The command has been forwarded to a backup, we don't care if the entry is expired or not entryFactory.wrapEntryForWritingSkipExpiration(ctx, command.getKey(), command.getSegment(), isOwner); return CompletableFutures.completedNull(); } return entryFactory.wrapEntryForWriting(ctx, command.getKey(), command.getSegment(), isOwner, command.loadType() != VisitableCommand.LoadType.DONT_LOAD, CompletableFutures.completedNull()); } private void removeFromContextOnRetry(InvocationContext ctx, Object key) { // When originator is a backup and it becomes primary (and we retry the command), the context already // contains the value before the command started to be executed. However, another modification could happen // after this node became an owner, so we have to force a reload. // With repeatable reads, we cannot just remove the entry from context; instead of we will rely // on the write skew check to do the reload & comparison in the end. // With pessimistic locking, there's no WSC but as we have the entry locked, there shouldn't be any // modification concurrent to the retried operation, therefore we don't have to deal with this problem. if (useRepeatableRead) { MVCCEntry entry = (MVCCEntry) ctx.lookupEntry(key); if (log.isTraceEnabled()) { log.tracef("This is a retry - resetting previous value in entry %s", entry); } if (entry != null) { entry.resetCurrentValue(); } } else { if (log.isTraceEnabled()) { log.tracef("This is a retry - removing looked up entry %s", ctx.lookupEntry(key)); } ctx.removeLookedUpEntry(key); } } private void removeFromContextOnRetry(InvocationContext ctx, Collection<?> keys) { if (useRepeatableRead) { if (log.isTraceEnabled()) { log.tracef("This is a retry - resetting previous values for %s", keys); } for (Object key : keys) { MVCCEntry entry = (MVCCEntry) ctx.lookupEntry(key); // When a non-transactional command is retried remotely, the context is going to be empty if (entry != null) { entry.resetCurrentValue(); } } } else { ctx.removeLookedUpEntries(keys); } } @Override public final Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) throws Throwable { boolean isOwner = ignoreOwnership(command) || canRead(command); entryFactory.wrapEntryForWritingSkipExpiration(ctx, command.getKey(), command.getSegment(), isOwner); return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, CompletableFutures.completedNull()); } @Override public final Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { boolean ignoreOwnership = ignoreOwnership(command); if (command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { removeFromContextOnRetry(ctx, command.getAffectedKeys()); } CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getMap().keySet()) { // as listeners may need the value, we'll load the previous value currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), command.loadType() != VisitableCommand.LoadType.DONT_LOAD, currentStage); } return setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(ctx, command, expirationCheckDelay(currentStage, initialStage)); } @Override public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { command.setFlagsBitSet(command.getFlagsBitSet() | EVICT_FLAGS_BITSET); //to force the wrapping return visitRemoveCommand(ctx, command); } @Override public Object visitReadOnlyKeyCommand(InvocationContext ctx, ReadOnlyKeyCommand command) throws Throwable { CompletionStage<Void> stage; if (command instanceof TxReadOnlyKeyCommand) { // TxReadOnlyKeyCommand may apply some mutations on the entry in context so we need to always wrap it stage = entryFactory.wrapEntryForWriting(ctx, command.getKey(), command.getSegment(), ignoreOwnership(command) || canRead(command), true, CompletableFutures.completedNull()); } else { stage = entryFactory.wrapEntryForReading(ctx, command.getKey(), command.getSegment(), ignoreOwnership(command) || canRead(command), false, CompletableFutures.completedNull()); } // Repeatable reads are not achievable with functional commands, as we don't store the value locally // and we don't "fix" it on the remote node; therefore, the value will be able to change and identity read // could return different values in the same transaction. // (Note: at this point TX mode is not implemented for functional commands anyway). return asyncInvokeNext(ctx, command, stage); } @Override public Object visitReadOnlyManyCommand(InvocationContext ctx, ReadOnlyManyCommand command) throws Throwable { boolean ignoreOwnership = ignoreOwnership(command); CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; if (command instanceof TxReadOnlyManyCommand) { // TxReadOnlyManyCommand may apply some mutations on the entry in context so we need to always wrap it for (Object key : command.getKeys()) { // TODO: need to handle this currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership(command) || canReadKey(key), true, currentStage); } } else { for (Object key : command.getKeys()) { currentStage = entryFactory.wrapEntryForReading(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), false, currentStage); } } // Repeatable reads are not achievable with functional commands, see visitReadOnlyKeyCommand return asyncInvokeNext(ctx, command, expirationCheckDelay(currentStage, initialStage)); } @Override public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) throws Throwable { if (command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { removeFromContextOnRetry(ctx, command.getAffectedKeys()); } boolean ignoreOwnership = ignoreOwnership(command); CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getArguments().keySet()) { //the put map never reads the keys currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), false, currentStage); } return setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(ctx, command, expirationCheckDelay(currentStage, initialStage)); } @Override public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) throws Throwable { if (command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { removeFromContextOnRetry(ctx, command.getAffectedKeys()); } boolean ignoreOwnership = ignoreOwnership(command); CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getAffectedKeys()) { currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), false, currentStage); } return setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(ctx, command, expirationCheckDelay(currentStage, initialStage)); } @Override public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) throws Throwable { return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command, wrapEntryIfNeeded(ctx, command)); } @Override public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) throws Throwable { if (command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { removeFromContextOnRetry(ctx, command.getAffectedKeys()); } boolean ignoreOwnership = ignoreOwnership(command); CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getAffectedKeys()) { currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), true, currentStage); } return setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(ctx, command, expirationCheckDelay(currentStage, initialStage)); } @Override public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) throws Throwable { if (command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { removeFromContextOnRetry(ctx, command.getAffectedKeys()); } boolean ignoreOwnership = ignoreOwnership(command); CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getAffectedKeys()) { currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), true, currentStage); } return setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(ctx, command, expirationCheckDelay(currentStage, initialStage)); } protected final CompletionStage<Void> commitContextEntries(InvocationContext ctx, FlagAffectedCommand command) { final Flag stateTransferFlag = FlagBitSets.extractStateTransferFlag(ctx, command); if (ctx instanceof SingleKeyNonTxInvocationContext) { SingleKeyNonTxInvocationContext singleKeyCtx = (SingleKeyNonTxInvocationContext) ctx; return commitEntryIfNeeded(ctx, command, singleKeyCtx.getKey(), singleKeyCtx.getCacheEntry(), stateTransferFlag); } else { AggregateCompletionStage<Void> aggregateCompletionStage = null; Map<Object, CacheEntry> entries = ctx.getLookedUpEntries(); for (Map.Entry<Object, CacheEntry> entry : entries.entrySet()) { CompletionStage<Void> stage = commitEntryIfNeeded(ctx, command, entry.getKey(), entry.getValue(), stateTransferFlag); if (!CompletionStages.isCompletedSuccessfully(stage)) { if (aggregateCompletionStage == null) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); } aggregateCompletionStage.dependsOn(stage); } } return aggregateCompletionStage != null ? aggregateCompletionStage.freeze() : CompletableFutures.completedNull(); } } protected CompletionStage<Void> commitContextEntry(CacheEntry<?, ?> entry, InvocationContext ctx, FlagAffectedCommand command, Flag stateTransferFlag, boolean l1Invalidation) { return cdl.commitEntry(entry, command, ctx, stateTransferFlag, l1Invalidation); } private boolean needTopologyCheck(WriteCommand command) { // No retry in local or invalidation caches if (isInvalidation || distributionManager == null || command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL)) return false; // Async commands cannot be retried return isSync && !command.hasAnyFlag(FlagBitSets.FORCE_ASYNCHRONOUS) || command.hasAnyFlag(FlagBitSets.FORCE_SYNCHRONOUS); } private LocalizedCacheTopology checkTopology(WriteCommand command, LocalizedCacheTopology commandTopology) { int commandTopologyId = command.getTopologyId(); LocalizedCacheTopology currentTopology = distributionManager.getCacheTopology(); int currentTopologyId = currentTopology.getTopologyId(); // Can't perform the check during preload or if the cache isn't clustered if (currentTopologyId == commandTopologyId || commandTopologyId == -1) return currentTopology; if (commandTopology != null) { // commandTopology != null means the modification is already committed to the data container // We want to retry the command if new owners were added since the command's topology, // but if there are no new owners retrying won't help. IntSet segments; boolean ownersAdded; if (command instanceof DataCommand) { int segment = ((DataCommand) command).getSegment(); ownersAdded = segmentAddedOwners(commandTopology, currentTopology, segment); } else { segments = IntSets.mutableEmptySet(currentTopology.getNumSegments()); for (Object key : command.getAffectedKeys()) { int segment = keyPartitioner.getSegment(key); segments.set(segment); } ownersAdded = false; for (int segment : segments) { if (segmentAddedOwners(commandTopology, currentTopology, segment)) { ownersAdded = true; break; } } } if (!ownersAdded) { if (log.isTraceEnabled()) log.tracef("Cache topology changed but no owners were added for keys %s", command.getAffectedKeys()); return null; } } if (log.isTraceEnabled()) log.tracef("Cache topology changed while the command was executing: expected %d, got %d", commandTopologyId, currentTopologyId); // This shouldn't be necessary, as we'll have a fresh command instance when retrying command.setValueMatcher(command.getValueMatcher().matcherForRetry()); throw OutdatedTopologyException.RETRY_NEXT_TOPOLOGY; } private boolean segmentAddedOwners(LocalizedCacheTopology commandTopology, LocalizedCacheTopology currentTopology, int segment) { List<Address> commandTopologyOwners = commandTopology.getSegmentDistribution(segment).writeOwners(); List<Address> currentOwners = currentTopology.getDistribution(segment).writeOwners(); return !commandTopologyOwners.containsAll(currentOwners); } private CompletionStage<Void> applyChanges(InvocationContext ctx, WriteCommand command) { // Unsuccessful commands do not modify anything so they don't need to be retried either if (!command.isSuccessful()) return CompletableFutures.completedNull(); boolean needTopologyCheck = needTopologyCheck(command); LocalizedCacheTopology commandTopology = needTopologyCheck ? checkTopology(command, null) : null; CompletionStage<Void> cs = commitContextEntries(ctx, command); if (needTopologyCheck) { if (CompletionStages.isCompletedSuccessfully(cs)) { checkTopology(command, commandTopology); } else { return cs.thenRun(() -> checkTopology(command, commandTopology)); } } return cs; } /** * Locks the value for the keys accessed by the command to avoid being override from a remote get. */ protected Object setSkipRemoteGetsAndInvokeNextForManyEntriesCommand(InvocationContext ctx, WriteCommand command, CompletionStage<Void> delay) { return makeStage(asyncInvokeNext(ctx, command, delay)).thenApply(ctx, command, applyAndFixVersionForMany); } private Object applyAndFixVersionForMany(InvocationContext ctx, WriteCommand writeCommand, Object rv) { if (!ctx.isInTxScope()) { return delayedValue(applyChanges(ctx, writeCommand), rv); } if (log.isTraceEnabled()) log.tracef("The return value is %s", toStr(rv)); if (useRepeatableRead) { boolean addVersionRead = isVersioned && writeCommand.loadType() != VisitableCommand.LoadType.DONT_LOAD; TxInvocationContext txCtx = (TxInvocationContext) ctx; for (Object key : writeCommand.getAffectedKeys()) { CacheEntry cacheEntry = ctx.lookupEntry(key); if (cacheEntry != null) { cacheEntry.setSkipLookup(true); if (addVersionRead && ((MVCCEntry) cacheEntry).isRead()) { WriteSkewHelper.addVersionRead(txCtx, cacheEntry, key, versionGenerator, log); } } } } return rv; } /** * Locks the value for the keys accessed by the command to avoid being override from a remote get. */ protected Object setSkipRemoteGetsAndInvokeNextForDataCommand(InvocationContext ctx, DataWriteCommand command, CompletionStage<Void> delay) { return makeStage(asyncInvokeNext(ctx, command, delay)).thenApply(ctx, command, applyAndFixVersion); } private Object applyAndFixVersion(InvocationContext ctx, DataWriteCommand dataWriteCommand, Object rv) { if (!ctx.isInTxScope()) { return delayedValue(applyChanges(ctx, dataWriteCommand), rv); } if (log.isTraceEnabled()) log.tracef("The return value is %s", rv); if (useRepeatableRead) { CacheEntry cacheEntry = ctx.lookupEntry(dataWriteCommand.getKey()); // The entry is not in context when the command's execution type does not contain origin if (cacheEntry != null) { cacheEntry.setSkipLookup(true); if (isVersioned && dataWriteCommand.loadType() != VisitableCommand.LoadType.DONT_LOAD && ((MVCCEntry) cacheEntry).isRead()) { WriteSkewHelper.addVersionRead((TxInvocationContext) ctx, cacheEntry, dataWriteCommand.getKey(), versionGenerator, log); } } } return rv; } private Object commitEntriesFinally(InvocationContext rCtx, VisitableCommand rCommand, Object rv, Throwable t) { // Do not commit if the command will be retried if (t instanceof OutdatedTopologyException) return new ExceptionSyncInvocationStage(t); return delayedValue(commitContextEntries(rCtx, null), rv, t); } // This visitor replays the entry wrapping during remote prepare. // The command is passed down the stack even if its keys do not belong to this node according // to writeCH, it's a role of TxDistributionInterceptor to ignore such command. // The entry is wrapped only if it's available for reading, otherwise it has to be wrapped // in TxDistributionInterceptor. When the entry is not wrapped, the value is not loaded in // CacheLoaderInterceptor, therefore passing the command down the stack causes only minimal overhead. private final class EntryWrappingVisitor extends AbstractVisitor { @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { return handleWriteManyCommand(ctx, command); } @Override public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable { return handleWriteManyCommand(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) throws Throwable { return handleWriteManyCommand(ctx, command); } @Override public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) throws Throwable { return handleWriteCommand(ctx, command); } @Override public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) throws Throwable { return handleWriteManyCommand(ctx, command); } @Override public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) throws Throwable { return handleWriteManyCommand(ctx, command); } @Override public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) throws Throwable { return handleWriteManyCommand(ctx, command); } @Override public Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) throws Throwable { boolean isOwner = ignoreOwnership(command) || canRead(command); entryFactory.wrapEntryForWritingSkipExpiration(ctx, command.getKey(), command.getSegment(), isOwner); return invokeNext(ctx, command); } private Object handleWriteCommand(InvocationContext ctx, DataWriteCommand command) throws Throwable { CompletionStage<Void> stage = entryFactory.wrapEntryForWriting(ctx, command.getKey(), command.getSegment(), ignoreOwnership(command) || canRead(command), command.loadType() != VisitableCommand.LoadType.DONT_LOAD, CompletableFutures.completedNull()); return asyncInvokeNext(ctx, command, stage); } private Object handleWriteManyCommand(InvocationContext ctx, WriteCommand command) { boolean ignoreOwnership = ignoreOwnership(command); CompletableFuture<Void> initialStage = new CompletableFuture<>(); CompletionStage<Void> currentStage = initialStage; for (Object key : command.getAffectedKeys()) { currentStage = entryFactory.wrapEntryForWriting(ctx, key, keyPartitioner.getSegment(key), ignoreOwnership || canReadKey(key), command.loadType() != VisitableCommand.LoadType.DONT_LOAD, currentStage); } return asyncInvokeNext(ctx, command, expirationCheckDelay(currentStage, initialStage)); } } private CompletionStage<Void> commitEntryIfNeeded(final InvocationContext ctx, final FlagAffectedCommand command, Object key, final CacheEntry entry, final Flag stateTransferFlag) { if (entry == null) { if (log.isTraceEnabled()) { log.tracef("Entry for key %s is null : not calling commitUpdate", toStr(key)); } return CompletableFutures.completedNull(); } final boolean l1Invalidation = command instanceof InvalidateL1Command; if (entry.isChanged()) { if (log.isTraceEnabled()) log.tracef("About to commit entry %s", entry); return commitContextEntry(entry, ctx, command, stateTransferFlag, l1Invalidation); } else if (log.isTraceEnabled()) { log.tracef("Entry for key %s is not changed(%s): not calling commitUpdate", toStr(key), entry); } return CompletableFutures.completedNull(); } protected final <P extends PrepareCommand> Object wrapEntriesForPrepareAndApply(TxInvocationContext ctx, P command, InvocationSuccessFunction<P> handler) throws Throwable { if (!ctx.isOriginLocal() || command.isReplayEntryWrapping()) { return applyModificationsAndThen(ctx, command, command.getModifications(), 0, handler); } else if (ctx.isOriginLocal()) { // If there's a functional command invoked in previous topology, it's possible that this node was not an owner // but now it has become one. In that case the modification was not applied into the context and we would not // commit the change. To be on the safe side we'll replay the whole transaction. for (WriteCommand mod : command.getModifications()) { if (mod.getTopologyId() < command.getTopologyId() && mod instanceof FunctionalCommand) { log.trace("Clearing looked up entries and replaying whole transaction"); ctx.getCacheTransaction().clearLookedUpEntries(); return applyModificationsAndThen(ctx, command, command.getModifications(), 0, handler); } } } return handler.apply(ctx, command, null); } private <P extends PrepareCommand> Object applyModificationsAndThen(TxInvocationContext ctx, P command, List<WriteCommand> modifications, int startIndex, InvocationSuccessFunction<P> handler) throws Throwable { // We need to execute modifications for the same key sequentially. In theory we could optimize // this loop if there are multiple remote invocations but since remote invocations are rare, we omit this. for (int i = startIndex; i < modifications.size(); i++) { WriteCommand c = modifications.get(i); c.setTopologyId(command.getTopologyId()); if (c.hasAnyFlag(FlagBitSets.PUT_FOR_X_SITE_STATE_TRANSFER)) { ctx.getCacheTransaction().setStateTransferFlag(Flag.PUT_FOR_X_SITE_STATE_TRANSFER); } Object result = c.acceptVisitor(ctx, entryWrappingVisitor); if (!isSuccessfullyDone(result)) { int nextIndex = i + 1; if (nextIndex >= modifications.size()) { return makeStage(result).thenApply(ctx, command, handler); } return makeStage(result).thenApply(ctx, command, (rCtx, rCommand, rv) -> applyModificationsAndThen(ctx, command, modifications, nextIndex, handler)); } } return handler.apply(ctx, command, null); } }
47,166
49.608369
213
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/ClusteringInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.util.logging.Log.CLUSTER; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.read.SizeCommand; import org.infinispan.commons.CacheException; import org.infinispan.container.impl.EntryFactory; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.expiration.TouchMode; import org.infinispan.expiration.impl.TouchCommand; import org.infinispan.factories.annotations.Inject; import org.infinispan.reactive.publisher.PublisherReducers; import org.infinispan.reactive.publisher.impl.ClusterPublisherManager; import org.infinispan.reactive.publisher.impl.DeliveryGuarantee; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.responses.CacheNotFoundResponse; import org.infinispan.remoting.responses.Response; import org.infinispan.remoting.responses.SuccessfulResponse; import org.infinispan.remoting.responses.UnsureResponse; import org.infinispan.remoting.responses.ValidResponse; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.ValidResponseCollector; import org.infinispan.remoting.transport.impl.SingleResponseCollector; import org.infinispan.statetransfer.AllOwnersLostException; import org.infinispan.statetransfer.OutdatedTopologyException; import org.infinispan.util.CacheTopologyUtil; import org.infinispan.util.concurrent.locks.LockManager; /** * Base class for distribution interceptors. * * @author anistor@redhat.com * @since 9.0 */ public abstract class ClusteringInterceptor extends BaseRpcInterceptor { @Inject protected CommandsFactory cf; @Inject protected EntryFactory entryFactory; @Inject protected LockManager lockManager; @Inject protected InternalDataContainer dataContainer; @Inject protected DistributionManager distributionManager; @Inject ClusterPublisherManager<?, ?> clusterPublisherManager; private TouchMode touchMode; @Override public void init() { super.init(); if (cacheConfiguration.clustering().cacheMode().isSynchronous()) { touchMode = cacheConfiguration.expiration().touch(); } else { touchMode = TouchMode.ASYNC; } } protected LocalizedCacheTopology getCacheTopology() { return distributionManager.getCacheTopology(); } private static abstract class AbstractTouchResponseCollector extends ValidResponseCollector<Boolean> { @Override protected Boolean addTargetNotFound(Address sender) { throw OutdatedTopologyException.RETRY_NEXT_TOPOLOGY; } @Override protected Boolean addException(Address sender, Exception exception) { if (exception instanceof CacheException) { throw (CacheException) exception; } throw new CacheException(exception); } @Override protected final Boolean addValidResponse(Address sender, ValidResponse response) { return addBooleanResponse(sender, (Boolean) response.getResponseValue()); } abstract Boolean addBooleanResponse(Address sender, Boolean response); } private static class TouchResponseCollector extends AbstractTouchResponseCollector { private static final TouchResponseCollector INSTANCE = new TouchResponseCollector(); @Override public Boolean finish() { // If all were touched, then the value isn't expired return Boolean.TRUE; } @Override protected Boolean addBooleanResponse(Address sender, Boolean response) { if (response == Boolean.FALSE) { // Return early if any value wasn't touched! return Boolean.FALSE; } return null; } } @Override public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable { if (isLocalModeForced(command)) { return invokeNext(ctx, command); } if (command.hasAnyFlag(FlagBitSets.SKIP_SIZE_OPTIMIZATION)) { return asyncValue(clusterPublisherManager.keyReduction(false, null, null, ctx, command.getFlagsBitSet(), DeliveryGuarantee.EXACTLY_ONCE, PublisherReducers.count(), PublisherReducers.add())); } return asyncValue(clusterPublisherManager.sizePublisher(command.getSegments(), ctx, command.getFlagsBitSet())); } @Override public Object visitTouchCommand(InvocationContext ctx, TouchCommand command) throws Throwable { if (command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_REMOTE_LOOKUP)) { return invokeNext(ctx, command); } LocalizedCacheTopology cacheTopology = CacheTopologyUtil.checkTopology(command, getCacheTopology()); DistributionInfo info = cacheTopology.getSegmentDistribution(command.getSegment()); // Scattered any node could be a backup, so we have to touch all members List<Address> owners = info.readOwners(); if (touchMode == TouchMode.ASYNC) { if (ctx.isOriginLocal()) { // Send to all the owners rpcManager.sendToMany(owners, command, DeliverOrder.NONE); } return invokeNext(ctx, command); } if (info.isPrimary()) { AbstractTouchResponseCollector collector = TouchResponseCollector.INSTANCE; CompletionStage<Boolean> remoteInvocation = rpcManager.invokeCommand(owners, command, collector, rpcManager.getSyncRpcOptions()); return invokeNextThenApply(ctx, command, (rCtx, rCommand, rValue) -> { Boolean touchedLocally = (Boolean) rValue; if (touchedLocally) { return asyncValue(remoteInvocation); } // If primary can't touch - it doesn't matter about others return Boolean.FALSE; }); } else if (ctx.isOriginLocal()) { // Send to the primary owner CompletionStage<ValidResponse> remoteInvocation = rpcManager.invokeCommand(info.primary(), command, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()); return asyncValue(remoteInvocation) .thenApply(ctx, command, (rCtx, rCommand, rResponse) -> ((ValidResponse) rResponse).getResponseValue()); } return invokeNext(ctx, command); } protected static SuccessfulResponse getSuccessfulResponseOrFail(Map<Address, Response> responseMap, CompletableFuture<?> future, Consumer<Response> cacheNotFound) { Iterator<Map.Entry<Address, Response>> it = responseMap.entrySet().iterator(); if (!it.hasNext()) { future.completeExceptionally(AllOwnersLostException.INSTANCE); return null; } Map.Entry<Address, Response> e = it.next(); Address sender = e.getKey(); Response response = e.getValue(); if (it.hasNext()) { future.completeExceptionally(new IllegalStateException("Too many responses " + responseMap)); } else if (response instanceof SuccessfulResponse) { return (SuccessfulResponse) response; } else if (response instanceof CacheNotFoundResponse || response instanceof UnsureResponse) { if (cacheNotFound == null) { future.completeExceptionally(unexpected(sender, response)); } else { try { cacheNotFound.accept(response); } catch (Throwable t) { future.completeExceptionally(t); } } } else { future.completeExceptionally(unexpected(sender, response)); } return null; } protected static RuntimeException unexpected(Address sender, Response response) { return CLUSTER.unexpectedResponse(sender, response); } /** * {@link #completeExceptionally(Throwable)} must be called from synchronized block since we must not complete * the future (exceptionally) when we're accessing the context - if there was an exception and we would retry, * the context could be accessed concurrently by dangling handlers and retry execution (that does not synchronize * on the same future). * * When completeExceptionally executes before the other responses processing, the future will be marked as done * and as soon as the other responses get into the synchronized block, these will check isDone and return. * If the response is being processed in sync block, running completeExceptionally and the related callbacks * will be blocked until we finish the processing. */ protected class ClusteredGetAllFuture extends CompletableFuture<Void> { public int counter; public ClusteredGetAllFuture(int counter) { this.counter = counter; } @Override public synchronized boolean completeExceptionally(Throwable ex) { return super.completeExceptionally(ex); } } }
9,324
40.079295
167
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/PassivationClusteredCacheLoaderInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.interceptors.impl.PassivationCacheLoaderInterceptor.activateAfterLoad; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.context.InvocationContext; import org.infinispan.eviction.impl.ActivationManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.concurrent.DataOperationOrderer; public class PassivationClusteredCacheLoaderInterceptor<K, V> extends ClusteredCacheLoaderInterceptor<K, V> { @Inject DataOperationOrderer orderer; @Inject ActivationManager activationManager; @Override public CompletionStage<InternalCacheEntry<K, V>> loadAndStoreInDataContainer(InvocationContext ctx, Object key, int segment, FlagAffectedCommand cmd) { CompletableFuture<DataOperationOrderer.Operation> future = new CompletableFuture<>(); CompletionStage<DataOperationOrderer.Operation> delayStage = orderer.orderOn(key, future); CompletionStage<InternalCacheEntry<K, V>> retrievalStage; if (delayStage != null && !CompletionStages.isCompletedSuccessfully(delayStage)) { retrievalStage = delayStage.thenCompose(ignore -> super.loadAndStoreInDataContainer(ctx, key, segment, cmd)); } else { retrievalStage = super.loadAndStoreInDataContainer(ctx, key, segment, cmd); } if (CompletionStages.isCompletedSuccessfully(retrievalStage)) { InternalCacheEntry<K, V> ice = CompletionStages.join(retrievalStage); activateAfterLoad(key, segment, orderer, activationManager, future, ice, null); return retrievalStage; } else { return retrievalStage.whenComplete((value, t) -> { activateAfterLoad(key, segment, orderer, activationManager, future, value, t); }); } } }
2,120
48.325581
119
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/QueueAsyncInvocationStage.java
package org.infinispan.interceptors.impl; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import org.infinispan.commands.VisitableCommand; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.ExceptionSyncInvocationStage; import org.infinispan.interceptors.InvocationCallback; import org.infinispan.interceptors.InvocationStage; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.jgroups.annotations.GuardedBy; /** * Invocation stage representing a computation that may or may not be done yet. * * <p>It stores handler objects in a queue instead of creating a new instance every time a handler is added. * The queue may be frozen based on internal conditions, like executing the last handler or reaching the capacity * of the queue, and adding a handler will create a new instance. * The queue will also be frozen when {@link #toCompletableFuture()} is invoked, to make that future behave like * a regular {@link CompletableFuture}. * </p> * * <p>When the queue is not frozen, adding a handler will change the result of the current stage. * When the queue is frozen, adding a handler may actually execute the handler synchronously.</p> * * @author Dan Berindei * @since 9.0 */ public class QueueAsyncInvocationStage extends SimpleAsyncInvocationStage implements BiConsumer<Object, Throwable>, InvocationCallback { private static final Log log = LogFactory.getLog(QueueAsyncInvocationStage.class); private final InvocationContext ctx; private final VisitableCommand command; public QueueAsyncInvocationStage(InvocationContext ctx, VisitableCommand command, CompletableFuture<?> valueFuture, InvocationCallback function) { super(new CompletableFuture<>()); this.ctx = ctx; this.command = command; queueAdd(function); if (CompletionStages.isCompletedSuccessfully(valueFuture)) { accept(valueFuture.join(), null); } else { valueFuture.whenComplete(this); } } @Override public Object addCallback(InvocationContext ctx, VisitableCommand command, InvocationCallback function) { if (ctx != this.ctx || command != this.command) { return new SimpleAsyncInvocationStage(future).addCallback(ctx, command, function); } if (queueAdd(function)) { return this; } return invokeDirectly(ctx, command, function); } private Object invokeDirectly(InvocationContext ctx, VisitableCommand command, InvocationCallback function) { Object rv; Throwable throwable; try { rv = future.join(); throwable = null; } catch (Throwable t) { rv = null; throwable = CompletableFutures.extractException(t); } try { return function.apply(ctx, command, rv, throwable); } catch (Throwable t) { return new ExceptionSyncInvocationStage(t); } } @Override public void accept(Object rv, Throwable throwable) { // We started with a CompletableFuture, which is now complete. invokeQueuedHandlers(rv, throwable); } @Override public Object apply(InvocationContext rCtx, VisitableCommand rCommand, Object rv, Throwable throwable) throws Throwable { // We started from another AsyncInvocationStage, which is now complete. invokeQueuedHandlers(rv, throwable); if (throwable == null) { return rv; } else { throw throwable; } } private void invokeQueuedHandlers(Object rv, Throwable throwable) { if (log.isTraceEnabled()) log.tracef("Resuming invocation of command %s with %d handlers", command, queueSize()); while (true) { InvocationCallback function = queuePoll(); if (function == null) { // Complete the future. // We finished running the handlers, and the last pollHandler() call locked the queue. if (throwable == null) { future.complete(rv); } else { future.completeExceptionally(throwable); } return; } // Run the handler try { if (throwable != null) { throwable = CompletableFutures.extractException(throwable); } rv = function.apply(ctx, command, rv, throwable); throwable = null; } catch (Throwable t) { rv = null; throwable = t; } if (rv instanceof InvocationStage) { InvocationStage currentStage = (InvocationStage) rv; currentStage.addCallback(ctx, command, this); return; } // We got a synchronous invocation stage, continue with the next handler } } /** * An inline implementation of a queue. The queue is frozen automatically when the last element is polled. */ // Capacity must be a power of 2 static final int QUEUE_INITIAL_CAPACITY = 8; @GuardedBy("this") private InvocationCallback[] elements = null; @GuardedBy("this") private byte mask; @GuardedBy("this") private byte head; @GuardedBy("this") private byte tail; @GuardedBy("this") private boolean frozen; boolean queueAdd(InvocationCallback element) { synchronized (this) { if (frozen) { return false; } if (elements == null || tail - head > mask) { queueExpand(); } elements[tail & mask] = element; tail++; return true; } } /** * Remove one handler from the deque, or freeze the deque if there are no more elements. * * @return The next handler, or {@code null} if the deque is empty. */ InvocationCallback queuePoll() { InvocationCallback element; synchronized (this) { if (tail != head) { element = elements[head & mask]; head++; } else { element = null; frozen = true; } } return element; } /** * @return The current number of elements in the deque, only useful for debugging. */ int queueSize() { synchronized (this) { // We can assume tail and head won't overflow in our use case return tail - head; } } @GuardedBy("this") private void queueExpand() { // We start with no elements and mask 0 if (elements == null) { elements = new InvocationCallback[QUEUE_INITIAL_CAPACITY]; mask = QUEUE_INITIAL_CAPACITY - 1; return; } InvocationCallback[] oldElements = elements; int oldCapacity = oldElements.length; int oldMask = mask; int oldHead = head; int oldTail = tail; int maskedHead = oldHead & oldMask; int maskedTail = oldTail & oldMask; int oldSize = tail - head; if (oldSize != oldCapacity) throw new IllegalStateException("Queue should be expanded only when full"); int newSize = oldCapacity * 2; int newMask = newSize - 1; elements = new InvocationCallback[newSize]; mask = (byte) newMask; head = 0; tail = (byte) (oldTail - oldHead); if (maskedHead < maskedTail) { System.arraycopy(oldElements, maskedHead, elements, 0, oldSize); } else { System.arraycopy(oldElements, maskedHead, elements, 0, oldCapacity - maskedHead); System.arraycopy(oldElements, 0, elements, oldCapacity - maskedHead, maskedTail); } } @Override public String toString() { return "QueueAsyncInvocationStage(" + queueSize() + " handlers, "+ future + ')'; } }
7,887
31.866667
115
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/CallInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.commons.util.Util.toStr; import static org.infinispan.functional.impl.EntryViews.snapshot; import static org.infinispan.transaction.impl.WriteSkewHelper.versionFromEntry; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.InternalCacheSet; import org.infinispan.cache.impl.AbstractDelegatingCache; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.Visitor; 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.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.DataWriteCommand; 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.commands.write.ValueMatcher; import org.infinispan.commons.reactive.RxJavaInterop; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.Configurations; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.ExpiryHelper; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.MVCCEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.container.versioning.IncrementableEntryVersion; import org.infinispan.container.versioning.VersionGenerator; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.distribution.group.impl.GroupManager; import org.infinispan.encoding.DataConversion; import org.infinispan.expiration.impl.TouchCommand; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.PublisherManagerFactory; 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.functional.EntryView; import org.infinispan.functional.Param; import org.infinispan.functional.impl.EntryViews; import org.infinispan.functional.impl.StatsEnvelope; import org.infinispan.interceptors.BaseAsyncInterceptor; import org.infinispan.metadata.Metadata; import org.infinispan.metadata.Metadatas; import org.infinispan.metadata.impl.InternalMetadataImpl; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.reactive.publisher.PublisherReducers; import org.infinispan.reactive.publisher.impl.ClusterPublisherManager; import org.infinispan.reactive.publisher.impl.DeliveryGuarantee; import org.infinispan.util.UserRaisedFunctionalException; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; /** * Always at the end of the chain, directly in front of the cache. Simply calls into the cache using reflection. If the * call resulted in a modification, add the Modification to the end of the modification list keyed by the current * transaction. * * @author Bela Ban * @author Mircea.Markus@jboss.com * @author Dan Berindei * @since 9.0 */ public class CallInterceptor extends BaseAsyncInterceptor implements Visitor { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); // The amount in milliseconds of a buffer we allow the system clock to be off, but still allow expiration removal private static final int CLOCK_BUFFER = 100; @Inject ComponentRef<Cache> cacheRef; @Inject CacheNotifier cacheNotifier; @Inject TimeService timeService; @Inject VersionGenerator versionGenerator; @Inject InternalDataContainer<?, ?> dataContainer; @Inject DistributionManager distributionManager; @Inject InternalEntryFactory internalEntryFactory; @Inject KeyPartitioner keyPartitioner; @Inject GroupManager groupManager; @ComponentName(PublisherManagerFactory.LOCAL_CLUSTER_PUBLISHER) @Inject ClusterPublisherManager<?, ?> localClusterPublisherManager; @Inject ComponentRegistry componentRegistry; // Internally we always deal with an unwrapped cache, so don't unwrap per invocation Cache unwrappedCache; private IncrementableEntryVersion nonExistentVersion; @Start public void start() { nonExistentVersion = versionGenerator.nonExistingVersion(); unwrappedCache = AbstractDelegatingCache.unwrapCache(cacheRef.wired()); } @Override public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable { if (log.isTraceEnabled()) log.tracef("Invoking: %s", command.getClass().getSimpleName()); return command.acceptVisitor(ctx, this); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { // It's not worth looking up the entry if we're never going to apply the change. ValueMatcher valueMatcher = command.getValueMatcher(); if (valueMatcher == ValueMatcher.MATCH_NEVER) { command.fail(); return null; } //noinspection unchecked Object key = command.getKey(); MVCCEntry<Object, Object> e = (MVCCEntry) ctx.lookupEntry(key); if (e == null) { throw new IllegalStateException("Not wrapped"); } Object newValue = command.getValue(); Metadata metadata = command.getMetadata(); if (metadata instanceof InternalMetadataImpl) { InternalMetadataImpl internalMetadata = (InternalMetadataImpl) metadata; metadata = internalMetadata.actual(); e.setCreated(internalMetadata.created()); e.setLastUsed(internalMetadata.lastUsed()); } Object prevValue = e.getValue(); if (!valueMatcher.matches(prevValue, null, newValue)) { command.fail(); return command.isReturnEntryNecessary() ? cloneEntry(e) : prevValue; } return performPut(e, ctx, valueMatcher, key, newValue, metadata, command, command.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER | FlagBitSets.PUT_FOR_X_SITE_STATE_TRANSFER), command.isReturnEntryNecessary()); } private Object performPut(MVCCEntry<Object, Object> e, InvocationContext ctx, ValueMatcher valueMatcher, Object key, Object value, Metadata metadata, FlagAffectedCommand command, boolean skipNotification, boolean returnEntry) { Object entryValue = e.getValue(); Object o; CompletionStage<Void> stage = null; // Non tx and tx both have this set if it was state transfer if (!skipNotification) { if (e.isCreated()) { stage = cacheNotifier.notifyCacheEntryCreated(key, value, metadata, true, ctx, command); } else { stage = cacheNotifier.notifyCacheEntryModified(key, value, metadata, entryValue, e.getMetadata(), true, ctx, command); } } e.updatePreviousValue(); Object response = null; o = e.setValue(value); if (valueMatcher != ValueMatcher.MATCH_EXPECTED_OR_NEW && o != null) { if (returnEntry) { response = cloneEntry(e); ((CacheEntry<Object, Object>) response).setValue(o); } else { response = o; } } Metadatas.updateMetadata(e, metadata); if (e.isRemoved()) { e.setCreated(true); e.setExpired(false); e.setRemoved(false); response = null; } e.setChanged(true); updateStoreFlags(command, e); // Return the expected value when retrying a putIfAbsent command (i.e. null) return delayedValue(stage, response); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { return visitRemoveCommand(ctx, command, true); } private Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command, boolean notifyRemove) throws Throwable { // It's not worth looking up the entry if we're never going to apply the change. ValueMatcher valueMatcher = command.getValueMatcher(); if (valueMatcher == ValueMatcher.MATCH_NEVER) { command.fail(); return null; } Object key = command.getKey(); MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); Object prevValue = e.getValue(); Object optionalValue = command.getValue(); if (prevValue == null) { command.nonExistant(); if (valueMatcher.matches(null, optionalValue, null)) { e.setChanged(true); e.setRemoved(true); e.setCreated(false); if (command instanceof EvictCommand) { e.setEvicted(true); } e.setValue(null); updateStoreFlags(command, e); return command.isConditional() ? true : null; } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is null"); command.fail(); return false; } } if (!valueMatcher.matches(prevValue, optionalValue, null)) { command.fail(); return false; } // Refactor this eventually if (command instanceof EvictCommand) { e.setEvicted(true); } return performRemove(e, ctx, valueMatcher, key, prevValue, optionalValue, command.getMetadata(), notifyRemove, command.isReturnEntryNecessary(), command); } protected Object performRemove(MVCCEntry<?, ?> e, InvocationContext ctx, ValueMatcher valueMatcher, Object key, Object prevValue, Object optionalValue, Metadata commandMetadata, boolean notifyRemove, boolean returnEntry, DataWriteCommand command) { CompletionStage<Void> stage = notifyRemove ? cacheNotifier.notifyCacheEntryRemoved(key, prevValue, e.getMetadata(), true, ctx, command) : null; Object returnValue; if (valueMatcher != ValueMatcher.MATCH_EXPECTED_OR_NEW) { returnValue = command.isConditional() ? true : returnEntry ? cloneEntry(e) : prevValue; } else { // Return the expected value when retrying returnValue = command.isConditional() ? true : optionalValue; } e.setRemoved(true); e.setChanged(true); e.setValue(null); if (commandMetadata != null) { e.setMetadata(commandMetadata); } updateStoreFlags(command, e); return delayedValue(stage, returnValue); } @Override public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) { Object key = command.getKey(); ValueMatcher valueMatcher = command.getValueMatcher(); Metadata metadata = command.getMetadata(); //noinspection unchecked MVCCEntry<Object, Object> e = (MVCCEntry<Object, Object>) ctx.lookupEntry(key); if (e == null) { throw new IllegalStateException("Not wrapped"); } return command.isRemove() ? performRemove(e, ctx, valueMatcher, key, null, null, metadata, true, false, command) : performPut(e, ctx, valueMatcher, key, command.getValue(), metadata, command, false, false); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { ValueMatcher valueMatcher = command.getValueMatcher(); // It's not worth looking up the entry if we're never going to apply the change. if (valueMatcher == ValueMatcher.MATCH_NEVER) { command.fail(); // TODO: this seems like a bug.. ? return null; } Object key = command.getKey(); //noinspection unchecked MVCCEntry<Object, Object> e = (MVCCEntry) ctx.lookupEntry(key); // We need the null check as in non-tx caches we don't always wrap the entry on the origin Object prevValue = e.getValue(); Object newValue = command.getNewValue(); Object expectedValue = command.getOldValue(); Object response = expectedValue == null && command.isReturnEntry() && prevValue != null ? cloneEntry(e) : null; if (valueMatcher.matches(prevValue, expectedValue, newValue)) { e.setChanged(true); e.setValue(newValue); Metadata newMetadata = command.getMetadata(); Metadata prevMetadata = e.getMetadata(); CompletionStage<Void> stage = cacheNotifier.notifyCacheEntryModified(key, newValue, newMetadata, expectedValue == null ? prevValue : expectedValue, prevMetadata, true, ctx, command); Metadatas.updateMetadata(e, newMetadata); updateStoreFlags(command, e); return delayedValue(stage, response != null ? response : expectedValue == null ? prevValue : true); } command.fail(); if (response != null) { return response; } return expectedValue == null ? prevValue : false; } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { Object key = command.getKey(); MVCCEntry<Object, Object> e = (MVCCEntry) ctx.lookupEntry(key); if (e == null) { throw new IllegalStateException("Not wrapped"); } Object oldValue = e.getValue(); Object newValue; if (command.isComputeIfPresent() && oldValue == null) { command.fail(); return null; } try { newValue = command.getRemappingBiFunction().apply(key, oldValue); } catch (RuntimeException ex) { throw new UserRaisedFunctionalException(ex); } if (oldValue == null && newValue == null) { return null; } CompletionStage<Void> stage; Metadata metadata = command.getMetadata(); if (oldValue != null) { // The key already has a value if (newValue != null) { //replace with the new value if there is a modification on the value stage = cacheNotifier.notifyCacheEntryModified(key, newValue, metadata, oldValue, e.getMetadata(), true, ctx, command); e.setChanged(true); e.setValue(newValue); Metadatas.updateMetadata(e, metadata); } else { // remove when new value is null stage = cacheNotifier.notifyCacheEntryRemoved(key, oldValue, e.getMetadata(), true, ctx, command); e.setRemoved(true); e.setChanged(true); e.setValue(null); } } else { // put if not present stage = cacheNotifier.notifyCacheEntryCreated(key, newValue, metadata, true, ctx, command); e.setValue(newValue); e.setChanged(true); Metadatas.updateMetadata(e, metadata); if (e.isRemoved()) { e.setCreated(true); e.setExpired(false); e.setRemoved(false); } } updateStoreFlags(command, e); return delayedValue(stage, newValue); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable { Object key = command.getKey(); MVCCEntry<Object, Object> e = (MVCCEntry) ctx.lookupEntry(key); if (e == null) { throw new IllegalStateException("Not wrapped"); } Object value = e.getValue(); CompletionStage<Void> stage = null; if (value == null) { try { value = command.getMappingFunction().apply(key); } catch (RuntimeException ex) { throw new UserRaisedFunctionalException(ex); } if (value != null) { e.setValue(value); Metadata metadata = command.getMetadata(); Metadatas.updateMetadata(e, metadata); // TODO: should this be below? if (e.isCreated()) { stage = cacheNotifier.notifyCacheEntryCreated(key, value, metadata, true, ctx, command); } if (e.isRemoved()) { e.setCreated(true); e.setExpired(false); e.setRemoved(false); } e.setChanged(true); } updateStoreFlags(command, e); } else { command.fail(); } return delayedValue(stage, value); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { AggregateCompletionStage<Void> aggregateCompletionStage = null; if (cacheNotifier.hasListener(CacheEntryRemoved.class)) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); for (InternalCacheEntry e : dataContainer) { aggregateCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryRemoved(e.getKey(), e.getValue(), e.getMetadata(), true, ctx, command)); } } return delayedNull(aggregateCompletionStage != null ? aggregateCompletionStage.freeze() : null); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { Map<Object, Object> inputMap = command.getMap(); Metadata metadata = command.getMetadata(); // Previous values are used by the query interceptor to locate the index for the old value Map<Object, Object> previousValues = command.hasAnyFlag(FlagBitSets.IGNORE_RETURN_VALUES) ? null : new HashMap<>(inputMap.size()); AggregateCompletionStage<Void> aggregateCompletionStage; if (cacheNotifier.hasListener(CacheEntryCreated.class) || cacheNotifier.hasListener(CacheEntryModified.class)) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); } else { aggregateCompletionStage = null; } for (Map.Entry<Object, Object> e : inputMap.entrySet()) { Object key = e.getKey(); MVCCEntry<Object, Object> contextEntry = lookupMvccEntry(ctx, key); if (contextEntry != null) { Object newValue = e.getValue(); Object previousValue = contextEntry.getValue(); Metadata previousMetadata = contextEntry.getMetadata(); // Even though putAll() returns void, QueryInterceptor reads the previous values // TODO The previous values are not correct if the entries exist only in a store // We have to add null values due to the handling in distribution interceptor, see ISPN-7975 if (previousValues != null) { previousValues.put(key, previousValue); } if (aggregateCompletionStage != null) { if (contextEntry.isCreated()) { aggregateCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryCreated(key, newValue, metadata, true, ctx, command)); } else { aggregateCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryModified(key, newValue, metadata, previousValue, previousMetadata, true, ctx, command)); } } contextEntry.setValue(newValue); Metadatas.updateMetadata(contextEntry, metadata); contextEntry.setChanged(true); updateStoreFlags(command, contextEntry); } } return delayedValue(aggregateCompletionStage != null ? aggregateCompletionStage.freeze() : null, previousValues); } private MVCCEntry<Object, Object> lookupMvccEntry(InvocationContext ctx, Object key) { //noinspection unchecked return (MVCCEntry) ctx.lookupEntry(key); } @Override public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { visitRemoveCommand(ctx, command, false); return null; } @Override public Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) throws Throwable { Object key = command.getKey(); MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); Metadata metadata = command.getMetadata(); // When it isn't the primary owner, just accept the removal as is, trusting the primary did the appropriate checks if (command.hasAnyFlag(FlagBitSets.BACKUP_WRITE)) { if (log.isTraceEnabled()) { log.trace("Removing expired entry without checks as we are backup as primary already performed them"); } e.setExpired(true); return performRemove(e, ctx, ValueMatcher.MATCH_ALWAYS, key, e.getValue() != null ? e.getValue() : null, command.getValue(), metadata, false, false, command); } if (e != null && !e.isRemoved()) { Object prevValue = e.getValue(); Object optionalValue = command.getValue(); Long lifespan = command.getLifespan(); ValueMatcher valueMatcher = command.getValueMatcher(); // If the command has the SKIP_SHARED_STORE flag it means it is an expiration from a store, so we may not // be able to verify the entry since it is possibly removed already, but we still need to notify // We also skip checks if lifespan is null as this is a max idle expiration if (lifespan == null || command.hasAnyFlag(FlagBitSets.SKIP_SHARED_CACHE_STORE)) { if (valueMatcher.matches(prevValue, optionalValue, null)) { e.setExpired(true); return performRemove(e, ctx, valueMatcher, key, prevValue, optionalValue, metadata, false, false, command); } } else if (versionFromEntry(e) == nonExistentVersion) { // If there is no metadata and no value that means it is gone currently or not shown due to expired // Non existent version is used when versioning is enabled and the entry doesn't exist // If we have a value though we should verify it matches the value as well if (optionalValue == null || valueMatcher.matches(prevValue, optionalValue, null)) { e.setExpired(true); return performRemove(e, ctx, valueMatcher, key, prevValue, optionalValue, metadata, false, false, command); } } else if (e.getLifespan() > 0 && e.getLifespan() == lifespan) { // If the entries lifespan is not positive that means it can't expire so don't even try to remove it // Lastly if there is metadata we have to verify it equals our lifespan and the value match. if (valueMatcher.matches(prevValue, optionalValue, null)) { // Only remove the entry if it is still expired. // Due to difference in system clocks between nodes - we also accept the expiration within 100 ms // of now. This along with the fact that entries are not normally access immediately when they // expire should give a good enough buffer range to not create a false positive. if (ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), timeService.wallClockTime() + CLOCK_BUFFER)) { if (log.isTraceEnabled()) { log.tracef("Removing entry as its lifespan and value match and it created on %s with a current time of %s", e.getCreated(), timeService.wallClockTime()); } e.setExpired(true); return performRemove(e, ctx, valueMatcher, key, prevValue, optionalValue, metadata, false, false, command); } else if (log.isTraceEnabled()) { log.tracef("Cannot remove entry due to it not being expired - this can be caused by different " + "clocks on nodes or a concurrent write"); } } else if (log.isTraceEnabled()) { log.tracef("Cannot remove entry due to the value not being equal. Matcher: %s, PrevValue: %s, ExpectedValue: %s. Double check equality is working for the value", valueMatcher, prevValue, optionalValue); } } else if (log.isTraceEnabled()) { log.trace("Cannot remove entry as its lifespan or value do not match"); } } else { if (log.isTraceEnabled()) { log.trace("Nothing to remove since the entry doesn't exist in the context or it is already removed - assume command was successful"); } return true; } command.fail(); return false; } @Override public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable { long size = trySizeOptimization(ctx, command); if (size >= 0) { return size; } return asyncValue(localClusterPublisherManager.keyReduction(false, command.getSegments(), null, ctx, command.getFlagsBitSet(), DeliveryGuarantee.EXACTLY_ONCE, PublisherReducers.count(), PublisherReducers.add())); } private long trySizeOptimization(InvocationContext ctx, SizeCommand command) { if (command.hasAnyFlag(FlagBitSets.SKIP_SIZE_OPTIMIZATION) || dataContainer.hasExpirable() || (ctx != null && ctx.lookedUpEntriesCount() > 0)) { return -1; } return dataContainer.sizeIncludingExpired(identifySegments(command.getSegments())); } private IntSet identifySegments(IntSet segments) { if (segments == null) { int maxSegments = 1; if (Configurations.needSegments(cacheConfiguration)) { maxSegments = cacheConfiguration.clustering().hash().numSegments(); } segments = IntSets.immutableRangeSet(maxSegments); } return segments; } @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { CacheEntry entry = ctx.lookupEntry(command.getKey()); if (entry.isRemoved()) { if (log.isTraceEnabled()) { log.tracef("Entry has been deleted and is of type %s", entry.getClass().getSimpleName()); } return null; } return entry.getValue(); } @Override public Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable { CacheEntry entry = ctx.lookupEntry(command.getKey()); if (entry.isNull() || entry.isRemoved()) { return null; } // TODO: this shouldn't need a copy when the context is not local return internalEntryFactory.copy(entry); } @Override public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { Map<Object, Object> map = new LinkedHashMap<>(); for (Object key : command.getKeys()) { CacheEntry entry = ctx.lookupEntry(key); if (entry == null) { throw new IllegalStateException("Entry for key " + toStr(key) + " not found"); } if (entry.isNull()) { if (log.isTraceEnabled()) { log.tracef("Entry for key %s is null in current context", toStr(key)); } map.put(key, null); continue; } if (entry.isRemoved()) { if (log.isTraceEnabled()) { log.tracef("Entry for key %s has been deleted and is of type %s", toStr(key), entry.getClass().getSimpleName()); } map.put(key, null); continue; } // Get cache entry instead of value if (command.isReturnEntries()) { CacheEntry copy; if (ctx.isOriginLocal()) { copy = internalEntryFactory.copy(entry); } else { copy = entry; } if (log.isTraceEnabled()) { log.tracef("Found entry %s -> %s", toStr(key), entry); log.tracef("Returning copied entry %s", copy); } map.put(key, copy); } else { Object value = entry.getValue(); if (log.isTraceEnabled()) { log.tracef("Found %s -> %s", toStr(key), toStr(value)); } map.put(key, value); } } return map; } @Override public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable { return new BackingKeySet<>(dataContainer); } @Override public Object visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) throws Throwable { return new BackingEntrySet<>(dataContainer); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { // Nothing to do return null; } @Override public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) throws Throwable { // Nothing to do return null; } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { // Nothing to do return null; } @Override public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand invalidateCommand) throws Throwable { Object[] keys = invalidateCommand.getKeys(); if (log.isTraceEnabled()) { log.tracef("Invalidating keys %s", toStr(Arrays.asList(keys))); } AggregateCompletionStage<Void> aggregateCompletionStage = null; if (cacheNotifier.hasListener(CacheEntryInvalidated.class)) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); } for (Object key : keys) { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); if (e != null) { e.setChanged(true); e.setRemoved(true); e.setCreated(false); if (aggregateCompletionStage != null) { aggregateCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryInvalidated(key, e.getValue(), e.getMetadata(), true, ctx, invalidateCommand)); } } } return delayedNull(aggregateCompletionStage != null ? aggregateCompletionStage.freeze() : null); } @Override public Object visitInvalidateL1Command(InvocationContext ctx, InvalidateL1Command invalidateL1Command) throws Throwable { Object[] keys = invalidateL1Command.getKeys(); if (log.isTraceEnabled()) { log.tracef("Preparing to invalidate keys %s", Arrays.asList(keys)); } AggregateCompletionStage<Void> aggregateCompletionStage = null; if (cacheNotifier.hasListener(CacheEntryInvalidated.class)) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); } for (Object key : keys) { InternalCacheEntry ice = dataContainer.peek(key); if (ice != null) { boolean isLocal = distributionManager.getCacheTopology().isWriteOwner(key); if (!isLocal) { if (log.isTraceEnabled()) log.tracef("Invalidating key %s.", key); MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); e.setRemoved(true); e.setChanged(true); e.setCreated(false); if (aggregateCompletionStage != null) { aggregateCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryInvalidated(key, e.getValue(), e.getMetadata(), true, ctx, invalidateL1Command)); } } else { log.tracef("Not invalidating key %s as it is local now", key); } } } return delayedNull(aggregateCompletionStage != null ? aggregateCompletionStage.freeze() : null); } @Override public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable { // Nothing to do return null; } @Override public Object visitUnknownCommand(InvocationContext ctx, VisitableCommand command) throws Throwable { return command.invoke(); } @Override public Object visitReadOnlyKeyCommand(InvocationContext ctx, ReadOnlyKeyCommand command) throws Throwable { if (command instanceof TxReadOnlyKeyCommand) { TxReadOnlyKeyCommand txReadOnlyKeyCommand = (TxReadOnlyKeyCommand) command; List<Mutation> mutations = txReadOnlyKeyCommand.getMutations(); if (mutations != null && !mutations.isEmpty()) { return visitTxReadOnlyKeyCommand(ctx, txReadOnlyKeyCommand, mutations); } } Object key = command.getKey(); CacheEntry entry = ctx.lookupEntry(key); if (entry == null) { throw new IllegalStateException(); } DataConversion keyDataConversion = command.getKeyDataConversion(); EntryView.ReadEntryView ro = entry.isNull() ? EntryViews.noValue(key, keyDataConversion) : EntryViews.readOnly(entry, keyDataConversion, command.getValueDataConversion()); Object ret = snapshot(command.getFunction().apply(ro)); // We'll consider the entry always read for stats purposes even if the function is a noop return Param.StatisticsMode.isSkip(command.getParams()) ? ret : StatsEnvelope.create(ret, entry.isNull()); } private Object visitTxReadOnlyKeyCommand(InvocationContext ctx, TxReadOnlyKeyCommand command, List<Mutation> mutations) { MVCCEntry entry = (MVCCEntry) ctx.lookupEntry(command.getKey()); EntryView.ReadWriteEntryView rw = EntryViews.readWrite(entry, command.getKeyDataConversion(), command.getValueDataConversion()); Object ret = null; for (Mutation mutation : mutations) { entry.updatePreviousValue(); ret = mutation.apply(rw); } Function function = command.getFunction(); if (function != null) { ret = function.apply(rw); } ret = snapshot(ret); return Param.StatisticsMode.isSkip(command.getParams()) ? ret : StatsEnvelope.create(ret, entry.isNull()); } @Override public Object visitReadOnlyManyCommand(InvocationContext ctx, ReadOnlyManyCommand command) throws Throwable { if (command instanceof TxReadOnlyManyCommand) { TxReadOnlyManyCommand txReadOnlyManyCommand = (TxReadOnlyManyCommand) command; List<List<Mutation>> mutations = txReadOnlyManyCommand.getMutations(); if (mutations != null && !mutations.isEmpty()) { return visitTxReadOnlyCommand(ctx, (TxReadOnlyManyCommand) command, mutations); } } Collection<?> keys = command.getKeys(); // lazy execution triggers exceptions on unexpected places ArrayList<Object> retvals = new ArrayList<>(keys.size()); boolean skipStats = Param.StatisticsMode.isSkip(command.getParams()); DataConversion keyDataConversion = command.getKeyDataConversion(); DataConversion valueDataConversion = command.getValueDataConversion(); Function function = command.getFunction(); for (Object k : keys) { CacheEntry me = ctx.lookupEntry(k); EntryView.ReadEntryView view = me.isNull() ? EntryViews.noValue(k, keyDataConversion) : EntryViews.readOnly(me, keyDataConversion, valueDataConversion); Object ret = snapshot(function.apply(view)); retvals.add(skipStats ? ret : StatsEnvelope.create(ret, me.isNull())); } return retvals.stream(); } private Object visitTxReadOnlyCommand(InvocationContext ctx, TxReadOnlyManyCommand command, List<List<Mutation>> mutations) { Collection<Object> keys = command.getKeys(); ArrayList<Object> retvals = new ArrayList<>(keys.size()); Iterator<List<Mutation>> mutIt = mutations.iterator(); boolean skipStats = Param.StatisticsMode.isSkip(command.getParams()); Function function = command.getFunction(); DataConversion keyDataConversion = command.getKeyDataConversion(); DataConversion valueDataConversion = command.getValueDataConversion(); for (Object k : keys) { List<Mutation> innerMutations = mutIt.next(); MVCCEntry entry = (MVCCEntry) ctx.lookupEntry(k); EntryView.ReadEntryView ro; Object ret = null; if (mutations.isEmpty()) { ro = entry.isNull() ? EntryViews.noValue(k, keyDataConversion) : EntryViews.readOnly(entry, keyDataConversion, valueDataConversion); } else { EntryView.ReadWriteEntryView rw = EntryViews.readWrite(entry, keyDataConversion, valueDataConversion); for (Mutation mutation : innerMutations) { entry.updatePreviousValue(); ret = mutation.apply(rw); } ro = rw; } if (function != null) { ret = function.apply(ro); } ret = snapshot(ret); retvals.add(skipStats ? ret : StatsEnvelope.create(ret, entry.isNull())); } return retvals.stream(); } @Override public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(command.getKey()); // Could be that the key is not local if (e == null) return null; // should we leak this to stats in write-only commands? we do that for events anyway... boolean exists = e.getValue() != null; command.getConsumer().accept(EntryViews.writeOnly(e, command.getValueDataConversion())); // The effective result of retried command is not safe; we'll go to backup anyway if (!e.isChanged() && !command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { command.fail(); } updateStoreFlags(command, e); return Param.StatisticsMode.isSkip(command.getParams()) ? null : StatsEnvelope.create(null, e, exists, false); } @Override public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) throws Throwable { ValueMatcher valueMatcher = command.getValueMatcher(); // It's not worth looking up the entry if we're never going to apply the change. if (valueMatcher == ValueMatcher.MATCH_NEVER) { command.fail(); return null; } MVCCEntry e = (MVCCEntry) ctx.lookupEntry(command.getKey()); // Could be that the key is not local if (e == null) return null; Object prevValue = command.getPrevValue(); Metadata prevMetadata = command.getPrevMetadata(); boolean hasCommandRetry = command.hasAnyFlag(FlagBitSets.COMMAND_RETRY); // Command only has one previous value, do not override it if (prevValue == null && !hasCommandRetry) { prevValue = e.getValue(); prevMetadata = e.getMetadata(); command.setPrevValueAndMetadata(prevValue, prevMetadata); } // Protect against outdated old value using the value matcher. // If the value has been update while on the retry, use the newer value. // Also take into account that the value might have been removed. // TODO: Configure equivalence function // TODO: this won't work properly until we store if the command was executed or not... Object oldPrevValue = e.getValue(); // Note: other commands don't clone the entry as they don't carry the previous value for comparison // using value matcher - if other commands are retried these can apply the function multiple times. // Here we don't want to modify the value in context when trying what would be the outcome of the operation. MVCCEntry copy = e.clone(); DataConversion valueDataConversion = command.getValueDataConversion(); Object decodedArgument = valueDataConversion.fromStorage(command.getArgument()); EntryViews.AccessLoggingReadWriteView view = EntryViews.readWrite(copy, prevValue, prevMetadata, command.getKeyDataConversion(), valueDataConversion); Object ret = snapshot(command.getBiFunction().apply(decodedArgument, view)); if (valueMatcher.matches(oldPrevValue, prevValue, copy.getValue())) { log.tracef("Execute read-write function on previous value %s and previous metadata %s", prevValue, prevMetadata); e.setValue(copy.getValue()); e.setMetadata(copy.getMetadata()); // These are the only flags that should be changed with EntryViews.readWrite e.setChanged(copy.isChanged()); e.setRemoved(copy.isRemoved()); } // The effective result of retried command is not safe; we'll go to backup anyway if (!e.isChanged() && !hasCommandRetry) { command.fail(); } updateStoreFlags(command, e); return Param.StatisticsMode.isSkip(command.getParams()) ? ret : StatsEnvelope.create(ret, e, prevValue != null, view.isRead()); } @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { // It's not worth looking up the entry if we're never going to apply the change. if (command.getValueMatcher() == ValueMatcher.MATCH_NEVER) { command.fail(); return null; } MVCCEntry e = (MVCCEntry) ctx.lookupEntry(command.getKey()); // Could be that the key is not local, 'null' is how this is signalled if (e == null) return null; Object ret; boolean exists = e.getValue() != null; EntryViews.AccessLoggingReadWriteView view = EntryViews.readWrite(e, command.getKeyDataConversion(), command.getValueDataConversion()); ret = snapshot(command.getFunction().apply(view)); // The effective result of retried command is not safe; we'll go to backup anyway if (!e.isChanged() && !command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { command.fail(); } updateStoreFlags(command, e); return Param.StatisticsMode.isSkip(command.getParams()) ? ret : StatsEnvelope.create(ret, e, exists, view.isRead()); } @Override public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) throws Throwable { Map<Object, Object> arguments = command.getArguments(); DataConversion valueDataConversion = command.getValueDataConversion(); for (Map.Entry entry : arguments.entrySet()) { MVCCEntry cacheEntry = (MVCCEntry) ctx.lookupEntry(entry.getKey()); // Could be that the key is not local, 'null' is how this is signalled if (cacheEntry == null) { throw new IllegalStateException(); } updateStoreFlags(command, cacheEntry); Object decodedValue = valueDataConversion.fromStorage(entry.getValue()); command.getBiConsumer().accept(decodedValue, EntryViews.writeOnly(cacheEntry, valueDataConversion)); } return null; } @Override public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(command.getKey()); // Could be that the key is not local if (e == null) return null; DataConversion valueDataConversion = command.getValueDataConversion(); Object decodedArgument = valueDataConversion.fromStorage(command.getArgument()); boolean exists = e.getValue() != null; command.getBiConsumer().accept(decodedArgument, EntryViews.writeOnly(e, valueDataConversion)); // The effective result of retried command is not safe; we'll go to backup anyway if (!e.isChanged() && !command.hasAnyFlag(FlagBitSets.COMMAND_RETRY)) { command.fail(); } updateStoreFlags(command, e); return Param.StatisticsMode.isSkip(command.getParams()) ? null : StatsEnvelope.create(null, e, exists, false); } @Override public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) throws Throwable { Consumer consumer = command.getConsumer(); DataConversion valueDataConversion = command.getValueDataConversion(); for (Object k : command.getAffectedKeys()) { MVCCEntry cacheEntry = (MVCCEntry) ctx.lookupEntry(k); if (cacheEntry == null) { throw new IllegalStateException(); } updateStoreFlags(command, cacheEntry); consumer.accept(EntryViews.writeOnly(cacheEntry, valueDataConversion)); } return null; } @Override public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) throws Throwable { // Can't return a lazy stream here because the current code in // EntryWrappingInterceptor expects any changes to be done eagerly, // otherwise they're not applied. So, apply the function eagerly and // return a lazy stream of the void returns. Collection<Object> keys = command.getAffectedKeys(); List<Object> returns = new ArrayList<>(keys.size()); boolean skipStats = Param.StatisticsMode.isSkip(command.getParams()); DataConversion keyDataConversion = command.getKeyDataConversion(); DataConversion valueDataConversion = command.getValueDataConversion(); Function function = command.getFunction(); keys.forEach(k -> { MVCCEntry entry = (MVCCEntry) ctx.lookupEntry(k); boolean exists = entry.getValue() != null; EntryViews.AccessLoggingReadWriteView view = EntryViews.readWrite(entry, keyDataConversion, valueDataConversion); Object r = snapshot(function.apply(view)); returns.add(skipStats ? r : StatsEnvelope.create(r, entry, exists, view.isRead())); updateStoreFlags(command, entry); }); return returns; } @Override public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) throws Throwable { Map<Object, Object> arguments = command.getArguments(); List<Object> returns = new ArrayList<>(arguments.size()); boolean skipStats = Param.StatisticsMode.isSkip(command.getParams()); BiFunction biFunction = command.getBiFunction(); DataConversion keyDataConversion = command.getKeyDataConversion(); DataConversion valueDataConversion = command.getValueDataConversion(); arguments.forEach((k, arg) -> { MVCCEntry entry = (MVCCEntry) ctx.lookupEntry(k); if (entry == null) { throw new IllegalStateException(); } Object decodedArgument = valueDataConversion.fromStorage(arg); boolean exists = entry.getValue() != null; EntryViews.AccessLoggingReadWriteView view = EntryViews.readWrite(entry, keyDataConversion, valueDataConversion); Object r = snapshot(biFunction.apply(decodedArgument, view)); returns.add(skipStats ? r : StatsEnvelope.create(r, entry, exists, view.isRead())); updateStoreFlags(command, entry); }); return returns; } @Override public Object visitTouchCommand(InvocationContext ctx, TouchCommand command) throws Throwable { int segment = command.getSegment(); Object key = command.getKey(); InternalCacheEntry<?, ?> ice = dataContainer.peek(segment, key); if (ice == null) { if (log.isTraceEnabled()) { log.tracef("Entry was not in the container to touch for key %s", key); } return Boolean.FALSE; } long currentTime = timeService.wallClockTime(); if (command.isTouchEvenIfExpired() || !ice.isExpired(currentTime)) { boolean touched = dataContainer.touch(segment, key, currentTime); if (log.isTraceEnabled()) { log.tracef("Entry was touched: %s for key %s.", touched, key); } return touched; } if (log.isTraceEnabled()) { log.tracef("Entry was expired for key %s and we could not touch it.", key); } return Boolean.FALSE; } private void updateStoreFlags(FlagAffectedCommand command, MVCCEntry e) { if (command.hasAnyFlag(FlagBitSets.SKIP_SHARED_CACHE_STORE)) { e.setSkipSharedStore(); } } private Object cloneEntry(CacheEntry<?, ?> entry) { if (entry instanceof MVCCEntry) { return internalEntryFactory.create(entry); } return internalEntryFactory.copy(entry); } static class BackingEntrySet<K, V> extends InternalCacheSet<CacheEntry<K, V>> { private final InternalDataContainer<K, V> dataContainer; BackingEntrySet(InternalDataContainer<K, V> dataContainer) { this.dataContainer = dataContainer; } @Override public Publisher<CacheEntry<K, V>> localPublisher(int segment) { // Cast is required since nested generic can't handle sub types properly return (Publisher) dataContainer.publisher(segment); } @Override public Publisher<CacheEntry<K, V>> localPublisher(IntSet segments) { // Cast is required since nested generic can't handle sub types properly return (Publisher) dataContainer.publisher(segments); } } private static class BackingKeySet<K, V> extends InternalCacheSet<K> { private final InternalDataContainer<K, V> dataContainer; BackingKeySet(InternalDataContainer<K, V> dataContainer) { this.dataContainer = dataContainer; } @Override public Publisher<K> localPublisher(int segment) { return Flowable.fromPublisher(dataContainer.publisher(segment)) .map(RxJavaInterop.entryToKeyFunction()); } @Override public Publisher<K> localPublisher(IntSet segments) { return Flowable.fromPublisher(dataContainer.publisher(segments)) .map(RxJavaInterop.entryToKeyFunction()); } } private interface KeyValueCollector { void addCacheEntry(CacheEntry entry); Object getResult(); } private static class LocalContextKeyValueCollector implements KeyValueCollector { private final Map<Object, Object> map; private LocalContextKeyValueCollector() { map = new HashMap<>(); } @Override public void addCacheEntry(CacheEntry entry) { map.put(entry.getKey(), entry.getValue()); } @Override public Object getResult() { return map; } } private static class RemoteContextKeyValueCollector implements KeyValueCollector { private final List<CacheEntry> list; private RemoteContextKeyValueCollector() { list = new LinkedList<>(); } @Override public void addCacheEntry(CacheEntry entry) { list.add(entry); } @Override public Object getResult() { return list; } } }
53,616
41.927942
176
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/DistCacheWriterInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.BOTH; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.PRIVATE; import java.util.concurrent.CompletionStage; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.SegmentSpecificCommand; import org.infinispan.commands.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; 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.FlagBitSets; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.DistributionManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Cache store interceptor specific for the distribution and replication cache modes. * <p> * <p>If the cache store is shared, only the primary owner of the key writes to the cache store.</p> * <p>If the cache store is not shared, every owner of a key writes to the cache store.</p> * <p>In non-tx caches, if the originator is an owner, the command is executed there twice. The first time, * ({@code isOriginLocal() == true}) we don't write anything to the cache store; the second time, * the normal rules apply.</p> * <p>For clear operations, either only the originator of the command clears the cache store (if it is * shared), or every node clears its cache store (if it is not shared). Note that in non-tx caches, this * happens without holding a lock on the primary owner of all the keys.</p> * * @author Galder Zamarreño * @author Dan Berindei * @since 9.0 */ public class DistCacheWriterInterceptor extends CacheWriterInterceptor { private static final Log log = LogFactory.getLog(DistCacheWriterInterceptor.class); @Inject DistributionManager dm; private boolean isUsingLockDelegation; @Override protected Log getLog() { return log; } protected void start() { super.start(); this.isUsingLockDelegation = !cacheConfiguration.transaction().transactionMode().isTransactional(); } // ---- WRITE commands @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, putKeyValueCommand, rv) -> { Object key = putKeyValueCommand.getKey(); if (!putKeyValueCommand.hasAnyFlag(FlagBitSets.ROLLING_UPGRADE) && (!isStoreEnabled(putKeyValueCommand) || rCtx.isInTxScope() || !putKeyValueCommand.isSuccessful())) return rv; if (!isProperWriter(rCtx, putKeyValueCommand, putKeyValueCommand.getKey())) return rv; return delayedValue(storeEntry(rCtx, key, putKeyValueCommand), rv); }); } @Override public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) { return invokeNextThenApply(ctx, command, (rCtx, cmd, rv) -> { Object key = cmd.getKey(); if (!isStoreEnabled(cmd) || !cmd.isSuccessful()) return rv; if (!isProperWriter(rCtx, cmd, cmd.getKey())) return rv; return delayedValue(storeEntry(rCtx, key, cmd), rv); }); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { if (!isStoreEnabled(command) || ctx.isInTxScope()) return invokeNext(ctx, command); return invokeNextThenApply(ctx, command, handlePutMapCommandReturn); } protected Object handlePutMapCommandReturn(InvocationContext rCtx, PutMapCommand putMapCommand, Object rv) { CompletionStage<Long> putMapStage = persistenceManager.writeMapCommand(putMapCommand, rCtx, ((writeCommand, key) -> !skipNonPrimary(rCtx, key, writeCommand) && isProperWriter(rCtx, writeCommand, key))); if (getStatisticsEnabled()) { putMapStage.thenAccept(cacheStores::getAndAdd); } return delayedValue(putMapStage, rv); } private boolean skipNonPrimary(InvocationContext rCtx, Object key, PutMapCommand command) { // In non-tx mode, a node may receive the same forwarded PutMapCommand many times - but each time // it must write only the keys locked on the primary owner that forwarded the rCommand return isUsingLockDelegation && command.isForwarded() && !dm.getCacheTopology().getDistribution(key).primary().equals(rCtx.getOrigin()); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, removeCommand, rv) -> { Object key = removeCommand.getKey(); if (!isStoreEnabled(removeCommand) || rCtx.isInTxScope() || !removeCommand.isSuccessful()) return rv; if (!isProperWriter(rCtx, removeCommand, key)) return rv; CompletionStage<?> stage = persistenceManager.deleteFromAllStores(key, removeCommand.getSegment(), skipSharedStores(rCtx, key, removeCommand) ? PRIVATE : BOTH); if (log.isTraceEnabled()) { stage = stage.thenAccept(removed -> getLog().tracef("Removed entry under key %s and got response %s from CacheStore", key, removed)); } return delayedValue(stage, rv); }); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, replaceCommand, rv) -> { Object key = replaceCommand.getKey(); if (!isStoreEnabled(replaceCommand) || rCtx.isInTxScope() || !replaceCommand.isSuccessful()) return rv; if (!isProperWriter(rCtx, replaceCommand, replaceCommand.getKey())) return rv; return delayedValue(storeEntry(rCtx, key, replaceCommand), rv); }); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, computeCommand, rv) -> { Object key = computeCommand.getKey(); if (!isStoreEnabled(computeCommand) || rCtx.isInTxScope() || !computeCommand.isSuccessful()) return rv; if (!isProperWriter(rCtx, computeCommand, computeCommand.getKey())) return rv; CompletionStage<?> stage; if (computeCommand.isSuccessful() && rv == null) { stage = persistenceManager.deleteFromAllStores(key, computeCommand.getSegment(), skipSharedStores(rCtx, key, computeCommand) ? PRIVATE : BOTH); if (log.isTraceEnabled()) { stage = stage.thenAccept(removed -> getLog().tracef("Removed entry under key %s and got response %s from CacheStore", key, removed)); } } else if (computeCommand.isSuccessful()) { stage = storeEntry(rCtx, key, computeCommand); } else { stage = CompletableFutures.completedNull(); } return delayedValue(stage, rv); }); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, computeIfAbsentCommand, rv) -> { Object key = computeIfAbsentCommand.getKey(); if (!isStoreEnabled(computeIfAbsentCommand) || rCtx.isInTxScope() || !computeIfAbsentCommand.isSuccessful()) return rv; if (!isProperWriter(rCtx, computeIfAbsentCommand, computeIfAbsentCommand.getKey())) return rv; return delayedValue(storeEntry(rCtx, key, computeIfAbsentCommand), rv); }); } @Override protected boolean skipSharedStores(InvocationContext ctx, Object key, FlagAffectedCommand command) { return !dm.getCacheTopology().getDistribution(key).isPrimary() || command.hasAnyFlag(FlagBitSets.SKIP_SHARED_CACHE_STORE); } @Override protected boolean isProperWriter(InvocationContext ctx, FlagAffectedCommand command, Object key) { if (command.hasAnyFlag(FlagBitSets.SKIP_OWNERSHIP_CHECK)) return true; int segment = SegmentSpecificCommand.extractSegment(command, key, keyPartitioner); DistributionInfo distributionInfo = dm.getCacheTopology().getSegmentDistribution(segment); boolean nonTx = isUsingLockDelegation || command.hasAnyFlag(FlagBitSets.IRAC_UPDATE); if (nonTx && ctx.isOriginLocal() && !command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL)) { // If the originator is a backup, the command will be forwarded back to it, and the value will be stored then // (while holding the lock on the primary owner). return distributionInfo.isPrimary(); } else { return distributionInfo.isWriteOwner(); } } }
9,310
44.866995
174
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/TransactionalExceptionEvictionInterceptor.java
package org.infinispan.interceptors.impl; import static org.infinispan.util.logging.Log.CONTAINER; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; 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.InvalidateCommand; import org.infinispan.commands.write.RemoveExpiredCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.MemoryConfiguration; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.MVCCEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.impl.KeyValueMetadataSizeCalculator; import org.infinispan.container.offheap.OffHeapConcurrentMap; import org.infinispan.container.offheap.UnpooledOffHeapMemoryAllocator; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.DistributionManager; import org.infinispan.eviction.EvictionType; import org.infinispan.expiration.impl.InternalExpirationManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.InvocationSuccessAction; import org.infinispan.metadata.Metadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Interceptor that prevents the cache from inserting too many entries over a configured maximum amount. * This interceptor assumes that there is a transactional cache without one phase commit semantics. * @author wburns * @since 9.0 */ public class TransactionalExceptionEvictionInterceptor extends DDAsyncInterceptor implements InternalExpirationManager.ExpirationConsumer<Object, Object>, Consumer<Iterable<InternalCacheEntry<Object, Object>>> { private final static Log log = LogFactory.getLog(TransactionalExceptionEvictionInterceptor.class); private final AtomicLong currentSize = new AtomicLong(); private final ConcurrentMap<GlobalTransaction, Long> pendingSize = new ConcurrentHashMap<>(); private MemoryConfiguration memoryConfiguration; private InternalDataContainer<Object, Object> container; private DistributionManager dm; private long maxSize; private long minSize; private KeyValueMetadataSizeCalculator<Object, Object> calculator; private InternalExpirationManager<Object, Object> expirationManager; private InvocationSuccessAction<RemoveExpiredCommand> removeExpiredAccept = this::removeExpiredAccept; public long getCurrentSize() { return currentSize.get(); } public long getMaxSize() { return maxSize; } public long getMinSize() { return minSize; } public long pendingTransactionCount() { return pendingSize.size(); } @Inject public void inject(Configuration config, InternalDataContainer<Object, Object> dataContainer, KeyValueMetadataSizeCalculator<Object, Object> calculator, DistributionManager dm, InternalExpirationManager<Object, Object> expirationManager) { this.memoryConfiguration = config.memory(); this.container = dataContainer; this.maxSize = config.memory().size(); this.calculator = calculator; this.dm = dm; this.expirationManager = expirationManager; } @Start public void start() { if (memoryConfiguration.storageType() == StorageType.OFF_HEAP && memoryConfiguration.evictionType() == EvictionType.MEMORY) { // TODO: this is technically not correct - as the underlying map can resize (also it doesn't take int account // we have a different map for each segment when not in LOCAL mode minSize = UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(OffHeapConcurrentMap.INITIAL_SIZE << 3); currentSize.set(minSize); } container.addRemovalListener(this); expirationManager.addInternalListener(this); } @Stop public void stop() { container.removeRemovalListener(this); expirationManager.removeInternalListener(this); } @Override public void expired(Object key, Object value, Metadata metadata, PrivateMetadata privateMetadata) { // If this is null it means it was from the store, so we don't care about that if (value != null) { if (log.isTraceEnabled()) { log.tracef("Key %s found to have expired", key); } adjustSize(- calculator.calculateSize(key, value, metadata, privateMetadata)); } } @Override public void accept(Iterable<InternalCacheEntry<Object, Object>> entries) { long changeAmount = 0; for (InternalCacheEntry<Object, Object> entry : entries) { changeAmount -= calculator.calculateSize(entry.getKey(), entry.getValue(), entry.getMetadata(), entry.getInternalMetadata()); } if (changeAmount != 0) { adjustSize(changeAmount); } } private boolean adjustSize(long amount) { while (true) { long size = currentSize.get(); long targetSize = size + amount; if (targetSize <= maxSize) { if (currentSize.compareAndSet(size, size + amount)) { if (log.isTraceEnabled()) { log.tracef("Adjusted exception based size by %d to %d", amount, size + amount); } return true; } } else { return false; } } } @Override public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable { /* * State transfer uses invalidate command to remove entries that are outside of the tx context */ Object[] keys = command.getKeys(); long changeAmount = 0; for (Object key : keys) { InternalCacheEntry<Object, Object> entry = container.peek(key); if (entry != null) { changeAmount -= calculator.calculateSize(key, entry.getValue(), entry.getMetadata(), entry.getInternalMetadata()); } } if (changeAmount != 0) { adjustSize(changeAmount); } return super.visitInvalidateCommand(ctx, command); } // Remove Expired is not transactional @Override public Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) { Object key = command.getKey(); // Skip adding changeAmount if originator is not primary if (ctx.isOriginLocal() && dm != null && !dm.getCacheTopology().getSegmentDistribution(command.getSegment()).isPrimary()) { return invokeNext(ctx, command); } return invokeNextThenAccept(ctx, command, removeExpiredAccept); } private void removeExpiredAccept(InvocationContext rCtx, RemoveExpiredCommand rCommand, Object rValue) { Object rKey = rCommand.getKey(); if (rCommand.isSuccessful()) { if (dm == null || dm.getCacheTopology().getSegmentDistribution(rCommand.getSegment()).isWriteOwner()) { MVCCEntry<?, ?> entry = (MVCCEntry<?, ?>) rCtx.lookupEntry(rKey); if (log.isTraceEnabled()) { log.tracef("Key %s was removed via expiration", rKey); } long changeAmount = -calculator.calculateSize(rKey, entry.getOldValue(), entry.getOldMetadata(), entry.getInternalMetadata()); if (changeAmount != 0 && !adjustSize(changeAmount)) { throw CONTAINER.containerFull(maxSize); } } } } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { if (log.isTraceEnabled()) { log.tracef("Clear command encountered, resetting size to %d", minSize); } // Clear is never invoked in the middle of a transaction with others so just set the size currentSize.set(minSize); return super.visitClearCommand(ctx, command); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { // If we just invoke ctx.getModifications it won't return the modifications for REPL state transfer List<WriteCommand> modifications = ctx.getCacheTransaction().getAllModifications(); Set<Object> modifiedKeys = new HashSet<>(); for (WriteCommand modification : modifications) { modifiedKeys.addAll(modification.getAffectedKeys()); } long changeAmount = 0; for (Object key : modifiedKeys) { if (dm == null || dm.getCacheTopology().isWriteOwner(key)) { CacheEntry<Object, Object> entry = ctx.lookupEntry(key); if (entry.isRemoved()) { // Need to subtract old value here InternalCacheEntry<Object, Object> containerEntry = container.peek(key); Object value = containerEntry != null ? containerEntry.getValue() : null; if (value != null) { if (log.isTraceEnabled()) { log.tracef("Key %s was removed", key); } changeAmount -= calculator.calculateSize(key, value, entry.getMetadata(), entry.getInternalMetadata()); } } else { // We check the container directly - this is to handle entries that are expired as the command // won't think it replaced a value InternalCacheEntry<Object, Object> containerEntry = container.peek(key); if (log.isTraceEnabled()) { log.tracef("Key %s was put into cache, replacing existing %s", key, containerEntry != null); } // Create and replace both add for the new value changeAmount += calculator.calculateSize(key, entry.getValue(), entry.getMetadata(), entry.getInternalMetadata()); // Need to subtract old value here if (containerEntry != null) { changeAmount -= calculator.calculateSize(key, containerEntry.getValue(), containerEntry.getMetadata(), containerEntry.getInternalMetadata()); } } } } if (changeAmount != 0 && !adjustSize(changeAmount)) { throw CONTAINER.containerFull(maxSize); } if (!command.isOnePhaseCommit()) { pendingSize.put(ctx.getGlobalTransaction(), changeAmount); } return super.visitPrepareCommand(ctx, command); } @Override public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) throws Throwable { Long size = pendingSize.remove(ctx.getGlobalTransaction()); if (size != null) { long newSize = currentSize.addAndGet(-size); if (log.isTraceEnabled()) { log.tracef("Rollback encountered subtracting exception size by %d to %d", size.longValue(), newSize); } } return super.visitRollbackCommand(ctx, command); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { pendingSize.remove(ctx.getGlobalTransaction()); return super.visitCommitCommand(ctx, command); } }
11,857
41.35
159
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/impl/InvalidationInterceptor.java
package org.infinispan.interceptors.impl; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicLong; import org.infinispan.commands.AbstractVisitor; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.TopologyAffectedCommand; import org.infinispan.commands.control.LockControlCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; import org.infinispan.commands.write.InvalidateCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.util.EnumUtil; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.LocalTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.interceptors.InvocationSuccessFunction; import org.infinispan.jmx.JmxStatisticsExposer; import org.infinispan.jmx.annotations.DataType; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedAttribute; import org.infinispan.jmx.annotations.ManagedOperation; import org.infinispan.jmx.annotations.MeasurementType; import org.infinispan.jmx.annotations.Parameter; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.transport.impl.VoidResponseCollector; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This interceptor acts as a replacement to the replication interceptor when the CacheImpl is configured with * ClusteredSyncMode as INVALIDATE. * * <p>The idea is that rather than replicating changes to all caches in a cluster when write methods are called, simply * broadcast an {@link InvalidateCommand} on the remote caches containing all keys modified. This allows the remote * cache to look up the value in a shared cache loader which would have been updated with the changes.</p> * * <p>Transactional caches, still lock affected keys on the primary owner: * <ul> * <li>Pessimistic caches acquire locks with an explicit lock command and release during the one-phase PrepareCommand.</li> * <li>Optimistic caches acquire locks during the 2-phase prepare command and release locks with a TxCompletionNotificationCommand.</li> * </ul> * </p> * * @author Manik Surtani * @author Galder Zamarreño * @author Mircea.Markus@jboss.com * @since 9.0 */ @MBean(objectName = "Invalidation", description = "Component responsible for invalidating entries on remote" + " caches when entries are written to locally.") public class InvalidationInterceptor extends BaseRpcInterceptor implements JmxStatisticsExposer { private static final Log log = LogFactory.getLog(InvalidationInterceptor.class); private final AtomicLong invalidations = new AtomicLong(0); private final InvocationSuccessFunction<CommitCommand> handleCommit = this::handleCommit; private final InvocationSuccessFunction<PrepareCommand> handlePrepare = this::handlePrepare; @Inject CommandsFactory commandsFactory; private boolean statisticsEnabled; @Override protected Log getLog() { return log; } @Start void start() { this.setStatisticsEnabled(cacheConfiguration.statistics().enabled()); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { if (!isPutForExternalRead(command)) { return handleInvalidate(ctx, command, command.getKey()); } return invokeNext(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { return handleInvalidate(ctx, command, command.getKey()); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { return handleInvalidate(ctx, command, command.getKey()); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) throws Throwable { return handleInvalidate(ctx, command, command.getKey()); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { return handleInvalidate(ctx, command, command.getKey()); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { return invokeNextThenApply(ctx, command, (rCtx, clearCommand, rv) -> { if (!isLocalModeForced(clearCommand)) { // just broadcast the clear command - this is simplest! if (rCtx.isOriginLocal()) { clearCommand.setTopologyId(rpcManager.getTopologyId()); CompletionStage<Void> remoteInvocation = rpcManager.invokeCommandOnAll(clearCommand, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); return asyncValue(remoteInvocation); } } return rv; }); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { Object[] keys = command.getMap() == null ? null : command.getMap().keySet().toArray(); return handleInvalidate(ctx, command, keys); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { return invokeNextThenApply(ctx, command, handlePrepare); } private Object handlePrepare(InvocationContext ctx, PrepareCommand prepareCommand, Object rv) throws Throwable { // fetch the modifications before the transaction is committed (and thus removed from the txTable) TxInvocationContext txInvocationContext = (TxInvocationContext) ctx; if (!shouldInvokeRemoteTxCommand(txInvocationContext)) { log.tracef("Nothing to invalidate - no modifications in the transaction."); return rv; } if (txInvocationContext.getTransaction() == null) throw new IllegalStateException("We must have an associated transaction"); List<WriteCommand> mods = prepareCommand.getModifications(); Collection<Object> remoteKeys = keysToInvalidateForPrepare(mods, txInvocationContext); if (remoteKeys == null) { return rv; } CompletionStage<Void> remoteInvocation = invalidateAcrossCluster(txInvocationContext, remoteKeys.toArray(), defaultSynchronous, prepareCommand.isOnePhaseCommit(), prepareCommand.getTopologyId()); return asyncValue(remoteInvocation.handle((responses, t) -> { if (t == null) { return null; } log.unableToRollbackInvalidationsDuringPrepare(t); if (t instanceof RuntimeException) throw ((RuntimeException) t); else throw new RuntimeException("Unable to broadcast invalidation messages", t); })); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { if (!shouldInvokeRemoteTxCommand(ctx)) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, handleCommit); } private Object handleCommit(InvocationContext ctx, CommitCommand command, Object ignored) { try { CompletionStage<Void> remoteInvocation = rpcManager.invokeCommandOnAll(command, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); return asyncValue(remoteInvocation); } catch (Throwable t) { throw wrapException(t); } } private RuntimeException wrapException(Throwable t) { if (t instanceof RuntimeException) return ((RuntimeException) t); else return log.unableToBroadcastInvalidation(t); } @Override public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable { if (!ctx.isOriginLocal()) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, (rCtx, lockControlCommand, rv) -> { //unlock will happen async as it is a best effort boolean sync = !lockControlCommand.isUnlock(); ((LocalTxInvocationContext) rCtx).remoteLocksAcquired(rpcManager.getTransport().getMembers()); if (sync) { CompletionStage<Void> remoteInvocation = rpcManager.invokeCommandOnAll(lockControlCommand, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); return asyncValue(remoteInvocation); } else { rpcManager.sendToAll(lockControlCommand, DeliverOrder.PER_SENDER); return null; } }); } private Object handleInvalidate(InvocationContext ctx, WriteCommand command, Object... keys) throws Throwable { if (ctx.isInTxScope()) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, (rCtx, writeCommand, rv) -> { if (writeCommand.isSuccessful()) { if (keys != null && keys.length != 0) { if (!isLocalModeForced(writeCommand)) { // Non-tx invalidation caches don't have a state transfer interceptor, // so the command topology id is not set int topologyId = rpcManager.getTopologyId(); CompletionStage<Void> remoteInvocation = invalidateAcrossCluster(rCtx, keys, isSynchronous(writeCommand), true, topologyId); return asyncValue(remoteInvocation.thenApply(responses -> rv)); } } } return rv; }); } private Collection<Object> keysToInvalidateForPrepare(List<WriteCommand> modifications, InvocationContext ctx) throws Throwable { // A prepare does not carry flags, so skip checking whether is local or not if (!ctx.isInTxScope()) return null; if (modifications.isEmpty()) return null; InvalidationFilterVisitor filterVisitor = new InvalidationFilterVisitor(modifications.size()); filterVisitor.visitCollection(ctx, modifications); if (filterVisitor.containsPutForExternalRead) { log.debug("Modification list contains a putForExternalRead operation. Not invalidating."); } else if (filterVisitor.containsLocalModeFlag) { log.debug("Modification list contains a local mode flagged operation. Not invalidating."); } else { return filterVisitor.result; } return null; } private static class InvalidationFilterVisitor extends AbstractVisitor { Set<Object> result; boolean containsPutForExternalRead = false; boolean containsLocalModeFlag = false; InvalidationFilterVisitor(int maxSetSize) { result = new HashSet<>(maxSetSize); } private void processCommand(FlagAffectedCommand command) { containsLocalModeFlag = containsLocalModeFlag || command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { processCommand(command); containsPutForExternalRead = containsPutForExternalRead || command.hasAnyFlag(FlagBitSets.PUT_FOR_EXTERNAL_READ); result.add(command.getKey()); return null; } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { processCommand(command); result.add(command.getKey()); return null; } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { processCommand(command); result.addAll(command.getAffectedKeys()); return null; } } private CompletionStage<Void> invalidateAcrossCluster(InvocationContext ctx, Object[] keys, boolean synchronous, boolean onePhaseCommit, int topologyId) throws Throwable { // increment invalidations counter if statistics maintained incrementInvalidations(); final InvalidateCommand invalidateCommand = commandsFactory.buildInvalidateCommand(EnumUtil.EMPTY_BIT_SET, keys); TopologyAffectedCommand command = invalidateCommand; if (ctx.isInTxScope()) { TxInvocationContext txCtx = (TxInvocationContext) ctx; // A Prepare command containing the invalidation command in its 'modifications' list is sent to the remote nodes // so that the invalidation is executed in the same transaction and locks can be acquired and released properly. command = commandsFactory.buildPrepareCommand(txCtx.getGlobalTransaction(), Collections.singletonList(invalidateCommand), onePhaseCommit); } command.setTopologyId(topologyId); if (synchronous) { return rpcManager.invokeCommandOnAll(command, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); } else { rpcManager.sendToAll(command, DeliverOrder.NONE); return CompletableFutures.completedNull(); } } private void incrementInvalidations() { if (statisticsEnabled) invalidations.incrementAndGet(); } private boolean isPutForExternalRead(FlagAffectedCommand command) { if (command.hasAnyFlag(FlagBitSets.PUT_FOR_EXTERNAL_READ)) { log.trace("Put for external read called. Suppressing clustered invalidation."); return true; } return false; } @Override @ManagedOperation( description = "Resets statistics gathered by this component", displayName = "Reset statistics" ) public void resetStatistics() { invalidations.set(0); } @Override @ManagedAttribute( displayName = "Statistics enabled", description = "Enables or disables the gathering of statistics by this component", dataType = DataType.TRAIT, writable = true ) public boolean getStatisticsEnabled() { return this.statisticsEnabled; } @Override public void setStatisticsEnabled(@Parameter(name = "enabled", description = "Whether statistics should be enabled or disabled (true/false)") boolean enabled) { this.statisticsEnabled = enabled; } @ManagedAttribute( description = "Number of invalidations", displayName = "Number of invalidations", measurementType = MeasurementType.TRENDSUP ) public long getInvalidations() { return invalidations.get(); } }
15,688
40.837333
162
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/xsite/package-info.java
/** * Interceptors dealing with cross-site replication. * * @api.private */ package org.infinispan.interceptors.xsite;
123
16.714286
52
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/xsite/PessimisticBackupInterceptor.java
package org.infinispan.interceptors.xsite; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.InvocationStage; /** * Handles x-site data backups for pessimistic transactional caches. * * @author Mircea Markus * @since 5.2 */ public class PessimisticBackupInterceptor extends BaseBackupInterceptor { @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { if (skipXSiteBackup(command) || !command.hasAnyFlag(FlagBitSets.PUT_FOR_EXTERNAL_READ)) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, handleSingleKeyWriteReturn); } @SuppressWarnings("rawtypes") @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) { //for pessimistic transaction we don't do a 2PC (as we already own the remote lock) but just //a 1PC throw new IllegalStateException("This should never happen!"); } @SuppressWarnings("rawtypes") @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) { if (isTxFromRemoteSite(command.getGlobalTransaction())) { return invokeNext(ctx, command); } InvocationStage stage; if (shouldInvokeRemoteTxCommand(ctx)) { //for sync, the originator is the one who backups the transaction to the remote site. stage = backupSender.backupPrepare(command, ctx.getCacheTransaction(), ctx.getTransaction()); } else { stage = InvocationStage.completedNullStage(); } return invokeNextThenApply(ctx, command, (rCtx, rCommand, rv) -> { //for async, all nodes need to keep track of the updates keys after it is applied locally. keysFromMods(rCommand.getModifications().stream()) .forEach(key -> iracManager.trackUpdatedKey(key.getSegment(), key.getKey(), rCommand.getGlobalTransaction())); return stage.thenReturn(rCtx, rCommand, rv); }); } }
2,285
38.413793
125
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/xsite/OptimisticBackupInterceptor.java
package org.infinispan.interceptors.xsite; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.tx.RollbackCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.LocalTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.InvocationStage; /** * Handles x-site data backups for optimistic transactional caches. * * @author Mircea Markus * @since 5.2 */ public class OptimisticBackupInterceptor extends BaseBackupInterceptor { @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { if (skipXSiteBackup(command) || !command.hasAnyFlag(FlagBitSets.PUT_FOR_EXTERNAL_READ)) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, handleSingleKeyWriteReturn); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) { //if this is a read-only tx or state transfer tx, no point replicating it to other sites if (!shouldInvokeRemoteTxCommand(ctx) || isTxFromRemoteSite(command.getGlobalTransaction())) { return invokeNext(ctx, command); } InvocationStage stage = backupSender.backupPrepare(command, ctx.getCacheTransaction(), ctx.getTransaction()); return invokeNextAndWaitForCrossSite(ctx, command, stage); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) { if (isTxFromRemoteSite(command.getGlobalTransaction())) { return invokeNext(ctx, command); } InvocationStage stage; if (shouldInvokeRemoteTxCommand(ctx)) { // this assumes sync. // for sync, the originator is the one who backups the transaction to the remote site. // we can send the update to the remote site in parallel with the local cluster update. stage = backupSender.backupCommit(command, ctx.getTransaction()); } else { //for async, all nodes need to keep track of the updates keys. stage = InvocationStage.completedNullStage(); } return invokeNextThenApply(ctx, command, (rCtx, rCommand, rv) -> { //we need to track the keys only after it is applied in the local node! keysFromMods(getModificationsFrom(rCommand)).forEach(key -> iracManager.trackUpdatedKey(key.getSegment(), key.getKey(), rCommand.getGlobalTransaction())); return stage.thenReturn(rCtx, rCommand, rv); }); } @Override public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) { if (!shouldRollbackRemoteTxCommand(ctx)) return invokeNext(ctx, command); if (isTxFromRemoteSite(command.getGlobalTransaction())) { return invokeNext(ctx, command); } InvocationStage stage = backupSender.backupRollback(command, ctx.getTransaction()); return invokeNextAndWaitForCrossSite(ctx, command, stage); } private boolean shouldRollbackRemoteTxCommand(TxInvocationContext<?> ctx) { return shouldInvokeRemoteTxCommand(ctx) && hasBeenPrepared((LocalTxInvocationContext) ctx); } /** * This 'has been prepared' logic only applies to optimistic transactions, hence it is not present in the * LocalTransaction object itself. */ private boolean hasBeenPrepared(LocalTxInvocationContext ctx) { return !ctx.getRemoteLocksAcquired().isEmpty(); } }
3,639
40.363636
163
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/xsite/BaseBackupInterceptor.java
package org.infinispan.interceptors.xsite; import java.util.concurrent.CompletionStage; import java.util.stream.Stream; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.SegmentSpecificCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.commands.write.RemoveExpiredCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.util.SegmentAwareKey; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.factories.annotations.Inject; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.InvocationStage; import org.infinispan.interceptors.InvocationSuccessAction; import org.infinispan.interceptors.InvocationSuccessFunction; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.transaction.impl.LocalTransaction; import org.infinispan.transaction.impl.RemoteTransaction; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.infinispan.xsite.BackupSender; import org.infinispan.xsite.irac.IracManager; /** * @author Mircea Markus * @since 5.2 */ public abstract class BaseBackupInterceptor extends DDAsyncInterceptor { @Inject protected BackupSender backupSender; @Inject protected TransactionTable txTable; @Inject protected IracManager iracManager; @Inject protected ClusteringDependentLogic clusteringDependentLogic; @Inject protected KeyPartitioner keyPartitioner; @Inject protected CommandsFactory commandsFactory; private static final Log log = LogFactory.getLog(BaseBackupInterceptor.class); private final InvocationSuccessFunction<ClearCommand> handleClearReturn = this::handleClearReturn; private final InvocationSuccessFunction<RemoveExpiredCommand> handleBackupMaxIdle = this::handleBackupMaxIdle; private final InvocationSuccessAction<RemoveExpiredCommand> handleExpiredReturn = this::handleExpiredReturn; protected final InvocationSuccessFunction<DataWriteCommand> handleSingleKeyWriteReturn = this::handleSingleKeyWriteReturn; @Override public final Object visitClearCommand(InvocationContext ctx, ClearCommand command) { if (skipXSiteBackup(command)) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, handleClearReturn); } Object invokeNextAndWaitForCrossSite(TxInvocationContext<?> ctx, VisitableCommand command, InvocationStage stage) { return invokeNextThenApply(ctx, command, stage::thenReturn); } @Override public Object visitRemoveExpiredCommand(InvocationContext ctx, RemoveExpiredCommand command) { if (skipXSiteBackup(command) || !command.isMaxIdle()) { return invokeNext(ctx, command); } // Max idle command shouldn't fail as the timestamps are updated on access, however the remote site may have // a read that we aren't aware of - so we must synchronously remove the entry if expired on the remote site // and if it isn't expired on the remote site we must update the access time locally here int segment = command.getSegment(); DistributionInfo dInfo = clusteringDependentLogic.getCacheTopology().getSegmentDistribution(segment); // Only require primary to check remote site and add to irac queue - If primary dies then a backup will end up // doing the same as promoted primary - We also don't add tracked up to backup as we don't care if the // remove expired is lost due to topology change it just will cause another check later but maintain consistency if (dInfo.isPrimary()) { CompletionStage<Boolean> expired = iracManager.checkAndTrackExpiration(command.getKey()); return asyncValue(expired).thenApply(ctx, command, handleBackupMaxIdle); } return invokeNext(ctx, command); } private Object handleBackupMaxIdle(InvocationContext rCtx, RemoveExpiredCommand rCommand, Object rv) { if ((Boolean) rv) { return invokeNextThenAccept(rCtx, rCommand, handleExpiredReturn); } rCommand.fail(); return rv; } private void handleExpiredReturn(InvocationContext context, RemoveExpiredCommand command, Object returnValue) { if (command.isSuccessful()) { iracManager.trackExpiredKey(command.getSegment(), command.getKey(), command.getCommandInvocationId()); } } boolean isTxFromRemoteSite(GlobalTransaction gtx) { LocalTransaction remoteTx = txTable.getLocalTransaction(gtx); return remoteTx != null && remoteTx.isFromRemoteSite(); } boolean shouldInvokeRemoteTxCommand(TxInvocationContext<?> ctx) { // ISPN-2362: For backups, we should only replicate to the remote site if there are modifications to replay. boolean shouldBackupRemotely = ctx.isOriginLocal() && ctx.hasModifications() && !ctx.getCacheTransaction().isFromStateTransfer(); log.tracef("Should backup remotely? %s", shouldBackupRemotely); return shouldBackupRemotely; } static boolean skipXSiteBackup(FlagAffectedCommand command) { return command.hasAnyFlag(FlagBitSets.SKIP_XSITE_BACKUP); } private static boolean backupToRemoteSite(WriteCommand command) { return !command.hasAnyFlag(FlagBitSets.SKIP_XSITE_BACKUP); } private Stream<SegmentAwareKey<?>> keyStream(WriteCommand command) { return command.getAffectedKeys().stream().map(key -> SegmentSpecificCommand.extractSegmentAwareKey(command, key, keyPartitioner)); } private Object handleClearReturn(InvocationContext ctx, ClearCommand rCommand, Object rv) { iracManager.trackClear(ctx.isOriginLocal()); return ctx.isOriginLocal() ? backupSender.backupClear(rCommand).thenReturn(ctx, rCommand, rv) : rv; } private Object handleSingleKeyWriteReturn(InvocationContext ctx, DataWriteCommand dataWriteCommand, Object rv) { if (!dataWriteCommand.isSuccessful()) { if (log.isTraceEnabled()) { log.tracef("Command %s is not successful, not replicating", dataWriteCommand); } return rv; } int segment = dataWriteCommand.getSegment(); if (clusteringDependentLogic.getCacheTopology().getSegmentDistribution(segment).isPrimary()) { //primary owner always tracks updates to the remote sites (and sends the update in the background) iracManager.trackUpdatedKey(segment, dataWriteCommand.getKey(), dataWriteCommand.getCommandInvocationId()); CacheEntry<?,?> entry = ctx.lookupEntry(dataWriteCommand.getKey()); WriteCommand crossSiteCommand = createCommandForXSite(entry, segment, dataWriteCommand.getFlagsBitSet()); return backupSender.backupWrite(crossSiteCommand, dataWriteCommand).thenReturn(ctx, dataWriteCommand, rv); } else if (!ctx.isOriginLocal()) { // backup owners need to keep track of the update in the remote context for ASYNC cross-site // if backup owner == originator, we don't want to track the key again when ctx.isOriginLocal==true iracManager.trackUpdatedKey(segment, dataWriteCommand.getKey(), dataWriteCommand.getCommandInvocationId()); } return rv; } private WriteCommand createCommandForXSite(CacheEntry<?, ?> entry, int segment, long flagsBitSet) { return entry.isRemoved() ? commandsFactory.buildRemoveCommand(entry.getKey(), null, segment, flagsBitSet) : commandsFactory.buildPutKeyValueCommand(entry.getKey(), entry.getValue(), segment, entry.getMetadata(), flagsBitSet); } private boolean isWriteOwner(SegmentAwareKey<?> key) { return clusteringDependentLogic.getCacheTopology().isSegmentWriteOwner(key.getSegment()); } protected Stream<WriteCommand> getModificationsFrom(CommitCommand cmd) { GlobalTransaction gtx = cmd.getGlobalTransaction(); LocalTransaction localTx = txTable.getLocalTransaction(gtx); if (localTx == null) { RemoteTransaction remoteTx = txTable.getRemoteTransaction(gtx); if (remoteTx == null) { if (log.isDebugEnabled()) { log.debugf("Transaction %s not found!", gtx); } return Stream.empty(); } else { return remoteTx.getModifications().stream(); } } else { return localTx.getModifications().stream(); } } public Stream<SegmentAwareKey<?>> keysFromMods(Stream<WriteCommand> modifications) { return modifications .filter(WriteCommand::isSuccessful) .filter(BaseBackupInterceptor::backupToRemoteSite) .flatMap(this::keyStream) .filter(this::isWriteOwner); } }
9,292
47.65445
136
java
null
infinispan-main/core/src/main/java/org/infinispan/interceptors/xsite/NonTransactionalBackupInterceptor.java
package org.infinispan.interceptors.xsite; import java.util.HashMap; import java.util.Map; 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.write.ComputeCommand; import org.infinispan.commands.write.ComputeIfAbsentCommand; import org.infinispan.commands.write.DataWriteCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.context.InvocationContext; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.encoding.DataConversion; import org.infinispan.factories.annotations.Inject; import org.infinispan.functional.impl.Params; import org.infinispan.interceptors.InvocationSuccessFunction; import org.infinispan.marshall.core.MarshallableFunctions; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Handles x-site data backups for non-transactional caches. * * @author Mircea Markus * @author Pedro Ruivo * @since 5.2 */ public class NonTransactionalBackupInterceptor extends BaseBackupInterceptor { private static final Log log = LogFactory.getLog(NonTransactionalBackupInterceptor.class); private final InvocationSuccessFunction<WriteCommand> handleMultipleKeysWriteReturn = this::handleMultipleKeysWriteReturn; @Inject InternalEntryFactory internalEntryFactory; @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitComputeIfAbsentCommand(InvocationContext ctx, ComputeIfAbsentCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitWriteOnlyKeyCommand(InvocationContext ctx, WriteOnlyKeyCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitReadWriteKeyValueCommand(InvocationContext ctx, ReadWriteKeyValueCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) { return handleMultipleKeysWriteCommand(ctx, command); } @Override public Object visitWriteOnlyKeyValueCommand(InvocationContext ctx, WriteOnlyKeyValueCommand command) { return handleSingleKeyWriteCommand(ctx, command); } @Override public Object visitWriteOnlyManyCommand(InvocationContext ctx, WriteOnlyManyCommand command) { return handleMultipleKeysWriteCommand(ctx, command); } @Override public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) { return handleMultipleKeysWriteCommand(ctx, command); } @Override public Object visitReadWriteManyEntriesCommand(InvocationContext ctx, ReadWriteManyEntriesCommand command) { return handleMultipleKeysWriteCommand(ctx, command); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { return handleMultipleKeysWriteCommand(ctx, command); } private Object handleSingleKeyWriteCommand(InvocationContext ctx, DataWriteCommand command) { if (skipXSiteBackup(command)) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, handleSingleKeyWriteReturn); } private Object handleMultipleKeysWriteCommand(InvocationContext ctx, WriteCommand command) { if (log.isTraceEnabled()) log.tracef("Processing %s", command); if (skipXSiteBackup(command)) { return invokeNext(ctx, command); } return invokeNextThenApply(ctx, command, handleMultipleKeysWriteReturn); } private Object handleMultipleKeysWriteReturn(InvocationContext ctx, WriteCommand writeCommand, Object rv) { if (log.isTraceEnabled()) log.tracef("Processing post %s", writeCommand); if (!writeCommand.isSuccessful()) { if (log.isTraceEnabled()) { log.tracef("Command %s is not successful, not replicating", writeCommand); } return rv; } Map<Object, Object> map = new HashMap<>(); // must support null values LocalizedCacheTopology localizedCacheTopology = clusteringDependentLogic.getCacheTopology(); for (Object key : writeCommand.getAffectedKeys()) { DistributionInfo info = localizedCacheTopology.getDistribution(key); if (info.isPrimary() || (!ctx.isOriginLocal() && info.isWriteOwner())) { // track the update for the ASYNC cross-site // backup owner only track updates when the context is remote. iracManager.trackUpdatedKey(info.segmentId(), key, writeCommand.getCommandInvocationId()); } if (!info.isPrimary()) { if (log.isTraceEnabled()) { log.tracef("Not replicating write to key %s as the primary owner is %s", key, info.primary()); } continue; } CacheEntry<?,?> entry = ctx.lookupEntry(key); if (entry instanceof InternalCacheEntry) { map.put(key, ((InternalCacheEntry<?,?>) entry).toInternalCacheValue()); } else { map.put(key, internalEntryFactory.createValue(entry)); } } if (map.isEmpty()) { return rv; } //TODO: Converters WriteCommand crossSiteCommand = commandsFactory.buildWriteOnlyManyEntriesCommand(map, MarshallableFunctions.setInternalCacheValueConsumer(), Params.fromFlagsBitSet(writeCommand.getFlagsBitSet()), DataConversion.IDENTITY_KEY, DataConversion.IDENTITY_VALUE); return backupSender.backupWrite(crossSiteCommand, writeCommand).thenReturn(ctx, writeCommand, rv); } }
7,319
40.590909
125
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/GlobalMarshaller.java
package org.infinispan.marshall.core; import static org.infinispan.util.logging.Log.CONTAINER; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.Array; import org.infinispan.commands.RemoteCommandsFactory; import org.infinispan.commons.CacheException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.LazyByteArrayOutputStream; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.Externalizer; import org.infinispan.commons.marshall.MarshallableTypeHints; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.MarshallingException; import org.infinispan.commons.marshall.NotSerializableException; import org.infinispan.commons.marshall.SerializeFunctionWith; import org.infinispan.commons.marshall.SerializeWith; import org.infinispan.commons.marshall.StreamAwareMarshaller; import org.infinispan.commons.marshall.StreamingMarshaller; import org.infinispan.configuration.global.GlobalConfiguration; 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.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.marshall.core.impl.ClassToExternalizerMap; import org.infinispan.marshall.core.impl.ClassToExternalizerMap.IdToExternalizerMap; import org.infinispan.marshall.core.impl.ExternalExternalizers; import org.infinispan.marshall.exts.ThrowableExternalizer; import org.infinispan.marshall.persistence.PersistenceMarshaller; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A globally-scoped marshaller. This is needed so that the transport layer * can unmarshall requests even before it's known which cache's marshaller can * do the job. * * @author Galder Zamarreño * @since 5.0 */ @Scope(Scopes.GLOBAL) public class GlobalMarshaller implements StreamingMarshaller { private static final Log log = LogFactory.getLog(GlobalMarshaller.class); public static final int NOT_FOUND = -1; public static final int ID_NULL = 0x00; public static final int ID_PRIMITIVE = 0x01; public static final int ID_INTERNAL = 0x02; public static final int ID_EXTERNAL = 0x03; public static final int ID_ANNOTATED = 0x04; public static final int ID_UNKNOWN = 0x05; /** * The array will be encoded as follows: * * ID_ARRAY | flags + component type | component type info | array length | [element type | element type info] | array elements | * 00000110 | ssncieee | depends on type | 0 - 4 bytes | [00000eee | depends on type ] | ... | * * Flags: * ss: {@link #FLAG_ARRAY_EMPTY}, {@link #FLAG_ARRAY_SMALL}, {@link #FLAG_ARRAY_MEDIUM}, {@link #FLAG_ARRAY_LARGE} * n: {@link #FLAG_ALL_NULL} * i: {@link #FLAG_SINGLE_TYPE} * c: {@link #FLAG_COMPONENT_TYPE_MATCH} * eee: {@link #ID_INTERNAL}, {@link #ID_EXTERNAL}, {@link #ID_ANNOTATED}, {@link #ID_CLASS} * * Element type will be present only if the {@link #FLAG_SINGLE_TYPE} is set. In that case the array elements * won't be preceded by the instance type identifier, this will be common for all elements. * * Multidimensional arrays are not supported ATM. */ static final int ID_ARRAY = 0x06; static final int ID_CLASS = 0x07; static final int ID_LAMBDA = 0x08; // Type is in last 3 bits static final int TYPE_MASK = 0x07; // Array size is in first 2 bits static final int ARRAY_SIZE_MASK = 0xC0; // All elements are of the same type static final int FLAG_SINGLE_TYPE = 0x08; // Component type matches to instance type static final int FLAG_COMPONENT_TYPE_MATCH = 0x10; // All elements of the array are null static final int FLAG_ALL_NULL = 0x20; // Length of the array static final int FLAG_ARRAY_EMPTY = 0x00; static final int FLAG_ARRAY_SMALL = 0x40; static final int FLAG_ARRAY_MEDIUM = 0x80; static final int FLAG_ARRAY_LARGE = 0xC0; private final MarshallableTypeHints marshallableTypeHints = new MarshallableTypeHints(); @Inject GlobalComponentRegistry gcr; @Inject RemoteCommandsFactory cmdFactory; @Inject @ComponentName(KnownComponentNames.PERSISTENCE_MARSHALLER) PersistenceMarshaller persistenceMarshaller; ClassToExternalizerMap internalExts; IdToExternalizerMap reverseInternalExts; ClassToExternalizerMap externalExts; IdToExternalizerMap reverseExternalExts; private ClassIdentifiers classIdentifiers; private ClassLoader classLoader; public GlobalMarshaller() { } @Override @Start(priority = 8) // Should start after the externalizer table and before transport public void start() { GlobalConfiguration globalCfg = gcr.getGlobalConfiguration(); classLoader = globalCfg.classLoader(); internalExts = InternalExternalizers.load(gcr, cmdFactory); reverseInternalExts = internalExts.reverseMap(Ids.MAX_ID); if (log.isTraceEnabled()) { log.tracef("Internal class to externalizer ids: %s", internalExts); log.tracef("Internal reverse externalizers: %s", reverseInternalExts); } externalExts = ExternalExternalizers.load(globalCfg); reverseExternalExts = externalExts.reverseMap(); if (log.isTraceEnabled()) { log.tracef("External class to externalizer ids: %s", externalExts); log.tracef("External reverse externalizers: %s", reverseExternalExts); } classIdentifiers = ClassIdentifiers.load(globalCfg); } @Override @Stop(priority = 130) // Stop after transport to avoid send/receive and marshaller not being ready public void stop() { internalExts = null; reverseInternalExts = null; externalExts = null; reverseExternalExts = null; classIdentifiers = null; persistenceMarshaller.stop(); } public PersistenceMarshaller getPersistenceMarshaller() { return persistenceMarshaller; } @Override public byte[] objectToByteBuffer(Object obj) throws IOException, InterruptedException { try { BytesObjectOutput out = writeObjectOutput(obj); return out.toBytes(); // trim out unused bytes } catch (java.io.NotSerializableException nse) { if (log.isDebugEnabled()) log.debug("Object is not serializable", nse); throw new NotSerializableException(nse.getMessage(), nse.getCause()); } } private BytesObjectOutput writeObjectOutput(Object obj) throws IOException { BufferSizePredictor sizePredictor = marshallableTypeHints.getBufferSizePredictor(obj); BytesObjectOutput out = writeObjectOutput(obj, sizePredictor.nextSize(obj)); sizePredictor.recordSize(out.pos); return out; } private BytesObjectOutput writeObjectOutput(Object obj, int estimatedSize) throws IOException { BytesObjectOutput out = new BytesObjectOutput(estimatedSize, this); writeNullableObject(obj, out); return out; } @Override public Object objectFromByteBuffer(byte[] buf) throws IOException, ClassNotFoundException { BytesObjectInput in = BytesObjectInput.from(buf, this); return objectFromObjectInput(in); } private Object objectFromObjectInput(BytesObjectInput in) throws IOException, ClassNotFoundException { return readNullableObject(in); } @Override public ObjectOutput startObjectOutput(OutputStream os, boolean isReentrant, int estimatedSize) throws IOException { BytesObjectOutput out = new BytesObjectOutput(estimatedSize, this); return new StreamBytesObjectOutput(os, out); } @Override public void objectToObjectStream(Object obj, ObjectOutput out) throws IOException { out.writeObject(obj); } @Override public void finishObjectOutput(ObjectOutput oo) { try { oo.flush(); } catch (IOException e) { // ignored } } @Override public Object objectFromByteBuffer(byte[] bytes, int offset, int len) throws IOException, ClassNotFoundException { // Ignore length since boundary checks are not so useful here where the // unmarshalling code knows what to expect specifically. E.g. if reading // a byte[] subset within it, it's always appended with length. BytesObjectInput in = BytesObjectInput.from(bytes, offset, this); return objectFromObjectInput(in); } @Override public Object objectFromInputStream(InputStream is) throws IOException, ClassNotFoundException { // This is a very limited use case, e.g. reading from a JDBC ResultSet InputStream // So, this copying of the stream into a byte[] has not been problematic so far, // though it's not really ideal. int len = is.available(); LazyByteArrayOutputStream bytes; byte[] buf; if(len > 0) { bytes = new LazyByteArrayOutputStream(len); buf = new byte[Math.min(len, 1024)]; } else { // Some input stream providers do not implement available() bytes = new LazyByteArrayOutputStream(); buf = new byte[1024]; } int bytesRead; while ((bytesRead = is.read(buf, 0, buf.length)) != -1) bytes.write(buf, 0, bytesRead); return objectFromByteBuffer(bytes.getRawBuffer(), 0, bytes.size()); } @Override public boolean isMarshallable(Object o) throws Exception { Class<?> clazz = o.getClass(); boolean containsMarshallable = marshallableTypeHints.isKnownMarshallable(clazz); if (containsMarshallable) { boolean marshallable = marshallableTypeHints.isMarshallable(clazz); if (log.isTraceEnabled()) log.tracef("Marshallable type '%s' known and is marshallable=%b", clazz.getName(), marshallable); return marshallable; } else { if (isMarshallableCandidate(o)) { boolean isMarshallable = true; try { objectToBuffer(o); } catch (Exception e) { isMarshallable = false; throw e; } finally { marshallableTypeHints.markMarshallable(clazz, isMarshallable); } return isMarshallable; } return false; } } private boolean isMarshallableCandidate(Object o) { return o instanceof Serializable || getExternalizer(internalExts, o.getClass()) != null || getExternalizer(externalExts, o.getClass()) != null || o.getClass().getAnnotation(SerializeWith.class) != null || isExternalMarshallable(o); } private boolean isExternalMarshallable(Object o) { try { return persistenceMarshaller.isMarshallable(o); } catch (Exception e) { throw new MarshallingException("Object of type " + o.getClass() + " expected to be marshallable", e); } } @Override public BufferSizePredictor getBufferSizePredictor(Object o) { return marshallableTypeHints.getBufferSizePredictor(o.getClass()); } @Override public MediaType mediaType() { return MediaType.APPLICATION_INFINISPAN_MARSHALLED; } @Override public ByteBuffer objectToBuffer(Object o) throws IOException, InterruptedException { try { BytesObjectOutput out = writeObjectOutput(o); return out.toByteBuffer(); } catch (java.io.NotSerializableException nse) { if (log.isDebugEnabled()) log.debug("Object is not serializable", nse); throw new NotSerializableException(nse.getMessage(), nse.getCause()); } } @Override public byte[] objectToByteBuffer(Object obj, int estimatedSize) throws IOException, InterruptedException { try { BytesObjectOutput out = writeObjectOutput(obj, estimatedSize); return out.toBytes(); } catch (java.io.NotSerializableException nse) { if (log.isDebugEnabled()) log.debug("Object is not serializable", nse); throw new NotSerializableException(nse.getMessage(), nse.getCause()); } } @Override public ObjectInput startObjectInput(InputStream is, boolean isReentrant) { throw new UnsupportedOperationException("No longer in use"); } @Override public void finishObjectInput(ObjectInput oi) { throw new UnsupportedOperationException("No longer in use"); } @Override public Object objectFromObjectStream(ObjectInput in) { throw new UnsupportedOperationException("No longer in use"); } public <T> Externalizer<T> findExternalizerFor(Object obj) { Class<?> clazz = obj.getClass(); Externalizer ext = getExternalizer(internalExts, clazz); if (ext == null) { ext = getExternalizer(externalExts, clazz); if (ext == null) ext = findAnnotatedExternalizer(clazz); } return ext; } void writeNullableObject(Object obj, BytesObjectOutput out) throws IOException { if (obj == null) out.writeByte(ID_NULL); else writeNonNullableObject(obj, out); } Object readNullableObject(BytesObjectInput in) throws IOException, ClassNotFoundException { int type = in.readUnsignedByte(); return type == ID_NULL ? null : readNonNullableObject(type, in); } private void writeNonNullableObject(Object obj, BytesObjectOutput out) throws IOException { Class<?> clazz = obj.getClass(); int id = Primitives.PRIMITIVES.getOrDefault(clazz, NOT_FOUND); if (id != NOT_FOUND) { writePrimitive(obj, out, id); } else if (clazz.isArray()) { writeArray(clazz, obj, out); } else { AdvancedExternalizer ext = getExternalizer(internalExts, clazz, obj); if (ext != null) { writeInternal(obj, ext, out); } else { ext = getExternalizer(externalExts, clazz); if (ext != null) { writeExternal(obj, ext, out); } else { Externalizer annotExt = findAnnotatedExternalizer(clazz); if (annotExt != null) { writeAnnotated(obj, out, annotExt); } else { if (clazz.isSynthetic()) writeUnknownLambda(obj, out); else writeUnknown(obj, out); } } } } } public static AdvancedExternalizer getInteralExternalizer(GlobalMarshaller gm, Class<?> clazz) { return gm.getExternalizer(gm.internalExts, clazz); } public static AdvancedExternalizer getExternalExternalizer(GlobalMarshaller gm, Class<?> clazz) { return gm.getExternalizer(gm.externalExts, clazz); } public static Object readObjectFromObjectInput(GlobalMarshaller gm, ObjectInput in) throws IOException, ClassNotFoundException { int type = in.readUnsignedByte(); switch (type) { case ID_INTERNAL: return gm.getExternalizer(gm.reverseInternalExts, in.readUnsignedByte()).readObject(in); case ID_EXTERNAL: return gm.getExternalizer(gm.reverseExternalExts, in.readInt()).readObject(in); case ID_UNKNOWN: return gm.readUnknown(gm.persistenceMarshaller, in); default: return null; } } AdvancedExternalizer getExternalizer(ClassToExternalizerMap class2ExternalizerMap, Class<?> clazz, Object o) { AdvancedExternalizer ext = getExternalizer(class2ExternalizerMap, clazz); if (ext != null) return ext; return o instanceof Throwable ? ThrowableExternalizer.INSTANCE : null; } AdvancedExternalizer getExternalizer(ClassToExternalizerMap class2ExternalizerMap, Class<?> clazz) { if (class2ExternalizerMap == null) { throw CONTAINER.cacheManagerIsStopping(); } return class2ExternalizerMap.get(clazz); } AdvancedExternalizer getExternalizer(IdToExternalizerMap id2ExternalizerMap, int i) { if (id2ExternalizerMap == null) { throw CONTAINER.cacheManagerIsStopping(); } return id2ExternalizerMap.get(i); } private void writeArray(Class<?> clazz, Object array, BytesObjectOutput out) throws IOException { out.writeByte(ID_ARRAY); Class<?> componentType = clazz.getComponentType(); int length = Array.getLength(array); boolean singleType = true; Class<?> elementType = null; int flags; if (length == 0) { flags = FLAG_ARRAY_EMPTY; } else { if (length <= Primitives.SMALL_ARRAY_MAX) { flags = FLAG_ARRAY_SMALL; } else if (length <= Primitives.MEDIUM_ARRAY_MAX) { flags = FLAG_ARRAY_MEDIUM; } else { flags = FLAG_ARRAY_LARGE; } Object firstElement = Array.get(array, 0); if (firstElement != null) { elementType = firstElement.getClass(); } for (int i = 1; i < length; ++i) { Object element = Array.get(array, i); if (element == null) { if (elementType != null) { singleType = false; break; } } else if (element.getClass() != elementType) { singleType = false; break; } } } boolean componentTypeMatch = false; if (singleType) { flags |= FLAG_SINGLE_TYPE; if (elementType == null) { flags |= FLAG_ALL_NULL; } else if (elementType == componentType) { flags |= FLAG_COMPONENT_TYPE_MATCH; componentTypeMatch = true; } } AdvancedExternalizer ext; if ((ext = getExternalizer(internalExts, componentType)) != null) { writeFlagsWithExternalizer(out, componentType, componentTypeMatch, ext, flags, ID_INTERNAL); } else if ((ext = getExternalizer(externalExts, componentType)) != null) { writeFlagsWithExternalizer(out, componentType, componentTypeMatch, ext, flags, ID_EXTERNAL); } else { // We cannot use annotated externalizer to specify the component type, so we will // clear the component type match flag and use class identifier or full name. // Theoretically we could write annotated externalizer and component type saving one byte // but it's not worth the complexity. componentTypeMatch = false; flags &= ~FLAG_COMPONENT_TYPE_MATCH; int classId; if ((classId = classIdentifiers.getId(componentType)) != -1) { out.writeByte(flags | ID_CLASS); if (classId < ClassIds.MAX_ID) { out.writeByte(classId); } else { out.writeByte(ClassIds.MAX_ID); out.writeInt(classId); } } else { out.writeByte(flags | ID_UNKNOWN); out.writeObject(componentType); } } if (length == 0) { } else if (length <= Primitives.SMALL_ARRAY_MAX) { out.writeByte(length - Primitives.SMALL_ARRAY_MIN); } else if (length <= Primitives.MEDIUM_ARRAY_MAX) { out.writeShort(length - Primitives.MEDIUM_ARRAY_MIN); } else { out.writeInt(length); } if (singleType) { Externalizer elementExt; int primitiveId; if (elementType == null) { return; } else if (componentTypeMatch) { // Note: ext can be null here! elementExt = ext; } else if ((elementExt = getExternalizer(internalExts, elementType)) != null) { out.writeByte(ID_INTERNAL); out.writeByte(((AdvancedExternalizer) elementExt).getId()); } else if ((elementExt = getExternalizer(externalExts, elementType)) != null) { out.writeByte(ID_EXTERNAL); out.writeInt(((AdvancedExternalizer) elementExt).getId()); } else if ((elementExt = findAnnotatedExternalizer(elementType)) != null) { // We could try if the externalizer class is registered in ClassIdentifier but most likely it is not, // because if an user registered it, he could rather explicitly register AdvancedExternalizer instead. out.writeByte(ID_ANNOTATED); out.writeObject(elementExt.getClass()); } else if ((primitiveId = Primitives.PRIMITIVES.getOrDefault(elementType, NOT_FOUND)) != NOT_FOUND) { out.writeByte(ID_PRIMITIVE); out.writeByte(primitiveId); for (int i = 0; i < length; ++i) { Object element = Array.get(array, i); assert element != null; Primitives.writeRawPrimitive(element, out, primitiveId); } // We are finished return; } else { out.writeByte(ID_UNKNOWN); // Do not write element type! } if (elementExt != null) { for (int i = 0; i < length; ++i) { Object element = Array.get(array, i); assert element != null; elementExt.writeObject(out, element); } } else { // component type matches but this type does not have an externalizer for (int i = 0; i < length; ++i) { Object element = Array.get(array, i); assert element != null; writeRawUnknown(element, out); } } } else { for (int i = 0; i < length; ++i) { Object element = Array.get(array, i); writeNullableObject(element, out); } } } private void writeFlagsWithExternalizer(BytesObjectOutput out, Class<?> componentType, boolean componentTypeMatch, AdvancedExternalizer ext, int flags, int externalizerType) throws IOException { // If the class can be identified by its externalizer, do that. // If there's a component type match, write the externalizer here anyway, otherwise we would // have to write it as element type later // If the class cannot be uniquely identified by its externalizer, try class identifiers boolean hasSingleClass = ext.getTypeClasses().size() == 1; int classId = -1; if (componentTypeMatch || hasSingleClass) { out.writeByte(flags | externalizerType); switch (externalizerType) { case ID_INTERNAL: out.writeByte(ext.getId()); break; case ID_EXTERNAL: out.writeInt(ext.getId()); break; default: throw new IllegalStateException(); } if (!hasSingleClass) { classId = classIdentifiers.getId(componentType); } } else if ((classId = classIdentifiers.getId(componentType)) >= 0) { out.writeByte(flags | ID_CLASS); } else { out.writeByte(flags | ID_UNKNOWN); } if (!hasSingleClass) { if (classId < 0) { out.writeObject(componentType); } else if (classId < ClassIds.MAX_ID){ out.writeByte(classId); } else { out.writeByte(ClassIds.MAX_ID); out.writeInt(classId); } } } private void writeUnknownLambda(Object obj, ObjectOutput out) throws IOException { out.writeByte(ID_LAMBDA); LambdaMarshaller.write(out, obj); } private void writeUnknown(Object obj, BytesObjectOutput out) throws IOException { writeUnknown(persistenceMarshaller, obj, out); } private void writeRawUnknown(Object obj, ObjectOutput out) throws IOException { writeRawUnknown(persistenceMarshaller, obj, out); } public static void writeUnknown(Marshaller marshaller, Object obj, ObjectOutput out) throws IOException { out.writeByte(ID_UNKNOWN); writeRawUnknown(marshaller, obj, out); } private static void writeRawUnknown(Marshaller marshaller, Object obj, ObjectOutput out) throws IOException { if (marshaller instanceof StreamingMarshaller) { ((StreamingMarshaller) marshaller).objectToObjectStream(obj, out); } else if (marshaller instanceof StreamAwareMarshaller && out instanceof StreamBytesObjectOutput) { OutputStream outputStream = ((StreamBytesObjectOutput) out).stream; ((StreamAwareMarshaller) marshaller).writeObject(obj, outputStream); } else { try { byte[] bytes = marshaller.objectToByteBuffer(obj); out.writeInt(bytes.length); out.write(bytes); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } private void writeAnnotated(Object obj, BytesObjectOutput out, Externalizer ext) throws IOException { out.writeByte(ID_ANNOTATED); out.writeObject(ext.getClass()); ext.writeObject(out, obj); } static void writeInternal(Object obj, AdvancedExternalizer ext, ObjectOutput out) throws IOException { out.writeByte(ID_INTERNAL); out.writeByte(ext.getId()); ext.writeObject(out, obj); } public static void writeInternalClean(Object obj, AdvancedExternalizer ext, ObjectOutput out) { try { writeInternal(obj, ext, out); } catch (IOException e) { throw new CacheException(e); } } private static void writeExternal(Object obj, AdvancedExternalizer ext, ObjectOutput out) throws IOException { out.writeByte(ID_EXTERNAL); out.writeInt(ext.getId()); ext.writeObject(out, obj); } public static void writeExternalClean(Object obj, AdvancedExternalizer ext, ObjectOutput out) { try { writeExternal(obj, ext, out); } catch (IOException e) { throw new CacheException(e); } } private void writePrimitive(Object obj, BytesObjectOutput out, int id) throws IOException { out.writeByte(ID_PRIMITIVE); Primitives.writePrimitive(obj, out, id); } private <T> Externalizer<T> findAnnotatedExternalizer(Class<?> clazz) { try { SerializeWith serialAnn = clazz.getAnnotation(SerializeWith.class); if (serialAnn != null) { return (Externalizer<T>) serialAnn.value().newInstance(); } else { SerializeFunctionWith funcSerialAnn = clazz.getAnnotation(SerializeFunctionWith.class); if (funcSerialAnn != null) return (Externalizer<T>) funcSerialAnn.value().newInstance(); } return null; } catch (Exception e) { throw new IllegalArgumentException(String.format( "Cannot instantiate externalizer for %s", clazz), e); } } private Object readNonNullableObject(int type, BytesObjectInput in) throws IOException, ClassNotFoundException { switch (type) { case ID_PRIMITIVE: return Primitives.readPrimitive(in); case ID_INTERNAL: return readWithExternalizer(in.readUnsignedByte(), reverseInternalExts, in); case ID_EXTERNAL: return readWithExternalizer(in.readInt(), reverseExternalExts, in); case ID_ANNOTATED: return readAnnotated(in); case ID_UNKNOWN: return readUnknown(in); case ID_ARRAY: return readArray(in); case ID_LAMBDA: return LambdaMarshaller.read(in, classLoader); default: throw new IOException("Unknown type: " + type); } } private Object readWithExternalizer(int id, IdToExternalizerMap reverseMap, BytesObjectInput in) throws IOException, ClassNotFoundException { AdvancedExternalizer ext = getExternalizer(reverseMap, id); return ext.readObject(in); } private Object readAnnotated(BytesObjectInput in) throws IOException, ClassNotFoundException { Class<? extends Externalizer> clazz = (Class<? extends Externalizer>) in.readObject(); try { Externalizer ext = clazz.newInstance(); return ext.readObject(in); } catch (Exception e) { throw new CacheException("Error instantiating class: " + clazz, e); } } private Object readArray(BytesObjectInput in) throws IOException, ClassNotFoundException { int flags = in.readByte(); int type = flags & TYPE_MASK; AdvancedExternalizer<?> componentExt = null; Class<?> extClazz = null; Class<?> componentType; switch (type) { case ID_NULL: case ID_PRIMITIVE: case ID_ARRAY: throw new IOException("Unexpected component type: " + type); case ID_INTERNAL: componentExt = getExternalizer(reverseInternalExts, in.readByte()); componentType = getOrReadClass(in, componentExt); break; case ID_EXTERNAL: componentExt = getExternalizer(reverseExternalExts, in.readInt()); componentType = getOrReadClass(in, componentExt); break; case ID_ANNOTATED: extClazz = (Class<?>) in.readObject(); // intentional no break case ID_UNKNOWN: componentType = (Class<?>) in.readObject(); break; case ID_CLASS: int classId = in.readByte(); if (classId < ClassIds.MAX_ID) { componentType = classIdentifiers.getClass(classId); } else { componentType = classIdentifiers.getClass(in.readInt()); } break; default: throw new IOException("Unknown component type: " + type); } int length; int maskedSize = flags & ARRAY_SIZE_MASK; switch (maskedSize) { case FLAG_ARRAY_EMPTY: length = 0; break; case FLAG_ARRAY_SMALL: length = in.readUnsignedByte() + Primitives.SMALL_ARRAY_MIN; break; case FLAG_ARRAY_MEDIUM: length = in.readUnsignedShort() + Primitives.MEDIUM_ARRAY_MIN; break; case FLAG_ARRAY_LARGE: length = in.readInt(); break; default: throw new IOException("Unknown array size: " + maskedSize); } Object array = Array.newInstance(componentType, length); if ((flags & FLAG_ALL_NULL) != 0) { return array; } boolean singleType = (flags & FLAG_SINGLE_TYPE) != 0; boolean componentTypeMatch = (flags & FLAG_COMPONENT_TYPE_MATCH) != 0; // If component type match is set, this must be a single type assert componentTypeMatch ? singleType : true; if (singleType) { Externalizer<?> ext; if (componentTypeMatch) { ext = getArrayElementExternalizer(type, componentExt, extClazz); } else { type = in.readByte(); ext = readExternalizer(in, type); } if (ext != null) { for (int i = 0; i < length; ++i) { Array.set(array, i, ext.readObject(in)); } } else { switch (type) { case ID_UNKNOWN: for (int i = 0; i < length; ++i) { Array.set(array, i, readUnknown(in)); } return array; case ID_PRIMITIVE: int primitiveId = in.readByte(); for (int i = 0; i < length; ++i) { Array.set(array, i, Primitives.readRawPrimitive(in, primitiveId)); } return array; default: throw new IllegalStateException(); } } } else { for (int i = 0; i < length; ++i) { Array.set(array, i, readNullableObject(in)); } } return array; } private Externalizer<?> getArrayElementExternalizer(int type, AdvancedExternalizer<?> componentExt, Class<?> extClazz) throws IOException { switch (type) { case ID_INTERNAL: case ID_EXTERNAL: return componentExt; case ID_ANNOTATED: try { return (Externalizer<?>) extClazz.newInstance(); } catch (Exception e) { throw new CacheException("Error instantiating class: " + extClazz, e); } case ID_UNKNOWN: return null; default: throw new IOException("Unexpected component type: " + type); } } private Externalizer<?> readExternalizer(BytesObjectInput in, int type) throws ClassNotFoundException, IOException { Class<?> extClazz; switch (type) { case ID_INTERNAL: return getExternalizer(reverseInternalExts, 0xFF & in.readByte()); case ID_EXTERNAL: return getExternalizer(reverseExternalExts, in.readInt()); case ID_ANNOTATED: extClazz = (Class<?>) in.readObject(); try { return (Externalizer<?>) extClazz.newInstance(); } catch (Exception e) { throw new CacheException("Error instantiating class: " + extClazz, e); } case ID_UNKNOWN: case ID_PRIMITIVE: return null; default: throw new IOException("Unexpected component type: " + type); } } private Class<?> getOrReadClass(BytesObjectInput in, AdvancedExternalizer<?> componentExt) throws ClassNotFoundException, IOException { if (componentExt.getTypeClasses().size() == 1) { return componentExt.getTypeClasses().iterator().next(); } else { return (Class<?>) in.readObject(); } } private Object readUnknown(ObjectInput in) throws IOException, ClassNotFoundException { return readUnknown(persistenceMarshaller, in); } Object readUnknown(Marshaller marshaller, ObjectInput in) throws IOException, ClassNotFoundException { if (marshaller instanceof StreamingMarshaller) { try { return ((StreamingMarshaller) marshaller).objectFromObjectStream(in); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } } else { int length = in.readInt(); byte[] bytes = new byte[length]; in.readFully(bytes); return marshaller.objectFromByteBuffer(bytes); } } }
35,168
37.689769
197
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/Ids.java
package org.infinispan.marshall.core; /** * Indexes for object types. These are currently limited to being unsigned ints, so valid values are considered those * in the range of 0 to 254. Please note that the use of 255 is forbidden since this is reserved for foreign, or user * defined, externalizers. * * @author Galder Zamarreño * @since 4.0 */ public interface Ids extends org.infinispan.commons.marshall.Ids { // All identifiers now defined in commons for a more complete view. }
497
30.125
117
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/SecurityActions.java
package org.infinispan.marshall.core; import java.lang.reflect.Method; /** * SecurityActions for the {@link org.infinispan.marshall.core} 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 Ryan Emerson * @since 10.0 */ final class SecurityActions { static Method getMethodAndSetAccessible(Object o, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { return getMethodAndSetAccessible(o.getClass(), methodName, parameterTypes); } static Method getMethodAndSetAccessible(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { Method method = clazz.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return method; } }
909
34
136
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/LambdaMarshaller.java
package org.infinispan.marshall.core; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.invoke.SerializedLambda; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.marshall.MarshallingException; /** * @author Ryan Emerson * @since 10.0 */ class LambdaMarshaller { static void write(ObjectOutput out, Object o) throws IOException { try { Method writeReplace = SecurityActions.getMethodAndSetAccessible(o, "writeReplace"); SerializedLambda sl = (SerializedLambda) writeReplace.invoke(o); writeSerializedLambda(out, sl); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new MarshallingException(e); } } private static void writeSerializedLambda(ObjectOutput out, SerializedLambda object) throws IOException { out.writeUTF(object.getCapturingClass()); out.writeUTF(object.getFunctionalInterfaceClass()); out.writeUTF(object.getFunctionalInterfaceMethodName()); out.writeUTF(object.getFunctionalInterfaceMethodSignature()); out.writeInt(object.getImplMethodKind()); out.writeUTF(object.getImplClass()); out.writeUTF(object.getImplMethodName()); out.writeUTF(object.getImplMethodSignature()); out.writeUTF(object.getInstantiatedMethodType()); int numberOfArgs = object.getCapturedArgCount(); MarshallUtil.marshallSize(out, numberOfArgs); for (int i = 0; i < numberOfArgs; i++) out.writeObject(object.getCapturedArg(i)); } public static Object read(ObjectInput in, ClassLoader classLoader) throws ClassNotFoundException, IOException { SerializedLambda sl = createSerializedLambda(in, classLoader); try { Class clazz = Class.forName(sl.getCapturingClass().replace("/", "."), true, classLoader); Method method = SecurityActions.getMethodAndSetAccessible(clazz, "$deserializeLambda$", SerializedLambda.class); return method.invoke(null, sl); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new MarshallingException(e); } } private static SerializedLambda createSerializedLambda(ObjectInput in, ClassLoader classLoader) throws ClassNotFoundException, IOException { String clazz = in.readUTF().replace("/", "."); Class<?> capturingClass = Class.forName(clazz, true, classLoader); String functionalInterfaceClass = in.readUTF(); String functionalInterfaceMethodName = in.readUTF(); String functionalInterfaceMethodSignature = in.readUTF(); int implMethodKind = in.readInt(); String implClass = in.readUTF(); String implMethodName = in.readUTF(); String implMethodSignature = in.readUTF(); String instantiatedMethodType = in.readUTF(); int numberOfArgs = MarshallUtil.unmarshallSize(in); Object[] args = new Object[numberOfArgs]; for (int i = 0; i < numberOfArgs; i++) args[i] = in.readObject(); return new SerializedLambda(capturingClass, functionalInterfaceClass, functionalInterfaceMethodName, functionalInterfaceMethodSignature, implMethodKind, implClass, implMethodName, implMethodSignature, instantiatedMethodType, args); } }
3,427
43.519481
143
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/ClassIdentifiers.java
package org.infinispan.marshall.core; import java.io.IOException; import java.util.List; import java.util.Map; import org.infinispan.commons.util.HopscotchHashMap; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.container.entries.InternalCacheValue; class ClassIdentifiers implements ClassIds { // the hashmap is not changed after static ctor, therefore concurrent access is safe private final Map<Class<?>, Integer> classToId = new HopscotchHashMap<>(MAX_ID); private final Class<?>[] internalIdToClass; // for external ids we'll probably use Map<Integer, Class<?>> instead of array public static ClassIdentifiers load(GlobalConfiguration globalConfiguration) { return new ClassIdentifiers(); } private ClassIdentifiers() { add(Object.class, OBJECT); add(String.class, STRING); add(List.class, LIST); add(Map.Entry.class, MAP_ENTRY); add(InternalCacheValue.class, INTERNAL_CACHE_VALUE); internalIdToClass = new Class[MAX_ID]; classToId.entrySet().stream().forEach(e -> internalIdToClass[e.getValue().intValue()] = e.getKey()); } private void add(Class<?> clazz, int id) { Integer prev = classToId.put(clazz, id); assert prev == null; } /** * This method throws IOException because it is assumed that we got the id from network. * @param id * @return * @throws IOException */ public Class<?> getClass(int id) throws IOException { if (id < 0 || id > internalIdToClass.length) { throw new IOException("Unknown class id " + id); } Class<?> clazz = internalIdToClass[id]; if (clazz == null) { throw new IOException("Unknown class id " + id); } return clazz; } /** * @param clazz * @return -1 if the id for given class is not found */ public int getId(Class<?> clazz) { Integer id = classToId.get(clazz); if (id == null) { return -1; } else { return id.intValue(); } } }
2,050
29.161765
106
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/WrappedByteArraySizeCalculator.java
package org.infinispan.marshall.core; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.commons.util.AbstractEntrySizeCalculatorHelper; import org.infinispan.commons.util.EntrySizeCalculator; /** * Size calculator that supports a {@link WrappedByteArray} by adding its size and the underlying byte[]. * @author wburns * @since 9.0 */ public class WrappedByteArraySizeCalculator<K, V> extends AbstractEntrySizeCalculatorHelper<K, V> { private final EntrySizeCalculator chained; public WrappedByteArraySizeCalculator(EntrySizeCalculator<?, ?> chained) { this.chained = chained; } @Override public long calculateSize(K key, V value) { long size = 0; Object keyToUse; Object valueToUse; if (key instanceof WrappedByteArray) { keyToUse = ((WrappedByteArray) key).getBytes(); // WBA object, the class pointer and the pointer to the byte[] size += roundUpToNearest8(OBJECT_SIZE + POINTER_SIZE * 2); } else { keyToUse = key; } if (value instanceof WrappedBytes) { valueToUse = ((WrappedBytes) value).getBytes(); // WBA object, the class pointer and the pointer to the byte[] size += roundUpToNearest8(OBJECT_SIZE + POINTER_SIZE * 2); } else { valueToUse = value; } return size + chained.calculateSize(keyToUse, valueToUse); } }
1,466
33.928571
105
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/EncoderRegistryImpl.java
package org.infinispan.marshall.core; import static org.infinispan.util.logging.Log.CONTAINER; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.commons.dataconversion.Encoder; import org.infinispan.commons.dataconversion.EncoderIds; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.Transcoder; import org.infinispan.commons.dataconversion.Wrapper; import org.infinispan.commons.dataconversion.WrapperIds; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * @see EncoderRegistry * @since 9.1 */ @Scope(Scopes.GLOBAL) public class EncoderRegistryImpl implements EncoderRegistry { private final Map<Short, Encoder> encoderMap = new ConcurrentHashMap<>(); private final Map<Byte, Wrapper> wrapperMap = new ConcurrentHashMap<>(); private final List<Transcoder> transcoders = Collections.synchronizedList(new ArrayList<>()); private final Map<MediaType, Map<MediaType, Transcoder>> transcoderCache = new ConcurrentHashMap<>(); @Override public void registerEncoder(Encoder encoder) { if (encoder == null) { throw new NullPointerException("Encoder cannot be null"); } short id = encoder.id(); if (encoderMap.containsKey(id)) { throw CONTAINER.duplicateIdEncoder(id); } encoderMap.put(id, encoder); } @Override public void registerWrapper(Wrapper wrapper) { if (wrapper == null) { throw new NullPointerException("Wrapper cannot be null"); } byte id = wrapper.id(); if (wrapperMap.containsKey(id)) { throw CONTAINER.duplicateIdWrapper(id); } wrapperMap.put(id, wrapper); } @Override public void registerTranscoder(Transcoder transcoder) { transcoders.add(transcoder); } @Override public Transcoder getTranscoder(MediaType mediaType, MediaType another) { Transcoder transcoder = getTranscoderOrNull(mediaType, another); if (transcoder == null) { throw CONTAINER.cannotFindTranscoder(mediaType, another); } return transcoder; } private Transcoder getTranscoderOrNull(MediaType mediaType, MediaType another) { return transcoderCache.computeIfAbsent(mediaType, mt -> new ConcurrentHashMap<>(4)) .computeIfAbsent(another, mt -> { return transcoders.stream() .filter(t -> t.supportsConversion(mediaType, another)) .findFirst() .orElse(null); }); } @Override public <T extends Transcoder> T getTranscoder(Class<T> clazz) { Transcoder transcoder = transcoders.stream() .filter(p -> p.getClass().equals(clazz)) .findAny() .orElse(null); return clazz.cast(transcoder); } @Override public boolean isConversionSupported(MediaType from, MediaType to) { if (from == null || to == null) { throw new NullPointerException("MediaType must not be null!"); } return from.match(to) || getTranscoderOrNull(from, to) != null; } @Override public Encoder getEncoder(Class<? extends Encoder> clazz, short encoderId) { if (clazz == null && encoderId == EncoderIds.NO_ENCODER) { throw new NullPointerException("Encoder class or identifier must be provided!"); } if (encoderId != EncoderIds.NO_ENCODER) { Encoder encoder = encoderMap.get(encoderId); if (encoder == null) { throw CONTAINER.encoderIdNotFound(encoderId); } return encoder; } else { for (Encoder e : encoderMap.values()) { if (e.getClass().equals(clazz)) { return e; } } throw CONTAINER.encoderClassNotFound(clazz); } } @Override public boolean isRegistered(Class<? extends Encoder> encoderClass) { return encoderMap.values().stream().anyMatch(e -> e.getClass().equals(encoderClass)); } @Override public Wrapper getWrapper(Class<? extends Wrapper> clazz, byte wrapperId) { if (clazz == null && wrapperId == WrapperIds.NO_WRAPPER) { return null; } Wrapper wrapper; if (wrapperId != WrapperIds.NO_WRAPPER) { wrapper = wrapperMap.get(wrapperId); if (wrapper == null) { throw CONTAINER.wrapperIdNotFound(wrapperId); } } else { wrapper = wrapperMap.values().stream() .filter(e -> e.getClass().equals(clazz)) .findAny() .orElse(null); if (wrapper == null) { throw CONTAINER.wrapperClassNotFound(clazz); } } return wrapper; } @Override public Object convert(Object o, MediaType from, MediaType to) { if (o == null) return null; Transcoder transcoder = getTranscoder(from, to); return transcoder.transcode(o, from, to); } }
5,333
33.636364
104
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/AbstractBytesObjectInput.java
package org.infinispan.marshall.core; import java.io.EOFException; import java.io.ObjectInput; /** * Array backed {@link ObjectInput} implementation. * * {@link #skip(long)} and {@link #skipBytes(int)} have been enhanced so that * if a negative number is passed in, they skip backwards effectively * providing rewind capabilities. * * This should be removed when the {@link GlobalMarshaller} is no longer based on {@link org.infinispan.commons.marshall.StreamingMarshaller}. */ abstract public class AbstractBytesObjectInput implements ObjectInput { final byte bytes[]; int pos; int offset; // needed for external JBoss Marshalling, to be able to rewind correctly when the bytes are prepended :( protected AbstractBytesObjectInput(byte[] bytes, int offset) { this.bytes = bytes; this.pos = offset; this.offset = offset; } @Override public int read() { if (pos >= bytes.length) { return -1; } return bytes[pos++] & 0xff; } @Override public int read(byte[] b) { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) { if (pos >= bytes.length) { return -1; } if (pos + len >= bytes.length) { len = bytes.length - pos; } System.arraycopy(bytes, pos, b, off, len); pos += len; return len; } @Override public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; if (skip > n) skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; // Calculate max to avoid skipping before offset pos = (int) Math.max(skip, offset); return skip; } } @Override public int available() { return bytes.length - pos; } @Override public void close() { // No-op } @Override public void readFully(byte[] b) throws EOFException { readFully(b, 0, b.length); } @Override public void readFully(byte[] b, int off, int len) throws EOFException { if (off + len >= bytes.length) throw new EOFException(); System.arraycopy(bytes, pos, b, off, len); pos += len; } @Override public int skipBytes(int n) throws EOFException { checkPosLength(n); return (int) skip(n); } @Override public boolean readBoolean() throws EOFException { return readByte() != 0; } @Override public byte readByte() throws EOFException { checkPosLength(1); return bytes[pos++]; } @Override public int readUnsignedByte() throws EOFException { return readByte() & 0xff; } @Override public short readShort() throws EOFException { checkPosLength(2); short v = (short) (bytes[pos] << 8 | (bytes[pos + 1] & 0xff)); pos += 2; return v; } @Override public int readUnsignedShort() throws EOFException { checkPosLength(2); int v = (bytes[pos] & 0xff) << 8 | (bytes[pos + 1] & 0xff); pos += 2; return v; } @Override public char readChar() throws EOFException { checkPosLength(2); char v = (char) (bytes[pos] << 8 | (bytes[pos + 1] & 0xff)); pos += 2; return v; } @Override public int readInt() throws EOFException { checkPosLength(4); int v = bytes[pos] << 24 | (bytes[pos + 1] & 0xff) << 16 | (bytes[pos + 2] & 0xff) << 8 | (bytes[pos + 3] & 0xff); pos = pos + 4; return v; } @Override public long readLong() throws EOFException { return (long) readInt() << 32L | (long) readInt() & 0xffffffffL; } @Override public float readFloat() throws EOFException { return Float.intBitsToFloat(readInt()); } @Override public double readDouble() throws EOFException { return Double.longBitsToDouble(readLong()); } @Override public String readLine() { return null; } @Override public String readUTF() throws EOFException { int utflen = readInt(); checkPosLength(utflen); byte[] bytearr = bytes; char[] chararr = new char[utflen]; utflen = pos + utflen; int c, char2, char3; int count = pos; int chararr_count=0; while (count < utflen) { c = (int) bytearr[count] & 0xff; if (c > 127) break; count++; chararr[chararr_count++]=(char)c; } while (count < utflen) { c = (int) bytearr[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: /* 0xxxxxxx*/ count++; chararr[chararr_count++]=(char)c; break; case 12: case 13: /* 110x xxxx 10xx xxxx*/ count += 2; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-1]; if ((char2 & 0xC0) != 0x80) throw new RuntimeException( "malformed input around byte " + count); chararr[chararr_count++]=(char)(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: /* 1110 xxxx 10xx xxxx 10xx xxxx */ count += 3; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-2]; char3 = (int) bytearr[count-1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) throw new RuntimeException( "malformed input around byte " + (count-1)); chararr[chararr_count++]=(char)(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | (char3 & 0x3F)); break; default: /* 10xx xxxx, 1111 xxxx */ throw new RuntimeException( "malformed input around byte " + count); } } pos = count; return new String(chararr, 0, chararr_count); } public String readString() throws EOFException { int mark = readByte(); switch(mark) { case 0: return ""; // empty string case 1: // small ascii int size = readByte(); String str = new String(bytes, 0, pos, size); pos += size; return str; case 2: // large string return readUTF(); default: throw new RuntimeException("Unknown marker(String). mark=" + mark); } } private void checkPosLength(int len) throws EOFException { if (len > 0 && pos + len > bytes.length) { throw new EOFException(); } } }
7,079
25.716981
142
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/BytesObjectInput.java
package org.infinispan.marshall.core; import java.io.IOException; import java.io.ObjectInput; /** * Array backed {@link ObjectInput} implementation. * * {@link #skip(long)} and {@link #skipBytes(int)} have been enhanced so that * if a negative number is passed in, they skip backwards effectively * providing rewind capabilities. */ final class BytesObjectInput extends AbstractBytesObjectInput { final GlobalMarshaller marshaller; private BytesObjectInput(byte[] bytes, int offset, GlobalMarshaller marshaller) { super(bytes, offset); this.marshaller = marshaller; } static BytesObjectInput from(byte[] bytes, GlobalMarshaller marshaller) { return from(bytes, 0, marshaller); } static BytesObjectInput from(byte[] bytes, int offset, GlobalMarshaller marshaller) { return new BytesObjectInput(bytes, offset, marshaller); } @Override public Object readObject() throws ClassNotFoundException, IOException { return marshaller.readNullableObject(this); } }
1,026
28.342857
88
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/MarshallableFunctions.java
package org.infinispan.marshall.core; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.UnaryOperator; import org.infinispan.commons.util.InjectiveFunction; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.functional.EntryView.ReadEntryView; import org.infinispan.functional.EntryView.ReadWriteEntryView; import org.infinispan.functional.EntryView.WriteEntryView; import org.infinispan.functional.MetaParam; public final class MarshallableFunctions { public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> setValueReturnPrevOrNull() { return SetValueReturnPrevOrNull.getInstance(); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> setValueMetasReturnPrevOrNull(MetaParam.Writable... metas) { return new SetValueMetasReturnPrevOrNull<>(metas); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, ReadWriteEntryView<K, V>> setValueReturnView() { return SetValueReturnView.getInstance(); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, ReadWriteEntryView<K, V>> setValueMetasReturnView(MetaParam.Writable... metas) { return new SetValueMetasReturnView<>(metas); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> setValueIfAbsentReturnPrevOrNull() { return SetValueIfAbsentReturnPrevOrNull.getInstance(); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> setValueMetasIfAbsentReturnPrevOrNull(MetaParam.Writable... metas) { return new SetValueMetasIfAbsentReturnPrevOrNull<>(metas); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> setValueIfAbsentReturnBoolean() { return SetValueIfAbsentReturnBoolean.getInstance(); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> setValueMetasIfAbsentReturnBoolean(MetaParam.Writable... metas) { return new SetValueMetasIfAbsentReturnBoolean<>(metas); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> setValueIfPresentReturnPrevOrNull() { return SetValueIfPresentReturnPrevOrNull.getInstance(); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> setValueMetasIfPresentReturnPrevOrNull(MetaParam.Writable... metas) { return new SetValueMetasIfPresentReturnPrevOrNull<>(metas); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> setValueIfPresentReturnBoolean() { return SetValueIfPresentReturnBoolean.getInstance(); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> setValueMetasIfPresentReturnBoolean(MetaParam.Writable... metas) { return new SetValueMetasIfPresentReturnBoolean<>(metas); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> setValueIfEqualsReturnBoolean(V oldValue, MetaParam.Writable... metas) { return new SetValueIfEqualsReturnBoolean<>(oldValue, metas); } public static <K, V> Function<ReadWriteEntryView<K, V>, V> removeReturnPrevOrNull() { return RemoveReturnPrevOrNull.getInstance(); } public static <K, V> Function<ReadWriteEntryView<K, V>, Boolean> removeReturnBoolean() { return RemoveReturnBoolean.getInstance(); } public static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> removeIfValueEqualsReturnBoolean() { return RemoveIfValueEqualsReturnBoolean.getInstance(); } public static <K, V> BiConsumer<V, WriteEntryView<K, V>> setValueConsumer() { return SetValue.getInstance(); } public static <K, V> BiConsumer<V, WriteEntryView<K, V>> setValueMetasConsumer(MetaParam.Writable... metas) { return new SetValueMetas<>(metas); } public static <K, V> BiConsumer<V, WriteEntryView<K, V>> setInternalCacheValueConsumer() { return SetInternalCacheValue.getInstance(); } public static <K, V> Consumer<WriteEntryView<K, V>> removeConsumer() { return Remove.getInstance(); } public static <K, V> Function<ReadWriteEntryView<K, V>, Optional<V>> returnReadWriteFind() { return ReturnReadWriteFind.getInstance(); } public static <K, V> Function<ReadWriteEntryView<K, V>, V> returnReadWriteGet() { return ReturnReadWriteGet.getInstance(); } public static <K, V> Function<ReadWriteEntryView<K, V>, ReadWriteEntryView<K, V>> returnReadWriteView() { return ReturnReadWriteView.getInstance(); } public static <K, V> Function<ReadEntryView<K, V>, V> returnReadOnlyFindOrNull() { return ReturnReadOnlyFindOrNull.getInstance(); } public static <K, V> Function<ReadEntryView<K, V>, Boolean> returnReadOnlyFindIsPresent() { return ReturnReadOnlyFindIsPresent.getInstance(); } public static <T> Function<T, T> identity() { return Identity.getInstance(); } private static abstract class AbstractSetValueReturnPrevOrNull<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, V> { final MetaParam.Writable[] metas; protected AbstractSetValueReturnPrevOrNull(MetaParam.Writable[] metas) { this.metas = metas; } @Override public V apply(V v, ReadWriteEntryView<K, V> rw) { V prev = rw.find().orElse(null); rw.set(v, metas); return prev; } } private static final class SetValueReturnPrevOrNull<K, V> extends AbstractSetValueReturnPrevOrNull<K, V> { protected SetValueReturnPrevOrNull(MetaParam.Writable[] metas) { super(metas); } private static final SetValueReturnPrevOrNull INSTANCE = new SetValueReturnPrevOrNull<>(new MetaParam.Writable[0]); @SuppressWarnings("unchecked") private static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> getInstance() { return SetValueReturnPrevOrNull.INSTANCE; } } interface LambdaWithMetas { MetaParam.Writable[] metas(); } static final class SetValueMetasReturnPrevOrNull<K, V> extends AbstractSetValueReturnPrevOrNull<K, V> implements LambdaWithMetas { SetValueMetasReturnPrevOrNull(MetaParam.Writable[] metas) { super(metas); } @Override public MetaParam.Writable[] metas() { return metas; } } private static abstract class AbstractSetValueReturnView<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, ReadWriteEntryView<K, V>> { final MetaParam.Writable[] metas; protected AbstractSetValueReturnView(MetaParam.Writable[] metas) { this.metas = metas; } @Override public ReadWriteEntryView<K, V> apply(V v, ReadWriteEntryView<K, V> rw) { rw.set(v); return rw; } } private static final class SetValueReturnView<K, V> extends AbstractSetValueReturnView<K, V> { protected SetValueReturnView(MetaParam.Writable[] metas) { super(metas); } private static final SetValueReturnView INSTANCE = new SetValueReturnView<>(new MetaParam.Writable[]{}); @SuppressWarnings("unchecked") private static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, ReadWriteEntryView<K, V>> getInstance() { return SetValueReturnView.INSTANCE; } } static final class SetValueMetasReturnView<K, V> extends AbstractSetValueReturnView<K, V> implements LambdaWithMetas { protected SetValueMetasReturnView(MetaParam.Writable[] metas) { super(metas); } @Override public MetaParam.Writable[] metas() { return metas; } } private static abstract class AbstractSetValueIfAbsentReturnPrevOrNull<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, V> { final MetaParam.Writable[] metas; protected AbstractSetValueIfAbsentReturnPrevOrNull(MetaParam.Writable[] metas) { this.metas = metas; } @Override public V apply(V v, ReadWriteEntryView<K, V> rw) { Optional<V> opt = rw.find(); V prev = opt.orElse(null); if (!opt.isPresent()) rw.set(v, metas); return prev; } } private static final class SetValueIfAbsentReturnPrevOrNull<K, V> extends AbstractSetValueIfAbsentReturnPrevOrNull<K, V> { protected SetValueIfAbsentReturnPrevOrNull(MetaParam.Writable[] metas) { super(metas); } private static final SetValueIfAbsentReturnPrevOrNull INSTANCE = new SetValueIfAbsentReturnPrevOrNull<>(new MetaParam.Writable[]{}); @SuppressWarnings("unchecked") private static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> getInstance() { return SetValueIfAbsentReturnPrevOrNull.INSTANCE; } } static final class SetValueMetasIfAbsentReturnPrevOrNull<K, V> extends AbstractSetValueIfAbsentReturnPrevOrNull<K, V> implements LambdaWithMetas { protected SetValueMetasIfAbsentReturnPrevOrNull(MetaParam.Writable[] metas) { super(metas); } @Override public MetaParam.Writable[] metas() { return metas; } } private static abstract class AbstractSetValueIfAbsentReturnBoolean<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, Boolean> { final MetaParam.Writable[] metas; private AbstractSetValueIfAbsentReturnBoolean(MetaParam.Writable[] metas) { this.metas = metas; } @Override public Boolean apply(V v, ReadWriteEntryView<K, V> rw) { Optional<V> opt = rw.find(); boolean success = !opt.isPresent(); if (success) rw.set(v, metas); return success; } } private static final class SetValueIfAbsentReturnBoolean<K, V> extends AbstractSetValueIfAbsentReturnBoolean<K, V> { private SetValueIfAbsentReturnBoolean(MetaParam.Writable[] metas) { super(metas); } private static final SetValueIfAbsentReturnBoolean INSTANCE = new SetValueIfAbsentReturnBoolean<>(new MetaParam.Writable[]{}); @SuppressWarnings("unchecked") private static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> getInstance() { return SetValueIfAbsentReturnBoolean.INSTANCE; } } static final class SetValueMetasIfAbsentReturnBoolean<K, V> extends AbstractSetValueIfAbsentReturnBoolean<K, V> implements LambdaWithMetas { SetValueMetasIfAbsentReturnBoolean(MetaParam.Writable[] metas) { super(metas); } @Override public MetaParam.Writable[] metas() { return metas; } } private static abstract class AbstractSetValueIfPresentReturnPrevOrNull<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, V> { final MetaParam.Writable[] metas; protected AbstractSetValueIfPresentReturnPrevOrNull(MetaParam.Writable[] metas) { this.metas = metas; } @Override public V apply(V v, ReadWriteEntryView<K, V> rw) { return rw.find().map(prev -> { rw.set(v, metas); return prev; }).orElse(null); } } private static final class SetValueIfPresentReturnPrevOrNull<K, V> extends AbstractSetValueIfPresentReturnPrevOrNull<K, V> { protected SetValueIfPresentReturnPrevOrNull(MetaParam.Writable[] metas) { super(metas); } private static final SetValueIfPresentReturnPrevOrNull INSTANCE = new SetValueIfPresentReturnPrevOrNull<>(new MetaParam.Writable[]{}); @SuppressWarnings("unchecked") private static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, V> getInstance() { return SetValueIfPresentReturnPrevOrNull.INSTANCE; } } static final class SetValueMetasIfPresentReturnPrevOrNull<K, V> extends AbstractSetValueIfPresentReturnPrevOrNull<K, V> implements LambdaWithMetas { protected SetValueMetasIfPresentReturnPrevOrNull(MetaParam.Writable[] metas) { super(metas); } @Override public MetaParam.Writable[] metas() { return metas; } } private static abstract class AbstractSetValueIfPresentReturnBoolean<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, Boolean> { final MetaParam.Writable[] metas; private AbstractSetValueIfPresentReturnBoolean(MetaParam.Writable[] metas) { this.metas = metas; } @Override public Boolean apply(V v, ReadWriteEntryView<K, V> rw) { return rw.find().map(prev -> { rw.set(v, metas); return true; }).orElse(false); } } private static final class SetValueIfPresentReturnBoolean<K, V> extends AbstractSetValueIfPresentReturnBoolean<K, V> { private SetValueIfPresentReturnBoolean(MetaParam.Writable[] metas) { super(metas); } private static final SetValueIfPresentReturnBoolean INSTANCE = new SetValueIfPresentReturnBoolean<>(new MetaParam.Writable[]{}); @SuppressWarnings("unchecked") private static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> getInstance() { return SetValueIfPresentReturnBoolean.INSTANCE; } } static final class SetValueMetasIfPresentReturnBoolean<K, V> extends AbstractSetValueIfPresentReturnBoolean<K, V> implements LambdaWithMetas { SetValueMetasIfPresentReturnBoolean(MetaParam.Writable[] metas) { super(metas); } @Override public MetaParam.Writable[] metas() { return metas; } } static final class SetValueIfEqualsReturnBoolean<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, Boolean>, LambdaWithMetas { final V oldValue; final MetaParam.Writable[] metas; public SetValueIfEqualsReturnBoolean(V oldValue, MetaParam.Writable[] metas) { this.oldValue = oldValue; this.metas = metas; } @Override public Boolean apply(V v, ReadWriteEntryView<K, V> rw) { return rw.find().map(prev -> { if (prev.equals(oldValue)) { rw.set(v, metas); return true; } return false; }).orElse(false); } @Override public MetaParam.Writable[] metas() { return metas; } } private static final class RemoveReturnPrevOrNull<K, V> implements Function<ReadWriteEntryView<K, V>, V> { @Override public V apply(ReadWriteEntryView<K, V> rw) { V prev = rw.find().orElse(null); rw.remove(); return prev; } private static final RemoveReturnPrevOrNull INSTANCE = new RemoveReturnPrevOrNull<>(); @SuppressWarnings("unchecked") private static <K, V> Function<ReadWriteEntryView<K, V>, V> getInstance() { return RemoveReturnPrevOrNull.INSTANCE; } } private static final class RemoveReturnBoolean<K, V> implements Function<ReadWriteEntryView<K, V>, Boolean> { @Override public Boolean apply(ReadWriteEntryView<K, V> rw) { boolean success = rw.find().isPresent(); rw.remove(); return success; } private static final RemoveReturnBoolean INSTANCE = new RemoveReturnBoolean<>(); @SuppressWarnings("unchecked") private static <K, V> Function<ReadWriteEntryView<K, V>, Boolean> getInstance() { return RemoveReturnBoolean.INSTANCE; } } private static final class RemoveIfValueEqualsReturnBoolean<K, V> implements BiFunction<V, ReadWriteEntryView<K, V>, Boolean> { @Override public Boolean apply(V v, ReadWriteEntryView<K, V> rw) { return rw.find().map(prev -> { if (prev.equals(v)) { rw.remove(); return true; } return false; }).orElse(false); } private static final RemoveIfValueEqualsReturnBoolean INSTANCE = new RemoveIfValueEqualsReturnBoolean<>(); @SuppressWarnings("unchecked") private static <K, V> BiFunction<V, ReadWriteEntryView<K, V>, Boolean> getInstance() { return RemoveIfValueEqualsReturnBoolean.INSTANCE; } } private static abstract class AbstractSetValue<K, V> implements BiConsumer<V, WriteEntryView<K, V>> { final MetaParam.Writable[] metas; protected AbstractSetValue(MetaParam.Writable[] metas) { this.metas = metas; } @Override public void accept(V v, WriteEntryView<K, V> wo) { wo.set(v, metas); } } private static final class SetValue<K, V> extends AbstractSetValue<K, V> { protected SetValue(MetaParam.Writable[] metas) { super(metas); } private static final SetValue INSTANCE = new SetValue<>(new MetaParam.Writable[0]); @SuppressWarnings("unchecked") private static <K, V> BiConsumer<V, WriteEntryView<K, V>> getInstance() { return SetValue.INSTANCE; } } static final class SetValueMetas<K, V> extends AbstractSetValue<K, V> implements LambdaWithMetas { SetValueMetas(MetaParam.Writable[] metas) { super(metas); } @Override public MetaParam.Writable[] metas() { return metas; } } private static final class SetInternalCacheValue<V> implements BiConsumer<InternalCacheValue<V>, WriteEntryView<?, V>> { private static final SetInternalCacheValue INSTANCE = new SetInternalCacheValue<>(); @SuppressWarnings("unchecked") private static <K, V> BiConsumer<V, WriteEntryView<K, V>> getInstance() { return SetInternalCacheValue.INSTANCE; } @Override public void accept(InternalCacheValue<V> icv, WriteEntryView<?, V> view) { view.set(icv.getValue(), icv.getMetadata()); } } private static final class Remove<V> implements Consumer<WriteEntryView<?, V>> { @Override public void accept(WriteEntryView<?, V> wo) { wo.remove(); } private static final Remove INSTANCE = new Remove<>(); @SuppressWarnings("unchecked") private static <K, V> Consumer<WriteEntryView<K, V>> getInstance() { return Remove.INSTANCE; } } private static final class ReturnReadWriteFind<K, V> implements Function<ReadWriteEntryView<K, V>, Optional<V>> { @Override public Optional<V> apply(ReadWriteEntryView<K, V> rw) { return rw.find(); } private static final ReturnReadWriteFind INSTANCE = new ReturnReadWriteFind<>(); @SuppressWarnings("unchecked") private static <K, V> Function<ReadWriteEntryView<K, V>, Optional<V>> getInstance() { return ReturnReadWriteFind.INSTANCE; } } private static final class ReturnReadWriteGet<K, V> implements Function<ReadWriteEntryView<K, V>, V> { @Override public V apply(ReadWriteEntryView<K, V> rw) { return rw.get(); } private static final ReturnReadWriteGet INSTANCE = new ReturnReadWriteGet<>(); @SuppressWarnings("unchecked") private static <K, V> Function<ReadWriteEntryView<K, V>, V> getInstance() { return ReturnReadWriteGet.INSTANCE; } } private static final class ReturnReadWriteView<K, V> implements Function<ReadWriteEntryView<K, V>, ReadWriteEntryView<K, V>> { @Override public ReadWriteEntryView<K, V> apply(ReadWriteEntryView<K, V> rw) { return rw; } private static final ReturnReadWriteView INSTANCE = new ReturnReadWriteView<>(); @SuppressWarnings("unchecked") private static <K, V> Function<ReadWriteEntryView<K, V>, ReadWriteEntryView<K, V>> getInstance() { return ReturnReadWriteView.INSTANCE; } } private static final class ReturnReadOnlyFindOrNull<K, V> implements Function<ReadEntryView<K, V>, V> { @Override public V apply(ReadEntryView<K, V> ro) { return ro.find().orElse(null); } private static final ReturnReadOnlyFindOrNull INSTANCE = new ReturnReadOnlyFindOrNull<>(); private static <K, V> Function<ReadEntryView<K, V>, V> getInstance() { return INSTANCE; } } private static final class ReturnReadOnlyFindIsPresent<K, V> implements Function<ReadEntryView<K, V>, Boolean> { @Override public Boolean apply(ReadEntryView<K, V> ro) { return ro.find().isPresent(); } private static final ReturnReadOnlyFindIsPresent INSTANCE = new ReturnReadOnlyFindIsPresent<>(); private static <K, V> Function<ReadEntryView<K, V>, Boolean> getInstance() { return INSTANCE; } } private static final class Identity<T> implements InjectiveFunction<T, T>, UnaryOperator<T> { @Override public T apply(T o) { return o; } private static final Identity INSTANCE = new Identity<>(); private static <T> Function<T, T> getInstance() { return INSTANCE; } } private MarshallableFunctions() { // No-op, holds static variables } }
21,134
33.590835
145
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/StreamBytesObjectOutput.java
package org.infinispan.marshall.core; import java.io.IOException; import java.io.ObjectOutput; import java.io.OutputStream; final class StreamBytesObjectOutput implements ObjectOutput { final OutputStream stream; final BytesObjectOutput out; StreamBytesObjectOutput(OutputStream stream, BytesObjectOutput out) { this.stream = stream; this.out = out; } @Override public void writeObject(Object obj) throws IOException { out.writeObject(obj); } @Override public void write(int b) throws IOException { out.write(b); } @Override public void write(byte[] b) throws IOException { out.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); } @Override public void writeBoolean(boolean v) throws IOException { out.writeBoolean(v); } @Override public void writeByte(int v) throws IOException { out.writeByte(v); } @Override public void writeShort(int v) throws IOException { out.writeShort(v); } @Override public void writeChar(int v) throws IOException { out.writeChar(v); } @Override public void writeInt(int v) throws IOException { out.writeInt(v); } @Override public void writeLong(long v) throws IOException { out.writeLong(v); } @Override public void writeFloat(float v) throws IOException { out.writeFloat(v); } @Override public void writeDouble(double v) throws IOException { out.writeDouble(v); } @Override public void writeBytes(String s) throws IOException { out.writeBytes(s); } @Override public void writeChars(String s) throws IOException { out.writeChars(s); } @Override public void writeUTF(String s) throws IOException { out.writeUTF(s); } @Override public void flush() throws IOException { stream.write(out.bytes); stream.flush(); } @Override public void close() throws IOException { stream.close(); } }
2,078
18.990385
72
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/Primitives.java
package org.infinispan.marshall.core; import java.io.EOFException; import java.io.IOException; import java.util.Map; import org.infinispan.commons.util.HopscotchHashMap; final class Primitives { // 0x03-0x0F reserved static final int ID_BYTE_ARRAY = 0x01; // byte[].class static final int ID_STRING = 0x02; // String.class static final int ID_BOOLEAN_OBJ = 0x10; // Boolean.class static final int ID_BYTE_OBJ = 0x11; // ..etc.. static final int ID_CHAR_OBJ = 0x12; static final int ID_DOUBLE_OBJ = 0x13; static final int ID_FLOAT_OBJ = 0x14; static final int ID_INT_OBJ = 0x15; static final int ID_LONG_OBJ = 0x16; static final int ID_SHORT_OBJ = 0x17; static final int ID_BOOLEAN_ARRAY = 0x18; // boolean[].class static final int ID_CHAR_ARRAY = 0x19; // ..etc.. static final int ID_DOUBLE_ARRAY = 0x1A; static final int ID_FLOAT_ARRAY = 0x1B; static final int ID_INT_ARRAY = 0x1C; static final int ID_LONG_ARRAY = 0x1D; static final int ID_SHORT_ARRAY = 0x1E; // 0x1F-0x27 unused static final int ID_ARRAY_EMPTY = 0x28; // zero elements static final int ID_ARRAY_SMALL = 0x29; // <=0x100 elements static final int ID_ARRAY_MEDIUM = 0x2A; // <=0x10000 elements static final int ID_ARRAY_LARGE = 0x2B; // <0x80000000 elements static final int SMALL_ARRAY_MIN = 0x1; static final int SMALL_ARRAY_MAX = 0x100; static final int MEDIUM_ARRAY_MIN = 0x101; static final int MEDIUM_ARRAY_MAX = 0x10100; static final Map<Class<?>, Integer> PRIMITIVES = new HopscotchHashMap<>(18); static { PRIMITIVES.put(String.class, ID_STRING); PRIMITIVES.put(byte[].class, ID_BYTE_ARRAY); PRIMITIVES.put(Boolean.class, ID_BOOLEAN_OBJ); PRIMITIVES.put(Byte.class, ID_BYTE_OBJ); PRIMITIVES.put(Character.class, ID_CHAR_OBJ); PRIMITIVES.put(Double.class, ID_DOUBLE_OBJ); PRIMITIVES.put(Float.class, ID_FLOAT_OBJ); PRIMITIVES.put(Integer.class, ID_INT_OBJ); PRIMITIVES.put(Long.class, ID_LONG_OBJ); PRIMITIVES.put(Short.class, ID_SHORT_OBJ); PRIMITIVES.put(boolean[].class, ID_BOOLEAN_ARRAY); PRIMITIVES.put(char[].class, ID_CHAR_ARRAY); PRIMITIVES.put(double[].class, ID_DOUBLE_ARRAY); PRIMITIVES.put(float[].class, ID_FLOAT_ARRAY); PRIMITIVES.put(int[].class, ID_INT_ARRAY); PRIMITIVES.put(long[].class, ID_LONG_ARRAY); PRIMITIVES.put(short[].class, ID_SHORT_ARRAY); } private Primitives() { } static void writePrimitive(Object obj, BytesObjectOutput out, int id) throws IOException { out.writeByte(id); writeRawPrimitive(obj, out, id); } static void writeRawPrimitive(Object obj, BytesObjectOutput out, int id) throws IOException { switch (id) { case ID_BYTE_ARRAY: Primitives.writeByteArray((byte[]) obj, out); break; case ID_STRING: out.writeString((String) obj); break; case ID_BOOLEAN_OBJ: out.writeBoolean((boolean) obj); break; case ID_BYTE_OBJ: out.writeByte((byte) obj); break; case ID_CHAR_OBJ: out.writeChar((char) obj); break; case ID_DOUBLE_OBJ: out.writeDouble((double) obj); break; case ID_FLOAT_OBJ: out.writeFloat((float) obj); break; case ID_INT_OBJ: out.writeInt((int) obj); break; case ID_LONG_OBJ: out.writeLong((long) obj); break; case ID_SHORT_OBJ: out.writeShort((short) obj); break; case ID_BOOLEAN_ARRAY: Primitives.writeBooleanArray((boolean[]) obj, out); break; case ID_CHAR_ARRAY: Primitives.writeCharArray((char[]) obj, out); break; case ID_DOUBLE_ARRAY: Primitives.writeDoubleArray((double[]) obj, out); break; case ID_FLOAT_ARRAY: Primitives.writeFloatArray((float[]) obj, out); break; case ID_INT_ARRAY: Primitives.writeIntArray((int[]) obj, out); break; case ID_LONG_ARRAY: Primitives.writeLongArray((long[]) obj, out); break; case ID_SHORT_ARRAY: Primitives.writeShortArray((short[]) obj, out); break; default: throw new IOException("Unknown primitive type: " + obj); } } static Object readPrimitive(BytesObjectInput in) throws IOException, ClassNotFoundException { int subId = in.readUnsignedByte(); return readRawPrimitive(in, subId); } static Object readRawPrimitive(BytesObjectInput in, int subId) throws IOException { switch (subId) { case ID_BYTE_ARRAY: return readByteArray(in); case ID_STRING: return in.readString(); case ID_BOOLEAN_OBJ: return in.readBoolean(); case ID_BYTE_OBJ: return in.readByte(); case ID_CHAR_OBJ: return in.readChar(); case ID_DOUBLE_OBJ: return in.readDouble(); case ID_FLOAT_OBJ: return in.readFloat(); case ID_INT_OBJ: return in.readInt(); case ID_LONG_OBJ: return in.readLong(); case ID_SHORT_OBJ: return in.readShort(); case ID_BOOLEAN_ARRAY: return readBooleanArray(in); case ID_CHAR_ARRAY: return readCharArray(in); case ID_DOUBLE_ARRAY: return readDoubleArray(in); case ID_FLOAT_ARRAY: return readFloatArray(in); case ID_INT_ARRAY: return readIntArray(in); case ID_LONG_ARRAY: return readLongArray(in); case ID_SHORT_ARRAY: return readShortArray(in); default: throw new IOException("Unknown primitive sub id: " + Integer.toHexString(subId)); } } private static void writeByteArray(byte[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); out.write(obj, 0, len); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); out.write(obj, 0, len); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); out.write(obj, 0, len); } } private static void writeBooleanArray(boolean[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); writeBooleans(obj, out); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); writeBooleans(obj, out); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); writeBooleans(obj, out); } } private static void writeBooleans(boolean[] obj, BytesObjectOutput out) { final int len = obj.length; final int bc = len & ~7; for (int i = 0; i < bc;) { out.write( (obj[i++] ? 1 : 0) | (obj[i++] ? 2 : 0) | (obj[i++] ? 4 : 0) | (obj[i++] ? 8 : 0) | (obj[i++] ? 16 : 0) | (obj[i++] ? 32 : 0) | (obj[i++] ? 64 : 0) | (obj[i++] ? 128 : 0) ); } if (bc < len) { int o = 0; int bit = 1; for (int i = bc; i < len; i++) { if (obj[i]) o |= bit; bit <<= 1; } out.writeByte(o); } } private static void writeCharArray(char[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); for (char v : obj) out.writeChar(v); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); for (char v : obj) out.writeChar(v); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); for (char v : obj) out.writeChar(v); } } private static void writeDoubleArray(double[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); for (double v : obj) out.writeDouble(v); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); for (double v : obj) out.writeDouble(v); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); for (double v : obj) out.writeDouble(v); } } private static void writeFloatArray(float[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); for (float v : obj) out.writeFloat(v); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); for (float v : obj) out.writeFloat(v); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); for (float v : obj) out.writeFloat(v); } } private static void writeIntArray(int[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); for (int v : obj) out.writeInt(v); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); for (int v : obj) out.writeInt(v); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); for (int v : obj) out.writeInt(v); } } private static void writeLongArray(long[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); for (long v : obj) out.writeLong(v); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); for (long v : obj) out.writeLong(v); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); for (long v : obj) out.writeLong(v); } } private static void writeShortArray(short[] obj, BytesObjectOutput out) { final int len = obj.length; if (len == 0) { out.writeByte(ID_ARRAY_EMPTY); } else if (len <= SMALL_ARRAY_MAX) { out.writeByte(ID_ARRAY_SMALL); out.writeByte(len - SMALL_ARRAY_MIN); for (short v : obj) out.writeShort(v); } else if (len <= MEDIUM_ARRAY_MAX) { out.writeByte(ID_ARRAY_MEDIUM); out.writeShort(len - MEDIUM_ARRAY_MIN); for (short v : obj) out.writeShort(v); } else { out.writeByte(ID_ARRAY_LARGE); out.writeInt(len); for (short v : obj) out.writeShort(v); } } private static byte[] readByteArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new byte[]{}; case ID_ARRAY_SMALL: return readFully(mkByteArray(in.readUnsignedByte() + SMALL_ARRAY_MIN), in); case ID_ARRAY_MEDIUM: return readFully(mkByteArray(in.readUnsignedShort() + MEDIUM_ARRAY_MIN), in); case ID_ARRAY_LARGE: return readFully(new byte[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static byte[] mkByteArray(int len) { return new byte[len]; } private static byte[] readFully(byte[] arr, BytesObjectInput in) throws EOFException { in.readFully(arr); return arr; } private static boolean[] readBooleanArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new boolean[]{}; case ID_ARRAY_SMALL: return readBooleans(mkBooleanArray(in.readUnsignedByte() + SMALL_ARRAY_MIN), in); case ID_ARRAY_MEDIUM: return readBooleans(mkBooleanArray(in.readUnsignedShort() + MEDIUM_ARRAY_MIN), in); case ID_ARRAY_LARGE: return readBooleans(new boolean[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static boolean[] mkBooleanArray(int len) { return new boolean[len]; } private static boolean[] readBooleans(boolean[] arr, BytesObjectInput in) throws EOFException { final int len = arr.length; int v; int bc = len & ~7; for (int i = 0; i < bc; ) { v = in.readByte(); arr[i++] = (v & 1) != 0; arr[i++] = (v & 2) != 0; arr[i++] = (v & 4) != 0; arr[i++] = (v & 8) != 0; arr[i++] = (v & 16) != 0; arr[i++] = (v & 32) != 0; arr[i++] = (v & 64) != 0; arr[i++] = (v & 128) != 0; } if (bc < len) { v = in.readByte(); switch (len & 7) { case 7: arr[bc + 6] = (v & 64) != 0; case 6: arr[bc + 5] = (v & 32) != 0; case 5: arr[bc + 4] = (v & 16) != 0; case 4: arr[bc + 3] = (v & 8) != 0; case 3: arr[bc + 2] = (v & 4) != 0; case 2: arr[bc + 1] = (v & 2) != 0; case 1: arr[bc] = (v & 1) != 0; } } return arr; } private static char[] readCharArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new char[]{}; case ID_ARRAY_SMALL: return readChars(mkCharArray(in.readUnsignedByte() + SMALL_ARRAY_MIN), in); case ID_ARRAY_MEDIUM: return readChars(mkCharArray(in.readUnsignedShort() + MEDIUM_ARRAY_MIN), in); case ID_ARRAY_LARGE: return readChars(new char[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static char[] mkCharArray(int len) { return new char[len]; } private static char[] readChars(char[] arr, BytesObjectInput in) throws EOFException { final int len = arr.length; for (int i = 0; i < len; i ++) arr[i] = in.readChar(); return arr; } private static double[] readDoubleArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new double[]{}; case ID_ARRAY_SMALL: return readDoubles(new double[in.readUnsignedByte() + SMALL_ARRAY_MIN], in); case ID_ARRAY_MEDIUM: return readDoubles(new double[in.readUnsignedShort() + MEDIUM_ARRAY_MIN], in); case ID_ARRAY_LARGE: return readDoubles(new double[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static double[] readDoubles(double[] arr, BytesObjectInput in) throws EOFException { final int len = arr.length; for (int i = 0; i < len; i ++) arr[i] = in.readDouble(); return arr; } private static float[] readFloatArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new float[]{}; case ID_ARRAY_SMALL: return readFloats(new float[in.readUnsignedByte() + SMALL_ARRAY_MIN], in); case ID_ARRAY_MEDIUM: return readFloats(new float[in.readUnsignedShort() + MEDIUM_ARRAY_MIN], in); case ID_ARRAY_LARGE: return readFloats(new float[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static float[] readFloats(float[] arr, BytesObjectInput in) throws EOFException { final int len = arr.length; for (int i = 0; i < len; i ++) arr[i] = in.readFloat(); return arr; } private static int[] readIntArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new int[]{}; case ID_ARRAY_SMALL: return readInts(new int[in.readUnsignedByte() + SMALL_ARRAY_MIN], in); case ID_ARRAY_MEDIUM: return readInts(new int[in.readUnsignedShort() + MEDIUM_ARRAY_MIN], in); case ID_ARRAY_LARGE: return readInts(new int[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static int[] readInts(int[] arr, BytesObjectInput in) throws EOFException { final int len = arr.length; for (int i = 0; i < len; i ++) arr[i] = in.readInt(); return arr; } private static long[] readLongArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new long[]{}; case ID_ARRAY_SMALL: return readLongs(new long[in.readUnsignedByte() + SMALL_ARRAY_MIN], in); case ID_ARRAY_MEDIUM: return readLongs(new long[in.readUnsignedShort() + MEDIUM_ARRAY_MIN], in); case ID_ARRAY_LARGE: return readLongs(new long[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static long[] readLongs(long[] arr, BytesObjectInput in) throws EOFException { final int len = arr.length; for (int i = 0; i < len; i ++) arr[i] = in.readLong(); return arr; } private static short[] readShortArray(BytesObjectInput in) throws IOException { byte type = in.readByte(); switch (type) { case ID_ARRAY_EMPTY: return new short[]{}; case ID_ARRAY_SMALL: return readShorts(new short[in.readUnsignedByte() + SMALL_ARRAY_MIN], in); case ID_ARRAY_MEDIUM: return readShorts(new short[in.readUnsignedShort() + MEDIUM_ARRAY_MIN], in); case ID_ARRAY_LARGE: return readShorts(new short[in.readInt()], in); default: throw new IOException("Unknown array type: " + Integer.toHexString(type)); } } private static short[] readShorts(short[] arr, BytesObjectInput in) throws EOFException { final int len = arr.length; for (int i = 0; i < len; i ++) arr[i] = in.readShort(); return arr; } }
20,468
34.536458
98
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/EncoderRegistry.java
package org.infinispan.marshall.core; import org.infinispan.commons.dataconversion.Encoder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.Transcoder; import org.infinispan.commons.dataconversion.Wrapper; import org.infinispan.encoding.DataConversion; /** * Manages existent {@link Encoder}, {@link Wrapper} and {@link Transcoder} instances. * * @since 9.1 */ public interface EncoderRegistry { @Deprecated Encoder getEncoder(Class<? extends Encoder> encoderClass, short encoderId); @Deprecated boolean isRegistered(Class<? extends Encoder> encoderClass); /** * @deprecated Since 11.0. To be removed in 14.0, with {@link DataConversion#getWrapper()} */ @Deprecated Wrapper getWrapper(Class<? extends Wrapper> wrapperClass, byte wrapperId); /** * @param encoder {@link Encoder to be registered}. */ @Deprecated void registerEncoder(Encoder encoder); /** * @deprecated Since 11.0. To be removed in 14.0, with {@link DataConversion#getWrapper()} */ @Deprecated void registerWrapper(Wrapper wrapper); void registerTranscoder(Transcoder transcoder); /** * Obtain an instance of {@link Transcoder} from the registry. * * @param type1 {@link MediaType} supported by the transcoder. * @param type2 {@link MediaType} supported by the transcoder. * @return An instance of {@link Transcoder} capable of doing conversions between the supplied MediaTypes. */ Transcoder getTranscoder(MediaType type1, MediaType type2); <T extends Transcoder> T getTranscoder(Class<T> clazz); boolean isConversionSupported(MediaType from, MediaType to); /** * Performs a data conversion. * * @param o object to convert * @param from the object MediaType * @param to the format to convert to * @return the object converted. * @since 11.0 */ Object convert(Object o, MediaType from, MediaType to); }
1,977
28.969697
109
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/MarshallableFunctionExternalizers.java
package org.infinispan.marshall.core; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.infinispan.commons.marshall.LambdaExternalizer; import org.infinispan.commons.marshall.ValueMatcherMode; import org.infinispan.commons.util.Util; import org.infinispan.functional.MetaParam; public class MarshallableFunctionExternalizers { // TODO: Should really rely on ValuteMatcherMode enumeration ordering private static final short VALUE_MATCH_ALWAYS = 0x1000; private static final short VALUE_MATCH_EXPECTED = 0x2000; private static final short VALUE_MATCH_EXPECTED_OR_NEW = 0x3000; private static final short VALUE_MATCH_NON_NULL = 0x4000; private static final short VALUE_MATCH_NEVER = 0x5000; private static final int VALUE_MATCH_MASK = 0xF000; private static final int SET_VALUE_RETURN_PREV_OR_NULL = 1 | VALUE_MATCH_ALWAYS; private static final int SET_VALUE_RETURN_VIEW = 2 | VALUE_MATCH_ALWAYS; private static final int SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL = 3 | VALUE_MATCH_EXPECTED; private static final int SET_VALUE_IF_ABSENT_RETURN_BOOLEAN = 4 | VALUE_MATCH_EXPECTED; private static final int SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL = 5 | VALUE_MATCH_NON_NULL; private static final int SET_VALUE_IF_PRESENT_RETURN_BOOLEAN = 6 | VALUE_MATCH_NON_NULL; private static final int REMOVE_RETURN_PREV_OR_NULL = 7 | VALUE_MATCH_ALWAYS; private static final int REMOVE_RETURN_BOOLEAN = 8 | VALUE_MATCH_ALWAYS; private static final int REMOVE_IF_VALUE_EQUALS_RETURN_BOOLEAN = 9 | VALUE_MATCH_EXPECTED; private static final int SET_VALUE_CONSUMER = 10 | VALUE_MATCH_ALWAYS; private static final int REMOVE_CONSUMER = 11 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_WRITE_FIND = 12 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_WRITE_GET = 13 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_WRITE_VIEW = 14 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_ONLY_FIND_OR_NULL = 15 | VALUE_MATCH_ALWAYS; private static final int RETURN_READ_ONLY_FIND_IS_PRESENT = 16 | VALUE_MATCH_ALWAYS; private static final int IDENTITY = 17 | VALUE_MATCH_ALWAYS; private static final int SET_INTERNAL_CACHE_VALUE_CONSUMER = 18 | VALUE_MATCH_ALWAYS; public static final class ConstantLambdaExternalizer implements LambdaExternalizer<Object> { private final Map<Class<?>, Integer> numbers = new HashMap<>(16); public ConstantLambdaExternalizer() { numbers.put(MarshallableFunctions.setValueReturnPrevOrNull().getClass(), SET_VALUE_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.setValueReturnView().getClass(), SET_VALUE_RETURN_VIEW); numbers.put(MarshallableFunctions.setValueIfAbsentReturnPrevOrNull().getClass(), SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.setValueIfAbsentReturnBoolean().getClass(), SET_VALUE_IF_ABSENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.setValueIfPresentReturnPrevOrNull().getClass(), SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.setValueIfPresentReturnBoolean().getClass(), SET_VALUE_IF_PRESENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.removeReturnPrevOrNull().getClass(), REMOVE_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.removeReturnBoolean().getClass(), REMOVE_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.removeIfValueEqualsReturnBoolean().getClass(), REMOVE_IF_VALUE_EQUALS_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.setValueConsumer().getClass(), SET_VALUE_CONSUMER); numbers.put(MarshallableFunctions.removeConsumer().getClass(), REMOVE_CONSUMER); numbers.put(MarshallableFunctions.returnReadWriteFind().getClass(), RETURN_READ_WRITE_FIND); numbers.put(MarshallableFunctions.returnReadWriteGet().getClass(), RETURN_READ_WRITE_GET); numbers.put(MarshallableFunctions.returnReadWriteView().getClass(), RETURN_READ_WRITE_VIEW); numbers.put(MarshallableFunctions.returnReadOnlyFindOrNull().getClass(), RETURN_READ_ONLY_FIND_OR_NULL); numbers.put(MarshallableFunctions.returnReadOnlyFindIsPresent().getClass(), RETURN_READ_ONLY_FIND_IS_PRESENT); numbers.put(MarshallableFunctions.identity().getClass(), IDENTITY); numbers.put(MarshallableFunctions.setInternalCacheValueConsumer().getClass(), SET_INTERNAL_CACHE_VALUE_CONSUMER); } @Override public ValueMatcherMode valueMatcher(Object o) { int i = numbers.getOrDefault(o.getClass(), -1); if (i > 0) { int valueMatcherId = ((i & VALUE_MATCH_MASK) >> 12) - 1; return ValueMatcherMode.valueOf(valueMatcherId); } return ValueMatcherMode.MATCH_ALWAYS; } @Override public Set<Class<?>> getTypeClasses() { return Util.<Class<?>>asSet( MarshallableFunctions.setValueReturnPrevOrNull().getClass(), MarshallableFunctions.setValueReturnView().getClass(), MarshallableFunctions.setValueIfAbsentReturnPrevOrNull().getClass(), MarshallableFunctions.setValueIfAbsentReturnBoolean().getClass(), MarshallableFunctions.setValueIfPresentReturnPrevOrNull().getClass(), MarshallableFunctions.setValueIfPresentReturnBoolean().getClass(), MarshallableFunctions.removeReturnPrevOrNull().getClass(), MarshallableFunctions.removeReturnBoolean().getClass(), MarshallableFunctions.removeIfValueEqualsReturnBoolean().getClass(), MarshallableFunctions.setValueConsumer().getClass(), MarshallableFunctions.removeConsumer().getClass(), MarshallableFunctions.returnReadWriteFind().getClass(), MarshallableFunctions.returnReadWriteGet().getClass(), MarshallableFunctions.returnReadWriteView().getClass(), MarshallableFunctions.returnReadOnlyFindOrNull().getClass(), MarshallableFunctions.returnReadOnlyFindIsPresent().getClass(), MarshallableFunctions.identity().getClass(), MarshallableFunctions.setInternalCacheValueConsumer().getClass() ); } @Override public Integer getId() { return org.infinispan.commons.marshall.Ids.LAMBDA_CONSTANT; } public void writeObject(ObjectOutput oo, Object o) throws IOException { int id = numbers.getOrDefault(o.getClass(), -1); oo.writeShort(id); } public Object readObject(ObjectInput input) throws IOException { short id = input.readShort(); switch (id) { case SET_VALUE_RETURN_PREV_OR_NULL: return MarshallableFunctions.setValueReturnPrevOrNull(); case SET_VALUE_RETURN_VIEW: return MarshallableFunctions.setValueReturnView(); case SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL: return MarshallableFunctions.setValueIfAbsentReturnPrevOrNull(); case SET_VALUE_IF_ABSENT_RETURN_BOOLEAN: return MarshallableFunctions.setValueIfAbsentReturnBoolean(); case SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL: return MarshallableFunctions.setValueIfPresentReturnPrevOrNull(); case SET_VALUE_IF_PRESENT_RETURN_BOOLEAN: return MarshallableFunctions.setValueIfPresentReturnBoolean(); case REMOVE_RETURN_PREV_OR_NULL: return MarshallableFunctions.removeReturnPrevOrNull(); case REMOVE_RETURN_BOOLEAN: return MarshallableFunctions.removeReturnBoolean(); case REMOVE_IF_VALUE_EQUALS_RETURN_BOOLEAN: return MarshallableFunctions.removeIfValueEqualsReturnBoolean(); case SET_VALUE_CONSUMER: return MarshallableFunctions.setValueConsumer(); case REMOVE_CONSUMER: return MarshallableFunctions.removeConsumer(); case RETURN_READ_WRITE_FIND: return MarshallableFunctions.returnReadWriteFind(); case RETURN_READ_WRITE_GET: return MarshallableFunctions.returnReadWriteGet(); case RETURN_READ_WRITE_VIEW: return MarshallableFunctions.returnReadWriteView(); case RETURN_READ_ONLY_FIND_OR_NULL: return MarshallableFunctions.returnReadOnlyFindOrNull(); case RETURN_READ_ONLY_FIND_IS_PRESENT: return MarshallableFunctions.returnReadOnlyFindIsPresent(); case IDENTITY: return MarshallableFunctions.identity(); case SET_INTERNAL_CACHE_VALUE_CONSUMER: return MarshallableFunctions.setInternalCacheValueConsumer(); default: throw new IllegalStateException("Unknown lambda ID: " + id); } } } public static final class LambdaWithMetasExternalizer implements LambdaExternalizer<MarshallableFunctions.LambdaWithMetas> { private final Map<Class<?>, Integer> numbers = new HashMap<>(7); public LambdaWithMetasExternalizer() { numbers.put(MarshallableFunctions.SetValueMetasReturnPrevOrNull.class, SET_VALUE_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.SetValueMetasReturnView.class, SET_VALUE_RETURN_VIEW); numbers.put(MarshallableFunctions.SetValueMetasIfAbsentReturnPrevOrNull.class, SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.SetValueMetasIfAbsentReturnBoolean.class, SET_VALUE_IF_ABSENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.SetValueMetasIfPresentReturnPrevOrNull.class, SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL); numbers.put(MarshallableFunctions.SetValueMetasIfPresentReturnBoolean.class, SET_VALUE_IF_PRESENT_RETURN_BOOLEAN); numbers.put(MarshallableFunctions.SetValueMetas.class, SET_VALUE_CONSUMER); } @Override public ValueMatcherMode valueMatcher(Object o) { // TODO: Code duplication int i = numbers.getOrDefault(o.getClass(), -1); if (i > 0) { int valueMatcherId = ((i & VALUE_MATCH_MASK) >> 12) - 1; return ValueMatcherMode.valueOf(valueMatcherId); } return ValueMatcherMode.MATCH_ALWAYS; } @Override public Set<Class<? extends MarshallableFunctions.LambdaWithMetas>> getTypeClasses() { return Util.<Class<? extends MarshallableFunctions.LambdaWithMetas>>asSet( MarshallableFunctions.SetValueMetasReturnPrevOrNull.class, MarshallableFunctions.SetValueMetasReturnView.class, MarshallableFunctions.SetValueMetasIfAbsentReturnPrevOrNull.class, MarshallableFunctions.SetValueMetasIfAbsentReturnBoolean.class, MarshallableFunctions.SetValueMetasIfPresentReturnPrevOrNull.class, MarshallableFunctions.SetValueMetasIfPresentReturnBoolean.class, MarshallableFunctions.SetValueMetas.class ); } @Override public Integer getId() { return org.infinispan.commons.marshall.Ids.LAMBDA_WITH_METAS; } @Override public void writeObject(ObjectOutput oo, MarshallableFunctions.LambdaWithMetas o) throws IOException { int id = numbers.getOrDefault(o.getClass(), -1); oo.writeShort(id); writeMetas(oo, o); } @Override public MarshallableFunctions.LambdaWithMetas readObject(ObjectInput input) throws IOException, ClassNotFoundException { short id = input.readShort(); MetaParam.Writable[] metas = readMetas(input); switch (id) { case SET_VALUE_RETURN_PREV_OR_NULL: return new MarshallableFunctions.SetValueMetasReturnPrevOrNull<>(metas); case SET_VALUE_IF_ABSENT_RETURN_PREV_OR_NULL: return new MarshallableFunctions.SetValueMetasIfAbsentReturnPrevOrNull<>(metas); case SET_VALUE_IF_ABSENT_RETURN_BOOLEAN: return new MarshallableFunctions.SetValueMetasIfAbsentReturnBoolean<>(metas); case SET_VALUE_RETURN_VIEW: return new MarshallableFunctions.SetValueMetasReturnView<>(metas); case SET_VALUE_IF_PRESENT_RETURN_PREV_OR_NULL: return new MarshallableFunctions.SetValueMetasIfPresentReturnPrevOrNull<>(metas); case SET_VALUE_IF_PRESENT_RETURN_BOOLEAN: return new MarshallableFunctions.SetValueMetasIfPresentReturnBoolean<>(metas); case SET_VALUE_CONSUMER: return new MarshallableFunctions.SetValueMetas<>(metas); default: throw new IllegalStateException("Unknown lambda and meta parameters with ID: " + id); } } } static MetaParam.Writable[] readMetas(ObjectInput input) throws IOException, ClassNotFoundException { int len = input.readInt(); MetaParam.Writable[] metas = new MetaParam.Writable[len]; for(int i = 0; i < len; i++) metas[i] = (MetaParam.Writable) input.readObject(); return metas; } private static void writeMetas(ObjectOutput oo, MarshallableFunctions.LambdaWithMetas o) throws IOException { oo.writeInt(o.metas().length); for (MetaParam.Writable meta : o.metas()) oo.writeObject(meta); } public static final class SetValueIfEqualsReturnBooleanExternalizer implements LambdaExternalizer<MarshallableFunctions.SetValueIfEqualsReturnBoolean> { public void writeObject(ObjectOutput oo, MarshallableFunctions.SetValueIfEqualsReturnBoolean o) throws IOException { oo.writeObject(o.oldValue); writeMetas(oo, o); } public MarshallableFunctions.SetValueIfEqualsReturnBoolean readObject(ObjectInput input) throws IOException, ClassNotFoundException { Object oldValue = input.readObject(); MetaParam.Writable[] metas = readMetas(input); return new MarshallableFunctions.SetValueIfEqualsReturnBoolean<>(oldValue, metas); } @Override public ValueMatcherMode valueMatcher(Object o) { return ValueMatcherMode.MATCH_EXPECTED; } @Override public Set<Class<? extends MarshallableFunctions.SetValueIfEqualsReturnBoolean>> getTypeClasses() { return Util.<Class<? extends MarshallableFunctions.SetValueIfEqualsReturnBoolean>>asSet(MarshallableFunctions.SetValueIfEqualsReturnBoolean.class); } @Override public Integer getId() { return org.infinispan.commons.marshall.Ids.LAMBDA_SET_VALUE_IF_EQUALS_RETURN_BOOLEAN; } } }
14,395
55.677165
156
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/BytesObjectOutput.java
package org.infinispan.marshall.core; import java.io.IOException; import java.io.ObjectOutput; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; /** * Array backed, expandable {@link ObjectOutput} implementation. */ final class BytesObjectOutput implements ObjectOutput { final GlobalMarshaller marshaller; byte bytes[]; int pos; BytesObjectOutput(int size, GlobalMarshaller marshaller) { this.bytes = new byte[size]; this.marshaller = marshaller; } @Override public void writeObject(Object obj) throws IOException { marshaller.writeNullableObject(obj, this); } @Override public void write(int b) { writeByte(b); } @Override public void write(byte[] b) { final int len = b.length; final int newcount = ensureCapacity(len); System.arraycopy(b, 0, bytes, pos, len); pos = newcount; } @Override public void write(byte[] b, int off, int len) { final int newcount = ensureCapacity(len); System.arraycopy(b, off, bytes, pos, len); pos = newcount; } @Override public void writeBoolean(boolean v) { writeByte((byte) (v ? 1 : 0)); } @Override public void writeByte(int v) { final int newcount = ensureCapacity(1); bytes[pos] = (byte) v; pos = newcount; } @Override public void writeShort(int v) { int newcount = ensureCapacity(2); final int s = pos; bytes[s] = (byte) (v >> 8); bytes[s+1] = (byte) v; pos = newcount; } @Override public void writeChar(int v) { int newcount = ensureCapacity(2); final int s = pos; bytes[s] = (byte) (v >> 8); bytes[s+1] = (byte) v; pos = newcount; } @Override public void writeInt(int v) { int newcount = ensureCapacity(4); final int s = pos; bytes[s] = (byte) (v >> 24); bytes[s+1] = (byte) (v >> 16); bytes[s+2] = (byte) (v >> 8); bytes[s+3] = (byte) v; pos = newcount; } @Override public void writeLong(long v) { int newcount = ensureCapacity(8); final int s = pos; bytes[s] = (byte) (v >> 56L); bytes[s+1] = (byte) (v >> 48L); bytes[s+2] = (byte) (v >> 40L); bytes[s+3] = (byte) (v >> 32L); bytes[s+4] = (byte) (v >> 24L); bytes[s+5] = (byte) (v >> 16L); bytes[s+6] = (byte) (v >> 8L); bytes[s+7] = (byte) v; pos = newcount; } @Override public void writeFloat(float v) { writeInt(Float.floatToIntBits(v)); } @Override public void writeDouble(double v) { writeLong(Double.doubleToLongBits(v)); } @Override public void writeBytes(String s) { writeString(s); } @Override public void writeChars(String s) { writeString(s); } void writeString(String s) { int len; if ((len = s.length()) == 0){ writeByte(0); // empty string } else if (isAscii(s, len)) { writeByte(1); // small ascii writeByte(len); int newcount = ensureCapacity(len); s.getBytes(0, len, bytes, pos); pos = newcount; } else { writeByte(2); // large string writeUTF(s); } } private boolean isAscii(String s, int len) { boolean ascii = false; if(len < 64) { ascii = true; for (int i = 0; i < len; i++) { if (s.charAt(i) > 127) { ascii = false; break; } } } return ascii; } @Override public void writeUTF(String s) { int strlen = s.length(); int startPos = pos; // First optimize for 1 - 127 case ensureCapacity(strlen + 4); // Note this will be overwritten if not all 1 - 127 characters below writeIntDirect(strlen, startPos); int localPos = pos; /* avoid getfield opcode */ byte[] localBuf = bytes; /* avoid getfield opcode */ localPos += 4; int c; int i; for (i = 0; i < strlen; i++) { c = s.charAt(i); if (c > 127) break; localBuf[localPos++] = (byte) c; } pos = localPos; // Means we completed with all latin characters if (i == strlen) { return; } // Resize the rest assuming worst case of 3 bytes ensureCapacity((strlen - i) * 3); localBuf = bytes; /* avoid getfield opcode */ for (; i < strlen; i++) { c = s.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { localBuf[localPos++] = (byte) c; } else if (c > 0x07FF) { localBuf[localPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); localBuf[localPos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); localBuf[localPos++] = (byte) (0x80 | (c & 0x3F)); } else { localBuf[localPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); localBuf[localPos++] = (byte) (0x80 | (c & 0x3F)); } } pos = localPos; writeIntDirect(localPos - 4 - startPos, startPos); } private void writeIntDirect(int intValue, int index) { byte[] buf = bytes; /* avoid getfield opcode */ buf[index] = (byte) ((intValue >>> 24) & 0xFF); buf[index+1] = (byte) ((intValue >>> 16) & 0xFF); buf[index+2] = (byte) ((intValue >>> 8) & 0xFF); buf[index+3] = (byte) (intValue & 0xFF); } @Override public void flush() { // No-op } @Override public void close() { // No-op } private int ensureCapacity(int len) { int newcount = pos + len; if (newcount > bytes.length) { byte newbuf[] = new byte[getNewBufferSize(bytes.length, newcount)]; System.arraycopy(bytes, 0, newbuf, 0, pos); bytes = newbuf; } else if (newcount < 0) { throw new OutOfMemoryError("Serialized objects must fit in 2GB"); } return newcount; } private static final int DEFAULT_DOUBLING_SIZE = 4 * 1024 * 1024; // 4MB /** * Gets the number of bytes to which the internal buffer should be resized. * If not enough space, it doubles the size until the internal buffer * reaches a configurable max size (default is 4MB), after which it begins * growing the buffer in 25% increments. This is intended to help prevent * an OutOfMemoryError during a resize of a large buffer. * * @param curSize the current number of bytes * @param minNewSize the minimum number of bytes required * @return the size to which the internal buffer should be resized */ private int getNewBufferSize(int curSize, int minNewSize) { if (curSize <= DEFAULT_DOUBLING_SIZE) return Math.max(curSize << 1, minNewSize); else return Math.max(curSize + (curSize >> 2), minNewSize); } byte[] toBytes() { // Trim out unused bytes byte[] b = new byte[pos]; System.arraycopy(bytes, 0, b, 0, pos); pos = 0; return b; } ByteBuffer toByteBuffer() { // No triming, just take position as length return ByteBufferImpl.create(bytes, 0, pos); } }
7,151
25.488889
78
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/ClassIds.java
package org.infinispan.marshall.core; /** * Identifiers for marshalling class name itself; this comes handy when marshalling arrays * and the array component type is interface (and therefore it does not have its AdvancedExternalizer). * * This identifiers don't clash with {@link org.infinispan.commons.marshall.Ids} and therefore it can use the same range. */ interface ClassIds { /* 0-15 Java classes */ int OBJECT = 0; int STRING = 1; int LIST = 2; int MAP_ENTRY = 3; /* 0-254 Infinispan internal classes */ int INTERNAL_CACHE_VALUE = 16; /* Do not use this id. External identifier (full integer) follows */ int MAX_ID = 255; }
666
29.318182
121
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/InternalExternalizers.java
package org.infinispan.marshall.core; import java.util.Set; import org.infinispan.cache.impl.BiFunctionMapper; import org.infinispan.cache.impl.EncoderEntryMapper; import org.infinispan.cache.impl.EncoderKeyMapper; import org.infinispan.cache.impl.EncoderValueMapper; import org.infinispan.cache.impl.FunctionMapper; import org.infinispan.commands.CommandInvocationId; import org.infinispan.commands.RemoteCommandsFactory; import org.infinispan.commands.functional.functions.MergeFunction; import org.infinispan.commons.hash.CRC16; import org.infinispan.commons.hash.MurmurHash3; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.marshall.AdminFlagExternalizer; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.tx.XidImpl; import org.infinispan.commons.util.ImmutableListCopy; import org.infinispan.commons.util.Immutables; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.ImmortalCacheValue; import org.infinispan.container.entries.MortalCacheEntry; import org.infinispan.container.entries.MortalCacheValue; import org.infinispan.container.entries.RemoteMetadata; import org.infinispan.container.entries.TransientCacheEntry; import org.infinispan.container.entries.TransientCacheValue; import org.infinispan.container.entries.TransientMortalCacheEntry; import org.infinispan.container.entries.TransientMortalCacheValue; import org.infinispan.container.entries.metadata.MetadataImmortalCacheEntry; import org.infinispan.container.entries.metadata.MetadataImmortalCacheValue; import org.infinispan.container.entries.metadata.MetadataMortalCacheEntry; import org.infinispan.container.entries.metadata.MetadataMortalCacheValue; import org.infinispan.container.entries.metadata.MetadataTransientCacheEntry; import org.infinispan.container.entries.metadata.MetadataTransientCacheValue; import org.infinispan.container.entries.metadata.MetadataTransientMortalCacheEntry; import org.infinispan.container.entries.metadata.MetadataTransientMortalCacheValue; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.container.versioning.SimpleClusteredVersion; import org.infinispan.context.Flag; import org.infinispan.distribution.ch.impl.DefaultConsistentHash; import org.infinispan.distribution.ch.impl.DefaultConsistentHashFactory; import org.infinispan.distribution.ch.impl.ReplicatedConsistentHash; import org.infinispan.distribution.ch.impl.ReplicatedConsistentHashFactory; import org.infinispan.distribution.ch.impl.SyncConsistentHashFactory; import org.infinispan.distribution.ch.impl.SyncReplicatedConsistentHashFactory; import org.infinispan.distribution.ch.impl.TopologyAwareConsistentHashFactory; import org.infinispan.distribution.ch.impl.TopologyAwareSyncConsistentHashFactory; import org.infinispan.distribution.group.impl.CacheEntryGroupPredicate; import org.infinispan.encoding.DataConversion; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.filter.AcceptAllKeyValueFilter; import org.infinispan.filter.CacheFilters; import org.infinispan.filter.CompositeKeyValueFilter; import org.infinispan.functional.impl.EntryViews; import org.infinispan.functional.impl.StatsEnvelope; import org.infinispan.globalstate.ScopeFilter; import org.infinispan.globalstate.ScopedState; import org.infinispan.interceptors.distribution.VersionedResult; import org.infinispan.interceptors.distribution.VersionedResults; import org.infinispan.marshall.core.impl.ClassToExternalizerMap; import org.infinispan.marshall.exts.CacheRpcCommandExternalizer; import org.infinispan.marshall.exts.ClassExternalizer; import org.infinispan.marshall.exts.CollectionExternalizer; import org.infinispan.marshall.exts.DoubleSummaryStatisticsExternalizer; import org.infinispan.marshall.exts.EnumExternalizer; import org.infinispan.marshall.exts.EnumSetExternalizer; import org.infinispan.marshall.exts.IntSummaryStatisticsExternalizer; import org.infinispan.marshall.exts.LongSummaryStatisticsExternalizer; import org.infinispan.marshall.exts.MapExternalizer; import org.infinispan.marshall.exts.MetaParamExternalizers; import org.infinispan.marshall.exts.OptionalExternalizer; import org.infinispan.marshall.exts.ReplicableCommandExternalizer; import org.infinispan.marshall.exts.ThrowableExternalizer; import org.infinispan.marshall.exts.TriangleAckExternalizer; import org.infinispan.marshall.exts.UuidExternalizer; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.impl.InternalMetadataImpl; import org.infinispan.notifications.cachelistener.cluster.ClusterEvent; import org.infinispan.notifications.cachelistener.cluster.ClusterListenerRemoveCallable; import org.infinispan.notifications.cachelistener.cluster.ClusterListenerReplicateCallable; import org.infinispan.notifications.cachelistener.filter.CacheEventConverterAsConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterAsKeyValueFilter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterAsKeyValueFilterConverter; import org.infinispan.notifications.cachelistener.filter.KeyValueFilterAsCacheEventFilter; import org.infinispan.notifications.cachelistener.filter.KeyValueFilterConverterAsCacheEventFilterConverter; import org.infinispan.partitionhandling.AvailabilityMode; import org.infinispan.reactive.publisher.PublisherReducers; import org.infinispan.reactive.publisher.PublisherTransformers; import org.infinispan.reactive.publisher.impl.commands.batch.PublisherResponseExternalizer; import org.infinispan.reactive.publisher.impl.commands.reduction.SegmentPublisherResult; import org.infinispan.remoting.responses.BiasRevocationResponse; import org.infinispan.remoting.responses.CacheNotFoundResponse; import org.infinispan.remoting.responses.ExceptionResponse; import org.infinispan.remoting.responses.PrepareResponse; import org.infinispan.remoting.responses.SuccessfulResponse; import org.infinispan.remoting.responses.UnsuccessfulResponse; import org.infinispan.remoting.responses.UnsureResponse; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.remoting.transport.jgroups.JGroupsTopologyAwareAddress; import org.infinispan.statetransfer.StateChunk; import org.infinispan.statetransfer.TransactionInfo; import org.infinispan.stats.impl.ClusterCacheStatsImpl; import org.infinispan.stream.StreamMarshalling; import org.infinispan.stream.impl.CacheBiConsumers; import org.infinispan.stream.impl.CacheIntermediatePublisher; import org.infinispan.stream.impl.CacheStreamIntermediateReducer; import org.infinispan.stream.impl.intops.IntermediateOperationExternalizer; import org.infinispan.topology.CacheJoinInfo; import org.infinispan.topology.CacheStatusResponse; import org.infinispan.topology.CacheTopology; import org.infinispan.topology.ManagerStatusResponse; import org.infinispan.topology.PersistentUUID; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.transaction.xa.recovery.InDoubtTxInfo; import org.infinispan.util.IntSetExternalizer; import org.infinispan.util.KeyValuePair; import org.infinispan.xsite.response.AutoStateTransferResponse; import org.infinispan.xsite.statetransfer.XSiteState; final class InternalExternalizers { private InternalExternalizers() { } static ClassToExternalizerMap load(GlobalComponentRegistry gcr, RemoteCommandsFactory cmdFactory) { // TODO Add initial value and load factor ClassToExternalizerMap exts = new ClassToExternalizerMap(512, 0.6f); // Add the stateful externalizer first ReplicableCommandExternalizer ext = new ReplicableCommandExternalizer(cmdFactory, gcr); addInternalExternalizer(ext, exts); // Add the rest of stateless externalizers addInternalExternalizer(new AcceptAllKeyValueFilter.Externalizer(), exts); addInternalExternalizer(new AvailabilityMode.Externalizer(), exts); addInternalExternalizer(new BiasRevocationResponse.Externalizer(), exts); addInternalExternalizer(new BiFunctionMapper.Externalizer(), exts); addInternalExternalizer(new ByteBufferImpl.Externalizer(), exts); addInternalExternalizer(new CacheEventConverterAsConverter.Externalizer(), exts); addInternalExternalizer(new CacheEventFilterAsKeyValueFilter.Externalizer(), exts); addInternalExternalizer(new CacheEventFilterConverterAsKeyValueFilterConverter.Externalizer(), exts); addInternalExternalizer(new CacheFilters.CacheFiltersExternalizer(), exts); addInternalExternalizer(new CacheJoinInfo.Externalizer(), exts); addInternalExternalizer(new CacheNotFoundResponse.Externalizer(), exts); addInternalExternalizer(new CacheRpcCommandExternalizer(gcr, ext), exts); addInternalExternalizer(new CacheStatusResponse.Externalizer(), exts); addInternalExternalizer(new CacheTopology.Externalizer(), exts); addInternalExternalizer(new ClusterEvent.Externalizer(), exts); addInternalExternalizer(new ClusterListenerRemoveCallable.Externalizer(), exts); addInternalExternalizer(new ClusterListenerReplicateCallable.Externalizer(), exts); addInternalExternalizer(new CollectionExternalizer(), exts); addInternalExternalizer(new CompositeKeyValueFilter.Externalizer(), exts); // TODO: Untested in core addInternalExternalizer(new DefaultConsistentHash.Externalizer(), exts); addInternalExternalizer(new DefaultConsistentHashFactory.Externalizer(), exts); // TODO: Untested in core addInternalExternalizer(new DoubleSummaryStatisticsExternalizer(), exts); addInternalExternalizer(new EmbeddedMetadata.Externalizer(), exts); addInternalExternalizer(new EntryViews.NoValueReadOnlyViewExternalizer(), exts); addInternalExternalizer(new EntryViews.ReadWriteSnapshotViewExternalizer(), exts); addInternalExternalizer(new EntryViews.ReadOnlySnapshotViewExternalizer(), exts); addInternalExternalizer(new EnumSetExternalizer(), exts); addInternalExternalizer(new ExceptionResponse.Externalizer(), exts); addInternalExternalizer(new Flag.Externalizer(), exts); addInternalExternalizer(new FunctionMapper.Externalizer(), exts); addInternalExternalizer(new GlobalTransaction.Externalizer(), exts); addInternalExternalizer(new KeyValueFilterConverterAsCacheEventFilterConverter.Externalizer(), exts); addInternalExternalizer(new KeyValueFilterAsCacheEventFilter.Externalizer(), exts); addInternalExternalizer(new ImmortalCacheEntry.Externalizer(), exts); addInternalExternalizer(new ImmortalCacheValue.Externalizer(), exts); addInternalExternalizer(new Immutables.ImmutableMapWrapperExternalizer(), exts); addInternalExternalizer(new Immutables.ImmutableSetWrapperExternalizer(), exts); addInternalExternalizer(InDoubtTxInfo.EXTERNALIZER, exts); addInternalExternalizer(new IntermediateOperationExternalizer(), exts); addInternalExternalizer(new IntSummaryStatisticsExternalizer(), exts); addInternalExternalizer(new JGroupsAddress.Externalizer(), exts); addInternalExternalizer(new JGroupsTopologyAwareAddress.Externalizer(), exts); addInternalExternalizer(new LongSummaryStatisticsExternalizer(), exts); addInternalExternalizer(new KeyValuePair.Externalizer(), exts); addInternalExternalizer(new ManagerStatusResponse.Externalizer(), exts); addInternalExternalizer(new MapExternalizer(), exts); addInternalExternalizer(new MarshallableFunctionExternalizers.ConstantLambdaExternalizer(), exts); addInternalExternalizer(new MarshallableFunctionExternalizers.LambdaWithMetasExternalizer(), exts); addInternalExternalizer(new MarshallableFunctionExternalizers.SetValueIfEqualsReturnBooleanExternalizer(), exts); addInternalExternalizer(new MergeFunction.Externalizer(), exts); addInternalExternalizer(new MetadataImmortalCacheEntry.Externalizer(), exts); addInternalExternalizer(new MetadataImmortalCacheValue.Externalizer(), exts); addInternalExternalizer(new MetadataMortalCacheEntry.Externalizer(), exts); addInternalExternalizer(new MetadataMortalCacheValue.Externalizer(), exts); addInternalExternalizer(new MetadataTransientCacheEntry.Externalizer(), exts); // TODO: Untested in core addInternalExternalizer(new MetadataTransientCacheValue.Externalizer(), exts); // TODO: Untested in core addInternalExternalizer(new MetadataTransientMortalCacheEntry.Externalizer(), exts); addInternalExternalizer(new MetadataTransientMortalCacheValue.Externalizer(), exts); // TODO: Untested in core addInternalExternalizer(new MetaParamExternalizers.LifespanExternalizer(), exts); addInternalExternalizer(new MetaParamExternalizers.EntryVersionParamExternalizer(), exts); addInternalExternalizer(new MetaParamExternalizers.MaxIdleExternalizer(), exts); addInternalExternalizer(new MortalCacheEntry.Externalizer(), exts); addInternalExternalizer(new MortalCacheValue.Externalizer(), exts); addInternalExternalizer(new MurmurHash3.Externalizer(), exts); addInternalExternalizer(new CRC16.Externalizer(), exts); addInternalExternalizer(new NumericVersion.Externalizer(), exts); addInternalExternalizer(new OptionalExternalizer(), exts); addInternalExternalizer(new PersistentUUID.Externalizer(), exts); addInternalExternalizer(new RemoteMetadata.Externalizer(), exts); addInternalExternalizer(new ReplicatedConsistentHash.Externalizer(), exts); addInternalExternalizer(new ReplicatedConsistentHashFactory.Externalizer(), exts); // TODO: Untested in core addInternalExternalizer(new SimpleClusteredVersion.Externalizer(), exts); addInternalExternalizer(new StateChunk.Externalizer(), exts); addInternalExternalizer(new StatsEnvelope.Externalizer(), exts); addInternalExternalizer(new StreamMarshalling.StreamMarshallingExternalizer(), exts); addInternalExternalizer(new SuccessfulResponse.Externalizer(), exts); addInternalExternalizer(new SyncConsistentHashFactory.Externalizer(), exts); addInternalExternalizer(new SyncReplicatedConsistentHashFactory.Externalizer(), exts); addInternalExternalizer(new TopologyAwareConsistentHashFactory.Externalizer(), exts); // TODO: Untested in core addInternalExternalizer(new TopologyAwareSyncConsistentHashFactory.Externalizer(), exts); addInternalExternalizer(new TransactionInfo.Externalizer(), exts); addInternalExternalizer(new TransientCacheEntry.Externalizer(), exts); addInternalExternalizer(new TransientCacheValue.Externalizer(), exts); addInternalExternalizer(new TransientMortalCacheEntry.Externalizer(), exts); addInternalExternalizer(new TransientMortalCacheValue.Externalizer(), exts); addInternalExternalizer(new UnsuccessfulResponse.Externalizer(), exts); addInternalExternalizer(new UnsureResponse.Externalizer(), exts); addInternalExternalizer(new UuidExternalizer(), exts); addInternalExternalizer(new VersionedResult.Externalizer(), exts); addInternalExternalizer(new VersionedResults.Externalizer(), exts); addInternalExternalizer(new WrappedByteArray.Externalizer(), exts); addInternalExternalizer(new XSiteState.XSiteStateExternalizer(), exts); addInternalExternalizer(new TriangleAckExternalizer(), exts); addInternalExternalizer(new PublisherResponseExternalizer(), exts); addInternalExternalizer(XidImpl.EXTERNALIZER, exts); addInternalExternalizer(new EncoderKeyMapper.Externalizer(), exts); addInternalExternalizer(new EncoderValueMapper.Externalizer(), exts); addInternalExternalizer(new EncoderEntryMapper.Externalizer(), exts); addInternalExternalizer(new IntSetExternalizer(), exts); addInternalExternalizer(new DataConversion.Externalizer(), exts); addInternalExternalizer(new ScopedState.Externalizer(), exts); addInternalExternalizer(new ScopeFilter.Externalizer(), exts); addInternalExternalizer(new AdminFlagExternalizer(), exts); addInternalExternalizer(new SegmentPublisherResult.Externalizer(), exts); addInternalExternalizer(new PublisherReducers.PublisherReducersExternalizer(), exts); addInternalExternalizer(new PublisherTransformers.PublisherTransformersExternalizer(), exts); addInternalExternalizer(new CacheStreamIntermediateReducer.ReducerExternalizer(), exts); addInternalExternalizer(new CacheIntermediatePublisher.ReducerExternalizer(), exts); addInternalExternalizer(new ClassExternalizer(gcr.getGlobalConfiguration().classLoader()), exts); addInternalExternalizer(new ClusterCacheStatsImpl.DistributedCacheStatsCallableExternalizer(), exts); addInternalExternalizer(ThrowableExternalizer.INSTANCE, exts); addInternalExternalizer(new ImmutableListCopy.Externalizer(), exts); addInternalExternalizer(EnumExternalizer.INSTANCE, exts); addInternalExternalizer(new CacheBiConsumers.Externalizer(), exts); addInternalExternalizer(PrepareResponse.EXTERNALIZER, exts); addInternalExternalizer(new InternalMetadataImpl.Externalizer(), exts); addInternalExternalizer(AutoStateTransferResponse.EXTERNALIZER, exts); addInternalExternalizer(CommandInvocationId.EXTERNALIZER, exts); addInternalExternalizer(CacheEntryGroupPredicate.EXTERNALIZER, exts); return exts; } private static void addInternalExternalizer( AdvancedExternalizer ext, ClassToExternalizerMap exts) { Set<Class<?>> subTypes = ext.getTypeClasses(); for (Class<?> subType : subTypes) exts.put(subType, ext); } }
17,804
65.685393
119
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/impl/package-info.java
/** * @api.private */ package org.infinispan.marshall.core.impl;
67
12.6
42
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/impl/ExternalExternalizers.java
package org.infinispan.marshall.core.impl; import static org.infinispan.util.logging.Log.CONTAINER; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Map; import java.util.Set; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; public final class ExternalExternalizers { private static final Log log = LogFactory.getLog(ExternalExternalizers.class); private ExternalExternalizers() { } public static ClassToExternalizerMap load(GlobalConfiguration globalCfg) { return load(globalCfg, 0, Integer.MAX_VALUE); } /** * Load the {@link AdvancedExternalizer} instances with Ids inclusive of the specified bounds. */ public static ClassToExternalizerMap load(GlobalConfiguration globalCfg, int lowerBound, int upperBound) { ClassToExternalizerMap exts = new ClassToExternalizerMap(4, 0.375f); Map<Integer, AdvancedExternalizer<?>> cfgExts = globalCfg.serialization().advancedExternalizers(); for (Map.Entry<Integer, AdvancedExternalizer<?>> config : cfgExts.entrySet()) { AdvancedExternalizer ext = config.getValue(); // If no XML or programmatic config, id in annotation is used // as long as it's not default one (meaning, user did not set it). // If XML or programmatic config in use ignore @Marshalls annotation and use value in config. Integer id = ext.getId(); if (config.getKey() == null && id == null) throw new CacheConfigurationException(String.format( "No advanced externalizer identifier set for externalizer %s", ext.getClass().getName())); else if (config.getKey() != null) id = config.getKey(); if (id < 0) throw CONTAINER.foreignExternalizerUsingNegativeId(ext, id); if (id < lowerBound || id > upperBound) continue; Set<Class> subTypes = ext.getTypeClasses(); ForeignAdvancedExternalizer foreignExt = new ForeignAdvancedExternalizer(id, ext); for (Class<?> subType : subTypes) exts.put(subType, foreignExt); } return exts; } private static final class ForeignAdvancedExternalizer implements AdvancedExternalizer<Object> { final AdvancedExternalizer<Object> ext; // Avoids instantiating an Integer on every `getId` call final Integer id; private ForeignAdvancedExternalizer(int id, AdvancedExternalizer<Object> ext) { this.id = id; this.ext = ext; } @Override public Set<Class<?>> getTypeClasses() { return ext.getTypeClasses(); } @Override public Integer getId() { return id; } @Override public void writeObject(ObjectOutput output, Object object) throws IOException { ext.writeObject(output, object); } @Override public Object readObject(ObjectInput input) throws IOException, ClassNotFoundException { return ext.readObject(input); } @Override public String toString() { // Each adapter is represented by the externalizer it delegates to, so just return the class name return ext.getClass().getName(); } } }
3,485
32.519231
109
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/impl/ClassToExternalizerMap.java
package org.infinispan.marshall.core.impl; import static org.infinispan.util.logging.Log.CONTAINER; import java.util.Arrays; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * An efficient identity object map whose keys are {@link Class} objects and * whose values are {@link AdvancedExternalizer} instances. */ public final class ClassToExternalizerMap { private static final Log log = LogFactory.getLog(ClassToExternalizerMap.class); private AdvancedExternalizer[] values; private Class[] keys; private int count; private int resizeCount; private final float loadFactor; /** * Construct a new instance with the given initial capacity and load factor. * * @param initialCapacity the initial capacity * @param loadF the load factor */ public ClassToExternalizerMap(int initialCapacity, final float loadF) { if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity must be > 0"); } if (loadF <= 0.0f || loadF >= 1.0f) { throw new IllegalArgumentException("loadFactor must be > 0.0 and < 1.0"); } if (initialCapacity < 16) { initialCapacity = 16; } else { // round up final int c = Integer.highestOneBit(initialCapacity) - 1; initialCapacity = Integer.highestOneBit(initialCapacity + c); } keys = new Class[initialCapacity]; values = new AdvancedExternalizer[initialCapacity]; resizeCount = (int) ((double) initialCapacity * (double) loadF); this.loadFactor = loadF; } /** * Construct a new instance with the given load factor and an initial capacity of 64. * * @param loadFactor the load factor */ public ClassToExternalizerMap(final float loadFactor) { this(64, loadFactor); } /** * Construct a new instance with the given initial capacity and a load factor of {@code 0.5}. * * @param initialCapacity the initial capacity */ public ClassToExternalizerMap(final int initialCapacity) { this(initialCapacity, 0.5f); } /** * Construct a new instance with an initial capacity of 64 and a load factor of {@code 0.5}. */ public ClassToExternalizerMap() { this(0.5f); } /** * Get a value from the map. * * @param key the key * @return the map value at the given key, or null if it's not found */ public AdvancedExternalizer get(Class key) { final Class[] keys = this.keys; final int mask = keys.length - 1; int hc = System.identityHashCode(key) & mask; Class k; for (;;) { k = keys[hc]; if (k == key) { return values[hc]; } if (k == null) { // not found return null; } hc = (hc + 1) & mask; } } /** * Put a value into the map. Any previous mapping is discarded silently. * * @param key the key * @param value the value to store */ public void put(Class key, AdvancedExternalizer value) { final Class[] keys = this.keys; final int mask = keys.length - 1; final AdvancedExternalizer[] values = this.values; Class k; int hc = System.identityHashCode(key) & mask; for (int idx = hc;; idx = hc++ & mask) { k = keys[idx]; if (k == null) { keys[idx] = key; values[idx] = value; if (++count > resizeCount) { resize(); } return; } if (k == key) { values[idx] = value; return; } } } private void resize() { final Class[] oldKeys = keys; final int oldsize = oldKeys.length; final AdvancedExternalizer[] oldValues = values; if (oldsize >= 0x40000000) { throw new IllegalStateException("Table full"); } final int newsize = oldsize << 1; final int mask = newsize - 1; final Class[] newKeys = new Class[newsize]; final AdvancedExternalizer[] newValues = new AdvancedExternalizer[newsize]; keys = newKeys; values = newValues; if ((resizeCount <<= 1) == 0) { resizeCount = Integer.MAX_VALUE; } for (int oi = 0; oi < oldsize; oi ++) { final Class key = oldKeys[oi]; if (key != null) { int ni = System.identityHashCode(key) & mask; for (;;) { final Object v = newKeys[ni]; if (v == null) { // found newKeys[ni] = key; newValues[ni] = oldValues[oi]; break; } ni = (ni + 1) & mask; } } } } public void clear() { Arrays.fill(keys, null); Arrays.fill(values, null); count = 0; } /** * Get a string summary representation of this map. * * @return a string representation */ public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Map length = ").append(keys.length).append(", count = ").append(count).append(", resize count = ").append(resizeCount).append('\n'); for (int i = 0; i < keys.length; i ++) { builder.append('[').append(i).append("] = "); if (keys[i] != null) { final int hc = System.identityHashCode(keys[i]); builder.append("{ ").append(keys[i]).append(" (hash ").append(hc).append(", modulus ").append(hc % keys.length).append(") => ").append(values[i]).append(" }"); } else { builder.append("(blank)"); } builder.append('\n'); } return builder.toString(); } public IdToExternalizerMap reverseMap() { IdToExternalizerMap reverse = new IdToExternalizerHashMap(8, loadFactor); fillReverseMap(reverse); return reverse; } public IdToExternalizerMap reverseMap(int maxId) { // If max identifier is known, provide a single array backed map IdToExternalizerMap reverse = new IdToExternalizerArrayMap(maxId); fillReverseMap(reverse); return reverse; } private void fillReverseMap(IdToExternalizerMap reverse) { for (AdvancedExternalizer ext : values) { if (ext != null) { AdvancedExternalizer prev = reverse.get(ext.getId()); if (prev != null && !prev.equals(ext)) throw CONTAINER.duplicateExternalizerIdFound( ext.getId(), prev.getClass().getName()); reverse.put(ext.getId(), ext); } } } public interface IdToExternalizerMap { AdvancedExternalizer get(int key); void put(int key, AdvancedExternalizer value); void clear(); } private static final class IdToExternalizerArrayMap implements IdToExternalizerMap { private AdvancedExternalizer[] values; private int count; private IdToExternalizerArrayMap(int initialCapacity) { if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity must be > 0"); } if (initialCapacity < 16) { initialCapacity = 16; } else { // round up final int c = Integer.highestOneBit(initialCapacity) - 1; initialCapacity = Integer.highestOneBit(initialCapacity + c); } values = new AdvancedExternalizer[initialCapacity]; } /** * Get a value from the map. * * @param key the key * @return the map value at the given key, or null if it's not found */ public AdvancedExternalizer get(int key) { final AdvancedExternalizer[] values = this.values; return values[key]; } /** * Put a value into the map. Any previous mapping is discarded silently. * * @param key the key * @param value the value to store */ public void put(int key, AdvancedExternalizer value) { final AdvancedExternalizer[] values = this.values; if (values[key] == null) { values[key] = value; if (++count > values.length) resize(); } } private void resize() { final AdvancedExternalizer[] oldValues = values; final int oldsize = oldValues.length; if (oldsize >= 0x40000000) { throw new IllegalStateException("Table full"); } final int newsize = oldsize << 1; final AdvancedExternalizer[] newValues = new AdvancedExternalizer[newsize]; values = newValues; for (int oi = 0; oi < oldsize; oi ++) { if (oldValues[oi] != null) { newValues[oi] = oldValues[oi]; } } } public void clear() { Arrays.fill(values, null); count = 0; } /** * Get a string summary representation of this map. * * @return a string representation */ public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Map length = ").append(values.length).append(", count = ").append(count).append('\n'); for (int i = 0; i < values.length; i ++) { builder.append('[').append(i).append("] = "); if (values[i] != null) { builder.append("{ ").append(values[i]).append("}"); } else { builder.append("(blank)"); } builder.append('\n'); } return builder.toString(); } } private static final class IdToExternalizerHashMap implements IdToExternalizerMap { private AdvancedExternalizer[] values; private int[] keys; private int count; private int resizeCount; private IdToExternalizerHashMap(int initialCapacity, final float loadFactor) { if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity must be > 0"); } if (loadFactor <= 0.0f || loadFactor >= 1.0f) { throw new IllegalArgumentException("loadFactor must be > 0.0 and < 1.0"); } if (initialCapacity < 16) { initialCapacity = 16; } else { // round up final int c = Integer.highestOneBit(initialCapacity) - 1; initialCapacity = Integer.highestOneBit(initialCapacity + c); } keys = new int[initialCapacity]; values = new AdvancedExternalizer[initialCapacity]; resizeCount = (int) ((double) initialCapacity * (double) loadFactor); } /** * Get a value from the map. * * @param key the key * @return the map value at the given key, or null if it's not found */ public AdvancedExternalizer get(int key) { final int[] keys = this.keys; final AdvancedExternalizer[] values = this.values; final int mask = keys.length - 1; int hc = key & mask; int k; for (;;) { k = keys[hc]; if (k == key) { return values[hc]; } if (values[hc] == null) { // not found return null; } hc = (hc + 1) & mask; } } /** * Put a value into the map. Any previous mapping is discarded silently. * * @param key the key * @param value the value to store */ public void put(int key, AdvancedExternalizer value) { final int[] keys = this.keys; final int mask = keys.length - 1; final AdvancedExternalizer[] values = this.values; int k; int hc = key & mask; for (int idx = hc;; idx = hc++ & mask) { k = keys[idx]; if (values[idx] == null) { keys[idx] = key; values[idx] = value; if (++count > resizeCount) { resize(); } return; } if (k == key) { values[idx] = value; return; } } } private void resize() { final int[] oldKeys = keys; final int oldsize = oldKeys.length; final AdvancedExternalizer[] oldValues = values; if (oldsize >= 0x40000000) { throw new IllegalStateException("Table full"); } final int newsize = oldsize << 1; final int mask = newsize - 1; final int[] newKeys = new int[newsize]; final AdvancedExternalizer[] newValues = new AdvancedExternalizer[newsize]; keys = newKeys; values = newValues; if ((resizeCount <<= 1) == 0) { resizeCount = Integer.MAX_VALUE; } for (int oi = 0; oi < oldsize; oi ++) { final int key = oldKeys[oi]; if (oldValues[oi] != null) { int ni = key & mask; for (;;) { if (newValues[ni] == null) { // found newKeys[ni] = key; newValues[ni] = oldValues[oi]; break; } ni = (ni + 1) & mask; } } } } public void clear() { Arrays.fill(keys, 0); count = 0; } /** * Get a string summary representation of this map. * * @return a string representation */ public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Map length = ").append(keys.length).append(", count = ").append(count).append(", resize count = ").append(resizeCount).append('\n'); for (int i = 0; i < keys.length; i ++) { builder.append('[').append(i).append("] = "); if (values[i] != null) { final int hc = keys[i]; builder.append("{ ").append(keys[i]).append(" (hash ").append(hc).append(", modulus ").append(hc % keys.length).append(") => ").append(values[i]).append(" }"); } else { builder.append("(blank)"); } builder.append('\n'); } return builder.toString(); } } }
14,415
31.035556
174
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/core/impl/DelegatingUserMarshaller.java
package org.infinispan.marshall.core.impl; import static org.infinispan.util.logging.Log.CONTAINER; import java.io.IOException; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * A delegate {@link Marshaller} implementation for the user marshaller that ensures that the {@link Marshaller#start()} and * {@link Marshaller#stop()} of the configured marshaller are called and logged as required. * * @author Ryan Emerson * @since 12.0 */ @Scope(Scopes.GLOBAL) public class DelegatingUserMarshaller implements Marshaller { final Marshaller marshaller; public DelegatingUserMarshaller(Marshaller marshaller) { this.marshaller = marshaller; } @Start @Override public void start() { CONTAINER.startingUserMarshaller(marshaller.getClass().getName()); marshaller.start(); } @Stop @Override public void stop() { marshaller.stop(); } @Override public void initialize(ClassAllowList classAllowList) { marshaller.initialize(classAllowList); } @Override public byte[] objectToByteBuffer(Object obj, int estimatedSize) throws IOException, InterruptedException { return marshaller.objectToByteBuffer(obj, estimatedSize); } @Override public byte[] objectToByteBuffer(Object obj) throws IOException, InterruptedException { return marshaller.objectToByteBuffer(obj); } @Override public Object objectFromByteBuffer(byte[] buf) throws IOException, ClassNotFoundException { return marshaller.objectFromByteBuffer(buf); } @Override public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException { return marshaller.objectFromByteBuffer(buf, offset, length); } @Override public ByteBuffer objectToBuffer(Object o) throws IOException, InterruptedException { return marshaller.objectToBuffer(o); } @Override public boolean isMarshallable(Object o) throws Exception { return marshaller.isMarshallable(o); } @Override public BufferSizePredictor getBufferSizePredictor(Object o) { return marshaller.getBufferSizePredictor(o); } @Override public MediaType mediaType() { return marshaller.mediaType(); } public Marshaller getDelegate() { return marshaller; } }
2,730
27.747368
124
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/ClassExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; public class ClassExternalizer implements AdvancedExternalizer<Class> { private final ClassLoader cl; public ClassExternalizer(ClassLoader cl) { this.cl = cl; } @Override public Set<Class<? extends Class>> getTypeClasses() { return Util.asSet(Class.class); } @Override public Integer getId() { return Ids.CLASS; } @Override public void writeObject(ObjectOutput out, Class o) throws IOException { out.writeUTF(o.getName()); } @Override public Class readObject(ObjectInput in) throws IOException, ClassNotFoundException { return Class.forName(in.readUTF(), true, cl); } }
942
22.575
87
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/package-info.java
/** * Externalizers for various JDK types that are marshalled using the marshalling framework. */ package org.infinispan.marshall.exts;
138
26.8
91
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/SecurityActions.java
package org.infinispan.marshall.exts; import java.lang.reflect.Constructor; import java.lang.reflect.Field; /** * SecurityActions for the org.infinispan.marshall.exts 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 William Burns * @since 8.2 */ final class SecurityActions { private static Field getDeclaredField(Class<?> c, String fieldName) { try { return c.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { return null; } } static Field getField(Class<?> c, String fieldName) { Field field = getDeclaredField(c, fieldName); if (field != null) { field.setAccessible(true); } return field; } static <T> Constructor<T> getConstructor(Class<T> c, Class<?>... parameterTypes) { try { return c.getConstructor(parameterTypes); } catch (NoSuchMethodException e) { return null; } } }
1,086
26.175
90
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/OptionalExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; public class OptionalExternalizer extends AbstractExternalizer<Optional> { @Override public void writeObject(ObjectOutput output, Optional object) throws IOException { int isPresent = (object.isPresent() ? 1 : 0); output.writeByte(isPresent); if (object.isPresent()) output.writeObject(object.get()); } @Override public Optional readObject(ObjectInput input) throws IOException, ClassNotFoundException { boolean isPresent = input.readByte() == 1; return isPresent ? Optional.of(input.readObject()) : Optional.empty(); } @Override public Set<Class<? extends Optional>> getTypeClasses() { return Util.<Class<? extends Optional>>asSet(Optional.class); } @Override public Integer getId() { return Ids.OPTIONAL; } }
1,112
27.538462
93
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/CacheRpcCommandExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import org.infinispan.commands.control.LockControlCommand; 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.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.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.commons.marshall.AbstractExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.marshall.core.Ids; 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.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.statetransfer.XSiteStatePushCommand; /** * Externalizer in charge of marshalling cache specific commands. At read time, * this marshaller is able to locate the right cache marshaller and provide * it any externalizers implementations that follow. * * @author Galder Zamarreño * @since 5.1 */ public final class CacheRpcCommandExternalizer extends AbstractExternalizer<CacheRpcCommand> { private final GlobalComponentRegistry gcr; private final ReplicableCommandExternalizer cmdExt; public CacheRpcCommandExternalizer(GlobalComponentRegistry gcr, ReplicableCommandExternalizer cmdExt) { this.cmdExt = cmdExt; this.gcr = gcr; } @Override public Set<Class<? extends CacheRpcCommand>> getTypeClasses() { Set<Class<? extends CacheRpcCommand>> coreCommands = Util.asSet(LockControlCommand.class, StateResponseCommand.class, ClusteredGetCommand.class, SingleRpcCommand.class, CommitCommand.class, PrepareCommand.class, RollbackCommand.class, TxCompletionNotificationCommand.class, GetInDoubtTransactionsCommand.class, GetInDoubtTxInfoCommand.class, CompleteTransactionCommand.class, VersionedPrepareCommand.class, VersionedCommitCommand.class, XSiteStatePushCommand.class, SingleXSiteRpcCommand.class, ClusteredGetAllCommand.class, SingleKeyBackupWriteCommand.class, SingleKeyFunctionalBackupWriteCommand.class, PutMapBackupWriteCommand.class, MultiEntriesFunctionalBackupWriteCommand.class, MultiKeyFunctionalBackupWriteCommand.class, SizeCommand.class, BackupNoopCommand.class, ReductionPublisherRequestCommand.class, MultiClusterEventCommand.class, InitialPublisherCommand.class, NextPublisherCommand.class, CancelPublisherCommand.class, CheckTransactionRpcCommand.class, XSiteAmendOfflineStatusCommand.class, XSiteBringOnlineCommand.class, XSiteOfflineStatusCommand.class, XSiteStatusCommand.class, XSiteTakeOfflineCommand.class, XSiteStateTransferCancelSendCommand.class, XSiteStateTransferClearStatusCommand.class, XSiteStateTransferFinishReceiveCommand.class, XSiteStateTransferFinishSendCommand.class, XSiteStateTransferRestartSendingCommand.class, XSiteStateTransferStartReceiveCommand.class, XSiteStateTransferStartSendCommand.class, XSiteStateTransferStatusRequestCommand.class, ConflictResolutionStartCommand.class, StateTransferCancelCommand.class, StateTransferGetListenersCommand.class, StateTransferGetTransactionsCommand.class, StateTransferStartCommand.class, IracClearKeysCommand.class, IracCleanupKeysCommand.class, IracMetadataRequestCommand.class, IracRequestStateCommand.class, IracStateResponseCommand.class, IracTouchKeyCommand.class, IracUpdateVersionCommand.class, XSiteAutoTransferStatusCommand.class, XSiteSetStateTransferModeCommand.class, IracTombstoneCleanupCommand.class, IracTombstoneStateResponseCommand.class, IracTombstonePrimaryCheckCommand.class, IracTombstoneRemoteSiteCheckCommand.class, IracPutManyCommand.class); // Only interested in cache specific replicable commands coreCommands.addAll(gcr.getModuleProperties().moduleCacheRpcCommands()); return coreCommands; } @Override public void writeObject(ObjectOutput output, CacheRpcCommand command) throws IOException { //header: type + method id. cmdExt.writeCommandHeader(output, command); ByteString cacheName = command.getCacheName(); ByteString.writeObject(output, cacheName); // Take the cache marshaller and generate the payload for the rest of // the command using that cache marshaller and the write the bytes in // the original payload. marshallParameters(command, output); } private void marshallParameters(CacheRpcCommand cmd, ObjectOutput oo) throws IOException { cmdExt.writeCommandParameters(oo, cmd); } @Override public CacheRpcCommand readObject(ObjectInput input) throws IOException, ClassNotFoundException { //header byte type = input.readByte(); byte methodId = (byte) input.readShort(); ByteString cacheName = ByteString.readObject(input); //create the object input CacheRpcCommand cacheRpcCommand = cmdExt.fromStream(methodId, type, cacheName); cmdExt.readCommandParameters(input, cacheRpcCommand); return cacheRpcCommand; } @Override public Integer getId() { return Ids.CACHE_RPC_COMMAND; } }
9,350
52.434286
113
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/IntSummaryStatisticsExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.IntSummaryStatistics; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.NotSerializableException; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; /** * Externalizer used for {@link IntSummaryStatistics}. Note this assumes given fields have specific names to use * through reflection. * * @author wburns * @since 8.2 */ public class IntSummaryStatisticsExternalizer extends AbstractExternalizer<IntSummaryStatistics> { static final Field countField; static final Field sumField; static final Field minField; static final Field maxField; static final boolean canSerialize; static final Constructor<IntSummaryStatistics> constructor; static { constructor = SecurityActions.getConstructor( IntSummaryStatistics.class, long.class, int.class, int.class, long.class); if (constructor != null) { // since JDK 10, *SummaryStatistics have parametrized constructors, so reflection can be avoided countField = null; sumField = null; minField = null; maxField = null; canSerialize = true; } else { countField = SecurityActions.getField(IntSummaryStatistics.class, "count"); sumField = SecurityActions.getField(IntSummaryStatistics.class, "sum"); minField = SecurityActions.getField(IntSummaryStatistics.class, "min"); maxField = SecurityActions.getField(IntSummaryStatistics.class, "max"); // We can only properly serialize if all of the fields are non null canSerialize = countField != null && sumField != null && minField != null && maxField != null; } } @Override public Set<Class<? extends IntSummaryStatistics>> getTypeClasses() { return Util.<Class<? extends IntSummaryStatistics>>asSet(IntSummaryStatistics.class); } private void verifySerialization() { if (!canSerialize) { throw new NotSerializableException("IntSummaryStatistics is not serializable, fields not available!"); } } @Override public void writeObject(ObjectOutput output, IntSummaryStatistics object) throws IOException { verifySerialization(); output.writeLong(object.getCount()); output.writeLong(object.getSum()); output.writeInt(object.getMin()); output.writeInt(object.getMax()); } @Override public IntSummaryStatistics readObject(ObjectInput input) throws IOException, ClassNotFoundException { verifySerialization(); final IntSummaryStatistics summaryStatistics; final long count = input.readLong(); final long sum = input.readLong(); final int min = input.readInt(); final int max = input.readInt(); if (constructor != null) { // JDK 10+, pass values to constructor try { summaryStatistics = constructor.newInstance(count, min, max, sum); } catch (ReflectiveOperationException e) { throw new IOException(e); } } else { // JDK 9 or older, fall back to reflection try { summaryStatistics = new IntSummaryStatistics(); countField.setLong(summaryStatistics, count); sumField.setLong(summaryStatistics, sum); minField.setInt(summaryStatistics, min); maxField.setInt(summaryStatistics, max); } catch (IllegalAccessException e) { // This can't happen as we force accessibility in the getField throw new IOException(e); } } return summaryStatistics; } @Override public Integer getId() { return Ids.INT_SUMMARY_STATISTICS; } }
3,938
33.552632
113
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/CollectionExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.AbstractMap; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.util.FastCopyHashMap; import org.infinispan.commons.util.Util; import org.infinispan.distribution.util.ReadOnlySegmentAwareCollection; import org.infinispan.marshall.core.Ids; public class CollectionExternalizer implements AdvancedExternalizer<Collection> { private static final int ARRAY_LIST = 0; private static final int LINKED_LIST = 1; private static final int SINGLETON_LIST = 2; private static final int EMPTY_LIST = 3; private static final int HASH_SET = 4; private static final int TREE_SET = 5; private static final int SINGLETON_SET = 6; private static final int SYNCHRONIZED_SET = 7; private static final int ARRAY_DEQUE = 8; private static final int READ_ONLY_SEGMENT_AWARE_COLLECTION = 9; private static final int ENTRY_SET = 10; private static final int EMPTY_SET = 11; private final Map<Class<?>, Integer> numbers = new HashMap<>(16); public CollectionExternalizer() { numbers.put(ArrayList.class, ARRAY_LIST); numbers.put(getPrivateArrayListClass(), ARRAY_LIST); numbers.put(getPrivateUnmodifiableListClass(), ARRAY_LIST); numbers.put(LinkedList.class, LINKED_LIST); numbers.put(getPrivateSingletonListClass(), SINGLETON_LIST); numbers.put(getPrivateEmptyListClass(), EMPTY_LIST); numbers.put(getPrivateEmptySetClass(), EMPTY_SET); numbers.put(ArrayDeque.class, ARRAY_DEQUE); numbers.put(HashSet.class, HASH_SET); numbers.put(TreeSet.class, TREE_SET); numbers.put(getPrivateSingletonSetClass(), SINGLETON_SET); numbers.put(getPrivateSynchronizedSetClass(), SYNCHRONIZED_SET); numbers.put(getPrivateUnmodifiableSetClass(), HASH_SET); numbers.put(ReadOnlySegmentAwareCollection.class, READ_ONLY_SEGMENT_AWARE_COLLECTION); numbers.put(FastCopyHashMap.KeySet.class, HASH_SET); numbers.put(FastCopyHashMap.Values.class, ARRAY_LIST); numbers.put(FastCopyHashMap.EntrySet.class, ENTRY_SET); } @Override public void writeObject(ObjectOutput output, Collection collection) throws IOException { int number = numbers.getOrDefault(collection.getClass(), -1); output.writeByte(number); switch (number) { case ARRAY_LIST: case LINKED_LIST: case HASH_SET: case SYNCHRONIZED_SET: case ARRAY_DEQUE: case READ_ONLY_SEGMENT_AWARE_COLLECTION: MarshallUtil.marshallCollection(collection, output); break; case SINGLETON_LIST: output.writeObject(((List) collection).get(0)); break; case SINGLETON_SET: output.writeObject(collection.iterator().next()); break; case TREE_SET: output.writeObject(((TreeSet) collection).comparator()); MarshallUtil.marshallCollection(collection, output); break; case ENTRY_SET: MarshallUtil.marshallCollection(collection, output, (out, element) -> { Map.Entry entry = (Map.Entry) element; out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); }); break; } } @Override public Collection readObject(ObjectInput input) throws IOException, ClassNotFoundException { int magicNumber = input.readUnsignedByte(); switch (magicNumber) { case ARRAY_LIST: return MarshallUtil.unmarshallCollection(input, ArrayList::new); case LINKED_LIST: return MarshallUtil.unmarshallCollectionUnbounded(input, LinkedList::new); case SINGLETON_LIST: return Collections.singletonList(input.readObject()); case EMPTY_LIST: return Collections.emptyList(); case HASH_SET: return MarshallUtil.unmarshallCollection(input, s -> new HashSet<>()); case TREE_SET: Comparator<Object> comparator = (Comparator<Object>) input.readObject(); return MarshallUtil.unmarshallCollection(input, s -> new TreeSet<>(comparator)); case SINGLETON_SET: return Collections.singleton(input.readObject()); case SYNCHRONIZED_SET: return Collections.synchronizedSet( MarshallUtil.unmarshallCollection(input, s -> new HashSet<>())); case ARRAY_DEQUE: return MarshallUtil.unmarshallCollection(input, ArrayDeque::new); case READ_ONLY_SEGMENT_AWARE_COLLECTION: return MarshallUtil.unmarshallCollection(input, ArrayList::new); case ENTRY_SET: return MarshallUtil.<Map.Entry, Set<Map.Entry>>unmarshallCollection(input, s -> new HashSet(), in -> new AbstractMap.SimpleEntry(in.readObject(), in.readObject())); case EMPTY_SET: return Collections.emptySet(); default: throw new IllegalStateException("Unknown Set type: " + magicNumber); } } @Override public Integer getId() { return Ids.COLLECTIONS; } @Override public Set<Class<? extends Collection>> getTypeClasses() { Set<Class<? extends Collection>> typeClasses = Util.asSet(ArrayList.class, LinkedList.class, HashSet.class, TreeSet.class, ArrayDeque.class, ReadOnlySegmentAwareCollection.class, FastCopyHashMap.KeySet.class, FastCopyHashMap.Values.class, FastCopyHashMap.EntrySet.class); typeClasses.addAll(getSupportedPrivateClasses()); return typeClasses; } /** * Returns an immutable Set that contains all of the private classes (e.g. java.util.Collections$EmptyList) that * are supported by this Externalizer. This method is to be used by external sources if these private classes * need additional processing to be available. * @return immutable set of the private classes */ public static Set<Class<Collection>> getSupportedPrivateClasses() { Set<Class<Collection>> classNames = new HashSet<>(Arrays.asList( getPrivateArrayListClass(), getPrivateUnmodifiableListClass(), getPrivateEmptyListClass(), getPrivateEmptySetClass(), getPrivateSingletonListClass(), getPrivateSingletonSetClass(), getPrivateSynchronizedSetClass(), getPrivateUnmodifiableSetClass())); return Collections.unmodifiableSet(classNames); } private static Class<Collection> getPrivateArrayListClass() { return getCollectionClass("java.util.Arrays$ArrayList"); } private static Class<Collection> getPrivateUnmodifiableListClass() { return getCollectionClass("java.util.Collections$UnmodifiableRandomAccessList"); } private static Class<Collection> getPrivateEmptyListClass() { return getCollectionClass("java.util.Collections$EmptyList"); } private static Class<Collection> getPrivateEmptySetClass() { return getCollectionClass("java.util.Collections$EmptySet"); } private static Class<Collection> getPrivateSingletonListClass() { return getCollectionClass("java.util.Collections$SingletonList"); } public static Class<Collection> getPrivateSingletonSetClass() { return getCollectionClass("java.util.Collections$SingletonSet"); } public static Class<Collection> getPrivateSynchronizedSetClass() { return getCollectionClass("java.util.Collections$SynchronizedSet"); } private static Class<Collection> getPrivateUnmodifiableSetClass() { return getCollectionClass("java.util.Collections$UnmodifiableSet"); } private static Class<Collection> getCollectionClass(String className) { return Util.<Collection>loadClass(className, Collection.class.getClassLoader()); } }
8,366
39.616505
115
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/ThrowableExternalizer.java
package org.infinispan.marshall.exts; import org.infinispan.InvalidCacheUsageException; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.CacheException; import org.infinispan.commons.CacheListenerException; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.commons.dataconversion.EncodingException; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.marshall.MarshallingException; import org.infinispan.commons.util.Util; import org.infinispan.interceptors.distribution.ConcurrentChangeException; import org.infinispan.interceptors.impl.ContainerFullException; import org.infinispan.manager.EmbeddedCacheManagerStartupException; import org.infinispan.marshall.core.Ids; import org.infinispan.notifications.IncorrectListenerException; import org.infinispan.partitionhandling.AvailabilityException; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.remoting.CacheUnreachableException; import org.infinispan.remoting.RemoteException; import org.infinispan.remoting.RpcException; import org.infinispan.remoting.transport.jgroups.SuspectException; import org.infinispan.statetransfer.AllOwnersLostException; import org.infinispan.statetransfer.OutdatedTopologyException; import org.infinispan.topology.CacheJoinException; import org.infinispan.topology.MissingMembersException; import org.infinispan.transaction.WriteSkewException; import org.infinispan.transaction.xa.InvalidTransactionException; import org.infinispan.util.UserRaisedFunctionalException; import org.infinispan.util.concurrent.locks.DeadlockDetectedException; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; public class ThrowableExternalizer implements AdvancedExternalizer<Throwable> { public static final ThrowableExternalizer INSTANCE = new ThrowableExternalizer(); private static final short UNKNOWN = -1; // Infinispan Exceptions private static final short ALL_OWNERS_LOST = 0; private static final short AVAILABILITY = 1; private static final short CACHE_CONFIGURATION = 2; private static final short CACHE_EXCEPTION = 3; private static final short CACHE_LISTENER = 4; private static final short CACHE_UNREACHABLE = 5; private static final short CACHE_JOIN = 6; private static final short CONCURRENT_CHANGE = 7; private static final short CONTAINER_FULL = 8; private static final short DEADLOCK_DETECTED = 9; private static final short EMBEDDED_CACHEMANAGER_STARTUP = 10; private static final short ENCODING = 11; private static final short INCORRECT_LISTENER = 12; private static final short ILLEGAL_LIFECYLE = 13; private static final short INVALID_CACHE_USAGE = 14; private static final short INVALID_TX = 15; private static final short MARSHALLING = 16; private static final short NOT_SERIALIZABLE = 17; // Probably not needed, deprecate? private static final short OUTDATED_TOPOLOGY = 18; private static final short PERSISTENCE = 19; private static final short REMOTE = 20; private static final short RPC = 21; private static final short SUSPECT = 22; private static final short TIMEOUT = 23; private static final short USER_RAISED_FUNCTIONAL = 24; private static final short WRITE_SKEW = 25; private static final short MISSING_MEMBERS = 26; private final Map<Class<?>, Short> numbers = new HashMap<>(24); public ThrowableExternalizer() { numbers.put(AllOwnersLostException.class, ALL_OWNERS_LOST); numbers.put(AvailabilityException.class, AVAILABILITY); numbers.put(CacheConfigurationException.class, CACHE_CONFIGURATION); numbers.put(CacheException.class, CACHE_EXCEPTION); numbers.put(CacheListenerException.class, CACHE_LISTENER); numbers.put(CacheUnreachableException.class, CACHE_UNREACHABLE); numbers.put(CacheJoinException.class, CACHE_JOIN); numbers.put(ConcurrentChangeException.class, CONCURRENT_CHANGE); numbers.put(ContainerFullException.class, CONTAINER_FULL); numbers.put(DeadlockDetectedException.class, DEADLOCK_DETECTED); numbers.put(EmbeddedCacheManagerStartupException.class, EMBEDDED_CACHEMANAGER_STARTUP); numbers.put(EncodingException.class, ENCODING); numbers.put(IncorrectListenerException.class, INCORRECT_LISTENER); numbers.put(IllegalLifecycleStateException.class, ILLEGAL_LIFECYLE); numbers.put(InvalidCacheUsageException.class, INVALID_CACHE_USAGE); numbers.put(InvalidTransactionException.class, INVALID_TX); numbers.put(MarshallingException.class, MARSHALLING); numbers.put(PersistenceException.class, PERSISTENCE); numbers.put(RemoteException.class, REMOTE); numbers.put(RpcException.class, RPC); numbers.put(SuspectException.class, SUSPECT); numbers.put(TimeoutException.class, TIMEOUT); numbers.put(UserRaisedFunctionalException.class, USER_RAISED_FUNCTIONAL); numbers.put(WriteSkewException.class, WRITE_SKEW); numbers.put(OutdatedTopologyException.class, OUTDATED_TOPOLOGY); numbers.put(MissingMembersException.class, MISSING_MEMBERS); } @Override public Set<Class<? extends Throwable>> getTypeClasses() { return Util.asSet(Throwable.class); } @Override public Integer getId() { return Ids.EXCEPTIONS; } @Override public void writeObject(ObjectOutput out, Throwable t) throws IOException { short id = numbers.getOrDefault(t.getClass(), UNKNOWN); out.writeShort(id); switch (id) { case ALL_OWNERS_LOST: case CONCURRENT_CHANGE: break; case AVAILABILITY: case CACHE_CONFIGURATION: case CACHE_EXCEPTION: case CACHE_LISTENER: case CACHE_JOIN: case EMBEDDED_CACHEMANAGER_STARTUP: case ENCODING: case ILLEGAL_LIFECYLE: case INVALID_CACHE_USAGE: case INVALID_TX: case MARSHALLING: case PERSISTENCE: case REMOTE: case RPC: case SUSPECT: writeMessageAndCause(out, t); break; case MISSING_MEMBERS: case CACHE_UNREACHABLE: case CONTAINER_FULL: case DEADLOCK_DETECTED: case INCORRECT_LISTENER: case TIMEOUT: MarshallUtil.marshallString(t.getMessage(), out); break; case OUTDATED_TOPOLOGY: OutdatedTopologyException ote = (OutdatedTopologyException) t; out.writeBoolean(ote.topologyIdDelta == 0); break; case USER_RAISED_FUNCTIONAL: out.writeObject(t.getCause()); break; case WRITE_SKEW: WriteSkewException wse = (WriteSkewException) t; writeMessageAndCause(out, wse); out.writeObject(wse.getKey()); default: writeGenericThrowable(out, t); break; } } @Override public Throwable readObject(ObjectInput in) throws IOException, ClassNotFoundException { short id = in.readShort(); String msg; Throwable t; switch (id) { case ALL_OWNERS_LOST: return AllOwnersLostException.INSTANCE; case AVAILABILITY: return new AvailabilityException(); case CACHE_CONFIGURATION: return readMessageAndCause(in, CacheConfigurationException::new); case CACHE_EXCEPTION: return readMessageAndCause(in, CacheException::new); case CACHE_LISTENER: return readMessageAndCause(in, CacheListenerException::new); case CACHE_JOIN: return readMessageAndCause(in, CacheJoinException::new); case CACHE_UNREACHABLE: msg = MarshallUtil.unmarshallString(in); return new CacheUnreachableException(msg); case CONCURRENT_CHANGE: return new ConcurrentChangeException(); case CONTAINER_FULL: msg = MarshallUtil.unmarshallString(in); return new ContainerFullException(msg); case DEADLOCK_DETECTED: msg = MarshallUtil.unmarshallString(in); return new DeadlockDetectedException(msg); case EMBEDDED_CACHEMANAGER_STARTUP: return readMessageAndCause(in, EmbeddedCacheManagerStartupException::new); case ENCODING: return readMessageAndCause(in, EncodingException::new); case INCORRECT_LISTENER: msg = MarshallUtil.unmarshallString(in); return new IncorrectListenerException(msg); case ILLEGAL_LIFECYLE: return readMessageAndCause(in, IllegalLifecycleStateException::new); case INVALID_CACHE_USAGE: return readMessageAndCause(in, InvalidCacheUsageException::new); case INVALID_TX: return readMessageAndCause(in, InvalidTransactionException::new); case MARSHALLING: return readMessageAndCause(in, MarshallingException::new); case OUTDATED_TOPOLOGY: boolean retryNextTopology = in.readBoolean(); return retryNextTopology ? OutdatedTopologyException.RETRY_NEXT_TOPOLOGY : OutdatedTopologyException.RETRY_SAME_TOPOLOGY; case PERSISTENCE: return readMessageAndCause(in, PersistenceException::new); case REMOTE: return readMessageAndCause(in, RemoteException::new); case RPC: return readMessageAndCause(in, RpcException::new); case SUSPECT: return readMessageAndCause(in, SuspectException::new); case TIMEOUT: msg = MarshallUtil.unmarshallString(in); return new TimeoutException(msg); case USER_RAISED_FUNCTIONAL: t = (Throwable) in.readObject(); return new UserRaisedFunctionalException(t); case WRITE_SKEW: msg = MarshallUtil.unmarshallString(in); t = (Throwable) in.readObject(); Throwable[] suppressed = MarshallUtil.unmarshallArray(in, Util::throwableArray); Object key = in.readObject(); return addSuppressed(new WriteSkewException(msg, t, key), suppressed); case MISSING_MEMBERS: msg = MarshallUtil.unmarshallString(in); return new MissingMembersException(msg); default: return readGenericThrowable(in); } } private void writeMessageAndCause(ObjectOutput out, Throwable t) throws IOException { MarshallUtil.marshallString(t.getMessage(), out); out.writeObject(t.getCause()); MarshallUtil.marshallArray(t.getSuppressed(), out); } private void writeGenericThrowable(ObjectOutput out, Throwable t) throws IOException { out.writeUTF(t.getClass().getName()); writeMessageAndCause(out, t); } private Throwable readMessageAndCause(ObjectInput in, BiFunction<String, Throwable, Throwable> throwableBuilder) throws ClassNotFoundException, IOException{ String msg = MarshallUtil.unmarshallString(in); Throwable cause = (Throwable) in.readObject(); return readSuppressed(in, throwableBuilder.apply(msg, cause)); } private Throwable readGenericThrowable(ObjectInput in) throws IOException, ClassNotFoundException { String impl = in.readUTF(); String msg = MarshallUtil.unmarshallString(in); Throwable cause = (Throwable) in.readObject(); Throwable throwable = newThrowableInstance(impl, msg, cause); return readSuppressed(in, throwable); } private Throwable readSuppressed(ObjectInput in, Throwable t) throws ClassNotFoundException, IOException { return addSuppressed(t, MarshallUtil.unmarshallArray(in, Util::throwableArray)); } private Throwable addSuppressed(Throwable t, Throwable[] suppressed) { if (suppressed != null) { for (Throwable s : suppressed) t.addSuppressed(s); } return t; } private Throwable newThrowableInstance(String impl, String msg, Throwable t) throws ClassNotFoundException { try { Class<?> clazz = Class.forName(impl); if (t == null && msg == null) { return (Throwable) clazz.getConstructor().newInstance(new Object[]{}); } else if (t == null) { return (Throwable) clazz.getConstructor(String.class).newInstance(msg); } else if (msg == null) { return (Throwable) clazz.getConstructor(Throwable.class).newInstance(t); } return (Throwable) clazz.getConstructor(String.class, Throwable.class).newInstance(msg, t); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { throw new MarshallingException(e); } } }
13,061
42.979798
159
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/LongSummaryStatisticsExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.LongSummaryStatistics; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.NotSerializableException; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; /** * Externalizer used for {@link LongSummaryStatistics}. Note this assumes given fields have specific names to use * through reflection. * * @author wburns * @since 8.2 */ public class LongSummaryStatisticsExternalizer extends AbstractExternalizer<LongSummaryStatistics> { static final Field countField; static final Field sumField; static final Field minField; static final Field maxField; static final boolean canSerialize; static final Constructor<LongSummaryStatistics> constructor; static { constructor = SecurityActions .getConstructor(LongSummaryStatistics.class, long.class, long.class, long.class, long.class); if (constructor != null) { // since JDK 10, *SummaryStatistics have parametrized constructors, so reflection can be avoided countField = null; sumField = null; minField = null; maxField = null; canSerialize = true; } else { countField = SecurityActions.getField(LongSummaryStatistics.class, "count"); sumField = SecurityActions.getField(LongSummaryStatistics.class, "sum"); minField = SecurityActions.getField(LongSummaryStatistics.class, "min"); maxField = SecurityActions.getField(LongSummaryStatistics.class, "max"); // We can only properly serialize if all of the fields are non null canSerialize = countField != null && sumField != null && minField != null && maxField != null; } } @Override public Set<Class<? extends LongSummaryStatistics>> getTypeClasses() { return Util.<Class<? extends LongSummaryStatistics>>asSet(LongSummaryStatistics.class); } private void verifySerialization() { if (!canSerialize) { throw new NotSerializableException("LongSummaryStatistics is not serializable, fields not available!"); } } @Override public void writeObject(ObjectOutput output, LongSummaryStatistics object) throws IOException { verifySerialization(); output.writeLong(object.getCount()); output.writeLong(object.getSum()); output.writeLong(object.getMin()); output.writeLong(object.getMax()); } @Override public LongSummaryStatistics readObject(ObjectInput input) throws IOException, ClassNotFoundException { verifySerialization(); final LongSummaryStatistics summaryStatistics; final long count = input.readLong(); final long sum = input.readLong(); final long min = input.readLong(); final long max = input.readLong(); if (constructor != null) { // JDK 10+, pass values to constructor try { summaryStatistics = constructor.newInstance(count, min, max, sum); } catch (ReflectiveOperationException e) { throw new IOException(e); } } else { // JDK 9 or older, fall back to reflection summaryStatistics = new LongSummaryStatistics(); try { countField.setLong(summaryStatistics, count); sumField.setLong(summaryStatistics, sum); minField.setLong(summaryStatistics, min); maxField.setLong(summaryStatistics, max); } catch (IllegalAccessException e) { // This can't happen as we force accessibility in the getField throw new IOException(e); } } return summaryStatistics; } @Override public Integer getId() { return Ids.LONG_SUMMARY_STATISTICS; } }
3,964
33.780702
114
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/DoubleSummaryStatisticsExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.DoubleSummaryStatistics; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.NotSerializableException; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; /** * Externalizer used for {@link DoubleSummaryStatistics}. Note this assumes given fields have specific names to use * through reflection. * * @author wburns * @since 8.2 */ public class DoubleSummaryStatisticsExternalizer extends AbstractExternalizer<DoubleSummaryStatistics> { private final static String CONSTRUCTOR_CALL_ERROR_MSG = "Unable to create instance of %s via [%s] with parameters (%s, %s, %s, %s)"; static final Field countField; static final Field sumField; static final Field minField; static final Field maxField; static final boolean canSerialize; static final Constructor<DoubleSummaryStatistics> constructor; static { constructor = SecurityActions.getConstructor( DoubleSummaryStatistics.class, long.class, double.class, double.class, double.class); if (constructor != null) { // since JDK 10, *SummaryStatistics have parametrized constructors, so reflection can be avoided countField = null; sumField = null; minField = null; maxField = null; canSerialize = true; } else { countField = SecurityActions.getField(DoubleSummaryStatistics.class, "count"); sumField = SecurityActions.getField(DoubleSummaryStatistics.class, "sum"); minField = SecurityActions.getField(DoubleSummaryStatistics.class, "min"); maxField = SecurityActions.getField(DoubleSummaryStatistics.class, "max"); // We can only properly serialize if all of the fields are non null canSerialize = countField != null && sumField != null && minField != null && maxField != null; } } @Override public Set<Class<? extends DoubleSummaryStatistics>> getTypeClasses() { return Util.<Class<? extends DoubleSummaryStatistics>>asSet(DoubleSummaryStatistics.class); } private void verifySerialization() { if (!canSerialize) { throw new NotSerializableException("DoubleSummaryStatistics is not serializable, fields not available!"); } } @Override public void writeObject(ObjectOutput output, DoubleSummaryStatistics object) throws IOException { verifySerialization(); output.writeLong(object.getCount()); output.writeDouble(object.getSum()); // To stay backward compatible with older versions of infinispan, write 0s for the compensation and simpleSum // fields. The API doesn't allow for obtaining nor setting values of these _implementation specific_ fields. // This means precision can be lost. output.writeDouble(0); // sumCompensation output.writeDouble(0); // simpleSum output.writeDouble(object.getMin()); output.writeDouble(object.getMax()); } @Override public DoubleSummaryStatistics readObject(ObjectInput input) throws IOException, ClassNotFoundException { verifySerialization(); final DoubleSummaryStatistics summaryStatistics; final long count = input.readLong(); final double sum = input.readDouble(); final double sumCompensation = input.readDouble(); // ignored, see writeObject() final double simpleSum = input.readDouble(); // ignored, see writeObject() final double min = input.readDouble(); final double max = input.readDouble(); if (constructor != null) { // JDK 10+, pass values to constructor try { summaryStatistics = constructor.newInstance(count, min, max, sum); } catch (ReflectiveOperationException e) { throw new IOException(String.format(CONSTRUCTOR_CALL_ERROR_MSG, DoubleSummaryStatistics.class, constructor.toString(), count, min, max, sum), e); } } else { // JDK 9 or older, fall back to reflection summaryStatistics = new DoubleSummaryStatistics(); try { countField.setLong(summaryStatistics, count); sumField.setDouble(summaryStatistics, sum); minField.setDouble(summaryStatistics, min); maxField.setDouble(summaryStatistics, max); } catch (IllegalAccessException e) { // This can't happen as we force accessibility in the getField throw new IOException(e); } } return summaryStatistics; } @Override public Integer getId() { return Ids.DOUBLE_SUMMARY_STATISTICS; } }
4,854
37.531746
116
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/TriangleAckExternalizer.java
package org.infinispan.marshall.exts; import static org.infinispan.commons.marshall.Ids.TRIANGLE_ACK_EXTERNALIZER; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import org.infinispan.commands.remote.CacheRpcCommand; import org.infinispan.commands.write.BackupAckCommand; import org.infinispan.commands.write.BackupMultiKeyAckCommand; import org.infinispan.commands.write.ExceptionAckCommand; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.util.ByteString; /** * Externalizer for the triangle acknowledges. * * @author Pedro Ruivo * @since 9.0 */ public class TriangleAckExternalizer implements AdvancedExternalizer<CacheRpcCommand> { public Set<Class<? extends CacheRpcCommand>> getTypeClasses() { //noinspection unchecked return Util.asSet(BackupAckCommand.class, ExceptionAckCommand.class, BackupMultiKeyAckCommand.class); } public Integer getId() { return TRIANGLE_ACK_EXTERNALIZER; } public void writeObject(ObjectOutput output, CacheRpcCommand object) throws IOException { output.writeByte(object.getCommandId()); ByteString.writeObject(output, object.getCacheName()); object.writeTo(output); } public CacheRpcCommand readObject(ObjectInput input) throws IOException, ClassNotFoundException { switch (input.readByte()) { case BackupAckCommand.COMMAND_ID: return backupAckCommand(input); case ExceptionAckCommand.COMMAND_ID: return exceptionAckCommand(input); case BackupMultiKeyAckCommand.COMMAND_ID: return backupMultiKeyAckCommand(input); default: throw new IllegalStateException(); } } private BackupMultiKeyAckCommand backupMultiKeyAckCommand(ObjectInput input) throws IOException, ClassNotFoundException { BackupMultiKeyAckCommand command = new BackupMultiKeyAckCommand(ByteString.readObject(input)); command.readFrom(input); return command; } private ExceptionAckCommand exceptionAckCommand(ObjectInput input) throws IOException, ClassNotFoundException { ExceptionAckCommand command = new ExceptionAckCommand(ByteString.readObject(input)); command.readFrom(input); return command; } private BackupAckCommand backupAckCommand(ObjectInput input) throws IOException, ClassNotFoundException { BackupAckCommand command = new BackupAckCommand(ByteString.readObject(input)); command.readFrom(input); return command; } }
2,615
34.835616
114
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/EnumSetExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.AbstractSet; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; import net.jcip.annotations.Immutable; /** * {@link EnumSet} externalizer. * * @author Galder Zamarreño * @since 6.0 */ @Immutable public class EnumSetExternalizer extends AbstractExternalizer<Set> { private static final int UNKNOWN_ENUM_SET = 0; private static final int ENUM_SET = 1; private static final int REGULAR_ENUM_SET = 2; private static final int JUMBO_ENUM_SET = 3; private static final int MINI_ENUM_SET = 4; // IBM class private static final int HUGE_ENUM_SET = 5; // IBM class private final Map<Class<?>, Integer> numbers = new HashMap<>(3); public EnumSetExternalizer() { numbers.put(EnumSet.class, ENUM_SET); addEnumSetClass(getRegularEnumSetClass(), REGULAR_ENUM_SET); addEnumSetClass(getJumboEnumSetClass(), JUMBO_ENUM_SET); addEnumSetClass(getMiniEnumSetClass(), MINI_ENUM_SET); addEnumSetClass(getHugeEnumSetClass(), HUGE_ENUM_SET); } private void addEnumSetClass(Class<EnumSet> clazz, int index) { if (clazz != null) numbers.put(clazz, index); } @Override public void writeObject(ObjectOutput output, Set set) throws IOException { Integer number = numbers.get(set.getClass()); if (number == null) { // Fallback on standard object write output.writeObject(set); } else { output.writeByte(number); UnsignedNumeric.writeUnsignedInt(output, set.size()); for (Object o : set) { output.writeObject(o); } } } @Override public Set readObject(ObjectInput input) throws IOException, ClassNotFoundException { int magicNumber = input.readUnsignedByte(); if (magicNumber == UNKNOWN_ENUM_SET) return (Set) input.readObject(); AbstractSet<Enum> enumSet = null; int size = UnsignedNumeric.readUnsignedInt(input); for (int i = 0; i < size; i++) { switch (magicNumber) { case ENUM_SET: case REGULAR_ENUM_SET: case JUMBO_ENUM_SET: case MINI_ENUM_SET: case HUGE_ENUM_SET: if (i == 0) enumSet = EnumSet.of((Enum) input.readObject()); else enumSet.add((Enum) input.readObject()); break; } } return enumSet; } @Override public Integer getId() { return Ids.ENUM_SET_ID; } @Override public Set<Class<? extends Set>> getTypeClasses() { Set<Class<? extends Set>> set = new HashSet<Class<? extends Set>>(); set.add(EnumSet.class); addEnumSetType(getRegularEnumSetClass(), set); addEnumSetType(getJumboEnumSetClass(), set); addEnumSetType(getMiniEnumSetClass(), set); addEnumSetType(getHugeEnumSetClass(), set); return set; } private void addEnumSetType(Class<? extends Set> clazz, Set<Class<? extends Set>> typeSet) { if (clazz != null) typeSet.add(clazz); } private Class<EnumSet> getJumboEnumSetClass() { return getEnumSetClass("java.util.JumboEnumSet"); } private Class<EnumSet> getRegularEnumSetClass() { return getEnumSetClass("java.util.RegularEnumSet"); } private Class<EnumSet> getMiniEnumSetClass() { return getEnumSetClass("java.util.MiniEnumSet"); } private Class<EnumSet> getHugeEnumSetClass() { return getEnumSetClass("java.util.HugeEnumSet"); } private Class<EnumSet> getEnumSetClass(String className) { try { return Util.loadClassStrict(className, EnumSet.class.getClassLoader()); } catch (ClassNotFoundException e) { return null; // Ignore } } }
4,123
28.884058
95
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/EnumExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; import org.infinispan.topology.RebalancingStatus; import org.infinispan.xsite.statetransfer.StateTransferStatus; import org.infinispan.xsite.status.BringSiteOnlineResponse; import org.infinispan.xsite.status.SiteState; import org.infinispan.xsite.status.TakeSiteOfflineResponse; /** * An externalizer for internal enum types. * * @author Ryan Emerson * @since 10.0 */ public class EnumExternalizer implements AdvancedExternalizer<Enum<?>> { public static final EnumExternalizer INSTANCE = new EnumExternalizer(); @Override public Set<Class<? extends Enum<?>>> getTypeClasses() { return Util.asSet( RebalancingStatus.class, BringSiteOnlineResponse.class, TakeSiteOfflineResponse.class, SiteState.class, StateTransferStatus.class ); } @Override public Integer getId() { return Ids.INTERNAL_ENUMS; } @Override public void writeObject(ObjectOutput output, Enum<?> e) throws IOException { output.writeObject(e.getClass()); output.writeUTF(e.name()); } @Override public Enum<?> readObject(ObjectInput input) throws IOException, ClassNotFoundException { Class enumClass = (Class) input.readObject(); String name = input.readUTF(); return Enum.valueOf(enumClass, name); } }
1,614
27.839286
92
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/MetaParamExternalizers.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.functional.MetaParam.MetaEntryVersion; import org.infinispan.functional.MetaParam.MetaLifespan; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.functional.MetaParam.MetaMaxIdle; import org.infinispan.marshall.core.Ids; public final class MetaParamExternalizers { private MetaParamExternalizers() { // Do not instantiate } public static final class LifespanExternalizer extends AbstractExternalizer<MetaLifespan> { @Override public void writeObject(ObjectOutput output, MetaLifespan object) throws IOException { output.writeLong(object.get()); } @Override public MetaLifespan readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new MetaLifespan(input.readLong()); } @Override public Set<Class<? extends MetaLifespan>> getTypeClasses() { return Util.<Class<? extends MetaLifespan>>asSet(MetaLifespan.class); } @Override public Integer getId() { return Ids.META_LIFESPAN; } } public static final class MaxIdleExternalizer extends AbstractExternalizer<MetaMaxIdle> { @Override public void writeObject(ObjectOutput output, MetaMaxIdle object) throws IOException { output.writeLong(object.get()); } @Override public MetaMaxIdle readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new MetaMaxIdle(input.readLong()); } @Override public Set<Class<? extends MetaMaxIdle>> getTypeClasses() { return Util.<Class<? extends MetaMaxIdle>>asSet(MetaMaxIdle.class); } @Override public Integer getId() { return Ids.META_MAX_IDLE; } } public static final class EntryVersionParamExternalizer extends AbstractExternalizer<MetaEntryVersion> { @Override public void writeObject(ObjectOutput output, MetaEntryVersion object) throws IOException { output.writeObject(object.get()); } @Override public MetaEntryVersion readObject(ObjectInput input) throws IOException, ClassNotFoundException { EntryVersion entryVersion = (EntryVersion) input.readObject(); return new MetaEntryVersion(entryVersion); } @Override public Set<Class<? extends MetaEntryVersion>> getTypeClasses() { return Util.<Class<? extends MetaEntryVersion>>asSet(MetaEntryVersion.class); } @Override public Integer getId() { return Ids.META_ENTRY_VERSION; } } }
2,842
30.588889
107
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/ReplicableCommandExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Set; import org.infinispan.commands.RemoteCommandsFactory; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.TopologyAffectedCommand; 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.read.GetKeyValueCommand; import org.infinispan.commands.remote.CacheRpcCommand; 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.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.commons.marshall.AbstractExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.expiration.impl.TouchCommand; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.impl.ReplicableManagerFunctionCommand; import org.infinispan.manager.impl.ReplicableRunnableCommand; import org.infinispan.marshall.core.Ids; import org.infinispan.topology.HeartBeatCommand; import org.infinispan.util.ByteString; import org.infinispan.xsite.commands.XSiteViewNotificationCommand; /** * ReplicableCommandExternalizer. * * @author Galder Zamarreño * @since 4.0 */ public class ReplicableCommandExternalizer extends AbstractExternalizer<ReplicableCommand> { private final RemoteCommandsFactory cmdFactory; private final GlobalComponentRegistry globalComponentRegistry; public ReplicableCommandExternalizer(RemoteCommandsFactory cmdFactory, GlobalComponentRegistry globalComponentRegistry) { this.cmdFactory = cmdFactory; this.globalComponentRegistry = globalComponentRegistry; } @Override public void writeObject(ObjectOutput output, ReplicableCommand command) throws IOException { writeCommandHeader(output, command); writeCommandParameters(output, command); } protected void writeCommandParameters(ObjectOutput output, ReplicableCommand command) throws IOException { command.writeTo(output); if (command instanceof TopologyAffectedCommand) { output.writeInt(((TopologyAffectedCommand) command).getTopologyId()); } } protected void writeCommandHeader(ObjectOutput output, ReplicableCommand command) throws IOException { // To decide whether it's a core or user defined command, load them all and check Collection<Class<? extends ReplicableCommand>> moduleCommands = getModuleCommands(); // Write an indexer to separate commands defined external to the // infinispan core module from the ones defined via module commands if (moduleCommands != null && moduleCommands.contains(command.getClass())) output.writeByte(1); else output.writeByte(0); output.writeShort(command.getCommandId()); } @Override public ReplicableCommand readObject(ObjectInput input) throws IOException, ClassNotFoundException { ReplicableCommand replicableCommand = readCommandHeader(input); readCommandParameters(input, replicableCommand); return replicableCommand; } private ReplicableCommand readCommandHeader(ObjectInput input) throws IOException { byte type = input.readByte(); short methodId = input.readShort(); return cmdFactory.fromStream((byte) methodId, type); } void readCommandParameters(ObjectInput input, ReplicableCommand command) throws IOException, ClassNotFoundException { command.readFrom(input); if (command instanceof TopologyAffectedCommand) { ((TopologyAffectedCommand) command).setTopologyId(input.readInt()); } } protected CacheRpcCommand fromStream(byte id, byte type, ByteString cacheName) { return cmdFactory.fromStream(id, type, cacheName); } @Override public Integer getId() { return Ids.REPLICABLE_COMMAND; } @Override public Set<Class<? extends ReplicableCommand>> getTypeClasses() { Set<Class<? extends ReplicableCommand>> coreCommands = Util.asSet( GetKeyValueCommand.class, ClearCommand.class, EvictCommand.class, InvalidateCommand.class, InvalidateL1Command.class, PutKeyValueCommand.class, PutMapCommand.class, RemoveCommand.class, RemoveExpiredCommand.class, ReplaceCommand.class, ComputeCommand.class, ComputeIfAbsentCommand.class, ReadOnlyKeyCommand.class, ReadOnlyManyCommand.class, ReadWriteKeyCommand.class, ReadWriteKeyValueCommand.class, WriteOnlyKeyCommand.class, WriteOnlyKeyValueCommand.class, WriteOnlyManyCommand.class, WriteOnlyManyEntriesCommand.class, ReadWriteManyCommand.class, ReadWriteManyEntriesCommand.class, TxReadOnlyKeyCommand.class, TxReadOnlyManyCommand.class, ReplicableRunnableCommand.class, ReplicableManagerFunctionCommand.class, HeartBeatCommand.class, CacheStatusRequestCommand.class, RebalancePhaseConfirmCommand.class, TopologyUpdateCommand.class, RebalancePolicyUpdateCommand.class, RebalanceStartCommand.class, RebalanceStatusRequestCommand.class, CacheShutdownCommand.class, CacheShutdownRequestCommand.class, TopologyUpdateStableCommand.class, CacheJoinCommand.class, CacheLeaveCommand.class, CacheAvailabilityUpdateCommand.class, IracPutKeyValueCommand.class, TouchCommand.class, XSiteViewNotificationCommand.class); // Search only those commands that replicable and not cache specific replicable commands Collection<Class<? extends ReplicableCommand>> moduleCommands = globalComponentRegistry.getModuleProperties().moduleOnlyReplicableCommands(); if (!moduleCommands.isEmpty()) coreCommands.addAll(moduleCommands); return coreCommands; } private Collection<Class<? extends ReplicableCommand>> getModuleCommands() { return globalComponentRegistry.getModuleProperties().moduleCommands(); } }
8,061
47.566265
147
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/UuidExternalizer.java
package org.infinispan.marshall.exts; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.marshall.core.Ids; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import java.util.UUID; public final class UuidExternalizer extends AbstractExternalizer<UUID> { @Override public Set<Class<? extends UUID>> getTypeClasses() { return Collections.<Class<? extends UUID>>singleton(UUID.class); } @Override public Integer getId() { return Ids.UUID; } @Override public void writeObject(ObjectOutput output, UUID object) throws IOException { MarshallUtil.marshallUUID(object, output, false); } @Override public UUID readObject(ObjectInput input) throws IOException { return MarshallUtil.unmarshallUUID(input, false); } }
946
24.594595
81
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/exts/MapExternalizer.java
package org.infinispan.marshall.exts; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.util.FastCopyHashMap; import org.infinispan.commons.util.Util; import org.infinispan.distribution.util.ReadOnlySegmentAwareMap; import org.infinispan.marshall.core.Ids; /** * Map externalizer for all map implementations except immutable maps and singleton maps, i.e. FastCopyHashMap, HashMap, * TreeMap. * * @author Galder Zamarreño * @since 4.0 * */ public class MapExternalizer extends AbstractExternalizer<Map> { private static final int HASHMAP = 0; private static final int TREEMAP = 1; private static final int FASTCOPYHASHMAP = 2; private static final int EQUIVALENTHASHMAP = 3; private static final int CONCURRENTHASHMAP = 4; // 5 reserved for the removed EntryVersionsMap private static final int SINGLETONMAP = 6; private static final int EMPTYMAP = 7; private final Map<Class<?>, Integer> numbers = new HashMap<>(8); public MapExternalizer() { numbers.put(HashMap.class, HASHMAP); numbers.put(ReadOnlySegmentAwareMap.class, HASHMAP); numbers.put(TreeMap.class, TREEMAP); numbers.put(FastCopyHashMap.class, FASTCOPYHASHMAP); numbers.put(ConcurrentHashMap.class, CONCURRENTHASHMAP); numbers.put(getPrivateSingletonMapClass(), SINGLETONMAP); numbers.put(getPrivateEmptyMapClass(), EMPTYMAP); } @Override public void writeObject(ObjectOutput output, Map map) throws IOException { int number = numbers.getOrDefault(map.getClass(), -1); output.write(number); switch (number) { case HASHMAP: case TREEMAP: case CONCURRENTHASHMAP: MarshallUtil.marshallMap(map, output); break; case FASTCOPYHASHMAP: //copy the map to avoid ConcurrentModificationException MarshallUtil.marshallMap(((FastCopyHashMap<?, ?>) map).clone(), output); break; case SINGLETONMAP: Map.Entry singleton = (Map.Entry) map.entrySet().iterator().next(); output.writeObject(singleton.getKey()); output.writeObject(singleton.getValue()); break; default: break; } } @Override public Map readObject(ObjectInput input) throws IOException, ClassNotFoundException { int magicNumber = input.readUnsignedByte(); switch (magicNumber) { case HASHMAP: return MarshallUtil.unmarshallMap(input, HashMap::new); case TREEMAP: return MarshallUtil.unmarshallMap(input, size -> new TreeMap<>()); case FASTCOPYHASHMAP: return MarshallUtil.unmarshallMap(input, FastCopyHashMap::new); case CONCURRENTHASHMAP: return MarshallUtil.unmarshallMap(input, ConcurrentHashMap::new); case SINGLETONMAP: return Collections.singletonMap(input.readObject(), input.readObject()); case EMPTYMAP: return Collections.emptyMap(); default: throw new IllegalStateException("Unknown Map type: " + magicNumber); } } @Override public Integer getId() { return Ids.MAPS; } @Override public Set<Class<? extends Map>> getTypeClasses() { Set<Class<? extends Map>> typeClasses = Util.asSet( HashMap.class, TreeMap.class, FastCopyHashMap.class, ReadOnlySegmentAwareMap.class, ConcurrentHashMap.class); typeClasses.addAll(getSupportedPrivateClasses()); return typeClasses; } /** * Returns an immutable Set that contains all of the private classes (e.g. java.util.Collections$EmptyMap) that * are supported by this Externalizer. This method is to be used by external sources if these private classes * need additional processing to be available. * @return immutable set of the private classes */ public static Set<Class<? extends Map>> getSupportedPrivateClasses() { Set<Class<? extends Map>> classNames = new HashSet<>(Arrays.asList( getPrivateSingletonMapClass(), getPrivateEmptyMapClass() )); return Collections.unmodifiableSet(classNames); } private static Class<? extends Map> getPrivateSingletonMapClass() { return getMapClass("java.util.Collections$SingletonMap"); } private static Class<? extends Map> getPrivateEmptyMapClass() { return getMapClass("java.util.Collections$EmptyMap"); } private static Class<? extends Map> getMapClass(String className) { return Util.loadClass(className, Map.class.getClassLoader()); } }
4,986
35.40146
120
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/protostream/impl/AbstractInternalProtoStreamMarshaller.java
package org.infinispan.marshall.protostream.impl; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.io.LazyByteArrayOutputStream; import org.infinispan.commons.marshall.BufferSizePredictor; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.MarshallingException; import org.infinispan.commons.marshall.StreamAwareMarshaller; 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.protostream.ImmutableSerializationContext; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.util.logging.Log; /** * An abstract ProtoStream based {@link Marshaller} and {@link StreamAwareMarshaller} implementation that is the basis * of the Persistence and Global marshallers. * * @author Ryan Emerson * @since 12.0 */ @Scope(Scopes.GLOBAL) public abstract class AbstractInternalProtoStreamMarshaller implements Marshaller, StreamAwareMarshaller { private static final int PROTOSTREAM_DEFAULT_BUFFER_SIZE = 4096; @Inject protected SerializationContextRegistry ctxRegistry; @Inject @ComponentName(KnownComponentNames.USER_MARSHALLER) ComponentRef<Marshaller> userMarshallerRef; protected Marshaller userMarshaller; protected Log log; abstract public ImmutableSerializationContext getSerializationContext(); protected AbstractInternalProtoStreamMarshaller(Log log) { this.log = log; } @Start @Override public void start() { userMarshaller = userMarshallerRef.running(); } public Marshaller getUserMarshaller() { return userMarshaller; } private LazyByteArrayOutputStream objectToOutputStream(Object obj, int estimatedSize) { if (obj == null) return null; try { if (requiresWrapping(obj)) obj = new MarshallableUserObject<>(obj); int size = estimatedSize < 0 ? PROTOSTREAM_DEFAULT_BUFFER_SIZE : estimatedSize; LazyByteArrayOutputStream baos = new LazyByteArrayOutputStream(size); ProtobufUtil.toWrappedStream(getSerializationContext(), baos, obj, size); return baos; } catch (Throwable t) { log.cannotMarshall(obj.getClass(), t); if (t instanceof MarshallingException) throw (MarshallingException) t; throw new MarshallingException(t.getMessage(), t.getCause()); } } @Override public ByteBuffer objectToBuffer(Object o) { LazyByteArrayOutputStream objectStream = objectToOutputStream(o, -1); return ByteBufferImpl.create(objectStream.getRawBuffer(), 0, objectStream.size()); } @Override public byte[] objectToByteBuffer(Object obj, int estimatedSize) { return objectToOutputStream(obj, estimatedSize).getTrimmedBuffer(); } @Override public byte[] objectToByteBuffer(Object obj) { return objectToByteBuffer(obj, sizeEstimate(obj)); } @Override public Object objectFromByteBuffer(byte[] buf) throws IOException { return objectFromByteBuffer(buf, 0, buf.length); } @Override public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException { return unwrapAndInit(ProtobufUtil.fromWrappedByteArray(getSerializationContext(), buf, offset, length)); } @Override public BufferSizePredictor getBufferSizePredictor(Object o) { // TODO if protobuf based, return estimate based upon schema return userMarshaller.getBufferSizePredictor(o); } @Override public void writeObject(Object o, OutputStream out) throws IOException { if (requiresWrapping(o)) o = new MarshallableUserObject<>(o); ProtobufUtil.toWrappedStream(getSerializationContext(), out, o, PROTOSTREAM_DEFAULT_BUFFER_SIZE); } @Override public Object readObject(InputStream in) throws ClassNotFoundException, IOException { return unwrapAndInit(ProtobufUtil.fromWrappedStream(getSerializationContext(), in)); } protected Object unwrapAndInit(Object o) { if (o instanceof MarshallableUserObject) return ((MarshallableUserObject<?>) o).get(); return o; } @Override public boolean isMarshallable(Object o) { return isMarshallableWithProtoStream(o) || isUserMarshallable(o); } @Override public int sizeEstimate(Object o) { if (isMarshallableWithProtoStream(o)) return PROTOSTREAM_DEFAULT_BUFFER_SIZE; int userBytesEstimate = userMarshaller.getBufferSizePredictor(o.getClass()).nextSize(o); return MarshallableUserObject.size(userBytesEstimate); } @Override public MediaType mediaType() { return MediaType.APPLICATION_PROTOSTREAM; } private boolean requiresWrapping(Object o) { return !isMarshallableWithProtoStream(o); } private boolean isMarshallableWithProtoStream(Object o) { return getSerializationContext().canMarshall(o.getClass()); } private boolean isUserMarshallable(Object o) { try { return userMarshaller.isMarshallable(o); } catch (Exception ignore) { return false; } } }
5,568
32.751515
118
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/protostream/impl/package-info.java
/** * @api.private */ package org.infinispan.marshall.protostream.impl;
74
14
49
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/protostream/impl/SerializationContextRegistry.java
package org.infinispan.marshall.protostream.impl; import org.infinispan.protostream.BaseMarshaller; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.ImmutableSerializationContext; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; /** * Manages {@link SerializationContext} across modules for use by various components. The user context should only * ever be updated using the {@link org.infinispan.configuration.global.GlobalConfiguration}, therefore we do not expose * it via {@link MarshallerType}. * * @author Ryan Emerson * @since 10.0 */ public interface SerializationContextRegistry { void addProtoFile(MarshallerType type, FileDescriptorSource fileDescriptorSource); void removeProtoFile(MarshallerType type, String fileName); void addMarshaller(MarshallerType type, BaseMarshaller marshaller); void addContextInitializer(MarshallerType type, SerializationContextInitializer sci); ImmutableSerializationContext getGlobalCtx(); ImmutableSerializationContext getPersistenceCtx(); ImmutableSerializationContext getUserCtx(); enum MarshallerType { GLOBAL, PERSISTENCE, USER } }
1,257
31.25641
120
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/protostream/impl/MarshallableUserObject.java
package org.infinispan.marshall.protostream.impl; import org.infinispan.commons.CacheException; import org.infinispan.commons.marshall.MarshallingException; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Util; import org.infinispan.protostream.BaseMarshaller; import org.infinispan.protostream.ProtobufTagMarshaller; import org.infinispan.protostream.TagReader; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.protostream.descriptors.WireType; import java.io.IOException; import java.util.Objects; /** * A wrapper message used by ProtoStream Marshallers to allow user objects to be marshalled/unmarshalled via the {@link * MarshallableUserObject.Marshaller} implementation, which delegates to the configured user marshaller in {@link * org.infinispan.configuration.global.SerializationConfiguration} if it exists. * <p> * This abstraction hides the details of the configured user marshaller from our internal Pojos, so that all calls to * the configured user marshaller can be limited to the {@link MarshallableUserObject.Marshaller} instance. * <p> * In order to allow this object to be utilised by our internal ProtoStream annotated Pojos, we need to generate the * proto schema for this object using the protostream-processor and {@link org.infinispan.protostream.annotations.AutoProtoSchemaBuilder}. * Consequently, it's necessary for the generated marshaller to be overridden, therefore calls to {@link * org.infinispan.protostream.SerializationContext#registerMarshaller(BaseMarshaller)} must be made after the * registration of any generated {@link org.infinispan.protostream.SerializationContextInitializer}'s that contain this * class. To ensure that the marshaller generated for this class is never used, we throw a {@link IllegalStateException} * if the {@link ProtoFactory} constructor is called. * * @author Ryan Emerson * @since 10.0 */ @ProtoTypeId(ProtoStreamTypeIds.MARSHALLABLE_USER_OBJECT) public class MarshallableUserObject<T> { private final T object; @ProtoFactory MarshallableUserObject(byte[] bytes) { // no-op never actually used, as we override the default marshaller throw new IllegalStateException(this.getClass().getSimpleName() + " marshaller not overridden in SerializationContext"); } public MarshallableUserObject(T object) { this.object = object; } @ProtoField(1) byte[] getBytes() { return Util.EMPTY_BYTE_ARRAY; } public T get() { return object; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MarshallableUserObject other = (MarshallableUserObject) o; return Objects.equals(object, other.object); } @Override public int hashCode() { return object != null ? object.hashCode() : 0; } public static int size(int objectBytes) { int typeId = ProtoStreamTypeIds.MARSHALLABLE_USER_OBJECT; int typeIdSize = tagSize(19, 1) + computeUInt32SizeNoTag(typeId); int userBytesFieldSize = tagSize(1, 2) + computeUInt32SizeNoTag(objectBytes) + objectBytes; int wrappedMessageSize = tagSize(17, 2) + computeUInt32SizeNoTag(objectBytes); return typeIdSize + userBytesFieldSize + wrappedMessageSize; } private static int tagSize(int fieldNumber, int wireType) { return computeUInt32SizeNoTag(fieldNumber << 3 | wireType); } // Protobuf logic included to avoid requiring a dependency on com.google.protobuf.CodedOutputStream private static int computeUInt32SizeNoTag(int value) { if ((value & -128) == 0) { return 1; } else if ((value & -16384) == 0) { return 2; } else if ((value & -2097152) == 0) { return 3; } else { return (value & -268435456) == 0 ? 4 : 5; } } public static class Marshaller implements ProtobufTagMarshaller<MarshallableUserObject> { private final String typeName; private final org.infinispan.commons.marshall.Marshaller userMarshaller; public Marshaller(String typeName, org.infinispan.commons.marshall.Marshaller userMarshaller) { this.typeName = typeName; this.userMarshaller = userMarshaller; } @Override public Class<MarshallableUserObject> getJavaClass() { return MarshallableUserObject.class; } @Override public String getTypeName() { return typeName; } @Override public MarshallableUserObject read(ReadContext ctx) throws IOException { TagReader in = ctx.getReader(); try { byte[] bytes = null; boolean done = false; while (!done) { final int tag = in.readTag(); switch (tag) { // end of message case 0: done = true; break; // field number 1 case 1 << WireType.TAG_TYPE_NUM_BITS | WireType.WIRETYPE_LENGTH_DELIMITED: { bytes = in.readByteArray(); break; } default: { if (!in.skipField(tag)) done = true; } } } Object userObject = userMarshaller.objectFromByteBuffer(bytes); return new MarshallableUserObject<>(userObject); } catch (ClassNotFoundException e) { throw new MarshallingException(e); } } @Override public void write(WriteContext ctx, MarshallableUserObject marshallableUserObject) throws IOException { try { Object userObject = marshallableUserObject.get(); byte[] bytes = userMarshaller.objectToByteBuffer(userObject); // field number 1 ctx.getWriter().writeBytes(1, bytes); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } } } }
6,203
37.534161
138
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/protostream/impl/SerializationContextRegistryImpl.java
package org.infinispan.marshall.protostream.impl; import static org.infinispan.marshall.protostream.impl.SerializationContextRegistry.MarshallerType.GLOBAL; import static org.infinispan.marshall.protostream.impl.SerializationContextRegistry.MarshallerType.PERSISTENCE; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.UserContextInitializerImpl; import org.infinispan.commons.util.ServiceFinder; import org.infinispan.configuration.global.GlobalConfiguration; 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.marshall.persistence.impl.PersistenceContextInitializer; import org.infinispan.marshall.persistence.impl.PersistenceContextInitializerImpl; import org.infinispan.protostream.BaseMarshaller; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.ImmutableSerializationContext; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.types.java.CommonContainerTypesSchema; import org.infinispan.protostream.types.java.CommonTypesSchema; @Scope(Scopes.GLOBAL) public class SerializationContextRegistryImpl implements SerializationContextRegistry { @Inject GlobalConfiguration globalConfig; @Inject @ComponentName(KnownComponentNames.USER_MARSHALLER) ComponentRef<Marshaller> userMarshaller; private final MarshallerContext global = new MarshallerContext(); private final MarshallerContext persistence = new MarshallerContext(); private final MarshallerContext user = new MarshallerContext(); @Start public void start() { user.addContextInitializer(new CommonTypesSchema()); user.addContextInitializer(new CommonContainerTypesSchema()); user.addContextInitializer(new UserContextInitializerImpl()); // Add user configured SCIs Collection<SerializationContextInitializer> initializers = globalConfig.serialization().contextInitializers(); if (initializers == null || initializers.isEmpty()) { // If no SCIs have been explicitly configured, then load all available SCI services initializers = ServiceFinder.load(SerializationContextInitializer.class, globalConfig.classLoader()); } initializers.forEach(user::addContextInitializer); String messageName = PersistenceContextInitializer.getFqTypeName(MarshallableUserObject.class); BaseMarshaller userObjectMarshaller = new MarshallableUserObject.Marshaller(messageName, userMarshaller.wired()); update(GLOBAL, ctx -> ctx.addContextInitializer(new PersistenceContextInitializerImpl()) .addContextInitializer(new org.infinispan.commons.GlobalContextInitializerImpl()) .addMarshaller(userObjectMarshaller) ); update(PERSISTENCE, ctx -> ctx.addContextInitializer(new PersistenceContextInitializerImpl()) .addMarshaller(userObjectMarshaller) ); } @Override public ImmutableSerializationContext getGlobalCtx() { return global.ctx; } @Override public ImmutableSerializationContext getPersistenceCtx() { return persistence.ctx; } @Override public ImmutableSerializationContext getUserCtx() { return user.ctx; } @Override public void addContextInitializer(MarshallerType type, SerializationContextInitializer sci) { update(type, ctx -> { ctx.addContextInitializer(sci); // Replay any marshaller overrides, e.g. MarshalledUserObject // Necessary because adding a new SCI re-registers the schemas/marshallers of all its dependencies ctx.marshallers.forEach(ctx.ctx::registerMarshaller); }); } @Override public void addProtoFile(MarshallerType type, FileDescriptorSource fileDescriptorSource) { update(type, ctx -> ctx.addProtoFile(fileDescriptorSource)); } @Override public void removeProtoFile(MarshallerType type, String fileName) { update(type, ctx -> ctx.removeProtoFile(fileName)); } @Override public void addMarshaller(MarshallerType type, BaseMarshaller marshaller) { update(type, ctx -> ctx.addMarshaller(marshaller)); } private void update(MarshallerType type, Consumer<MarshallerContext> consumer) { MarshallerContext ctx = type == GLOBAL ? global : type == PERSISTENCE ? persistence : user; synchronized (ctx) { consumer.accept(ctx); } } private static void register(SerializationContextInitializer sci, SerializationContext ctx) { sci.registerSchema(ctx); sci.registerMarshallers(ctx); } // Required until IPROTO-136 is resolved to ensure that custom marshaller implementations are not overridden by // non-core modules registering their SerializationContextInitializer(s) which depend on a core initializer. private static final class MarshallerContext { private final List<BaseMarshaller<?>> marshallers = new ArrayList<>(); private final SerializationContext ctx = ProtobufUtil.newSerializationContext(); MarshallerContext addContextInitializer(SerializationContextInitializer sci) { register(sci, ctx); return this; } MarshallerContext addProtoFile(FileDescriptorSource fileDescriptorSource) { ctx.registerProtoFiles(fileDescriptorSource); return this; } MarshallerContext removeProtoFile(String fileName) { ctx.unregisterProtoFile(fileName); return this; } MarshallerContext addMarshaller(BaseMarshaller marshaller) { marshallers.add(marshaller); ctx.registerMarshaller(marshaller); return this; } } }
6,174
39.625
119
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/package-info.java
/** * @api.public */ package org.infinispan.marshall.persistence;
68
12.8
44
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/PersistenceMarshaller.java
package org.infinispan.marshall.persistence; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.StreamAwareMarshaller; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; /** * The marshaller that is responsible serializing/deserializing objects which are to be persisted. * * @author Ryan Emerson * @since 10.0 */ public interface PersistenceMarshaller extends Marshaller, StreamAwareMarshaller { /** * Registers the schemas and marshallers defined by the provided {@link SerializationContextInitializer} with the * {@link PersistenceMarshaller}'s {@link SerializationContext}. * * @param initializer whose schemas and marshallers' will be registered with the {@link PersistenceMarshaller} {@link * SerializationContext} * @throws NullPointerException if initializer is null. */ void register(SerializationContextInitializer initializer); /** * @return a custom marshaller configured by {@link SerializationContext} if one exists, otherwise the default * ProtoStream based marshaller is returned. */ Marshaller getUserMarshaller(); }
1,225
37.3125
120
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/impl/package-info.java
/** * This package should mainly contain {@link org.infinispan.protostream.MessageMarshaller} implementations for classes * which a static inner class is not possible. For example it's necessary for the {@link org.infinispan.commons.marshall.WrappedByteArray} * marshaller to be in this package as the infinispan-commons module does not contain a dependency on protostream. * * @author Ryan Emerson * @since 10.0 * @api.private */ package org.infinispan.marshall.persistence.impl;
489
43.545455
138
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/impl/PersistenceContextInitializer.java
package org.infinispan.marshall.persistence.impl; import org.infinispan.container.entries.RemoteMetadata; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.container.versioning.SimpleClusteredVersion; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.TopologyIracVersion; import org.infinispan.functional.impl.MetaParamsInternalMetadata; import org.infinispan.marshall.protostream.impl.MarshallableUserObject; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.impl.CacheRoleImpl; import org.infinispan.security.impl.SubjectAdapter; import org.infinispan.security.mappers.ClusterRoleMapper; import org.infinispan.util.ByteString; import org.infinispan.util.logging.events.EventLogCategory; import org.infinispan.util.logging.events.EventLogLevel; /** * Interface used to initialise the {@link PersistenceMarshallerImpl}'s {@link org.infinispan.protostream.SerializationContext} * using the specified Pojos, Marshaller implementations and provided .proto schemas. * * @author Ryan Emerson * @since 10.0 */ @AutoProtoSchemaBuilder( dependsOn = org.infinispan.commons.marshall.PersistenceContextInitializer.class, includeClasses = { ByteString.class, EmbeddedMetadata.class, EmbeddedMetadata.EmbeddedExpirableMetadata.class, EmbeddedMetadata.EmbeddedLifespanExpirableMetadata.class, EmbeddedMetadata.EmbeddedMaxIdleExpirableMetadata.class, EventLogCategory.class, EventLogLevel.class, JGroupsAddress.class, MarshalledValueImpl.class, MetaParamsInternalMetadata.class, NumericVersion.class, RemoteMetadata.class, SimpleClusteredVersion.class, MarshallableUserObject.class, PrivateMetadata.class, IracEntryVersion.class, IracEntryVersion.MapEntry.class, TopologyIracVersion.class, IracMetadata.class, ClusterRoleMapper.RoleSet.class, AuthorizationPermission.class, CacheRoleImpl.class, SubjectAdapter.class }, schemaFileName = "persistence.core.proto", schemaFilePath = "proto/generated", schemaPackageName = PersistenceContextInitializer.PACKAGE_NAME, service = false ) public interface PersistenceContextInitializer extends SerializationContextInitializer { String PACKAGE_NAME = "org.infinispan.persistence.core"; static String getFqTypeName(Class<?> clazz) { return PACKAGE_NAME + "." + clazz.getSimpleName(); } }
3,040
42.442857
127
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/impl/MarshalledValueImpl.java
package org.infinispan.marshall.persistence.impl; import java.util.Objects; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Util; import org.infinispan.persistence.spi.MarshalledValue; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * A marshallable object that can be used by our internal store implementations to store values, metadata and timestamps. * * @author Ryan Emerson * @since 10.0 */ @ProtoTypeId(ProtoStreamTypeIds.MARSHALLED_VALUE_IMPL) public class MarshalledValueImpl implements MarshalledValue { static final MarshalledValue EMPTY = new MarshalledValueImpl(null, null, null, -1, -1); private final ByteBuffer valueBytes; private final ByteBuffer metadataBytes; private final ByteBuffer internalMetadataBytes; private final long created; private final long lastUsed; @ProtoFactory MarshalledValueImpl(byte[] value, byte[] metadata, long created, long lastUsed, byte[] internalMetadata) { this(ByteBufferImpl.create(value), ByteBufferImpl.create(metadata), ByteBufferImpl.create(internalMetadata), created, lastUsed); } MarshalledValueImpl(ByteBuffer valueBytes, ByteBuffer metadataBytes, ByteBuffer internalMetadataBytes, long created, long lastUsed) { this.valueBytes = valueBytes; this.metadataBytes = metadataBytes; this.internalMetadataBytes = internalMetadataBytes; this.created = created; this.lastUsed = lastUsed; } @ProtoField(number = 1, name = "value") byte[] getValue() { return valueBytes == null ? Util.EMPTY_BYTE_ARRAY : MarshallUtil.toByteArray(valueBytes); } @ProtoField(number = 2, name = "metadata") byte[] getMetadata() { return metadataBytes == null ? Util.EMPTY_BYTE_ARRAY : MarshallUtil.toByteArray(metadataBytes); } @Override @ProtoField(number = 3, name = "created", defaultValue = "-1") public long getCreated() { return created; } @Override @ProtoField(number = 4, name = "lastUsed", defaultValue = "-1") public long getLastUsed() { return lastUsed; } @ProtoField(5) byte[] getInternalMetadata() { return internalMetadataBytes == null ? Util.EMPTY_BYTE_ARRAY : MarshallUtil.toByteArray(internalMetadataBytes); } @Override public ByteBuffer getValueBytes() { return valueBytes; } @Override public ByteBuffer getMetadataBytes() { return metadataBytes; } @Override public ByteBuffer getInternalMetadataBytes() { return internalMetadataBytes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MarshalledValueImpl that = (MarshalledValueImpl) o; return created == that.created && lastUsed == that.lastUsed && Objects.equals(valueBytes, that.valueBytes) && Objects.equals(metadataBytes, that.metadataBytes) && Objects.equals(internalMetadataBytes, that.internalMetadataBytes); } @Override public int hashCode() { return Objects.hash(valueBytes, metadataBytes, internalMetadataBytes, created, lastUsed); } @Override public String toString() { return "MarshalledValueImpl{" + "valueBytes=" + valueBytes + ", metadataBytes=" + metadataBytes + ", internalMetadataBytes=" + internalMetadataBytes + ", created=" + created + ", lastUsed=" + lastUsed + '}'; } }
3,804
32.086957
136
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/impl/MarshallableEntryImpl.java
package org.infinispan.marshall.persistence.impl; import static java.lang.Math.min; import java.util.Objects; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.metadata.Metadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.MarshalledValue; import org.infinispan.persistence.spi.PersistenceException; /** * @author Ryan Emerson * @since 10.0 */ public class MarshallableEntryImpl<K, V> implements MarshallableEntry<K, V> { long created; long lastUsed; ByteBuffer valueBytes; ByteBuffer metadataBytes; ByteBuffer internalMetadataBytes; volatile ByteBuffer keyBytes; volatile transient K key; volatile transient V value; volatile transient Metadata metadata; volatile transient PrivateMetadata internalMetadata; transient org.infinispan.commons.marshall.Marshaller marshaller; MarshallableEntryImpl() {} MarshallableEntryImpl(K key, V value, Metadata metadata, PrivateMetadata internalMetadata, long created, long lastUsed, Marshaller marshaller) { this.key = key; this.value = value; this.metadata = metadata; this.internalMetadata = internalMetadata; this.created = created; this.lastUsed = lastUsed; this.marshaller = marshaller; } MarshallableEntryImpl(ByteBuffer key, ByteBuffer valueBytes, ByteBuffer metadataBytes, ByteBuffer internalMetadataBytes, long created, long lastUsed, Marshaller marshaller) { this.keyBytes = key; this.valueBytes = valueBytes; this.metadataBytes = metadataBytes; this.internalMetadataBytes = internalMetadataBytes; this.created = created; this.lastUsed = lastUsed; this.marshaller = marshaller; } MarshallableEntryImpl(K key, ByteBuffer valueBytes, ByteBuffer metadataBytes, ByteBuffer internalMetadataBytes, long created, long lastUsed, Marshaller marshaller) { this((ByteBuffer) null, valueBytes, metadataBytes, internalMetadataBytes, created, lastUsed, marshaller); this.key = key; } @Override public K getKey() { if (key == null) { if (keyBytes == null) { return null; } key = unmarshall(keyBytes); } return key; } @Override public V getValue() { if (value == null) { if (valueBytes == null) { return null; } value = unmarshall(valueBytes); } return value; } @Override public Metadata getMetadata() { if (metadata == null) { if (metadataBytes == null) return null; else metadata = unmarshall(metadataBytes); } return metadata; } @Override public PrivateMetadata getInternalMetadata() { if (internalMetadata == null) { if (internalMetadataBytes == null) return null; else internalMetadata = unmarshall(internalMetadataBytes); } return internalMetadata; } @Override public ByteBuffer getKeyBytes() { if (keyBytes == null) keyBytes = marshall(key, marshaller); return keyBytes; } @Override public ByteBuffer getValueBytes() { if (valueBytes == null) valueBytes = marshall(value, marshaller); return valueBytes; } @Override public ByteBuffer getMetadataBytes() { if (metadataBytes == null) metadataBytes = marshall(metadata, marshaller); return metadataBytes; } @Override public ByteBuffer getInternalMetadataBytes() { if (internalMetadataBytes == null) internalMetadataBytes = marshall(internalMetadata, marshaller); return internalMetadataBytes; } @Override public long created() { return created; } @Override public long lastUsed() { return lastUsed; } @Override public boolean isExpired(long now) { return isExpired(getMetadata(), now, created(), lastUsed()); } public static boolean isExpired(Metadata metadata, long now, long created, long lastUsed) { long expiry = expiryTime(metadata, created, lastUsed); return expiry > 0 && expiry <= now; } @Override public long expiryTime() { return expiryTime(getMetadata(), created(), lastUsed()); } public static long expiryTime(Metadata metadata, long created, long lastUsed) { if (metadata == null) return -1; long lifespan = metadata.lifespan(); long lset = lifespan > -1 ? created + lifespan : -1; long maxIdle = metadata.maxIdle(); long muet = maxIdle > -1 ? lastUsed + maxIdle : -1; if (lset == -1) return muet; if (muet == -1) return lset; return min(lset, muet); } @Override public MarshalledValue getMarshalledValue() { return new MarshalledValueImpl(getValueBytes(), getMetadataBytes(), getInternalMetadataBytes(), created, lastUsed); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MarshallableEntryImpl)) return false; MarshallableEntryImpl<?, ?> that = (MarshallableEntryImpl<?, ?>) o; return Objects.equals(getKeyBytes(), that.getKeyBytes()) && Objects.equals(getMetadataBytes(), that.getMetadataBytes()) && Objects.equals(getInternalMetadata(), that.getInternalMetadata()) && Objects.equals(getValueBytes(), that.getValueBytes()) && expiryTime() == that.expiryTime(); } @Override public int hashCode() { long expiryTime = expiryTime(); int result = getKeyBytes() != null ? getKeyBytes().hashCode() : 0; result = 31 * result + (getValueBytes() != null ? getValueBytes().hashCode() : 0); result = 31 * result + (getMetadataBytes() != null ? getMetadataBytes().hashCode() : 0); result = 31 * result + (getInternalMetadataBytes() != null ? getInternalMetadataBytes().hashCode() : 0); result = 31 * result + (int) (expiryTime ^ (expiryTime >>> 32)); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder().append(this.getClass().getSimpleName()) .append("{keyBytes=").append(keyBytes) .append(", valueBytes=").append(valueBytes) .append(", metadataBytes=").append(metadataBytes) .append(", internalMetadataBytes=").append(internalMetadataBytes) .append(", key=").append(key); if (key == null && keyBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(keyBytes)); } sb.append(", value=").append(value); if (value == null && valueBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(valueBytes)); } sb.append(", metadata=").append(metadata); if (metadata == null && metadataBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(metadataBytes)); } sb.append(", internalMetadata=").append(internalMetadata); if (internalMetadata == null && internalMetadataBytes != null && marshaller != null) { sb.append('/').append(this.<Object>unmarshall(internalMetadataBytes)); } sb.append(", created=").append(created); sb.append(", lastUsed=").append(lastUsed); sb.append(", marshaller=").append(marshaller).append('}'); return sb.toString(); } static ByteBuffer marshall(Object obj, Marshaller marshaller) { if (obj == null) return null; try { return marshaller.objectToBuffer(obj); } catch (Exception e) { throw new PersistenceException(e); } } <T> T unmarshall(ByteBuffer buf) { return unmarshall(buf, marshaller); } @SuppressWarnings(value = "unchecked") static <T> T unmarshall(ByteBuffer buf, Marshaller marshaller) { if (buf == null) return null; try { return (T) marshaller.objectFromByteBuffer(buf.getBuf(), buf.getOffset(), buf.getLength()); } catch (Exception e) { throw new PersistenceException(e); } } }
8,227
31.393701
177
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/impl/MarshalledEntryFactoryImpl.java
package org.infinispan.marshall.persistence.impl; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.marshall.Marshaller; 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.metadata.EmbeddedMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.MarshallableEntryFactory; import org.infinispan.persistence.spi.MarshalledValue; /** * @author Ryan Emerson * @since 10.0 */ @Scope(Scopes.NAMED_CACHE) public class MarshalledEntryFactoryImpl implements MarshallableEntryFactory { private static final MarshallableEntry EMPTY = new MarshallableEntryImpl(); @Inject @ComponentName(KnownComponentNames.PERSISTENCE_MARSHALLER) Marshaller marshaller; public MarshalledEntryFactoryImpl() { } public MarshalledEntryFactoryImpl(Marshaller marshaller) { this.marshaller = marshaller; } @Override public MarshallableEntry create(ByteBuffer key, ByteBuffer valueBytes) { return create(key, valueBytes, (ByteBuffer) null, null, -1, -1); } @Override public MarshallableEntry create(ByteBuffer key, ByteBuffer valueBytes, ByteBuffer metadataBytes, ByteBuffer internalMetadataBytes, long created, long lastUsed) { return new MarshallableEntryImpl<>(key, valueBytes, metadataBytes, internalMetadataBytes, created, lastUsed, marshaller); } @Override public MarshallableEntry create(Object key, ByteBuffer valueBytes, ByteBuffer metadataBytes, ByteBuffer internalMetadataBytes, long created, long lastUsed) { return new MarshallableEntryImpl<>(key, valueBytes, metadataBytes, internalMetadataBytes, created, lastUsed, marshaller); } @Override public MarshallableEntry create(Object key) { return create(key, MarshalledValueImpl.EMPTY); } @Override public MarshallableEntry create(Object key, Object value) { return create(key, value, null, null, -1, -1); } @Override public MarshallableEntry create(Object key, Object value, Metadata metadata, PrivateMetadata internalMetadata, long created, long lastUsed) { PrivateMetadata privateMetadataToUse = internalMetadata != null && !internalMetadata.isEmpty() ? internalMetadata : null; if (metadata == null || metadata.isEmpty()) { return new MarshallableEntryImpl<>(key, value, null, privateMetadataToUse, -1, -1, marshaller); } return new MarshallableEntryImpl<>(key, value, metadata, privateMetadataToUse, created, lastUsed, marshaller); } @Override public MarshallableEntry create(Object key, MarshalledValue value) { return new MarshallableEntryImpl<>(key, value.getValueBytes(), value.getMetadataBytes(), value.getInternalMetadataBytes(), value.getCreated(), value.getLastUsed(), marshaller); } @Override public MarshallableEntry cloneWithExpiration(MarshallableEntry me, long creationTime, long lifespan) { Metadata metadata = me.getMetadata(); Metadata.Builder builder; if (metadata != null) { // Lifespan already applied, nothing to add here if (metadata.lifespan() > 0) { return me; } builder = metadata.builder(); } else { builder = new EmbeddedMetadata.Builder(); } metadata = builder.lifespan(lifespan).build(); if (!(me instanceof MarshallableEntryImpl)) { return new MarshallableEntryImpl(me.getKey(), me.getValue(), metadata, me.getInternalMetadata(), creationTime, creationTime, marshaller); } MarshallableEntryImpl meCast = (MarshallableEntryImpl) me; meCast.metadata = metadata; meCast.metadataBytes = null; meCast.created = creationTime; return meCast; } @Override public MarshallableEntry getEmpty() { return EMPTY; } }
4,134
37.64486
182
java
null
infinispan-main/core/src/main/java/org/infinispan/marshall/persistence/impl/PersistenceMarshallerImpl.java
package org.infinispan.marshall.persistence.impl; import static org.infinispan.util.logging.Log.PERSISTENCE; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.marshall.persistence.PersistenceMarshaller; import org.infinispan.marshall.protostream.impl.AbstractInternalProtoStreamMarshaller; import org.infinispan.marshall.protostream.impl.MarshallableUserObject; import org.infinispan.marshall.protostream.impl.SerializationContextRegistry.MarshallerType; import org.infinispan.protostream.ImmutableSerializationContext; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; /** * A Protostream based {@link PersistenceMarshaller} implementation that is responsible * for marshalling/unmarshalling objects which are to be persisted. * <p> * Known internal objects that are required by stores and loaders, such as {@link org.infinispan.metadata.EmbeddedMetadata}, * are registered with this marshaller's {@link SerializationContext} so that they can be natively marshalled by the * underlying Protostream marshaller. If no entry exists in the {@link SerializationContext} for a given object, then * the marshalling of said object is delegated to a user marshaller if configured * ({@link org.infinispan.configuration.global.SerializationConfiguration#MARSHALLER}) and the generated bytes are wrapped * in a {@link MarshallableUserObject} object and marshalled by ProtoStream. * * @author Ryan Emerson * @since 10.0 */ @Scope(Scopes.GLOBAL) public class PersistenceMarshallerImpl extends AbstractInternalProtoStreamMarshaller implements PersistenceMarshaller { public PersistenceMarshallerImpl() { super(PERSISTENCE); } public ImmutableSerializationContext getSerializationContext() { return ctxRegistry.getPersistenceCtx(); } @Override public void register(SerializationContextInitializer initializer) { ctxRegistry.addContextInitializer(MarshallerType.PERSISTENCE, initializer); } }
2,074
45.111111
124
java
null
infinispan-main/core/src/main/java/org/infinispan/batch/package-info.java
/** * Support for batching calls using the {@link org.infinispan.Cache#startBatch()} and {@link org.infinispan.Cache#endBatch(boolean)} * API. */ package org.infinispan.batch;
179
29
132
java
null
infinispan-main/core/src/main/java/org/infinispan/batch/AutoBatchSupport.java
package org.infinispan.batch; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.cache.Configuration; import net.jcip.annotations.NotThreadSafe; /** * Enables for automatic batching. * * @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>) * @since 4.0 */ @NotThreadSafe public abstract class AutoBatchSupport { protected BatchContainer batchContainer; protected static void assertBatchingSupported(Configuration c) { if (!c.invocationBatching().enabled()) throw new CacheConfigurationException("Invocation batching not enabled in current configuration! Please enable it."); } protected void startAtomic() { batchContainer.startBatch(true); } protected void endAtomic() { batchContainer.endBatch(true, true); } protected void failAtomic() { batchContainer.endBatch(true, false); } }
937
25.8
126
java
null
infinispan-main/core/src/main/java/org/infinispan/batch/BatchContainer.java
package org.infinispan.batch; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.commons.CacheException; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * A container for holding thread locals for batching, to be used with the {@link org.infinispan.Cache#startBatch()} and * {@link org.infinispan.Cache#endBatch(boolean)} calls. * * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>) * @since 4.0 */ @Scope(Scopes.NAMED_CACHE) public class BatchContainer { @Inject TransactionManager transactionManager; private final ThreadLocal<BatchDetails> batchDetailsTl = new ThreadLocal<BatchDetails>(); /** * Starts a batch * * @return true if a batch was started; false if one was already available. */ public boolean startBatch() throws CacheException { return startBatch(false); } public boolean startBatch(boolean autoBatch) throws CacheException { BatchDetails bd = batchDetailsTl.get(); if (bd == null) bd = new BatchDetails(); try { if (transactionManager.getTransaction() == null && bd.tx == null) { transactionManager.begin(); bd.nestedInvocationCount = 1; bd.suspendTxAfterInvocation = !autoBatch; bd.thread = Thread.currentThread(); // do not suspend if this is from an AutoBatch! if (autoBatch) bd.tx = transactionManager.getTransaction(); else bd.tx = transactionManager.suspend(); batchDetailsTl.set(bd); return true; } else { bd.nestedInvocationCount++; batchDetailsTl.set(bd); return false; } } catch (Exception e) { batchDetailsTl.remove(); throw new CacheException("Unable to start batch", e); } } public void endBatch(boolean success) { endBatch(false, success); } public void endBatch(boolean autoBatch, boolean success) { BatchDetails bd = batchDetailsTl.get(); if (bd == null) return; if (bd.tx == null) { batchDetailsTl.remove(); return; } if (autoBatch) bd.nestedInvocationCount--; if (!autoBatch || bd.nestedInvocationCount == 0) { Transaction existingTx = null; try { existingTx = transactionManager.getTransaction(); if ((existingTx == null && !autoBatch) || !bd.tx.equals(existingTx)) transactionManager.resume(bd.tx); resolveTransaction(bd, success); } catch (Exception e) { throw new CacheException("Unable to end batch", e); } finally { batchDetailsTl.remove(); try { if (!autoBatch && existingTx != null) transactionManager.resume(existingTx); } catch (Exception e) { throw new CacheException("Failed resuming existing transaction " + existingTx, e); } } } } private void resolveTransaction(BatchDetails bd, boolean success) throws Exception { Thread currentThread = Thread.currentThread(); if (bd.thread.equals(currentThread)) { if (success) transactionManager.commit(); else transactionManager.rollback(); } else { if (success) bd.tx.commit(); else bd.tx.rollback(); } } public Transaction getBatchTransaction() { Transaction tx = null; BatchDetails bd = batchDetailsTl.get(); if (bd != null) { tx = bd.tx; if (tx == null) batchDetailsTl.remove(); } return tx; } public boolean isSuspendTxAfterInvocation() { BatchDetails bd = batchDetailsTl.get(); return bd != null && bd.suspendTxAfterInvocation; } private static class BatchDetails { int nestedInvocationCount; boolean suspendTxAfterInvocation; Transaction tx; Thread thread; } }
4,136
30.340909
120
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/package-info.java
/** * Metadata interfaces * * @api.public */ package org.infinispan.metadata;
82
10.857143
32
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/EmbeddedMetadata.java
package org.infinispan.metadata; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.Ids; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Util; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.container.versioning.SimpleClusteredVersion; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * Metadata class for embedded caches. * * @author Galder Zamarreño * @since 5.3 */ @ProtoTypeId(ProtoStreamTypeIds.EMBEDDED_METADATA) public class EmbeddedMetadata implements Metadata { public static final EmbeddedMetadata EMPTY = new EmbeddedMetadata(null, null); protected final EntryVersion version; private EmbeddedMetadata(EntryVersion version) { this.version = version; } @ProtoFactory EmbeddedMetadata(NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion) { version = numericVersion != null ? numericVersion : clusteredVersion; } @Override public long lifespan() { return -1; } @Override public long maxIdle() { return -1; } @Override public EntryVersion version() { return version; } @ProtoField(1) public NumericVersion getNumericVersion() { return version instanceof NumericVersion ? (NumericVersion) version : null; } @ProtoField(2) public SimpleClusteredVersion getClusteredVersion() { return version instanceof SimpleClusteredVersion ? (SimpleClusteredVersion) version : null; } @Override public boolean isEmpty() { return version == null; } @Override public Metadata.Builder builder() { return new Builder().version(version); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EmbeddedMetadata that = (EmbeddedMetadata) o; return version != null ? version.equals(that.version) : that.version == null; } @Override public int hashCode() { return version != null ? version.hashCode() : 0; } @Override public String toString() { return "EmbeddedMetadata{version=" + version + '}'; } public static class Builder implements Metadata.Builder { protected Long lifespan = null; protected TimeUnit lifespanUnit = TimeUnit.MILLISECONDS; protected Long maxIdle = null; protected TimeUnit maxIdleUnit = TimeUnit.MILLISECONDS; protected EntryVersion version; @Override public Metadata.Builder lifespan(long time, TimeUnit unit) { lifespan = time; lifespanUnit = unit; return this; } @Override public Metadata.Builder lifespan(long time) { return lifespan(time, TimeUnit.MILLISECONDS); } @Override public Metadata.Builder maxIdle(long time, TimeUnit unit) { maxIdle = time; maxIdleUnit = unit; return this; } @Override public Metadata.Builder maxIdle(long time) { return maxIdle(time, TimeUnit.MILLISECONDS); } @Override public Metadata.Builder version(EntryVersion version) { this.version = version; return this; } @Override public Metadata build() { boolean hasLifespan = hasLifespan(); boolean hasMaxIdle = hasMaxIdle(); if (hasLifespan && hasMaxIdle) return new EmbeddedExpirableMetadata(toMillis(lifespan, lifespanUnit), toMillis(maxIdle, maxIdleUnit), version); else if (hasLifespan) return new EmbeddedLifespanExpirableMetadata(toMillis(lifespan, lifespanUnit), version); else if (hasMaxIdle) return new EmbeddedMaxIdleExpirableMetadata(toMillis(maxIdle, lifespanUnit), version); else return new EmbeddedMetadata(version); } protected boolean hasLifespan() { return lifespan != null; } protected boolean hasMaxIdle() { return maxIdle != null; } @Override public Metadata.Builder merge(Metadata metadata) { if (lifespan == null) { // if lifespan not set, apply default lifespan = metadata.lifespan(); lifespanUnit = TimeUnit.MILLISECONDS; } if (maxIdle == null) { // if maxIdle not set, apply default maxIdle = metadata.maxIdle(); maxIdleUnit = TimeUnit.MILLISECONDS; } if (version == null) version = metadata.version(); return this; } } @ProtoTypeId(ProtoStreamTypeIds.EMBEDDED_EXPIRABLE_METADATA) public static class EmbeddedExpirableMetadata extends EmbeddedMetadata { private final long lifespan; private final long maxIdle; @ProtoFactory EmbeddedExpirableMetadata(long lifespan, long maxIdle, NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion) { this(lifespan, maxIdle, numericVersion != null ? numericVersion : clusteredVersion); } private EmbeddedExpirableMetadata(long lifespan, long maxIdle, EntryVersion version) { super(version); this.lifespan = lifespan; this.maxIdle = maxIdle; } @ProtoField(number = 3, defaultValue = "-1") @Override public long lifespan() { return lifespan; } @ProtoField(number = 4, defaultValue = "-1") @Override public long maxIdle() { return maxIdle; } @Override public Metadata.Builder builder() { return super.builder().lifespan(lifespan).maxIdle(maxIdle); } @Override public boolean isEmpty() { return super.isEmpty() && lifespan < 0 && maxIdle < 0; } @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; EmbeddedExpirableMetadata that = (EmbeddedExpirableMetadata) o; return lifespan == that.lifespan && maxIdle == that.maxIdle; } @Override public int hashCode() { return Objects.hash(super.hashCode(), lifespan, maxIdle); } @Override public String toString() { return "EmbeddedExpirableMetadata{" + "version=" + version + ", lifespan=" + lifespan + ", maxIdle=" + maxIdle + '}'; } } @ProtoTypeId(ProtoStreamTypeIds.EMBEDDED_LIFESPAN_METADATA) public static class EmbeddedLifespanExpirableMetadata extends EmbeddedMetadata { private final long lifespan; protected EmbeddedLifespanExpirableMetadata(long lifespan, EntryVersion version) { super(version); this.lifespan = lifespan; } @ProtoFactory protected EmbeddedLifespanExpirableMetadata(long lifespan, NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion) { this(lifespan, numericVersion != null ? numericVersion : clusteredVersion); } @ProtoField(number = 3, defaultValue = "-1") @Override public long lifespan() { return lifespan; } @Override public Metadata.Builder builder() { return super.builder().lifespan(lifespan); } @Override public boolean isEmpty() { return super.isEmpty() && lifespan < 0; } @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; EmbeddedLifespanExpirableMetadata that = (EmbeddedLifespanExpirableMetadata) o; return lifespan == that.lifespan; } @Override public int hashCode() { return Objects.hash(super.hashCode(), lifespan); } @Override public String toString() { return "EmbeddedLifespanExpirableMetadata{" + "lifespan=" + lifespan + ", version=" + version + '}'; } } @ProtoTypeId(ProtoStreamTypeIds.EMBEDDED_MAX_IDLE_METADATA) public static class EmbeddedMaxIdleExpirableMetadata extends EmbeddedMetadata { private final long maxIdle; @ProtoFactory EmbeddedMaxIdleExpirableMetadata(long maxIdle, NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion) { this(maxIdle, numericVersion != null ? numericVersion : clusteredVersion); } private EmbeddedMaxIdleExpirableMetadata(long maxIdle, EntryVersion entryVersion) { super(entryVersion); this.maxIdle = maxIdle; } @ProtoField(number = 3, defaultValue = "-1") @Override public long maxIdle() { return maxIdle; } @Override public boolean isEmpty() { return super.isEmpty() && maxIdle < 0; } @Override public Metadata.Builder builder() { return super.builder().maxIdle(maxIdle); } @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; EmbeddedMaxIdleExpirableMetadata that = (EmbeddedMaxIdleExpirableMetadata) o; return maxIdle == that.maxIdle; } @Override public int hashCode() { return Objects.hash(super.hashCode(), maxIdle); } @Override public String toString() { return "EmbeddedMaxIdleExpirableMetadata{" + "version=" + version + ", maxIdle=" + maxIdle + '}'; } } public static class Externalizer extends AbstractExternalizer<EmbeddedMetadata> { private static final int IMMORTAL = 0; private static final int EXPIRABLE = 1; private static final int LIFESPAN_EXPIRABLE = 2; private static final int MAXIDLE_EXPIRABLE = 3; private final Map<Class<?>, Integer> numbers = new HashMap<>(2); public Externalizer() { numbers.put(EmbeddedMetadata.class, IMMORTAL); numbers.put(EmbeddedExpirableMetadata.class, EXPIRABLE); numbers.put(EmbeddedLifespanExpirableMetadata.class, LIFESPAN_EXPIRABLE); numbers.put(EmbeddedMaxIdleExpirableMetadata.class, MAXIDLE_EXPIRABLE); } @Override public Set<Class<? extends EmbeddedMetadata>> getTypeClasses() { return Util.asSet(EmbeddedMetadata.class, EmbeddedExpirableMetadata.class, EmbeddedLifespanExpirableMetadata.class, EmbeddedMaxIdleExpirableMetadata.class); } @Override public Integer getId() { return Ids.EMBEDDED_METADATA; } @Override public void writeObject(ObjectOutput output, EmbeddedMetadata object) throws IOException { int number = numbers.getOrDefault(object.getClass(), -1); output.write(number); switch (number) { case EXPIRABLE: output.writeLong(object.lifespan()); output.writeLong(object.maxIdle()); break; case LIFESPAN_EXPIRABLE: output.writeLong(object.lifespan()); break; case MAXIDLE_EXPIRABLE: output.writeLong(object.maxIdle()); break; } output.writeObject(object.version()); } @Override public EmbeddedMetadata readObject(ObjectInput input) throws IOException, ClassNotFoundException { int number = input.readByte(); long lifespan; long maxIdle; switch (number) { case IMMORTAL: return new EmbeddedMetadata((EntryVersion) input.readObject()); case EXPIRABLE: lifespan = toMillis(input.readLong(), TimeUnit.MILLISECONDS); maxIdle = toMillis(input.readLong(), TimeUnit.MILLISECONDS); return new EmbeddedExpirableMetadata(lifespan, maxIdle, (EntryVersion) input.readObject()); case LIFESPAN_EXPIRABLE: lifespan = toMillis(input.readLong(), TimeUnit.MILLISECONDS); return new EmbeddedLifespanExpirableMetadata(lifespan, (EntryVersion) input.readObject()); case MAXIDLE_EXPIRABLE: maxIdle = toMillis(input.readLong(), TimeUnit.MILLISECONDS); return new EmbeddedMaxIdleExpirableMetadata(maxIdle, (EntryVersion) input.readObject()); default: throw new IllegalStateException("Unknown metadata type " + number); } } } private static long toMillis(long duration, TimeUnit timeUnit) { return duration < 0 ? -1 : timeUnit.toMillis(duration); } }
13,280
30.323113
138
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/InternalMetadata.java
package org.infinispan.metadata; /** * @author Mircea Markus * @since 6.0 * @deprecated since 10.0 */ @Deprecated public interface InternalMetadata extends Metadata { long created(); long lastUsed(); boolean isExpired(long now); long expiryTime(); }
271
13.315789
52
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/Metadatas.java
package org.infinispan.metadata; import org.infinispan.container.entries.CacheEntry; /** * Utility method for Metadata classes. * * @author Galder Zamarreño * @since 5.3 */ public class Metadatas { private Metadatas() { } /** * Applies version in source metadata to target metadata, if no version * in target metadata. This method can be useful in scenarios where source * version information must be kept around, i.e. write skew, or when * reading metadata from cache store. * * @param source Metadata object which is source, whose version might be * is of interest for the target metadata * @param target Metadata object on which version might be applied * @return either, the target Metadata instance as it was when it was * called, or a brand new target Metadata instance with version from source * metadata applied. */ public static Metadata applyVersion(Metadata source, Metadata target) { if (target.version() == null && source.version() != null) return target.builder().version(source.version()).build(); return target; } /** * Set the {@code providedMetadata} on the cache entry. * * If the entry already has a version, copy the version in the new metadata. */ public static void updateMetadata(CacheEntry entry, Metadata providedMetadata) { if (entry != null && providedMetadata != null) { Metadata mergedMetadata; if (entry.getMetadata() == null) { mergedMetadata = providedMetadata; } else { mergedMetadata = applyVersion(entry.getMetadata(), providedMetadata); } entry.setMetadata(mergedMetadata); } } }
1,732
31.698113
83
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/Metadata.java
package org.infinispan.metadata; import java.util.concurrent.TimeUnit; import org.infinispan.commons.util.Experimental; import org.infinispan.container.versioning.EntryVersion; /** * This interface encapsulates metadata information that can be stored * alongside values in the cache. * * @author Galder Zamarreño * @since 5.3 */ public interface Metadata { /** * Returns the lifespan of the cache entry with which this metadata object * is associated, in milliseconds. Negative values are interpreted as * unlimited lifespan. * * @return lifespan of the entry in number of milliseconds */ long lifespan(); /** * Returns the the maximum amount of time that the cache entry associated * with this metadata object is allowed to be idle for before it is * considered as expired, in milliseconds. * * @return maximum idle time of the entry in number of milliseconds */ long maxIdle(); /** * Returns the version of the cache entry with which this metadata object * is associated. * * @return version of the entry */ EntryVersion version(); /** * Returns if the creation timestamp is updated when an entry is modified. * <p> * Created entries always update the creation timestamp. * <p> * This capability is experimental and all Infinispan implementations return {@code true}. To update creation * timestamps you must create a custom {@link Metadata} implementation. * * @return {@code true} to update the creation timestamp when entries are modified. */ @Experimental default boolean updateCreationTimestamp() { return true; } /** * Returns whether this metadata is effectively empty, that is that persisting or replicating it to another * node would be no different then sending a null metadata object. * @return if this metadata has no actual data to store */ default boolean isEmpty() { return false; } /** * Returns an instance of {@link Builder} which can be used to build * new instances of {@link Metadata} instance which are full copies of * this {@link Metadata}. * * @return instance of {@link Builder} */ Builder builder(); /** * Metadata builder */ public interface Builder { /** * Set lifespan time with a given time unit. * * @param time of lifespan * @param unit unit of time for lifespan time * @return a builder instance with the lifespan time applied */ Builder lifespan(long time, TimeUnit unit); /** * Set lifespan time assuming that the time unit is milliseconds. * * @param time of lifespan, in milliseconds * @return a builder instance with the lifespan time applied */ Builder lifespan(long time); /** * Set max idle time with a given time unit. * * @param time of max idle * @param unit of max idle time * @return a builder instance with the max idle time applied */ Builder maxIdle(long time, TimeUnit unit); /** * Set max idle time assuming that the time unit is milliseconds. * * @param time of max idle, in milliseconds * @return a builder instance with the max idle time applied */ Builder maxIdle(long time); /** * Set version. * * @param version of the metadata * @return a builder instance with the version applied */ Builder version(EntryVersion version); /** * Sets how the creation timestamp is updated. * <p> * Affects mortal entries only; in other words, for entries where {@link Metadata#lifespan()} is greater than * zero. * <p> * When {@code true} (default), the creation timestamp is updated when an entry is created or modified. When set * to {@code false}, the creation timestamp is updated only when the entry is created. * <p> * The capability is experimental and Infinispan {@link Metadata} and {@link Builder} does not implement this * method. To not update creation timestamps you must create a custom {@link Metadata} and {@link Builder} * implementation. * * @param enabled {@code false} to disable creation timestamp update when modifying entries. * @return a builder instance with the version applied. */ @Experimental default Builder updateCreationTimestamp(boolean enabled) { //no-op by default return this; } /** * Build a metadata instance. * * @return an instance of metadata */ Metadata build(); /** * Merges the given metadata information into the given builder. * * @param metadata to merge into this builder * @return a builder instance with the metadata applied */ Builder merge(Metadata metadata); } }
4,987
29.790123
118
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/impl/IracMetadata.java
package org.infinispan.metadata.impl; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Objects; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.util.ByteString; import org.infinispan.xsite.XSiteNamedCache; /** * The metadata stored for an entry needed for IRAC (async cross-site replication). * * @author Pedro Ruivo * @since 11.0 */ @ProtoTypeId(ProtoStreamTypeIds.IRAC_METADATA) public class IracMetadata { private final ByteString site; private final IracEntryVersion version; @ProtoFactory public IracMetadata(String site, IracEntryVersion version) { this(XSiteNamedCache.cachedByteString(Objects.requireNonNull(site)), Objects.requireNonNull(version)); } public IracMetadata(ByteString site, IracEntryVersion version) { this.site = Objects.requireNonNull(site); this.version = Objects.requireNonNull(version); } public static void writeTo(ObjectOutput output, IracMetadata metadata) throws IOException { if (metadata == null) { output.writeObject(null); return; } output.writeObject(metadata.version); ByteString.writeObject(output, metadata.site); } public static IracMetadata readFrom(ObjectInput in) throws IOException, ClassNotFoundException { IracEntryVersion version = (IracEntryVersion) in.readObject(); return version == null ? null : new IracMetadata(XSiteNamedCache.cachedByteString(ByteString.readObject(in)), version); } @ProtoField(1) public String getSite() { return site.toString(); } @ProtoField(2) public IracEntryVersion getVersion() { return version; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IracMetadata that = (IracMetadata) o; return site.equals(that.site) && version.equals(that.version); } @Override public int hashCode() { int result = site.hashCode(); result = 31 * result + version.hashCode(); return result; } @Override public String toString() { return "IracMetadata{" + "site='" + site + '\'' + ", version=" + version + '}'; } }
2,589
27.461538
125
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/impl/L1Metadata.java
package org.infinispan.metadata.impl; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.metadata.Metadata; /** * {@link org.infinispan.metadata.Metadata} implementation that must be passed to the {@link * org.infinispan.container.DataContainer#put(Object, Object, org.infinispan.metadata.Metadata)} when the entry to store * is a L1 entry. * * @author Pedro Ruivo * @since 7.1 */ public class L1Metadata implements Metadata { private final Metadata metadata; public L1Metadata(Metadata metadata) { this.metadata = metadata; } @Override public long lifespan() { return metadata.lifespan(); } @Override public long maxIdle() { return metadata.maxIdle(); } @Override public EntryVersion version() { return metadata.version(); } @Override public boolean isEmpty() { return metadata.isEmpty(); } @Override public Metadata.Builder builder() { return metadata.builder(); } public Metadata metadata() { return metadata; } }
1,064
19.882353
120
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/impl/PrivateMetadata.java
package org.infinispan.metadata.impl; import java.util.Objects; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.container.versioning.IncrementableEntryVersion; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.container.versioning.SimpleClusteredVersion; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import net.jcip.annotations.Immutable; /** * A class to store internal metadata. * <p> * This class should not be exposed to users. * * @author Pedro Ruivo * @since 11.0 */ @Immutable @ProtoTypeId(ProtoStreamTypeIds.PRIVATE_METADATA) public final class PrivateMetadata { /** * A cached empty {@link PrivateMetadata}. */ private static final PrivateMetadata EMPTY = new PrivateMetadata(null, null); @ProtoField(1) final IracMetadata iracMetadata; private final IncrementableEntryVersion entryVersion; private PrivateMetadata(IracMetadata iracMetadata, IncrementableEntryVersion entryVersion) { this.iracMetadata = iracMetadata; this.entryVersion = entryVersion; } /** * @return An empty instance of {@link PrivateMetadata}, i.e., without any metadata stored. */ public static PrivateMetadata empty() { return EMPTY; } /** * Returns a {@link Builder} with the metadata stored by {@code metadata}. * <p> * If {@code metadata} is {@code null}, an empty {@link Builder} instance is created. * * @param metadata The {@link PrivateMetadata} to copy from. * @return The {@link Builder} instance. */ public static Builder getBuilder(PrivateMetadata metadata) { return metadata == null ? new Builder() : metadata.builder(); } /** * Factory used by protostream. * <p> * It allows to do some logic before instantiate a new instance. */ @ProtoFactory static PrivateMetadata protoFactory(IracMetadata iracMetadata, NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion) { IncrementableEntryVersion entryVersion = numericVersion == null ? clusteredVersion : numericVersion; return newInstance(iracMetadata, entryVersion); } private static PrivateMetadata newInstance(IracMetadata iracMetadata, IncrementableEntryVersion entryVersion) { return iracMetadata == null && entryVersion == null ? EMPTY : new PrivateMetadata(iracMetadata, entryVersion); } /** * @return A {@link Builder} pre-filled with the data stored in this instance. */ public Builder builder() { return new Builder(this); } /** * @return The {@link IracMetadata} stored. It can be {@code null}. */ public IracMetadata iracMetadata() { return iracMetadata; } /** * @return The {@link IncrementableEntryVersion} associated with the entry. */ public IncrementableEntryVersion entryVersion() { return entryVersion; } /** * @return {@code true} if not metadata is stored in this instance. */ public boolean isEmpty() { return iracMetadata == null && entryVersion == null; } @Override public String toString() { return "PrivateMetadata{" + "iracMetadata=" + iracMetadata + ", entryVersion=" + entryVersion + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PrivateMetadata metadata = (PrivateMetadata) o; return Objects.equals(iracMetadata, metadata.iracMetadata) && Objects.equals(entryVersion, metadata.entryVersion); } @Override public int hashCode() { return Objects.hash(iracMetadata, entryVersion); } @ProtoField(2) public NumericVersion getNumericVersion() { return entryVersion instanceof NumericVersion ? (NumericVersion) entryVersion : null; } @ProtoField(3) public SimpleClusteredVersion getClusteredVersion() { return entryVersion instanceof SimpleClusteredVersion ? (SimpleClusteredVersion) entryVersion : null; } public static class Builder { private IracMetadata iracMetadata; private IncrementableEntryVersion entryVersion; public Builder() { } private Builder(PrivateMetadata metadata) { this.iracMetadata = metadata.iracMetadata; this.entryVersion = metadata.entryVersion; } /** * @return A new instance of {@link PrivateMetadata}. */ public PrivateMetadata build() { return newInstance(iracMetadata, entryVersion); } /** * Sets the {@link IracMetadata} to store. * * @param metadata The {@link IracMetadata} to store. * @return This instance. */ public Builder iracMetadata(IracMetadata metadata) { this.iracMetadata = metadata; return this; } /** * Sets the {@link IncrementableEntryVersion} to store. * * @param entryVersion The version to store. * @return This instance. */ public Builder entryVersion(IncrementableEntryVersion entryVersion) { this.entryVersion = entryVersion; return this; } } }
5,385
27.802139
116
java
null
infinispan-main/core/src/main/java/org/infinispan/metadata/impl/InternalMetadataImpl.java
package org.infinispan.metadata.impl; import static java.lang.Math.min; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Set; import java.util.concurrent.TimeUnit; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.Ids; import org.infinispan.commons.util.Util; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.InternalMetadata; import org.infinispan.metadata.Metadata; /** * @author Mircea Markus * @since 6.0 */ @Deprecated public class InternalMetadataImpl implements InternalMetadata { private final Metadata actual; private final long created; private final long lastUsed; public InternalMetadataImpl() { //required by the AZUL VM in order to run the tests this(null, -1, -1); } public InternalMetadataImpl(InternalCacheEntry ice) { this(ice.getMetadata(), ice.getCreated(), ice.getLastUsed()); } public InternalMetadataImpl(InternalCacheValue icv) { this(icv.getMetadata(), icv.getCreated(), icv.getLastUsed()); } public InternalMetadataImpl(Metadata actual, long created, long lastUsed) { this.actual = extractMetadata(actual); this.created = created; this.lastUsed = lastUsed; } @Override public long lifespan() { return actual.lifespan(); } @Override public long maxIdle() { return actual.maxIdle(); } @Override public EntryVersion version() { return actual.version(); } @Override public boolean isEmpty() { return actual.isEmpty(); } @Override public Builder builder() { return new InternalBuilder(actual, created, lastUsed); } @Override public long created() { return created; } @Override public long lastUsed() { return lastUsed; } public Metadata actual() { return actual; } static class InternalBuilder implements Builder { private Builder actualBuilder; private final long created; private final long lastUsed; InternalBuilder(Metadata actual, long created, long lastUsed) { actualBuilder = actual != null ? actual.builder() : new EmbeddedMetadata.Builder(); this.created = created; this.lastUsed = lastUsed; } @Override public Builder lifespan(long time, TimeUnit unit) { actualBuilder = actualBuilder.lifespan(time, unit); return this; } @Override public Builder lifespan(long time) { actualBuilder = actualBuilder.lifespan(time); return this; } @Override public Builder maxIdle(long time, TimeUnit unit) { actualBuilder = actualBuilder.maxIdle(time, unit); return this; } @Override public Builder maxIdle(long time) { actualBuilder = actualBuilder.maxIdle(time); return this; } @Override public Builder version(EntryVersion version) { actualBuilder = actualBuilder.version(version); return this; } @Override public Builder merge(Metadata metadata) { actualBuilder = actualBuilder.merge(metadata); return this; } @Override public Metadata build() { return new InternalMetadataImpl(actualBuilder.build(), created, lastUsed); } } @Override public long expiryTime() { long lifespan = actual.lifespan(); long lset = lifespan > -1 ? created + lifespan : -1; long maxIdle = actual.maxIdle(); long muet = maxIdle > -1 ? lastUsed + maxIdle : -1; if (lset == -1) return muet; if (muet == -1) return lset; return min(lset, muet); } @Override public boolean isExpired(long now) { long expiry = expiryTime(); return expiry > 0 && expiry <= now; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InternalMetadataImpl)) return false; InternalMetadataImpl that = (InternalMetadataImpl) o; if (created != that.created) return false; if (lastUsed != that.lastUsed) return false; if (actual != null ? !actual.equals(that.actual) : that.actual != null) return false; return true; } @Override public int hashCode() { int result = actual != null ? actual.hashCode() : 0; result = 31 * result + (int) (created ^ (created >>> 32)); result = 31 * result + (int) (lastUsed ^ (lastUsed >>> 32)); return result; } @Override public String toString() { return "InternalMetadataImpl{" + "actual=" + actual + ", created=" + created + ", lastUsed=" + lastUsed + '}'; } public static Metadata extractMetadata(Metadata metadata) { Metadata toCheck = metadata; while (toCheck != null) { if (toCheck instanceof InternalMetadataImpl) { toCheck = ((InternalMetadataImpl) toCheck).actual(); } else { break; } } return toCheck; } public static class Externalizer extends AbstractExternalizer<InternalMetadataImpl> { @Override public void writeObject(ObjectOutput output, InternalMetadataImpl b) throws IOException { output.writeLong(b.created); output.writeLong(b.lastUsed); output.writeObject(b.actual); } @Override public InternalMetadataImpl readObject(ObjectInput input) throws IOException, ClassNotFoundException { long created = input.readLong(); long lastUsed = input.readLong(); Metadata actual = (Metadata) input.readObject(); return new InternalMetadataImpl(actual, created, lastUsed); } @Override public Integer getId() { return Ids.INTERNAL_METADATA_ID; } @Override public Set<Class<? extends InternalMetadataImpl>> getTypeClasses() { return Util.asSet(InternalMetadataImpl.class); } } }
6,227
26.196507
108
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/package-info.java
/** * JTA transaction support. * * @api.public */ package org.infinispan.transaction;
90
12
35
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/WriteSkewException.java
package org.infinispan.transaction; import org.infinispan.commons.CacheException; /** * Thrown when a write skew is detected * * @author Manik Surtani * @since 5.1 */ public class WriteSkewException extends CacheException { private final Object key; public WriteSkewException() { this.key = null; } public WriteSkewException(Throwable cause, Object key) { super(cause); this.key = key; } public WriteSkewException(String msg, Object key) { super(msg); this.key = key; } public WriteSkewException(String msg, Throwable cause, Object key) { super(msg, cause); this.key = key; } public final Object getKey() { return key; } }
717
17.894737
71
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/LockingMode.java
package org.infinispan.transaction; /** * Defines the locking modes that are available for transactional caches: * <a href="http://community.jboss.org/wiki/OptimisticLockingInInfinispan"></a>optimistic</a> or pessimistic. * * @author Mircea Markus * @since 5.1 */ public enum LockingMode { OPTIMISTIC, PESSIMISTIC }
326
24.153846
109
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/TransactionTable.java
package org.infinispan.transaction; import java.util.Collection; import jakarta.transaction.Transaction; import org.infinispan.transaction.xa.GlobalTransaction; /** * Interface that allows to fetch the {@link org.infinispan.transaction.xa.GlobalTransaction} associated to local or * remote transactions. * * @author Pedro Ruivo * @since 7.1 */ public interface TransactionTable { /** * @param transaction the local transaction. Must be non-null. * @return the {@link org.infinispan.transaction.xa.GlobalTransaction} associated with the transaction or {@code * null} if doesn't exists. */ GlobalTransaction getGlobalTransaction(Transaction transaction); /** * @return an unmodified collection of {@link org.infinispan.transaction.xa.GlobalTransaction} associated with local * running transactions. */ Collection<GlobalTransaction> getLocalGlobalTransaction(); /** * @return an unmodified collection of {@link org.infinispan.transaction.xa.GlobalTransaction} associated with remote * transactions. */ Collection<GlobalTransaction> getRemoteGlobalTransaction(); }
1,133
28.842105
120
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/TransactionMode.java
package org.infinispan.transaction; /** * Enumeration containing the available transaction modes for a cache. * * Starting with Infinispan version 5.1 a cache doesn't support mixed access: * i.e. won't support transactional and non-transactional operations. * A cache is transactional if one the following: * * <pre> * - a transactionManagerLookup is configured for the cache * - batching is enabled * - it is explicitly marked as transactional: config.fluent().transaction().transactionMode(TransactionMode.TRANSACTIONAL). * In this last case a transactionManagerLookup needs to be explicitly set * </pre> * * By default a cache is not transactional. * * @author Mircea Markus * @since 5.1 */ public enum TransactionMode { NON_TRANSACTIONAL, TRANSACTIONAL; public boolean isTransactional() { return this == TRANSACTIONAL; } }
867
27.933333
124
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/synchronization/SyncLocalTransaction.java
package org.infinispan.transaction.synchronization; import jakarta.transaction.Transaction; import org.infinispan.transaction.impl.LocalTransaction; import org.infinispan.transaction.xa.GlobalTransaction; /** * {@link LocalTransaction} implementation to be used with {@link SynchronizationAdapter}. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class SyncLocalTransaction extends LocalTransaction { public SyncLocalTransaction(Transaction transaction, GlobalTransaction tx, boolean implicitTransaction, int topologyId, long txCreationTime) { super(transaction, tx, implicitTransaction, topologyId, txCreationTime); } private boolean enlisted; @Override public boolean isEnlisted() { return enlisted; } public void setEnlisted(boolean enlisted) { this.enlisted = enlisted; } }
874
26.34375
106
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/synchronization/SynchronizationAdapter.java
package org.infinispan.transaction.synchronization; import java.util.Objects; import java.util.concurrent.CompletionStage; import jakarta.transaction.Synchronization; import org.infinispan.commons.tx.AsyncSynchronization; import org.infinispan.transaction.impl.AbstractEnlistmentAdapter; import org.infinispan.transaction.impl.LocalTransaction; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; /** * {@link Synchronization} implementation for integrating with the TM. See <a href="https://issues.jboss.org/browse/ISPN-888">ISPN-888</a> * for more information on this. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class SynchronizationAdapter extends AbstractEnlistmentAdapter implements Synchronization, AsyncSynchronization { private final LocalTransaction localTransaction; private final TransactionTable txTable; public SynchronizationAdapter(LocalTransaction localTransaction, TransactionTable txTable) { super(localTransaction); this.localTransaction = localTransaction; this.txTable = txTable; } @Override public void beforeCompletion() { CompletionStages.join(txTable.beforeCompletion(localTransaction)); } @Override public void afterCompletion(int status) { CompletionStages.join(txTable.afterCompletion(localTransaction, status)); } @Override public String toString() { return "SynchronizationAdapter{" + "localTransaction=" + localTransaction + "} " + super.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SynchronizationAdapter that = (SynchronizationAdapter) o; return Objects.equals(localTransaction, that.localTransaction); } @Override public CompletionStage<Void> asyncBeforeCompletion() { return txTable.beforeCompletion(localTransaction) .thenApply(CompletableFutures.toNullFunction()); } @Override public CompletionStage<Void> asyncAfterCompletion(int status) { return txTable.afterCompletion(localTransaction, status); } }
2,276
31.528571
138
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/CacheTransaction.java
package org.infinispan.transaction.xa; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.container.versioning.IncrementableEntryVersion; import org.infinispan.context.impl.TxInvocationContext; /** * Defines the state a infinispan transaction should have. * * @author Mircea.Markus@jboss.com * @since 4.0 */ public interface CacheTransaction { /** * Returns the transaction identifier. */ GlobalTransaction getGlobalTransaction(); /** * Returns the modifications visible within the current transaction. Any modifications using Flag#CACHE_MODE_LOCAL are excluded. * The returned list is never null. */ List<WriteCommand> getModifications(); /** * Returns all the modifications visible within the current transaction, including those using Flag#CACHE_MODE_LOCAL. * The returned list is never null. */ List<WriteCommand> getAllModifications(); /** * Checks if a modification of the given class (or subclass) is present in this transaction. Any modifications using Flag#CACHE_MODE_LOCAL are ignored. * * @param modificationClass the modification type to look for * @return true if found, false otherwise * @deprecated since 14.0. To be removed without replacement. */ @Deprecated default boolean hasModification(Class<?> modificationClass) { return false; } CacheEntry lookupEntry(Object key); Map<Object, CacheEntry> getLookedUpEntries(); void putLookedUpEntry(Object key, CacheEntry e); void putLookedUpEntries(Map<Object, CacheEntry> entries); void removeLookedUpEntry(Object key); void clearLookedUpEntries(); boolean ownsLock(Object key); void clearLockedKeys(); Set<Object> getLockedKeys(); int getTopologyId(); void addBackupLockForKey(Object key); /** * @see org.infinispan.interceptors.locking.AbstractTxLockingInterceptor#checkPendingAndLockKey(TxInvocationContext, VisitableCommand, Object, long) */ void notifyOnTransactionFinished(); Map<Object, IncrementableEntryVersion> getUpdatedEntryVersions(); void setUpdatedEntryVersions(Map<Object, IncrementableEntryVersion> updatedEntryVersions); boolean isMarkedForRollback(); void markForRollback(boolean markForRollback); /** * Sets the version read for this key. The version is only set at the first time, i.e. multiple invocation of this * method will not change the state. * <p/> * Note: used in Repeatable Read + Write Skew + Clustering + Versioning. */ void addVersionRead(Object key, EntryVersion version); /** * Note: used in Repeatable Read + Write Skew + Clustering + Versioning. * * @return a non-null map between key and version. The map represents the version read for that key. If no version * exists, the key has not been read. */ Map<Object, IncrementableEntryVersion> getVersionsRead(); long getCreationTime(); void addListener(TransactionCompletedListener listener); interface TransactionCompletedListener { void onCompletion(); } /** * Prevent new modifications after prepare or commit started. */ void freezeModifications(); /** * It returns a {@link CompletableFuture} that completes when the lock for the {@code key} is released. * * If the {@code key} is not locked by this transaction, it returns {@code null}. * * @param key the key. * @return the {@link CompletableFuture} or {@code null} if the key is not locked by this transaction. */ CompletableFuture<Void> getReleaseFutureForKey(Object key); /** * Same as {@link #getReleaseFutureForKey(Object)} but it returns a pair with the key and the future. */ Map<Object, CompletableFuture<Void>> getReleaseFutureForKeys(Collection<Object> keys); /** * It cleans up the backup locks for this transaction. */ void cleanupBackupLocks(); /** * It cleans up the backup lock for the {@code keys}. * * @param keys The keys to clean up the backup lock. */ void removeBackupLocks(Collection<?> keys); /** * It cleans up the backup for {@code key}. * * @param key The key to clean up the backup lock. */ void removeBackupLock(Object key); /** * Invokes the {@link Consumer} with each lock. * @param consumer The backup lock {@link Consumer} */ void forEachLock(Consumer<Object> consumer); /** * Invokes the {@link Consumer} with each backup lock. * @param consumer The backup lock {@link Consumer} */ void forEachBackupLock(Consumer<Object> consumer); }
4,958
29.054545
154
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/LocalXaTransaction.java
package org.infinispan.transaction.xa; import jakarta.transaction.Transaction; import org.infinispan.commons.tx.XidImpl; import org.infinispan.transaction.impl.LocalTransaction; /** * {@link LocalTransaction} implementation to be used with {@link TransactionXaAdapter}. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class LocalXaTransaction extends LocalTransaction { private XidImpl xid; public LocalXaTransaction(Transaction transaction, GlobalTransaction tx, boolean implicitTransaction, int topologyId, long txCreationTime) { super(transaction, tx, implicitTransaction, topologyId, txCreationTime); } public void setXid(XidImpl xid) { this.xid = xid; tx.setXid(xid); } public XidImpl getXid() { return xid; } /** * As per the JTA spec, XAResource.start is called on enlistment. That method also sets the xid for this local * transaction. */ @Override public boolean isEnlisted() { return xid != null; } @Override public String toString() { return "LocalXaTransaction{" + "xid=" + xid + "} " + super.toString(); } }
1,190
23.8125
120
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/package-info.java
/** * XA transaction support. */ package org.infinispan.transaction.xa;
74
14
38
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/InvalidTransactionException.java
package org.infinispan.transaction.xa; import org.infinispan.commons.CacheException; /** * Thrown if an operation is to be performed on an invalid transaction context. * * @author Manik Surtani * @since 4.2 */ public class InvalidTransactionException extends CacheException { public InvalidTransactionException() { } public InvalidTransactionException(Throwable cause) { super(cause); } public InvalidTransactionException(String msg) { super(msg); } public InvalidTransactionException(String msg, Throwable cause) { super(msg, cause); } }
591
20.925926
79
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/GlobalTransaction.java
package org.infinispan.transaction.xa; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.tx.XidImpl; import org.infinispan.commons.util.Util; import org.infinispan.marshall.core.Ids; import org.infinispan.remoting.transport.Address; /** * Uniquely identifies a transaction that spans all JVMs in a cluster. This is used when replicating all modifications * in a transaction; the PREPARE and COMMIT (or ROLLBACK) messages have to have a unique identifier to associate the * changes with<br>. GlobalTransaction should be instantiated thorough {@link TransactionFactory} class, * as their type depends on the runtime configuration. * * @author <a href="mailto:bela@jboss.org">Bela Ban</a> Apr 12, 2003 * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a> * @author Mircea.Markus@jboss.com * @since 4.0 */ public class GlobalTransaction implements Cloneable { private static final AtomicLong sid = new AtomicLong(0); private long id; private Address addr; private int hash_code = -1; // in the worst case, hashCode() returns 0, then increases, so we're safe here private boolean remote = false; private volatile XidImpl xid = null; private volatile long internalId = -1; public GlobalTransaction(Address addr, boolean remote) { this.id = sid.incrementAndGet(); this.addr = addr; this.remote = remote; } private GlobalTransaction(long id, Address addr, XidImpl xid, long internalId) { this.id = id; this.addr = addr; this.xid = xid; this.internalId = internalId; } public Address getAddress() { return addr; } public long getId() { return id; } public boolean isRemote() { return remote; } public void setRemote(boolean remote) { this.remote = remote; } @Override public int hashCode() { if (hash_code == -1) { hash_code = (addr != null ? addr.hashCode() : 0) + (int) id; } return hash_code; } @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof GlobalTransaction)) return false; GlobalTransaction otherGtx = (GlobalTransaction) other; return id == otherGtx.id && Objects.equals(addr, otherGtx.addr); } /** * Returns a simplified representation of the transaction. */ public final String globalId() { return getAddress() + ":" + getId(); } public void setId(long id) { this.id = id; } public void setAddress(Address address) { this.addr = address; } public XidImpl getXid() { return xid; } public void setXid(XidImpl xid) { this.xid = xid; } public long getInternalId() { return internalId; } public void setInternalId(long internalId) { this.internalId = internalId; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Impossible!"); } } @Override public String toString() { return "GlobalTransaction{" + "id=" + id + ", addr=" + Objects.toString(addr, "local") + ", remote=" + remote + ", xid=" + xid + ", internalId=" + internalId + '}'; } public static class Externalizer implements AdvancedExternalizer<GlobalTransaction> { @Override public Set<Class<? extends GlobalTransaction>> getTypeClasses() { return Util.asSet(GlobalTransaction.class); } @Override public Integer getId() { return Ids.GLOBAL_TRANSACTION; } @Override public void writeObject(ObjectOutput output, GlobalTransaction gtx) throws IOException { output.writeLong(gtx.id); output.writeObject(gtx.addr); output.writeObject(gtx.xid); output.writeLong(gtx.internalId); } @Override public GlobalTransaction readObject(ObjectInput input) throws IOException, ClassNotFoundException { long id = input.readLong(); Address addr = (Address) input.readObject(); XidImpl xid = (XidImpl) input.readObject(); long internalId = input.readLong(); return new GlobalTransaction(id, addr, xid, internalId); } } }
4,609
26.440476
118
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/TransactionFactory.java
package org.infinispan.transaction.xa; import java.util.Arrays; import java.util.Collections; import java.util.List; import jakarta.transaction.Transaction; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.Configuration; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.container.versioning.VersionGenerator; 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.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.synchronization.SyncLocalTransaction; import org.infinispan.transaction.xa.recovery.RecoveryAwareLocalTransaction; import org.infinispan.transaction.xa.recovery.RecoveryAwareRemoteTransaction; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Factory for transaction related state. * * @author Mircea.Markus@jboss.com */ @Scope(Scopes.NAMED_CACHE) public class TransactionFactory { private static final Log log = LogFactory.getLog(TransactionFactory.class); @Inject Configuration configuration; @Inject @ComponentName(value = KnownComponentNames.TRANSACTION_VERSION_GENERATOR) VersionGenerator clusterIdGenerator; @Inject TimeService timeService; private TxFactoryEnum txFactoryEnum; private boolean isClustered; public enum TxFactoryEnum { NODLD_RECOVERY_XA { @Override public LocalTransaction newLocalTransaction(Transaction tx, GlobalTransaction gtx, boolean implicitTransaction, int topologyId, long txCreationTime) { return new RecoveryAwareLocalTransaction(tx, gtx, implicitTransaction, topologyId, txCreationTime); } @Override public GlobalTransaction newGlobalTransaction(Address addr, boolean remote, VersionGenerator clusterIdGenerator, boolean clustered) { GlobalTransaction recoveryAwareGlobalTransaction = new GlobalTransaction(addr, remote); // TODO: Not ideal... but causes no issues so far. Could the internal id be an Object instead of a long? recoveryAwareGlobalTransaction.setInternalId(((NumericVersion) clusterIdGenerator.generateNew()).getVersion()); return recoveryAwareGlobalTransaction; } @Override public RemoteTransaction newRemoteTransaction(List<WriteCommand> modifications, GlobalTransaction tx, int topologyId, long txCreationTime) { return new RecoveryAwareRemoteTransaction(modifications, tx, topologyId, txCreationTime); } }, NODLD_NORECOVERY_XA { @Override public LocalTransaction newLocalTransaction(Transaction tx, GlobalTransaction gtx, boolean implicitTransaction, int topologyId, long txCreationTime) { return new LocalXaTransaction(tx, gtx, implicitTransaction, topologyId, txCreationTime); } @Override public GlobalTransaction newGlobalTransaction(Address addr, boolean remote, VersionGenerator clusterIdGenerator, boolean clustered) { return new GlobalTransaction(addr, remote); } @Override public RemoteTransaction newRemoteTransaction(List<WriteCommand> modifications, GlobalTransaction tx, int topologyId, long txCreationTime) { return new RemoteTransaction(modifications, tx, topologyId, txCreationTime); } }, NODLD_NORECOVERY_NOXA { @Override public LocalTransaction newLocalTransaction(Transaction tx, GlobalTransaction gtx, boolean implicitTransaction, int topologyId, long txCreationTime) { return new SyncLocalTransaction(tx, gtx, implicitTransaction, topologyId, txCreationTime); } @Override public GlobalTransaction newGlobalTransaction(Address addr, boolean remote, VersionGenerator clusterIdGenerator, boolean clustered) { return new GlobalTransaction(addr, remote); } @Override public RemoteTransaction newRemoteTransaction(List<WriteCommand> modifications, GlobalTransaction tx, int topologyId, long txCreationTime) { return new RemoteTransaction(modifications, tx, topologyId, txCreationTime); } }; public abstract LocalTransaction newLocalTransaction(Transaction tx, GlobalTransaction gtx, boolean implicitTransaction, int topologyId, long txCreationTime); public abstract GlobalTransaction newGlobalTransaction(Address addr, boolean remote, VersionGenerator clusterIdGenerator, boolean clustered); public RemoteTransaction newRemoteTransaction(WriteCommand[] modifications, GlobalTransaction tx, int topologyId, long txCreationTime) { return newRemoteTransaction(Arrays.asList(modifications), tx, topologyId, txCreationTime); } public RemoteTransaction newRemoteTransaction(GlobalTransaction tx, int topologyId, long txCreationTime) { return newRemoteTransaction(Collections.emptyList(), tx, topologyId, txCreationTime); } public abstract RemoteTransaction newRemoteTransaction(List<WriteCommand> modifications, GlobalTransaction tx, int topologyId, long txCreationTime); } public GlobalTransaction newGlobalTransaction(Address addr, boolean remote) { return txFactoryEnum.newGlobalTransaction(addr, remote, this.clusterIdGenerator, isClustered); } public LocalTransaction newLocalTransaction(Transaction tx, GlobalTransaction gtx, boolean implicitTransaction, int topologyId) { return txFactoryEnum.newLocalTransaction(tx, gtx, implicitTransaction, topologyId, timeService.time()); } public RemoteTransaction newRemoteTransaction(WriteCommand[] modifications, GlobalTransaction tx, int topologyId) { return txFactoryEnum.newRemoteTransaction(modifications, tx, topologyId, timeService.time()); } public RemoteTransaction newRemoteTransaction(GlobalTransaction tx, int topologyId) { return txFactoryEnum.newRemoteTransaction(tx, topologyId, timeService.time()); } public RemoteTransaction newRemoteTransaction(List<WriteCommand> modifications, GlobalTransaction gtx, int topologyId) { return txFactoryEnum.newRemoteTransaction(modifications, gtx, topologyId, timeService.time()); } @Start public void start() { boolean xa = !configuration.transaction().useSynchronization(); boolean recoveryEnabled = configuration.transaction().recovery().enabled(); boolean batchingEnabled = configuration.invocationBatching().enabled(); init(false, recoveryEnabled, xa, batchingEnabled); isClustered = configuration.clustering().cacheMode().isClustered(); } public void init(boolean dldEnabled, boolean recoveryEnabled, boolean xa, boolean batchingEnabled) { if (batchingEnabled) { txFactoryEnum = TxFactoryEnum.NODLD_NORECOVERY_NOXA; } else { if (recoveryEnabled) { if (xa) { txFactoryEnum = TxFactoryEnum.NODLD_RECOVERY_XA; } else { //using synchronisation enlistment txFactoryEnum = TxFactoryEnum.NODLD_NORECOVERY_NOXA; } } else { if (xa) { txFactoryEnum = TxFactoryEnum.NODLD_NORECOVERY_XA; } else { txFactoryEnum = TxFactoryEnum.NODLD_NORECOVERY_NOXA; } } } log.tracef("Setting factory enum to %s", txFactoryEnum); } }
8,349
46.714286
149
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/XaTransactionTable.java
package org.infinispan.transaction.xa; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import jakarta.transaction.Transaction; import javax.transaction.xa.XAException; import org.infinispan.commons.CacheException; import org.infinispan.commons.tx.XidImpl; 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.transaction.impl.LocalTransaction; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.xa.recovery.RecoveryManager; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * {@link TransactionTable} to be used with {@link TransactionXaAdapter}. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class XaTransactionTable extends TransactionTable { private static final Log log = LogFactory.getLog(XaTransactionTable.class); @Inject protected RecoveryManager recoveryManager; @ComponentName(KnownComponentNames.CACHE_NAME) @Inject protected String cacheName; protected ConcurrentMap<XidImpl, LocalXaTransaction> xid2LocalTx; @Start(priority = 9) // Start before cache loader manager @SuppressWarnings("unused") public void startXidMapping() { final int concurrencyLevel = configuration.locking().concurrencyLevel(); xid2LocalTx = new ConcurrentHashMap<>(concurrencyLevel, 0.75f, concurrencyLevel); } @Override public boolean removeLocalTransaction(LocalTransaction localTx) { boolean result = false; if (localTx.getTransaction() != null) {//this can be null when we force the invocation during recovery, perhaps on a remote node result = super.removeLocalTransaction(localTx); } removeXidTxMapping((LocalXaTransaction) localTx); return result; } private void removeXidTxMapping(LocalXaTransaction localTx) { XidImpl xid = localTx.getXid(); if (xid != null) { xid2LocalTx.remove(xid); } } public LocalXaTransaction getLocalTransaction(XidImpl xid) { LocalXaTransaction localTransaction = this.xid2LocalTx.get(xid); if (localTransaction == null) { if (log.isTraceEnabled()) log.tracef("no tx found for %s", xid); } return localTransaction; } private void addLocalTransactionMapping(LocalXaTransaction localTransaction) { if (localTransaction.getXid() == null) throw new IllegalStateException("Initialize xid first!"); this.xid2LocalTx.put(localTransaction.getXid(), localTransaction); } @Override public void enlist(Transaction transaction, LocalTransaction ltx) { LocalXaTransaction localTransaction = (LocalXaTransaction) ltx; if (!localTransaction.isEnlisted()) { //make sure that you only enlist it once try { transaction.enlistResource(new TransactionXaAdapter(localTransaction, this)); } catch (Exception e) { XidImpl xid = localTransaction.getXid(); if (xid != null && !localTransaction.getLookedUpEntries().isEmpty()) { log.debug("Attempting a rollback to clear stale resources asynchronously!"); txCoordinator.rollback(localTransaction).exceptionally(t -> { log.warn("Caught exception attempting to clean up " + xid + " for " + localTransaction.getGlobalTransaction(), t); return null; }); } log.failedToEnlistTransactionXaAdapter(e); throw new CacheException(e); } } } @Override public void enlistClientTransaction(Transaction transaction, LocalTransaction localTransaction) { enlist(transaction, localTransaction); } @Override public int getLocalTxCount() { return xid2LocalTx.size(); } public CompletionStage<Integer> prepare(XidImpl xid) { LocalXaTransaction localTransaction = getLocalTransaction(xid); if (localTransaction == null) { return CompletableFuture.failedFuture(new XAException(XAException.XAER_NOTA)); } return txCoordinator.prepare(localTransaction); } public CompletionStage<Void> commit(XidImpl xid, boolean isOnePhase) { LocalXaTransaction localTransaction = getLocalTransaction(xid); if (localTransaction == null) { return CompletableFuture.failedFuture(new XAException(XAException.XAER_NOTA)); } CompletionStage<Boolean> commitStage; CompletionStage<Integer> prepareStage; //isOnePhase being true means that we're the only participant in the distributed transaction and TM does the //1PC optimization. We run a 2PC though, as running only 1PC has a high chance of leaving the cluster in //inconsistent state. if (isOnePhase && !CompletionStages.isCompletedSuccessfully(prepareStage = txCoordinator.prepare(localTransaction))) { commitStage = prepareStage.thenCompose(ignore -> txCoordinator.commit(localTransaction, false)); } else { commitStage = txCoordinator.commit(localTransaction, false); } if (CompletionStages.isCompletedSuccessfully(commitStage)) { boolean committedInOnePhase = CompletionStages.join(commitStage); forgetSuccessfullyCompletedTransaction(localTransaction, committedInOnePhase); return CompletableFutures.completedNull(); } return commitStage.thenApply(committedInOnePhase -> { forgetSuccessfullyCompletedTransaction(localTransaction, committedInOnePhase); return null; }); } CompletionStage<Void> rollback(XidImpl xid) { LocalXaTransaction localTransaction = getLocalTransaction(xid); if (localTransaction == null) { return CompletableFuture.failedFuture(new XAException(XAException.XAER_NOTA)); } localTransaction.markForRollback(true); //ISPN-879 : make sure that locks are no longer associated to this transactions return txCoordinator.rollback(localTransaction); } void start(XidImpl xid, LocalXaTransaction localTransaction) { //transform in our internal format in order to be able to serialize localTransaction.setXid(xid); addLocalTransactionMapping(localTransaction); if (log.isTraceEnabled()) log.tracef("start called on tx %s", localTransaction.getGlobalTransaction()); } void end(LocalXaTransaction localTransaction) { if (log.isTraceEnabled()) log.tracef("end called on tx %s(%s)", localTransaction.getGlobalTransaction(), cacheName); } CompletionStage<Void> forget(XidImpl xid) { if (log.isTraceEnabled()) log.tracef("forget called for xid %s", xid); if (isRecoveryEnabled()) { return recoveryManager.removeRecoveryInformation(null, xid, null, false) .exceptionally(t -> { log.warnExceptionRemovingRecovery(t); XAException xe = new XAException(XAException.XAER_RMERR); xe.initCause(t); throw new CompletionException(xe); }); } else { if (log.isTraceEnabled()) log.trace("Recovery not enabled"); } return CompletableFutures.completedNull(); } boolean isRecoveryEnabled() { return recoveryManager != null; } private void forgetSuccessfullyCompletedTransaction(LocalXaTransaction localTransaction, boolean committedInOnePhase) { final GlobalTransaction gtx = localTransaction.getGlobalTransaction(); XidImpl xid = localTransaction.getXid(); if (isRecoveryEnabled()) { recoveryManager.removeRecoveryInformation(localTransaction.getRemoteLocksAcquired(), xid, gtx, partitionHandlingManager.isTransactionPartiallyCommitted(gtx)); removeLocalTransaction(localTransaction); } else { releaseLocksForCompletedTransaction(localTransaction, committedInOnePhase); } } }
8,355
40.572139
134
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/TransactionXaAdapter.java
package org.infinispan.transaction.xa; import java.util.Objects; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.infinispan.commons.tx.AsyncXaResource; import org.infinispan.commons.tx.XidImpl; import org.infinispan.transaction.impl.AbstractEnlistmentAdapter; import org.infinispan.transaction.xa.recovery.RecoveryManager; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This acts both as an local {@link org.infinispan.transaction.xa.CacheTransaction} and implementor of an {@link * javax.transaction.xa.XAResource} that will be called by tx manager on various tx stages. * * @author Mircea.Markus@jboss.com * @since 4.0 */ public class TransactionXaAdapter extends AbstractEnlistmentAdapter implements XAResource, AsyncXaResource { private static final Log log = LogFactory.getLog(TransactionXaAdapter.class); /** * It is really useful only if TM and client are in separate processes and TM fails. This is because a client might * call tm.begin and then the TM (running separate process) crashes. In this scenario the TM won't ever call * XAResource.rollback, so these resources would be held there forever. By knowing the timeout the RM can proceed * releasing the resources associated with given tx. */ private int txTimeout; private final XaTransactionTable txTable; /** * XAResource is associated with a transaction between enlistment (XAResource.start()) XAResource.end(). It's only the * boundary methods (prepare, commit, rollback) that need to be "stateless". * Reefer to section 3.4.4 from JTA spec v.1.1 */ private final LocalXaTransaction localTransaction; private volatile RecoveryManager.RecoveryIterator recoveryIterator; public TransactionXaAdapter(LocalXaTransaction localTransaction, XaTransactionTable txTable) { super(localTransaction); this.txTable = txTable; this.localTransaction = localTransaction; } public TransactionXaAdapter(XaTransactionTable txTable) { super(); this.txTable = txTable; localTransaction = null; } /** * This can be call for any transaction object. See Section 3.4.6 (Resource Sharing) from JTA spec v1.1. */ @Override public int prepare(Xid externalXid) throws XAException { return runRethrowingXAException(txTable.prepare(XidImpl.copy(externalXid))); } /** * Same comment as for {@link #prepare(javax.transaction.xa.Xid)} applies for commit. */ @Override public void commit(Xid externalXid, boolean isOnePhase) throws XAException { runRethrowingXAException(txTable.commit(XidImpl.copy(externalXid), isOnePhase)); } /** * Same comment as for {@link #prepare(javax.transaction.xa.Xid)} applies for commit. */ @Override public void rollback(Xid externalXid) throws XAException { runRethrowingXAException(txTable.rollback(XidImpl.copy(externalXid))); } @Override public void start(Xid externalXid, int i) throws XAException { assert localTransaction != null; txTable.start(XidImpl.copy(externalXid), localTransaction); } @Override public void end(Xid externalXid, int i) { txTable.end(this.localTransaction); } @Override public void forget(Xid externalXid) throws XAException { runRethrowingXAException(txTable.forget(XidImpl.copy(externalXid))); } @Override public int getTransactionTimeout() { if (log.isTraceEnabled()) log.trace("start called"); return txTimeout; } /** * the only situation in which it returns true is when the other xa resource pertains to the same cache, on * the same node. */ @Override public boolean isSameRM(XAResource xaResource) { return isIsSameRM(xaResource); } private boolean isIsSameRM(XAResource xaResource) { if (!(xaResource instanceof TransactionXaAdapter)) { return false; } TransactionXaAdapter other = (TransactionXaAdapter) xaResource; //there is only one enlistment manager per cache and this is more efficient that equals. return this.txTable == other.txTable; } @Override public Xid[] recover(int flag) { if (!txTable.isRecoveryEnabled()) { log.recoveryIgnored(); return RecoveryManager.RecoveryIterator.NOTHING; } if (log.isTraceEnabled()) log.trace("recover called: " + flag); if (isFlag(flag, TMSTARTRSCAN)) { recoveryIterator = txTable.recoveryManager.getPreparedTransactionsFromCluster(); if (log.isTraceEnabled()) log.tracef("Fetched a new recovery iterator: %s", recoveryIterator); } if (isFlag(flag, TMENDRSCAN)) { if (log.isTraceEnabled()) log.trace("Flushing the iterator"); return recoveryIterator.all(); } else { //as per the spec: "TMNOFLAGS this flag must be used when no other flags are specified." if (!isFlag(flag, TMSTARTRSCAN) && !isFlag(flag, TMNOFLAGS)) throw new IllegalArgumentException( "TMNOFLAGS this flag must be used when no other flags are specified." + " Received " + flag); return recoveryIterator.hasNext() ? recoveryIterator.next() : RecoveryManager.RecoveryIterator.NOTHING; } } @Override public boolean setTransactionTimeout(int i) { this.txTimeout = i; return true; } @Override public String toString() { return "TransactionXaAdapter{" + "localTransaction=" + localTransaction + '}'; } public LocalXaTransaction getLocalTransaction() { return localTransaction; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionXaAdapter that = (TransactionXaAdapter) o; //also include the enlistment manager in comparison - needed when same tx spans multiple caches. return Objects.equals(localTransaction, that.localTransaction) && txTable == that.txTable; } private static boolean isFlag(int value, int flag) { return (value & flag) != 0; } private static <T> T runRethrowingXAException(CompletionStage<T> completionStage) throws XAException { try { return CompletionStages.join(completionStage); } catch (CompletionException e) { Throwable cause = e.getCause(); if (cause instanceof XAException) { throw (XAException) cause; } throw e; } } @Override public CompletionStage<Void> asyncEnd(XidImpl xid, int flags) { txTable.end(localTransaction); return CompletableFutures.completedNull(); } @Override public CompletionStage<Integer> asyncPrepare(XidImpl xid) { return txTable.prepare(xid); } @Override public CompletionStage<Void> asyncCommit(XidImpl xid, boolean onePhase) { return txTable.commit(xid, onePhase); } @Override public CompletionStage<Void> asyncRollback(XidImpl xid) { return txTable.rollback(xid); } }
7,438
32.660633
121
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/RecoveryAwareLocalTransaction.java
package org.infinispan.transaction.xa.recovery; import jakarta.transaction.Transaction; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.transaction.xa.LocalXaTransaction; /** * Extends {@link org.infinispan.transaction.xa.LocalXaTransaction} and adds recovery related information. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class RecoveryAwareLocalTransaction extends LocalXaTransaction implements RecoveryAwareTransaction { private boolean prepared; private boolean completionFailed; public RecoveryAwareLocalTransaction(Transaction transaction, GlobalTransaction tx, boolean implicitTransaction, int topologyId, long txCreationTime) { super(transaction, tx, implicitTransaction, topologyId, txCreationTime); } @Override public boolean isPrepared() { return prepared; } @Override public void setPrepared(boolean prepared) { this.prepared = prepared; } /** * Returns true if this transaction failed during 2nd phase of 2PC(prepare or commit). E.g. when the transaction successfully * prepared but the commit failed due to a network issue. */ public boolean isCompletionFailed() { return completionFailed; } /** * @see #isCompletionFailed() */ public void setCompletionFailed(boolean completionFailed) { this.completionFailed = completionFailed; } }
1,449
28
128
java