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/transaction/xa/recovery/RecoveryAwareRemoteTransaction.java
package org.infinispan.transaction.xa.recovery; import java.util.Collection; import java.util.List; import jakarta.transaction.Status; import org.infinispan.commands.write.WriteCommand; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.impl.RemoteTransaction; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Extends {@link org.infinispan.transaction.impl.RemoteTransaction} and adds recovery related information and functionality. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class RecoveryAwareRemoteTransaction extends RemoteTransaction implements RecoveryAwareTransaction { private static final Log log = LogFactory.getLog(RecoveryAwareRemoteTransaction.class); private boolean prepared; private boolean isOrphan; private Integer status; public RecoveryAwareRemoteTransaction(List<WriteCommand> modifications, GlobalTransaction tx, int topologyId, long txCreationTime) { super(modifications, tx, topologyId, txCreationTime); } /** * A transaction is in doubt if it is prepared and and it is orphan. */ public boolean isInDoubt() { return prepared && isOrphan; } /** * A remote transaction is orphan if the node on which the transaction originated (ie the originator) is no longer * part of the cluster. */ public boolean isOrphan() { return isOrphan; } /** * Check's if this transaction's originator is no longer part of the cluster (orphan transaction) and updates * {@link #isOrphan()}. * @param currentMembers The current members of the cache. */ public void computeOrphan(Collection<Address> currentMembers) { if (!currentMembers.contains(getGlobalTransaction().getAddress())) { if (log.isTraceEnabled()) log.tracef("This transaction's originator has left the cluster: %s", getGlobalTransaction()); isOrphan = true; } } @Override public boolean isPrepared() { return prepared; } @Override public void setPrepared(boolean prepared) { this.prepared = prepared; if (prepared) status = Status.STATUS_PREPARED; } @Override public String toString() { return getClass().getSimpleName() + "{prepared=" + prepared + ", isOrphan=" + isOrphan + ", modifications=" + modifications + ", lookedUpEntries=" + lookedUpEntries + ", tx=" + tx + "} "; } /** * Called when after the 2nd phase of a 2PC is successful. * * @param committed true if tx successfully committed, false if tx successfully rolled back. */ public void markCompleted(boolean committed) { status = committed ? Status.STATUS_COMMITTED : Status.STATUS_ROLLEDBACK; } /** * Following values might be returned: * <ul> * <li> - {@link Status#STATUS_PREPARED} if the tx is prepared </li> * <li> - {@link Status#STATUS_COMMITTED} if the tx is committed</li> * <li> - {@link Status#STATUS_ROLLEDBACK} if the tx is rollback</li> * <li> - null otherwise</li> * </ul> */ public Integer getStatus() { return status; } }
3,320
30.037383
128
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/RecoveryManagerImpl.java
package org.infinispan.transaction.xa.recovery; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import org.infinispan.commands.CommandsFactory; 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.commons.CacheException; import org.infinispan.commons.tx.XidImpl; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.remoting.responses.Response; import org.infinispan.remoting.responses.SuccessfulResponse; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.impl.MapResponseCollector; import org.infinispan.remoting.transport.impl.VoidResponseCollector; import org.infinispan.transaction.impl.LocalTransaction; import org.infinispan.transaction.impl.TransactionCoordinator; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.transaction.xa.LocalXaTransaction; import org.infinispan.transaction.xa.TransactionFactory; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Default implementation for {@link RecoveryManager} * * @author Mircea.Markus@jboss.com * @since 5.0 */ @Scope(Scopes.NAMED_CACHE) public class RecoveryManagerImpl implements RecoveryManager { private static final Log log = LogFactory.getLog(RecoveryManagerImpl.class); private volatile RpcManager rpcManager; private volatile CommandsFactory commandFactory; /** * This relies on XIDs for different TMs being unique. E.g. for JBossTM this is correct as long as we have the right * config for <IP,port/process,sequence number>. This is expected to stand true for all major TM on the market. */ private final ConcurrentMap<RecoveryInfoKey, RecoveryAwareRemoteTransaction> inDoubtTransactions; private final String cacheName; private ComponentRef<TransactionTable> txTable; private TransactionCoordinator txCoordinator; private TransactionFactory txFactory; /** * we only broadcast the first time when node is started, then we just return the local cached prepared * transactions. */ private volatile boolean broadcastForPreparedTx = true; public RecoveryManagerImpl(ConcurrentMap<RecoveryInfoKey, RecoveryAwareRemoteTransaction> recoveryHolder, String cacheName) { this.inDoubtTransactions = recoveryHolder; this.cacheName = cacheName; } @Inject public void init(RpcManager rpcManager, CommandsFactory commandsFactory, ComponentRef<TransactionTable> txTable, TransactionCoordinator txCoordinator, TransactionFactory txFactory) { this.rpcManager = rpcManager; this.commandFactory = commandsFactory; this.txTable = txTable; this.txCoordinator = txCoordinator; this.txFactory = txFactory; } @Override public RecoveryIterator getPreparedTransactionsFromCluster() { PreparedTxIterator iterator = new PreparedTxIterator(); //1. get local transactions first //add the locally prepared transactions. The list of prepared transactions (even if they are not in-doubt) //is mandated by the recovery process according to the JTA spec: "The transaction manager calls this [i.e. recover] // method during recovery to obtain the list of transaction branches that are currently in prepared or heuristically // completed states." iterator.add((recoveryAwareTxTable()).getLocalPreparedXids()); //2. now also add the in-doubt transactions. iterator.add(getInDoubtTransactions()); //3. then the remote ones if (notOnlyMeInTheCluster() && broadcastForPreparedTx) { boolean success = true; Map<Address, Response> responses = getAllPreparedTxFromCluster(); for (Map.Entry<Address, Response> rEntry : responses.entrySet()) { Response thisResponse = rEntry.getValue(); if (isSuccessful(thisResponse)) { //noinspection unchecked List<XidImpl> responseValue = ((SuccessfulResponse<List<XidImpl>>) thisResponse).getResponseValue(); if (log.isTraceEnabled()) { log.tracef("Received Xid lists %s from node %s", responseValue, rEntry.getKey()); } iterator.add(responseValue); } else { log.missingListPreparedTransactions(rEntry.getKey(), rEntry.getValue()); success = false; } } //this makes sure that the broadcast only happens once! this.broadcastForPreparedTx = !success; if (!broadcastForPreparedTx) log.debug("Finished broadcasting for remote prepared transactions. Returning only local values from now on."); } return iterator; } @Override public CompletionStage<Void> removeRecoveryInformation(Collection<Address> lockOwners, XidImpl xid, GlobalTransaction gtx, boolean fromCluster) { if (log.isTraceEnabled()) log.tracef("Forgetting tx information for %s", gtx); //todo make sure this gets broad casted or at least flushed if (rpcManager != null && !fromCluster) { TxCompletionNotificationCommand ftc = commandFactory.buildTxCompletionNotificationCommand(xid, gtx); CompletionStage<Void> stage = sendTxCompletionNotification(lockOwners, ftc); removeRecoveryInformation(xid); return stage; } else { removeRecoveryInformation(xid); return CompletableFutures.completedNull(); } } @Override public CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId) { if (rpcManager != null) { TxCompletionNotificationCommand ftc = commandFactory.buildTxCompletionNotificationCommand(internalId); CompletionStage<Void> stage = sendTxCompletionNotification(where, ftc); removeRecoveryInformation(internalId); return stage; } else { removeRecoveryInformation(internalId); return CompletableFutures.completedNull(); } } private CompletionStage<Void> sendTxCompletionNotification(Collection<Address> where, TxCompletionNotificationCommand ftc) { ftc.setTopologyId(rpcManager.getTopologyId()); if (where == null) return rpcManager.invokeCommandOnAll(ftc, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); else return rpcManager.invokeCommand(where, ftc, VoidResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); } @Override public RecoveryAwareTransaction removeRecoveryInformation(XidImpl xid) { RecoveryAwareTransaction remove = inDoubtTransactions.remove(new RecoveryInfoKey(xid, cacheName)); log.tracef("removed in doubt xid: %s", xid); if (remove == null) { return (RecoveryAwareTransaction) recoveryAwareTxTable().removeRemoteTransaction(xid); } return remove; } @Override public RecoveryAwareTransaction removeRecoveryInformation(Long internalId) { XidImpl remoteTransactionXid = recoveryAwareTxTable().getRemoteTransactionXid(internalId); if (remoteTransactionXid != null) { return removeRecoveryInformation(remoteTransactionXid); } else { for (RecoveryAwareRemoteTransaction raRemoteTx : inDoubtTransactions.values()) { GlobalTransaction globalTransaction = raRemoteTx.getGlobalTransaction(); if (internalId.equals(globalTransaction.getInternalId())) { XidImpl xid = globalTransaction.getXid(); log.tracef("Found transaction xid %s that maps internal id %s", xid, internalId); removeRecoveryInformation(xid); return raRemoteTx; } } } log.tracef("Could not find tx to map to internal id %s", internalId); return null; } @Override public List<XidImpl> getInDoubtTransactions() { List<XidImpl> result = inDoubtTransactions.keySet().stream() .filter(recoveryInfoKey -> recoveryInfoKey.cacheName.equals(cacheName)) .map(recoveryInfoKey -> recoveryInfoKey.xid) .collect(Collectors.toList()); log.tracef("Returning %s ", result); return result; } @Override public Set<InDoubtTxInfo> getInDoubtTransactionInfo() { Set<RecoveryAwareLocalTransaction> localTxs = recoveryAwareTxTable().getLocalTxThatFailedToComplete(); log.tracef("Local transactions that failed to complete is %s", localTxs); Set<InDoubtTxInfo> result = new HashSet<>(); for (RecoveryAwareLocalTransaction r : localTxs) { long internalId = r.getGlobalTransaction().getInternalId(); result.add(new InDoubtTxInfo(r.getXid(), internalId)); } for (XidImpl xid : getInDoubtTransactions()) { RecoveryAwareRemoteTransaction pTx = getPreparedTransaction(xid); if (pTx == null) continue; //might be removed concurrently, 2check for null GlobalTransaction gtx = pTx.getGlobalTransaction(); InDoubtTxInfo infoInDoubt = new InDoubtTxInfo(xid, gtx.getInternalId(), pTx.getStatus()); result.add(infoInDoubt); } log.tracef("The set of in-doubt txs from this node is %s", result); return result; } @Override public Set<InDoubtTxInfo> getInDoubtTransactionInfoFromCluster() { Map<XidImpl, InDoubtTxInfo> result = new HashMap<>(); if (rpcManager != null) { GetInDoubtTxInfoCommand inDoubtTxInfoCommand = commandFactory.buildGetInDoubtTxInfoCommand(); CompletionStage<Map<Address, Response>> completionStage = rpcManager.invokeCommandOnAll(inDoubtTxInfoCommand, MapResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); Map<Address, Response> addressResponseMap = rpcManager.blocking(completionStage); for (Map.Entry<Address, Response> re : addressResponseMap.entrySet()) { Response r = re.getValue(); if (!isSuccessful(r)) { throw new CacheException("Could not fetch in doubt transactions: " + r); } // noinspection unchecked Set<InDoubtTxInfo> infoInDoubtSet = ((SuccessfulResponse<Set<InDoubtTxInfo>>) r).getResponseValue(); for (InDoubtTxInfo infoInDoubt : infoInDoubtSet) { InDoubtTxInfo inDoubtTxInfo = result.get(infoInDoubt.getXid()); if (inDoubtTxInfo == null) { inDoubtTxInfo = infoInDoubt; result.put(infoInDoubt.getXid(), inDoubtTxInfo); } else { inDoubtTxInfo.setStatus(infoInDoubt.getStatus()); } inDoubtTxInfo.addOwner(re.getKey()); } } } Set<InDoubtTxInfo> onThisNode = getInDoubtTransactionInfo(); Iterator<InDoubtTxInfo> iterator = onThisNode.iterator(); while (iterator.hasNext()) { InDoubtTxInfo info = iterator.next(); InDoubtTxInfo inDoubtTxInfo = result.get(info.getXid()); if (inDoubtTxInfo != null) { inDoubtTxInfo.setLocal(true); iterator.remove(); } else { info.setLocal(true); } } HashSet<InDoubtTxInfo> value = new HashSet<>(result.values()); value.addAll(onThisNode); return value; } public void registerInDoubtTransaction(RecoveryAwareRemoteTransaction remoteTransaction) { XidImpl xid = remoteTransaction.getGlobalTransaction().getXid(); RecoveryAwareTransaction previous = inDoubtTransactions.put(new RecoveryInfoKey(xid, cacheName), remoteTransaction); if (previous != null) { log.preparedTxAlreadyExists(previous, remoteTransaction); throw new IllegalStateException("Are there two different transactions having same Xid in the cluster?"); } } @Override public RecoveryAwareRemoteTransaction getPreparedTransaction(XidImpl xid) { return inDoubtTransactions.get(new RecoveryInfoKey(xid, cacheName)); } @Override public CompletionStage<String> forceTransactionCompletion(XidImpl xid, boolean commit) { //this means that we have this as a local transaction that originated here LocalXaTransaction localTransaction = recoveryAwareTxTable().getLocalTransaction(xid); if (localTransaction != null) { localTransaction.clearRemoteLocksAcquired(); return completeTransaction(localTransaction, commit, xid); } else { RecoveryAwareRemoteTransaction tx = getPreparedTransaction(xid); if (tx == null) return CompletableFuture.completedFuture("Could not find transaction " + xid); GlobalTransaction globalTransaction = tx.getGlobalTransaction(); globalTransaction.setAddress(rpcManager.getAddress()); globalTransaction.setRemote(false); RecoveryAwareLocalTransaction localTx = (RecoveryAwareLocalTransaction) txFactory.newLocalTransaction(null, globalTransaction, false, tx.getTopologyId()); localTx.setModifications(tx.getModifications()); localTx.setXid(xid); localTx.addAllAffectedKeys(tx.getAffectedKeys()); for (Object lk : tx.getLockedKeys()) localTx.registerLockedKey(lk); return completeTransaction(localTx, commit, xid); } } private CompletionStage<String> completeTransaction(LocalTransaction localTx, boolean commit, XidImpl xid) { GlobalTransaction gtx = localTx.getGlobalTransaction(); if (commit) { localTx.clearLookedUpEntries(); return txCoordinator.prepare(localTx, true) .thenCompose(ignore -> txCoordinator.commit(localTx, false)) .thenCompose(ignore -> removeRecoveryInformation(null, xid, gtx, false)) .thenApply(ignore -> "Commit successful!") .exceptionally(t -> { log.warnCouldNotCommitLocalTx(localTx, t); return "Could not commit transaction " + xid + " : " + t.getMessage(); }); } else { return txCoordinator.rollback(localTx) .thenCompose(ignore -> removeRecoveryInformation(null, xid, gtx, false)) .thenApply(ignore -> "Rollback successful") .exceptionally(t -> { log.warnCouldNotRollbackLocalTx(localTx, t); return "Could not rollback transaction " + xid + " : " + t.getMessage(); }); } } @Override public String forceTransactionCompletionFromCluster(XidImpl xid, Address where, boolean commit) { CompleteTransactionCommand ctc = commandFactory.buildCompleteTransactionCommand(xid, commit); CompletionStage<Map<Address, Response>> completionStage = rpcManager.invokeCommand(where, ctc, MapResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()); Map<Address, Response> responseMap = rpcManager.blocking(completionStage); if (responseMap.size() != 1 || responseMap.get(where) == null) { log.expectedJustOneResponse(responseMap); throw new CacheException("Expected response size is 1, received " + responseMap); } //noinspection rawtypes return (String) ((SuccessfulResponse) responseMap.get(where)).getResponseValue(); } @Override public boolean isTransactionPrepared(GlobalTransaction globalTx) { XidImpl xid = globalTx.getXid(); RecoveryAwareRemoteTransaction remoteTransaction = (RecoveryAwareRemoteTransaction) recoveryAwareTxTable().getRemoteTransaction(globalTx); boolean remotePrepared = remoteTransaction != null && remoteTransaction.isPrepared(); boolean result = inDoubtTransactions.get(new RecoveryInfoKey(xid, cacheName)) != null//if it is in doubt must be prepared || recoveryAwareTxTable().getLocalPreparedXids().contains(xid) || remotePrepared; if (log.isTraceEnabled()) log.tracef("Is tx %s prepared? %s", xid, result); return result; } private RecoveryAwareTransactionTable recoveryAwareTxTable() { return (RecoveryAwareTransactionTable) txTable.running(); } private boolean isSuccessful(Response thisResponse) { return thisResponse != null && thisResponse.isValid() && thisResponse.isSuccessful(); } private boolean notOnlyMeInTheCluster() { return rpcManager != null && rpcManager.getTransport().getMembers().size() > 1; } private Map<Address, Response> getAllPreparedTxFromCluster() { GetInDoubtTransactionsCommand command = commandFactory.buildGetInDoubtTransactionsCommand(); CompletionStage<Map<Address, Response>> completionStage = rpcManager.invokeCommandOnAll(command, MapResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); Map<Address, Response> addressResponseMap = rpcManager.blocking(completionStage); if (log.isTraceEnabled()) log.tracef("getAllPreparedTxFromCluster received from cluster: %s", addressResponseMap); return addressResponseMap; } public ConcurrentMap<RecoveryInfoKey, RecoveryAwareRemoteTransaction> getInDoubtTransactionsMap() { return inDoubtTransactions; } }
17,980
46.318421
173
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/RecoveryAdminOperations.java
package org.infinispan.transaction.xa.recovery; import java.util.Set; import org.infinispan.commons.tx.Util; import org.infinispan.commons.tx.XidImpl; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedOperation; import org.infinispan.jmx.annotations.Parameter; import org.infinispan.remoting.transport.Address; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Admin utility class for allowing management of in-doubt transactions (e.g. transactions for which the * originator node crashed after prepare). * * @author Mircea Markus * @since 5.0 */ @Scope(Scopes.NAMED_CACHE) @SurvivesRestarts @MBean(objectName = "RecoveryAdmin", description = "Exposes tooling for handling transaction recovery.") public class RecoveryAdminOperations { private static final Log log = LogFactory.getLog(RecoveryAdminOperations.class); private static final String SEPARATOR = ", "; @Inject RecoveryManager recoveryManager; @ManagedOperation(description = "Shows all the prepared transactions for which the originating node crashed", displayName="Show in doubt transactions") public String showInDoubtTransactions() { Set<InDoubtTxInfo> info = getRecoveryInfoFromCluster(); if (log.isTraceEnabled()) { log.tracef("Found in doubt transactions: %s", info.size()); } StringBuilder result = new StringBuilder(); for (InDoubtTxInfo i : info) { result.append("xid = [").append(i.getXid()).append("], ").append(SEPARATOR) .append("internalId = ").append(i.getInternalId()).append(SEPARATOR); result.append("status = [ "); int status = i.getStatus(); if (status != -1) result.append(Util.transactionStatusToString(status)); result.append(" ]"); result.append('\n'); } return result.toString(); } @ManagedOperation(description = "Forces the commit of an in-doubt transaction", displayName="Force commit by internal id") public String forceCommit(@Parameter(name = "internalId", description = "The internal identifier of the transaction") long internalId) { if (log.isTraceEnabled()) log.tracef("Forces the commit of an in-doubt transaction: %s", internalId); return completeBasedOnInternalId(internalId, true); } @ManagedOperation(description = "Forces the commit of an in-doubt transaction", displayName="Force commit by Xid", name="forceCommit") public String forceCommit( @Parameter(name = "formatId", description = "The formatId of the transaction") int formatId, @Parameter(name = "globalTxId", description = "The globalTxId of the transaction") byte[] globalTxId, @Parameter(name = "branchQualifier", description = "The branchQualifier of the transaction") byte[] branchQualifier) { return completeBasedOnXid(formatId, globalTxId, branchQualifier, true); } @ManagedOperation(description = "Forces the rollback of an in-doubt transaction", displayName="Force rollback by internal id") public String forceRollback(@Parameter(name = "internalId", description = "The internal identifier of the transaction") long internalId) { return completeBasedOnInternalId(internalId, false); } @ManagedOperation(description = "Forces the rollback of an in-doubt transaction", displayName="Force rollback by Xid", name="forceRollback") public String forceRollback( @Parameter(name = "formatId", description = "The formatId of the transaction") int formatId, @Parameter(name = "globalTxId", description = "The globalTxId of the transaction") byte[] globalTxId, @Parameter(name = "branchQualifier", description = "The branchQualifier of the transaction") byte[] branchQualifier) { return completeBasedOnXid(formatId, globalTxId, branchQualifier, false); } @ManagedOperation(description = "Removes recovery info for the given transaction.", displayName="Remove recovery info by Xid", name="forget") public String forget( @Parameter(name = "formatId", description = "The formatId of the transaction") int formatId, @Parameter(name = "globalTxId", description = "The globalTxId of the transaction") byte[] globalTxId, @Parameter(name = "branchQualifier", description = "The branchQualifier of the transaction") byte[] branchQualifier) { CompletionStages.join(recoveryManager.removeRecoveryInformation(null, XidImpl.create(formatId, globalTxId, branchQualifier), null, false)); return "Recovery info removed."; } @ManagedOperation(description = "Removes recovery info for the given transaction.", displayName="Remove recovery info by internal id") public String forget(@Parameter(name = "internalId", description = "The internal identifier of the transaction") long internalId) { CompletionStages.join(recoveryManager.removeRecoveryInformationFromCluster(null, internalId)); return "Recovery info removed."; } private String completeBasedOnXid(int formatId, byte[] globalTxId, byte[] branchQualifier, boolean commit) { InDoubtTxInfo inDoubtTxInfo = lookupRecoveryInfo(formatId, globalTxId, branchQualifier); if (inDoubtTxInfo != null) { return completeTransaction(inDoubtTxInfo, commit); } else { return transactionNotFound(formatId, globalTxId, branchQualifier); } } private String completeBasedOnInternalId(long internalId, boolean commit) { InDoubtTxInfo inDoubtTxInfo = lookupRecoveryInfo(internalId); if (inDoubtTxInfo != null) { return completeTransaction(inDoubtTxInfo, commit); } else { return transactionNotFound(internalId); } } private String completeTransaction(InDoubtTxInfo i, boolean commit) { //try to run it locally at first if (i.isLocal()) { log.tracef("Forcing completion of local transaction: %s", i); return CompletionStages.join(recoveryManager.forceTransactionCompletion(i.getXid(), commit)); } else { log.tracef("Forcing completion of remote transaction: %s", i); Set<Address> owners = i.getOwners(); if (owners == null || owners.isEmpty()) throw new IllegalStateException("Owner list cannot be empty for " + i); return recoveryManager.forceTransactionCompletionFromCluster(i.getXid(), owners.iterator().next(), commit); } } private InDoubtTxInfo lookupRecoveryInfo(int formatId, byte[] globalTxId, byte[] branchQualifier) { Set<InDoubtTxInfo> info = getRecoveryInfoFromCluster(); XidImpl xid = XidImpl.create(formatId, globalTxId, branchQualifier); for (InDoubtTxInfo i : info) { if (i.getXid().equals(xid)) { log.tracef("Found matching recovery info: %s", i); return i; } } return null; } private Set<InDoubtTxInfo> getRecoveryInfoFromCluster() { Set<InDoubtTxInfo> info = recoveryManager.getInDoubtTransactionInfoFromCluster(); log.tracef("Recovery info from cluster is: %s", info); return info; } private InDoubtTxInfo lookupRecoveryInfo(long internalId) { Set<InDoubtTxInfo> info = getRecoveryInfoFromCluster(); for (InDoubtTxInfo i : info) { if (i.getInternalId() == internalId) { log.tracef("Found matching recovery info: %s", i); return i; } } return null; } private String transactionNotFound(int formatId, byte[] globalTxId, byte[] branchQualifier) { return "Transaction not found: " + XidImpl.printXid(formatId, globalTxId, branchQualifier); } private String transactionNotFound(long internalId) { return "Transaction not found for internal id: " + internalId; } }
8,055
46.668639
154
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/RecoveryInfoKey.java
package org.infinispan.transaction.xa.recovery; import java.util.Objects; import org.infinispan.commons.tx.XidImpl; /** * This makes sure that only xids pertaining to a certain cache are being returned when needed. This is required as the * {@link RecoveryManagerImpl#registerInDoubtTransaction(RecoveryAwareRemoteTransaction)} is shared between different * RecoveryManagers/caches. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public final class RecoveryInfoKey { final XidImpl xid; final String cacheName; public RecoveryInfoKey(XidImpl xid, String cacheName) { this.xid = xid; this.cacheName = cacheName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RecoveryInfoKey recoveryInfoKey = (RecoveryInfoKey) o; return Objects.equals(cacheName, recoveryInfoKey.cacheName) && Objects.equals(xid, recoveryInfoKey.xid); } @Override public int hashCode() { int result = xid != null ? xid.hashCode() : 0; result = 31 * result + (cacheName != null ? cacheName.hashCode() : 0); return result; } @Override public String toString() { return "RecoveryInfoKey{" + "xid=" + xid + ", cacheName='" + cacheName + '\'' + '}'; } }
1,357
26.16
119
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/RecoveryAwareTransactionTable.java
package org.infinispan.transaction.xa.recovery; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import jakarta.transaction.Transaction; import org.infinispan.commons.CacheException; import org.infinispan.commons.tx.XidImpl; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.impl.LocalTransaction; import org.infinispan.transaction.impl.RemoteTransaction; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.transaction.xa.LocalXaTransaction; import org.infinispan.transaction.xa.XaTransactionTable; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Transaction table that delegates prepared transaction's management to the {@link RecoveryManager}. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class RecoveryAwareTransactionTable extends XaTransactionTable { private static final Log log = LogFactory.getLog(RecoveryAwareTransactionTable.class); /** * Marks the transaction as prepared. If at a further point the originator fails, the transaction is removed form the * "normal" transactions collection and moved into the cache that holds in-doubt transactions. * See {@link #cleanupLeaverTransactions(java.util.List)} */ @Override public void remoteTransactionPrepared(GlobalTransaction gtx) { RecoveryAwareRemoteTransaction remoteTransaction = (RecoveryAwareRemoteTransaction) getRemoteTransaction(gtx); if (remoteTransaction == null) throw new CacheException(String.format( "Remote transaction for global transaction (%s) not found", gtx)); remoteTransaction.setPrepared(true); } /** * @see #localTransactionPrepared(org.infinispan.transaction.impl.LocalTransaction) */ @Override public void localTransactionPrepared(LocalTransaction localTransaction) { ((RecoveryAwareLocalTransaction) localTransaction).setPrepared(true); } /** * First moves the prepared transactions originated on the leavers into the recovery cache and then cleans up the * transactions that are not yet prepared. * @param members The list of cluster members */ @Override public void cleanupLeaverTransactions(List<Address> members) { Iterator<RemoteTransaction> it = getRemoteTransactions().iterator(); HashSet<Address> membersSet = new HashSet<>(members); //faster lookup while (it.hasNext()) { RecoveryAwareRemoteTransaction recTx = (RecoveryAwareRemoteTransaction) it.next(); if (!transactionOriginatorChecker.isOriginatorMissing(recTx.getGlobalTransaction(), membersSet)) { continue; //Hot Rod transaction } recTx.computeOrphan(membersSet); if (recTx.isInDoubt()) { recoveryManager.registerInDoubtTransaction(recTx); it.remove(); } } //this cleans up the transactions that are not yet prepared super.cleanupLeaverTransactions(members); } @Override public RemoteTransaction getRemoteTransaction(GlobalTransaction txId) { RemoteTransaction remoteTransaction = super.getRemoteTransaction(txId); if (remoteTransaction != null) return remoteTransaction; //also look in the recovery manager, as this transaction might be prepared return (RemoteTransaction) recoveryManager .getPreparedTransaction(txId.getXid()); } @Override public void remoteTransactionRollback(GlobalTransaction gtx) { super.remoteTransactionRollback(gtx); recoveryManager.removeRecoveryInformation(gtx.getXid()); } @Override public void remoteTransactionCommitted(GlobalTransaction gtx, boolean onePc) { RecoveryAwareRemoteTransaction remoteTransaction = (RecoveryAwareRemoteTransaction) getRemoteTransaction(gtx); if (remoteTransaction == null) throw new CacheException(String.format("Remote transaction for global transaction (%s) not found", gtx)); remoteTransaction.markCompleted(true); super.remoteTransactionCommitted(gtx, onePc); } public List<XidImpl> getLocalPreparedXids() { List<XidImpl> result = new LinkedList<>(); for (Map.Entry<XidImpl, LocalXaTransaction> e : xid2LocalTx.entrySet()) { RecoveryAwareLocalTransaction value = (RecoveryAwareLocalTransaction) e.getValue(); if (value.isPrepared()) { result.add(e.getKey()); } } return result; } @Override public void failureCompletingTransaction(Transaction tx) { // TODO Change the Transaction parameter to LocalTransaction to avoid the reverse lookup and the // NullPointerException when called from RecoveryManagerImpl.forceTransactionCompletion RecoveryAwareLocalTransaction localTx = (RecoveryAwareLocalTransaction) getLocalTransaction(tx); if (localTx == null) throw new CacheException(String.format("Local transaction for transaction (%s) not found", tx)); localTx.setCompletionFailed(true); log.tracef("Marked as completion failed %s", localTx); } public Set<RecoveryAwareLocalTransaction> getLocalTxThatFailedToComplete() { Set<RecoveryAwareLocalTransaction> result = new HashSet<>(4); for (LocalTransaction lTx : xid2LocalTx.values()) { RecoveryAwareLocalTransaction lTx1 = (RecoveryAwareLocalTransaction) lTx; if (lTx1.isCompletionFailed()) { result.add(lTx1); } } return result; } /** * Iterates over the remote transactions and returns the XID of the one that has an internal id equal with the * supplied internal Id. */ public XidImpl getRemoteTransactionXid(Long internalId) { for (RemoteTransaction rTx : getRemoteTransactions()) { GlobalTransaction gtx = rTx.getGlobalTransaction(); if (gtx.getInternalId() == internalId) { if (log.isTraceEnabled()) log.tracef("Found xid %s matching internal id %s", gtx.getXid(), internalId); return gtx.getXid(); } } if (log.isTraceEnabled()) log.tracef("Could not find remote transactions matching internal id %s", internalId); return null; } public RemoteTransaction removeRemoteTransaction(XidImpl xid) { if (clustered) { Iterator<RemoteTransaction> it = getRemoteTransactions().iterator(); while (it.hasNext()) { RemoteTransaction next = it.next(); GlobalTransaction gtx = next.getGlobalTransaction(); if (xid.equals(gtx.getXid())) { it.remove(); recalculateMinTopologyIdIfNeeded(next); next.notifyOnTransactionFinished(); return next; } } } return null; } }
6,880
39.005814
120
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/RecoveryAwareTransaction.java
package org.infinispan.transaction.xa.recovery; import org.infinispan.transaction.xa.CacheTransaction; /** * Base interface for transactions that are holders of recovery information. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public interface RecoveryAwareTransaction extends CacheTransaction { boolean isPrepared(); void setPrepared(boolean prepared); }
379
21.352941
76
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/PreparedTxIterator.java
package org.infinispan.transaction.xa.recovery; import java.util.HashSet; import java.util.List; import org.infinispan.commons.tx.XidImpl; /** * Default implementation for RecoveryIterator. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public class PreparedTxIterator implements RecoveryManager.RecoveryIterator { private final HashSet<XidImpl> xids = new HashSet<>(4); @Override public boolean hasNext() { return !xids.isEmpty(); } @Override public XidImpl[] next() { XidImpl[] result = xids.toArray(new XidImpl[0]); xids.clear(); return result; } public void add(List<XidImpl> xids) { this.xids.addAll(xids); } @Override public XidImpl[] all() { return next(); } @Override public void remove() { throw new RuntimeException("Unsupported operation!"); } }
859
18.545455
77
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/RecoveryManager.java
package org.infinispan.transaction.xa.recovery; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.CompletionStage; import org.infinispan.commons.tx.XidImpl; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.xa.GlobalTransaction; /** * RecoveryManager is the component responsible with managing recovery related information and the functionality * associated with it. Refer to <a href="http://community.jboss.org/wiki/Transactionrecoverydesign">this</a> document * for details on the design of recovery. * * @author Mircea.Markus@jboss.com * @since 5.0 */ public interface RecoveryManager { /** * Returns the list of transactions in prepared state from both local and remote cluster nodes. Implementation can * take advantage of several optimisations: * * <ul> * <li>in order to get all tx from the cluster a broadcast is performed. This can be performed only once * (assuming the call is successful), the first time this method is called. After that a local, cached list of tx * prepared on this node is returned.</li> * <li>during the broadcast just return the list of prepared transactions that are not originated on other active * nodes of the cluster.</li> * </ul> */ RecoveryIterator getPreparedTransactionsFromCluster(); /** * Returns a {@link Set} containing all the in-doubt transactions from the cluster, including the local node. This * does not include transactions that are prepared successfully and for which the originator is still in the * cluster. * * @see InDoubtTxInfo */ Set<InDoubtTxInfo> getInDoubtTransactionInfoFromCluster(); /** * Same as {@link #getInDoubtTransactionInfoFromCluster()}, but only returns transactions from the local node. */ Set<InDoubtTxInfo> getInDoubtTransactionInfo(); /** * Removes from the specified nodes (or all nodes if the value of 'where' is null) the recovery information * associated with these Xids. * * @param where on which nodes should this be executed. * @param xid the list of xids to be removed. * @param gtx the global transaction * @param fromCluster {@code true} to remove the recovery information from all cluster. */ CompletionStage<Void> removeRecoveryInformation(Collection<Address> where, XidImpl xid, GlobalTransaction gtx, boolean fromCluster); /** * Same as {@link #removeRecoveryInformation(Collection, XidImpl, GlobalTransaction, boolean)} * but the transaction is identified by its internal id, and not by its xid. */ CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId); /** * Local call that returns a list containing: * <pre> * - all the remote transactions prepared on this node for which the originator(i.e. the node where the tx * stared) is no longer part of the cluster. * AND * - all the locally originated transactions which are prepared and for which the commit failed * </pre> * * @see RecoveryAwareRemoteTransaction#isInDoubt() */ List<XidImpl> getInDoubtTransactions(); /** * Local call returning the remote transaction identified by the supplied xid or null. */ RecoveryAwareTransaction getPreparedTransaction(XidImpl xid); /** * Replays the given transaction by re-running the prepare and commit. This call expects the transaction to exist on * this node either as a local or remote transaction. * * @param xid tx to commit or rollback * @param commit if true tx is committed, if false it is rolled back */ CompletionStage<String> forceTransactionCompletion(XidImpl xid, boolean commit); /** * This method invokes {@link #forceTransactionCompletion(XidImpl, boolean)} on the specified node. */ String forceTransactionCompletionFromCluster(XidImpl xid, Address where, boolean commit); /** * Checks both internal state and transaction table's state for the given tx. If it finds it, returns true if tx * is prepared. */ boolean isTransactionPrepared(GlobalTransaction globalTx); /** * Same as {@link #removeRecoveryInformation(XidImpl)} but identifies the tx by its internal id. */ RecoveryAwareTransaction removeRecoveryInformation(Long internalId); /** * Remove recovery information stored on this node (doesn't involve rpc). * * @see #removeRecoveryInformation(Collection, XidImpl, GlobalTransaction, boolean) */ RecoveryAwareTransaction removeRecoveryInformation(XidImpl xid); void registerInDoubtTransaction(RecoveryAwareRemoteTransaction tx); /** * Stateful structure allowing prepared-tx retrieval in a batch-oriented manner, as required by {@link * javax.transaction.xa.XAResource#recover(int)}. */ interface RecoveryIterator extends Iterator<XidImpl[]> { XidImpl[] NOTHING = new XidImpl[]{}; /** * Exhaust the iterator. After this call, {@link #hasNext()} returns false. */ XidImpl[] all(); } }
5,187
37.147059
119
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/xa/recovery/InDoubtTxInfo.java
package org.infinispan.transaction.xa.recovery; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.tx.XidImpl; import org.infinispan.marshall.core.Ids; import org.infinispan.remoting.transport.Address; /** * An object describing in doubt transaction's state. Needed by the transaction recovery process, for displaying * transactions to the user. * * @author Mircea Markus * @since 5.0 */ public class InDoubtTxInfo { public static final AbstractExternalizer<InDoubtTxInfo> EXTERNALIZER = new Externalizer(); private final XidImpl xid; private final long internalId; private int status; private final transient Set<Address> owners = new HashSet<>(); private transient boolean isLocal; public InDoubtTxInfo(XidImpl xid, long internalId, int status) { this.xid = xid; this.internalId = internalId; this.status = status; } public InDoubtTxInfo(XidImpl xid, long internalId) { this(xid, internalId, -1); } /** * @return The transaction's {@link XidImpl}. */ public XidImpl getXid() { return xid; } /** * @return The unique long object associated to {@link XidImpl}. It makes possible the invocation of recovery * operations. */ public long getInternalId() { return internalId; } /** * The value represent transaction's state as described by the {@code status} field. * * @return The {@link jakarta.transaction.Status} or -1 if not set. */ public int getStatus() { return status; } /** * Sets the transaction's state. */ public void setStatus(int status) { this.status = status; } /** * @return The set of nodes where this transaction information is maintained. */ public Set<Address> getOwners() { return owners; } /** * Adds {@code owner} as a node where this transaction information is maintained. */ public void addOwner(Address owner) { owners.add(owner); } /** * @return {@code True} if the transaction information is also present on this node. */ public boolean isLocal() { return isLocal; } /** * Sets {@code true} if this transaction information is stored locally. */ public void setLocal(boolean local) { isLocal = local; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InDoubtTxInfo that = (InDoubtTxInfo) o; return internalId == that.internalId && status == that.status && isLocal == that.isLocal && Objects.equals(xid, that.xid) && Objects.equals(owners, that.owners); } @Override public int hashCode() { return Objects.hash(xid, internalId, status, owners, isLocal); } @Override public String toString() { return getClass().getSimpleName() + "{xid=" + xid + ", internalId=" + internalId + ", status=" + status + ", owners=" + owners + ", isLocal=" + isLocal + '}'; } private static class Externalizer extends AbstractExternalizer<InDoubtTxInfo> { @Override public void writeObject(ObjectOutput output, InDoubtTxInfo info) throws IOException { XidImpl.writeTo(output, info.xid); output.writeLong(info.internalId); output.writeInt(info.status); } @Override public InDoubtTxInfo readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new InDoubtTxInfo(XidImpl.readFrom(input), input.readLong(), input.readInt()); } @Override public Integer getId() { return Ids.IN_DOUBT_TX_INFO; } @Override public Set<Class<? extends InDoubtTxInfo>> getTypeClasses() { return Collections.singleton(InDoubtTxInfo.class); } } }
4,188
25.345912
112
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/lookup/TransactionSynchronizationRegistryLookup.java
package org.infinispan.transaction.lookup; import jakarta.transaction.TransactionSynchronizationRegistry; /** * @author Stuart Douglas * * If we are in a JTA transaction that tx.commit has already been called and * we are invoked as part of a interposed synchronization, we need to use the TransactionSynchronizationRegistry * to register any further needed synchronizations. This interface is how we will lookup the * TransactionSynchronizationRegistry. Although, in most cases, we will already have it * injected via some other means (avoiding a JNDI lookup). * * See ISPN-1168 for more details. * */ public interface TransactionSynchronizationRegistryLookup { /** * Returns a new TransactionSynchronizationRegistry. * * @throws Exception if lookup failed */ TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() throws Exception; }
895
32.185185
112
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/lookup/package-info.java
/** * Interfaces and implementations of lookup classes to locate and/or instantiate JTA {@link javax.transaction.TransactionManager}s. */ package org.infinispan.transaction.lookup;
183
35.8
131
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/lookup/EmbeddedTransactionManagerLookup.java
package org.infinispan.transaction.lookup; import jakarta.transaction.TransactionManager; import jakarta.transaction.UserTransaction; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransactionManager; /** * Returns an instance of {@link org.infinispan.transaction.tm.EmbeddedTransactionManager}. * * @author Bela Ban * @author Pedro Ruivo * @since 9.0 */ public class EmbeddedTransactionManagerLookup implements TransactionManagerLookup { public static UserTransaction getUserTransaction() { return EmbeddedTransactionManager.getUserTransaction(); } public static void cleanup() { EmbeddedTransactionManager.destroy(); } @Override public TransactionManager getTransactionManager() throws Exception { return EmbeddedTransactionManager.getInstance(); } @Override public String toString() { return "EmbeddedTransactionManagerLookup"; } }
968
24.5
91
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/lookup/GenericTransactionManagerLookup.java
package org.infinispan.transaction.lookup; import static org.infinispan.util.logging.Log.CONTAINER; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.TransactionManager; import org.infinispan.commons.tx.lookup.LookupNames; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.commons.util.Util; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.transaction.tm.EmbeddedTransactionManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A transaction manager lookup class that attempts to locate a TransactionManager. A variety of different classes and * JNDI locations are tried, for servers such as: <ul> <li> JBoss <li> JRun4 <li> Resin <li> Orion <li> JOnAS <li> BEA * Weblogic <li> Websphere 4.0, 5.0, 5.1, 6.0 <li> Sun, Glassfish </ul> If a transaction manager is not found, returns * an {@link org.infinispan.transaction.tm.EmbeddedTransactionManager}. * * @author Markus Plesser * @since 4.0 */ @Scope(Scopes.GLOBAL) public class GenericTransactionManagerLookup implements TransactionManagerLookup { private static final Log log = LogFactory.getLog(GenericTransactionManagerLookup.class); public static final GenericTransactionManagerLookup INSTANCE = new GenericTransactionManagerLookup(); /** * JNDI lookups performed? */ private boolean lookupDone = false; /** * No JNDI available? */ private boolean lookupFailed = false; /** * No JBoss TM embedded jars found? */ private boolean noJBossTM = false; /** * The JTA TransactionManager found. */ private TransactionManager tm = null; @Inject GlobalConfiguration globalCfg; /** * Get the system-wide used TransactionManager * * @return TransactionManager */ @Override public synchronized TransactionManager getTransactionManager() { if (!lookupDone) { doLookups(globalCfg.classLoader()); } if (tm != null) return tm; if (lookupFailed) { if (!noJBossTM) { // First try an embedded JBossTM/Wildly instance tryEmbeddedJBossTM(); } if (noJBossTM) { //fall back to a dummy from Infinispan useDummyTM(); } } return tm; } private void useDummyTM() { tm = EmbeddedTransactionManager.getInstance(); CONTAINER.fallingBackToEmbeddedTm(); } private void tryEmbeddedJBossTM() { try { WildflyTransactionManagerLookup lookup = new WildflyTransactionManagerLookup(); lookup.init(globalCfg); tm = lookup.getTransactionManager(); return; } catch (Exception e) { //ignore. lets try JBossStandalone } try { JBossStandaloneJTAManagerLookup jBossStandaloneJTAManagerLookup = new JBossStandaloneJTAManagerLookup(); jBossStandaloneJTAManagerLookup.init(globalCfg); tm = jBossStandaloneJTAManagerLookup.getTransactionManager(); } catch (Exception e) { noJBossTM = true; } } /** * Try to figure out which TransactionManager to use */ private void doLookups(ClassLoader cl) { if (lookupFailed) return; InitialContext ctx; try { ctx = new InitialContext(); } catch (NamingException e) { CONTAINER.failedToCreateInitialCtx(e); lookupFailed = true; return; } try { //probe jndi lookups first for (LookupNames.JndiTransactionManager knownJNDIManager : LookupNames.JndiTransactionManager.values()) { Object jndiObject; try { log.debugf("Trying to lookup TransactionManager for %s", knownJNDIManager.getPrettyName()); jndiObject = ctx.lookup(knownJNDIManager.getJndiLookup()); } catch (NamingException e) { log.debugf("Failed to perform a lookup for [%s (%s)]", knownJNDIManager.getJndiLookup(), knownJNDIManager.getPrettyName()); continue; } if (jndiObject instanceof TransactionManager) { tm = (TransactionManager) jndiObject; log.debugf("Found TransactionManager for %s", knownJNDIManager.getPrettyName()); return; } } } finally { Util.close(ctx); } boolean found = true; // The TM may be deployed embedded alongside the app, so this needs to be looked up on the same CL as the Cache for (LookupNames.TransactionManagerFactory transactionManagerFactory : LookupNames.TransactionManagerFactory.values()) { log.debugf("Trying %s: %s", transactionManagerFactory.getPrettyName(), transactionManagerFactory.getFactoryClazz()); TransactionManager transactionManager = transactionManagerFactory.tryLookup(cl); if (transactionManager != null) { log.debugf("Found %s: %s", transactionManagerFactory.getPrettyName(), transactionManagerFactory.getFactoryClazz()); tm = transactionManager; found = false; } } lookupDone = true; lookupFailed = found; } }
5,452
32.660494
127
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/lookup/WildflyTransactionManagerLookup.java
package org.infinispan.transaction.lookup; import java.lang.reflect.Method; import jakarta.transaction.TransactionManager; import jakarta.transaction.UserTransaction; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.commons.util.Util; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * WildFly transaction client lookup (WildFly 11 and later). * * @author Pedro Ruivo * @since 9.3 */ @Scope(Scopes.GLOBAL) public class WildflyTransactionManagerLookup implements TransactionManagerLookup { private static final String WILDFLY_TM_CLASS_NAME = "org.wildfly.transaction.client.ContextTransactionManager"; private static final String WILDFLY_UT_CLASS_NAME = "org.wildfly.transaction.client.LocalUserTransaction"; private static final String WILDFLY_STATIC_METHOD = "getInstance"; private static final Log log = LogFactory.getLog(WildflyTransactionManagerLookup.class); private Method manager, user; @Inject public void init(GlobalConfiguration globalCfg) { init(globalCfg.classLoader()); } @Override public synchronized TransactionManager getTransactionManager() throws Exception { TransactionManager tm = (TransactionManager) manager.invoke(null); if (log.isInfoEnabled()) { log.retrievingTm(tm); } return tm; } public UserTransaction getUserTransaction() throws Exception { return (UserTransaction) user.invoke(null); } @Override public String toString() { return "JBossStandaloneJTAManagerLookup"; } private void init(ClassLoader classLoader) { // The TM may be deployed embedded alongside the app, so this needs to be looked up on the same CL as the Cache try { manager = Util.loadClassStrict(WILDFLY_TM_CLASS_NAME, classLoader).getMethod(WILDFLY_STATIC_METHOD); user = Util.loadClassStrict(WILDFLY_UT_CLASS_NAME, classLoader).getMethod(WILDFLY_STATIC_METHOD); } catch (SecurityException | NoSuchMethodException | ClassNotFoundException e) { throw new RuntimeException(e); } } }
2,338
35.546875
117
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/lookup/JBossStandaloneJTAManagerLookup.java
package org.infinispan.transaction.lookup; import java.lang.reflect.Method; import jakarta.transaction.TransactionManager; import jakarta.transaction.UserTransaction; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.commons.util.Util; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * JTA standalone TM lookup (JBoss AS 7 and earlier, and WildFly 8, 9, and 10). * * @author Jason T. Greene * @since 4.0 */ @Scope(Scopes.GLOBAL) public class JBossStandaloneJTAManagerLookup implements TransactionManagerLookup { private Method manager, user; private static final Log log = LogFactory.getLog(JBossStandaloneJTAManagerLookup.class); @Inject public void init(GlobalConfiguration globalCfg) { init(globalCfg.classLoader()); } private void init(ClassLoader classLoader) { // The TM may be deployed embedded alongside the app, so this needs to be looked up on the same CL as the Cache try { manager = Util.loadClass("com.arjuna.ats.jta.TransactionManager", classLoader).getMethod("transactionManager"); user = Util.loadClass("com.arjuna.ats.jta.UserTransaction", classLoader).getMethod("userTransaction"); } catch (SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } @Override public synchronized TransactionManager getTransactionManager() throws Exception { TransactionManager tm = (TransactionManager) manager.invoke(null); if (log.isInfoEnabled()) log.retrievingTm(tm); return tm; } public UserTransaction getUserTransaction() throws Exception { return (UserTransaction) user.invoke(null); } @Override public String toString() { return "JBossStandaloneJTAManagerLookup"; } }
2,038
33.559322
120
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/AbstractEnlistmentAdapter.java
package org.infinispan.transaction.impl; import org.infinispan.transaction.xa.CacheTransaction; /** * Base class for both Sync and XAResource enlistment adapters. * * @author Mircea Markus * @since 5.1 */ public abstract class AbstractEnlistmentAdapter { private final int hashCode; public AbstractEnlistmentAdapter(CacheTransaction cacheTransaction) { hashCode = preComputeHashCode(cacheTransaction); } public AbstractEnlistmentAdapter() { hashCode = 31; } /** * Invoked by TransactionManagers, make sure it's an efficient implementation. * System.identityHashCode(x) is NOT an efficient implementation. */ @Override public final int hashCode() { return this.hashCode; } private static int preComputeHashCode(final CacheTransaction cacheTx) { return 31 + cacheTx.hashCode(); } }
860
23.6
81
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/TransactionTable.java
package org.infinispan.transaction.impl; import static org.infinispan.factories.KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR; import static org.infinispan.util.logging.Log.CLUSTER; import static org.infinispan.util.logging.Log.CONTAINER; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; import java.util.stream.Collectors; import jakarta.transaction.Status; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import jakarta.transaction.TransactionSynchronizationRegistry; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.remote.CheckTransactionRpcCommand; import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand; import org.infinispan.commands.tx.RollbackCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.CacheException; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.ByRef; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.Configuration; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.annotations.ComponentName; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; import org.infinispan.notifications.cachelistener.annotation.TransactionRegistered; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier; import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.partitionhandling.impl.PartitionHandlingManager; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.rpc.RpcOptions; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.synchronization.SyncLocalTransaction; import org.infinispan.transaction.synchronization.SynchronizationAdapter; import org.infinispan.transaction.xa.CacheTransaction; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.transaction.xa.TransactionFactory; import org.infinispan.util.ByteString; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import net.jcip.annotations.GuardedBy; /** * Repository for {@link RemoteTransaction} and {@link org.infinispan.transaction.xa.TransactionXaAdapter}s (locally * originated transactions). * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño * @since 4.0 */ @Listener @Scope(Scopes.NAMED_CACHE) public class TransactionTable implements org.infinispan.transaction.TransactionTable { public enum CompletedTransactionStatus { NOT_COMPLETED, COMMITTED, ABORTED, EXPIRED } private static final Log log = LogFactory.getLog(TransactionTable.class); public static final int CACHE_STOPPED_TOPOLOGY_ID = -1; @ComponentName(KnownComponentNames.CACHE_NAME) @Inject String cacheName; @Inject protected Configuration configuration; @Inject protected TransactionCoordinator txCoordinator; @Inject TransactionFactory txFactory; @Inject protected RpcManager rpcManager; @Inject protected CommandsFactory commandsFactory; @Inject ClusteringDependentLogic clusteringLogic; @Inject CacheNotifier<?, ?> notifier; @Inject TransactionSynchronizationRegistry transactionSynchronizationRegistry; @Inject TimeService timeService; @Inject CacheManagerNotifier cacheManagerNotifier; @Inject protected PartitionHandlingManager partitionHandlingManager; @Inject @ComponentName(TIMEOUT_SCHEDULE_EXECUTOR) ScheduledExecutorService timeoutExecutor; @Inject protected TransactionOriginatorChecker transactionOriginatorChecker; @Inject TransactionManager transactionManager; @Inject ComponentRegistry componentRegistry; /** * minTxTopologyId is the minimum topology ID across all ongoing local and remote transactions. */ private volatile int minTxTopologyId = CACHE_STOPPED_TOPOLOGY_ID; private volatile int currentTopologyId = CACHE_STOPPED_TOPOLOGY_ID; private CompletedTransactionsInfo completedTransactionsInfo; private boolean isPessimisticLocking; private ConcurrentMap<Transaction, LocalTransaction> localTransactions; private ConcurrentMap<GlobalTransaction, LocalTransaction> globalToLocalTransactions; private ConcurrentMap<GlobalTransaction, RemoteTransaction> remoteTransactions; private Lock minTopologyRecalculationLock; protected boolean clustered = false; protected volatile boolean running = false; @Start(priority = 9) // Start before cache loader manager public void start() { this.clustered = configuration.clustering().cacheMode().isClustered(); this.isPessimisticLocking = configuration.transaction().lockingMode() == LockingMode.PESSIMISTIC; final int concurrencyLevel = configuration.locking().concurrencyLevel(); //use the IdentityEquivalence because some Transaction implementation does not have a stable hash code function //and it can cause some leaks in the concurrent map. localTransactions = new ConcurrentHashMap<>(concurrencyLevel, 0.75f, concurrencyLevel); globalToLocalTransactions = new ConcurrentHashMap<>(concurrencyLevel, 0.75f, concurrencyLevel); boolean transactional = configuration.transaction().transactionMode().isTransactional(); if (clustered && transactional) { minTopologyRecalculationLock = new ReentrantLock(); remoteTransactions = new ConcurrentHashMap<>(concurrencyLevel, 0.75f, concurrencyLevel); notifier.addListener(this); cacheManagerNotifier.addListener(this); completedTransactionsInfo = new CompletedTransactionsInfo(); // Periodically run a task to cleanup the transaction table of completed transactions. long interval = configuration.transaction().reaperWakeUpInterval(); timeoutExecutor.scheduleAtFixedRate(() -> completedTransactionsInfo.cleanupCompletedTransactions(), interval, interval, TimeUnit.MILLISECONDS); timeoutExecutor.scheduleAtFixedRate(this::cleanupTimedOutTransactions, interval, interval, TimeUnit.MILLISECONDS); } running = true; } @Override public GlobalTransaction getGlobalTransaction(Transaction transaction) { if (transaction == null) { throw new NullPointerException("Transaction must not be null."); } LocalTransaction localTransaction = localTransactions.get(transaction); return localTransaction != null ? localTransaction.getGlobalTransaction() : null; } @Override public Collection<GlobalTransaction> getLocalGlobalTransaction() { return Collections.unmodifiableCollection(globalToLocalTransactions.keySet()); } @Override public Collection<GlobalTransaction> getRemoteGlobalTransaction() { return Collections.unmodifiableCollection(remoteTransactions.keySet()); } @Stop @SuppressWarnings("unused") void stop() { running = false; cacheManagerNotifier.removeListener(this); if (clustered) { notifier.removeListener(this); currentTopologyId = CACHE_STOPPED_TOPOLOGY_ID; // indicate that the cache has stopped } shutDownGracefully(); } public void remoteTransactionPrepared(GlobalTransaction gtx) { //do nothing } public void localTransactionPrepared(LocalTransaction localTransaction) { //nothing, only used by recovery } public void enlist(Transaction transaction, LocalTransaction localTransaction) { if (!localTransaction.isEnlisted()) { SynchronizationAdapter sync = new SynchronizationAdapter(localTransaction, this); if (transactionSynchronizationRegistry != null) { boolean needsSuspend = false; try { // ISPN-8853: TransactionSynchronizationRegistry retrieves the running transaction from // thread-local context in TM, so we need to set it there if it's not set already. Transaction currentTransaction = transactionManager.getTransaction(); if (currentTransaction == null) { transactionManager.resume(transaction); needsSuspend = true; } else { assert currentTransaction == transaction; } transactionSynchronizationRegistry.registerInterposedSynchronization(sync); } catch (Exception e) { log.failedSynchronizationRegistration(e); throw new CacheException(e); } finally { if (needsSuspend) { try { transactionManager.suspend(); } catch (Exception e) { throw new CacheException(e); } } } } else { try { transaction.registerSynchronization(sync); } catch (Exception e) { log.failedSynchronizationRegistration(e); throw new CacheException(e); } } ((SyncLocalTransaction) localTransaction).setEnlisted(true); } } public void enlistClientTransaction(Transaction transaction, LocalTransaction localTransaction) { if (!localTransaction.isEnlisted()) { SynchronizationAdapter sync = new SynchronizationAdapter(localTransaction, this); try { transaction.registerSynchronization(sync); } catch (Exception e) { log.failedSynchronizationRegistration(e); throw new CacheException(e); } ((SyncLocalTransaction) localTransaction).setEnlisted(true); } } public void failureCompletingTransaction(Transaction tx) { final LocalTransaction localTransaction = localTransactions.get(tx); if (localTransaction != null) { removeLocalTransaction(localTransaction); } } public int getMinTopologyId() { return minTxTopologyId; } public void cleanupLeaverTransactions(List<Address> members) { // Can happen if the cache is non-transactional if (remoteTransactions == null) return; if (log.isTraceEnabled()) log.tracef("Checking for transactions originated on leavers. Current cache members are %s, remote transactions: %d", members, remoteTransactions.size()); HashSet<Address> membersSet = new HashSet<>(members); List<GlobalTransaction> toKill = new ArrayList<>(); for (Map.Entry<GlobalTransaction, RemoteTransaction> e : remoteTransactions.entrySet()) { GlobalTransaction gt = e.getKey(); if (log.isTraceEnabled()) log.tracef("Checking transaction %s", gt); if (transactionOriginatorChecker.isOriginatorMissing(gt, membersSet)) { toKill.add(gt); } } if (toKill.isEmpty()) { if (log.isTraceEnabled()) log.tracef("No remote transactions pertain to originator(s) who have left the cluster."); } else { log.debugf("The originating node left the cluster for %d remote transactions", toKill.size()); for (GlobalTransaction gtx : toKill) { if (partitionHandlingManager.canRollbackTransactionAfterOriginatorLeave(gtx)) { log.debugf("Rolling back transaction %s because originator %s left the cluster", gtx, gtx.getAddress()); killTransactionAsync(gtx); } else { log.debugf("Keeping transaction %s after the originator %s left the cluster.", gtx, gtx.getAddress()); } } if (log.isTraceEnabled()) log.tracef("Completed cleaning transactions originating on leavers. Remote transactions remaining: %d", remoteTransactions.size()); } } /** * Removes the {@link RemoteTransaction} corresponding to the given tx. */ public void remoteTransactionCommitted(GlobalTransaction gtx, boolean onePc) { boolean optimisticWih1Pc = onePc && (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC); if (optimisticWih1Pc) { removeRemoteTransaction(gtx); } } @ViewChanged public void onViewChange(final ViewChangedEvent e) { timeoutExecutor.submit(() -> cleanupLeaverTransactions(e.getNewMembers())); } private void cleanupTimedOutTransactions() { if (log.isTraceEnabled()) log.tracef("About to cleanup remote transactions older than %d ms", configuration.transaction().completedTxTimeout()); long beginning = timeService.time(); long cutoffCreationTime = beginning - TimeUnit.MILLISECONDS.toNanos(configuration.transaction().completedTxTimeout()); List<GlobalTransaction> toKill = new ArrayList<>(); Map<Address, Collection<GlobalTransaction>> toCheck = new HashMap<>(); // Check remote transactions. for(Map.Entry<GlobalTransaction, RemoteTransaction> e : remoteTransactions.entrySet()) { GlobalTransaction gtx = e.getKey(); RemoteTransaction remoteTx = e.getValue(); assert remoteTx != null; //concurrent map doesn't accept null values if (log.isTraceEnabled()) { log.tracef("Checking transaction %s", gtx); } // Check the time. long creationTime = remoteTx.getCreationTime(); if (creationTime - cutoffCreationTime >= 0) { //transaction still valid continue; } if (transactionOriginatorChecker.isOriginatorMissing(gtx)) { //originator no longer available. Transaction can be rolled back. long duration = timeService.timeDuration(creationTime, beginning, TimeUnit.MILLISECONDS); log.remoteTransactionTimeout(gtx, duration); toKill.add(gtx); } else { //originator alive or hot rod transaction Address orig = gtx.getAddress(); if (rpcManager.getMembers().contains(orig)) { //originator still in view. Check if the transaction is valid. Collection<GlobalTransaction> addressCheckList = toCheck.computeIfAbsent(orig, k -> new ArrayList<>()); addressCheckList.add(gtx); } //else, it is a hot rod transaction. don't kill it since the server reaper will take appropriate action } } // check if the transaction is running on originator for (Map.Entry<Address, Collection<GlobalTransaction>> entry : toCheck.entrySet()) { CheckTransactionRpcCommand cmd = commandsFactory.buildCheckTransactionRpcCommand(entry.getValue()); RpcOptions rpcOptions = rpcManager.getSyncRpcOptions(); rpcManager.invokeCommand(entry.getKey(), cmd, CheckTransactionRpcCommand.responseCollector(), rpcOptions) .thenAccept(this::killAllTransactionsAsync); } // Rollback the orphaned transactions and release any held locks. killAllTransactionsAsync(toKill); } private void killTransaction(GlobalTransaction gtx) { RollbackCommand rc = new RollbackCommand(ByteString.fromString(cacheName), gtx); rc.markTransactionAsRemote(false); try { CompletionStages.join(rc.invokeAsync(componentRegistry)); if (log.isTraceEnabled()) log.tracef("Rollback of transaction %s complete.", gtx); } catch (Throwable e) { log.unableToRollbackGlobalTx(gtx, e); } } /** * Returns the {@link RemoteTransaction} associated with the supplied transaction id. Returns null if no such * association exists. */ public RemoteTransaction getRemoteTransaction(GlobalTransaction txId) { return remoteTransactions.get(txId); } public void remoteTransactionRollback(GlobalTransaction gtx) { final RemoteTransaction remove = removeRemoteTransaction(gtx); if (log.isTraceEnabled()) log.tracef("Removed local transaction %s? %b", gtx, remove); } /** * Returns an existing remote transaction or creates one if none exists. * Atomicity: this method supports concurrent invocations, guaranteeing that all threads will see the same * transaction object. */ // TODO: consider returning null instead of throwing exception when the transaction is already completed public RemoteTransaction getOrCreateRemoteTransaction(GlobalTransaction globalTx, List<WriteCommand> modifications) { return getOrCreateRemoteTransaction(globalTx, modifications, currentTopologyId); } public RemoteTransaction getOrCreateRemoteTransaction(GlobalTransaction globalTx, List<WriteCommand> modifications, int topologyId) { RemoteTransaction existingTransaction = remoteTransactions.get(globalTx); if (existingTransaction != null) return existingTransaction; if (!running) { // Assume that we wouldn't get this far if the cache was already stopped throw CONTAINER.cacheIsStopping(cacheName); } int viewId = rpcManager.getTransport().getViewId(); if (transactionOriginatorChecker.isOriginatorMissing(globalTx, rpcManager.getTransport().getMembers())) { throw CLUSTER.remoteTransactionOriginatorNotInView(globalTx); } RemoteTransaction newTransaction = txFactory.newRemoteTransaction(modifications, globalTx, topologyId); RemoteTransaction remoteTransaction = remoteTransactions.compute(globalTx, (gtx, existing) -> { if (existing != null) { if (log.isTraceEnabled()) log.tracef("Remote transaction already registered: %s", existing); return existing; } else { if (isTransactionCompleted(gtx)) { throw CLUSTER.remoteTransactionAlreadyCompleted(gtx); } if (log.isTraceEnabled()) log.tracef("Created and registered remote transaction %s", newTransaction); if (topologyId < minTxTopologyId) { if (log.isTraceEnabled()) log.tracef("Changing minimum topology ID from %d to %d", minTxTopologyId, topologyId); minTxTopologyId = topologyId; } return newTransaction; } }); if (rpcManager.getTransport().getViewId() != viewId && transactionOriginatorChecker.isOriginatorMissing(globalTx, rpcManager.getTransport().getMembers())) { // Either cleanupLeaverTransactions didn't run for this view yet, or it missed the transaction we just created. // Kill the transaction here if necessary, but return normally, as if the cleanup task did it. if (partitionHandlingManager.canRollbackTransactionAfterOriginatorLeave(globalTx)) { log.debugf("Rolling back transaction %s because originator %s left the cluster", globalTx, globalTx.getAddress()); killTransaction(globalTx); } return remoteTransaction; } return remoteTransaction; } /** * Returns the {@link org.infinispan.transaction.xa.TransactionXaAdapter} corresponding to the supplied transaction. * If none exists, will be created first. */ public LocalTransaction getOrCreateLocalTransaction(Transaction transaction, boolean implicitTransaction) { return getOrCreateLocalTransaction(transaction, implicitTransaction, this::newGlobalTransaction); } /** * Similar to {@link #getOrCreateLocalTransaction(Transaction, boolean)} but with a custom global transaction factory. */ public LocalTransaction getOrCreateLocalTransaction(Transaction transaction, boolean implicitTransaction, Supplier<GlobalTransaction> gtxFactory) { LocalTransaction current = localTransactions.get(transaction); if (current == null) { if (!running) { // Assume that we wouldn't get this far if the cache was already stopped throw CONTAINER.cacheIsStopping(cacheName); } GlobalTransaction tx = gtxFactory.get(); current = txFactory.newLocalTransaction(transaction, tx, implicitTransaction, currentTopologyId); if (log.isTraceEnabled()) log.tracef("Created a new local transaction: %s", current); localTransactions.put(transaction, current); globalToLocalTransactions.put(current.getGlobalTransaction(), current); if (notifier.hasListener(TransactionRegistered.class)) { // TODO: this should be allowed to be async at some point CompletionStages.join(notifier.notifyTransactionRegistered(tx, true)); } } return current; } /** * Removes the {@link org.infinispan.transaction.xa.TransactionXaAdapter} corresponding to the given tx. Returns true * if such an tx exists. */ public boolean removeLocalTransaction(LocalTransaction localTransaction) { return localTransaction != null && (removeLocalTransactionInternal(localTransaction.getTransaction()) != null); } private GlobalTransaction newGlobalTransaction() { Address localAddress = rpcManager != null ? rpcManager.getTransport().getAddress() : null; return txFactory.newGlobalTransaction(localAddress, false); } private LocalTransaction removeLocalTransactionInternal(Transaction tx) { LocalTransaction localTx = localTransactions.get(tx); if (localTx != null) { globalToLocalTransactions.remove(localTx.getGlobalTransaction()); localTransactions.remove(tx); releaseResources(localTx); } return localTx; } private void releaseResources(CacheTransaction cacheTransaction) { if (cacheTransaction != null) { if (clustered) { recalculateMinTopologyIdIfNeeded(cacheTransaction); } if (log.isTraceEnabled()) log.tracef("Removed %s from transaction table.", cacheTransaction); cacheTransaction.notifyOnTransactionFinished(); } } private void killAllTransactionsAsync(Collection<GlobalTransaction> transactions) { for (GlobalTransaction gtx : transactions) { killTransactionAsync(gtx); } } public final RemoteTransaction removeRemoteTransaction(GlobalTransaction txId) { ByRef<RemoteTransaction> removed = new ByRef<>(null); // we need to mark the transaction inside compute() even if it does not exist remoteTransactions.compute(txId, (gtx, remoteTx) -> { boolean successful = remoteTx != null && !remoteTx.isMarkedForRollback(); markTransactionCompleted(gtx, successful); removed.set(remoteTx); return null; }); if (log.isTraceEnabled()) log.tracef("Removed remote transaction %s ? %s", txId, removed.get()); releaseResources(removed.get()); return removed.get(); } public int getRemoteTxCount() { return remoteTransactions.size(); } public int getLocalTxCount() { return localTransactions.size(); } /** * Looks up a LocalTransaction given a GlobalTransaction. * @param txId the global transaction identifier * @return the LocalTransaction or null if not found */ public LocalTransaction getLocalTransaction(GlobalTransaction txId) { return globalToLocalTransactions.get(txId); } public boolean containsLocalTx(GlobalTransaction globalTransaction) { return globalToLocalTransactions.containsKey(globalTransaction); } public LocalTransaction getLocalTransaction(Transaction tx) { return localTransactions.get(tx); } public boolean containRemoteTx(GlobalTransaction globalTransaction) { return remoteTransactions.containsKey(globalTransaction); } public Collection<RemoteTransaction> getRemoteTransactions() { return remoteTransactions.values(); } public Collection<LocalTransaction> getLocalTransactions() { return localTransactions.values(); } protected final void recalculateMinTopologyIdIfNeeded(CacheTransaction removedTransaction) { if (removedTransaction == null) throw new IllegalArgumentException("Transaction cannot be null!"); if (currentTopologyId != CACHE_STOPPED_TOPOLOGY_ID) { // Assume that we only get here if we are clustered. int removedTransactionTopologyId = removedTransaction.getTopologyId(); if (removedTransactionTopologyId < minTxTopologyId) { if (log.isTraceEnabled()) log.tracef("A transaction has a topology ID (%s) that is smaller than the smallest transaction topology ID (%s) this node knows about! This can happen if a concurrent thread recalculates the minimum topology ID after the current transaction has been removed from the transaction table.", removedTransactionTopologyId, minTxTopologyId); } else if (removedTransactionTopologyId == minTxTopologyId && removedTransactionTopologyId < currentTopologyId) { // We should only need to re-calculate the minimum topology ID if the transaction being completed // has the same ID as the smallest known transaction ID, to check what the new smallest is, and this is // not the current topology ID. calculateMinTopologyId(removedTransactionTopologyId); } } } @TopologyChanged @SuppressWarnings("unused") public void onTopologyChange(TopologyChangedEvent<?, ?> tce) { // don't do anything if this cache is not clustered if (clustered) { if (!tce.isPre()) { // The topology id must be updated after the topology was updated in StateConsumerImpl, // as state transfer requires transactions not sent to the new owners to have a smaller topology id. currentTopologyId = tce.getNewTopologyId(); log.debugf("Topology changed, recalculating minimum topology id"); calculateMinTopologyId(-1); } } } private void killTransactionAsync(GlobalTransaction gtx) { RollbackCommand rc = new RollbackCommand(ByteString.fromString(cacheName), gtx); rc.markTransactionAsRemote(false); try { rc.invokeAsync(componentRegistry); } catch (Throwable throwable) { log.unableToRollbackGlobalTx(gtx, throwable); } } /** * This method calculates the minimum topology ID known by the current node. This method is only used in a clustered * cache, and only invoked when either a topology change is detected, or a transaction whose topology ID is not the same as * the current topology ID. * <p/> * This method is guarded by minTopologyRecalculationLock to prevent concurrent updates to the minimum topology ID field. * * @param idOfRemovedTransaction the topology ID associated with the transaction that triggered this recalculation, or -1 * if triggered by a topology change event. */ @GuardedBy("minTopologyRecalculationLock") private void calculateMinTopologyId(int idOfRemovedTransaction) { minTopologyRecalculationLock.lock(); try { // We should only need to re-calculate the minimum topology ID if the transaction being completed // has the same ID as the smallest known transaction ID, to check what the new smallest is. We do this check // again here, since this is now within a synchronized method. if (idOfRemovedTransaction == -1 || (idOfRemovedTransaction == minTxTopologyId && idOfRemovedTransaction < currentTopologyId)) { int minTopologyIdFound = currentTopologyId; for (CacheTransaction ct : localTransactions.values()) { int topologyId = ct.getTopologyId(); if (topologyId < minTopologyIdFound) minTopologyIdFound = topologyId; } for (CacheTransaction ct : remoteTransactions.values()) { int topologyId = ct.getTopologyId(); if (topologyId < minTopologyIdFound) minTopologyIdFound = topologyId; } if (minTopologyIdFound != minTxTopologyId) { if (log.isTraceEnabled()) log.tracef("Changing minimum topology ID from %s to %s", minTxTopologyId, minTopologyIdFound); minTxTopologyId = minTopologyIdFound; } else { if (log.isTraceEnabled()) log.tracef("Minimum topology ID still is %s; nothing to change", minTopologyIdFound); } } } finally { minTopologyRecalculationLock.unlock(); } } private void shutDownGracefully() { if (log.isDebugEnabled()) log.debugf("Wait for on-going transactions to finish for %s.", Util.prettyPrintTime(configuration.transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS)); // We can't use TimeService for this: some tests replace the time service so that it never // advances by cacheStopTimeout milliseconds. long now = System.nanoTime(); long failTime = now + TimeUnit.MILLISECONDS.toNanos(configuration.transaction().cacheStopTimeout()); boolean localTxsOnGoing = !localTransactions.isEmpty(); while (localTxsOnGoing && System.nanoTime() - failTime < 0) { try { Thread.sleep(30); localTxsOnGoing = !localTransactions.isEmpty(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.debugf("Interrupted waiting for %d on-going local transactions to finish.", localTransactions.size()); } } if (remoteTransactions != null) { Future<?> remoteTxsFuture = timeoutExecutor.submit(() -> { for (RemoteTransaction tx : remoteTransactions.values()) { // By synchronizing on the transaction we are waiting for in-progress commands affecting // this transaction (and synchronizing on it in TransactionSynchronizerInterceptor). //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (tx) { // Don't actually roll back the transaction, it would just delay the shutdown tx.markForRollback(true); } if (Thread.currentThread().isInterrupted()) break; } }); try { remoteTxsFuture.get(failTime - System.nanoTime(), TimeUnit.NANOSECONDS); } catch (InterruptedException e) { log.debug("Interrupted waiting for on-going remote transactional commands to finish."); remoteTxsFuture.cancel(true); Thread.currentThread().interrupt(); } catch (ExecutionException e) { log.debug("Exception while waiting for on-going remote transactional commands to finish", e); } catch (TimeoutException e) { remoteTxsFuture.cancel(true); } } if (!localTransactions.isEmpty() || remoteTransactionsCount() != 0) { log.unfinishedTransactionsRemain(localTransactions.size(), remoteTransactionsCount()); if (log.isTraceEnabled()) { log.tracef("Unfinished local transactions: %s", localTransactions.values().stream().map(tx -> tx.getGlobalTransaction().toString()) .collect(Collectors.joining(", ", "[", "]"))); log.tracef("Unfinished remote transactions: %s", remoteTransactions == null ? "none" : remoteTransactions.keySet()); } } else { log.debug("All transactions terminated"); } } private int remoteTransactionsCount() { return remoteTransactions == null ? 0 : remoteTransactions.size(); } /** * With the current state transfer implementation it is possible for a transaction to be prepared several times * on a remote node. This might cause leaks, e.g. if the transaction is prepared, committed and prepared again. * Once marked as completed (because of commit or rollback) any further prepare received on that transaction are discarded. */ public void markTransactionCompleted(GlobalTransaction gtx, boolean successful) { if (completedTransactionsInfo != null) { completedTransactionsInfo.markTransactionCompleted(gtx, successful); } } /** * @see #markTransactionCompleted(org.infinispan.transaction.xa.GlobalTransaction, boolean) */ public boolean isTransactionCompleted(GlobalTransaction gtx) { return completedTransactionsInfo != null && completedTransactionsInfo.isTransactionCompleted(gtx); } /** * @see #markTransactionCompleted(org.infinispan.transaction.xa.GlobalTransaction, boolean) */ public CompletedTransactionStatus getCompletedTransactionStatus(GlobalTransaction gtx) { if (completedTransactionsInfo == null) return CompletedTransactionStatus.NOT_COMPLETED; return completedTransactionsInfo.getTransactionStatus(gtx); } private class CompletedTransactionsInfo { final ConcurrentMap<GlobalTransaction, CompletedTransactionInfo> completedTransactions; // The ConcurrentMap transaction id previously cleared, one per originator final ConcurrentMap<Address, Long> nodeMaxPrunedTxIds; // The highest transaction id previously cleared, with any originator volatile long globalMaxPrunedTxId; CompletedTransactionsInfo() { nodeMaxPrunedTxIds = new ConcurrentHashMap<>(); completedTransactions = new ConcurrentHashMap<>(); globalMaxPrunedTxId = -1; } /** * With the current state transfer implementation it is possible for a transaction to be prepared several times * on a remote node. This might cause leaks, e.g. if the transaction is prepared, committed and prepared again. * Once marked as completed (because of commit or rollback) any further prepare received on that transaction are discarded. */ void markTransactionCompleted(GlobalTransaction globalTx, boolean successful) { if (log.isTraceEnabled()) log.tracef("Marking transaction %s as completed", globalTx); completedTransactions.put(globalTx, new CompletedTransactionInfo(timeService.time(), successful)); } /** * @see #markTransactionCompleted(GlobalTransaction, boolean) */ boolean isTransactionCompleted(GlobalTransaction gtx) { if (completedTransactions.containsKey(gtx)) return true; // Transaction ids are allocated in sequence, so any transaction with a smaller id must have been started // before a transaction that was already removed from the completed transactions map because it was too old. // We assume that the transaction was either committed, or it was rolled back (e.g. because the prepare // RPC timed out. // Note: We must check the id *after* verifying that the tx doesn't exist in the map. if (gtx.getId() > globalMaxPrunedTxId) return false; Long nodeMaxPrunedTxId = nodeMaxPrunedTxIds.get(gtx.getAddress()); return nodeMaxPrunedTxId != null && gtx.getId() <= nodeMaxPrunedTxId; } CompletedTransactionStatus getTransactionStatus(GlobalTransaction gtx) { CompletedTransactionInfo completedTx = completedTransactions.get(gtx); if (completedTx != null) { return completedTx.successful ? CompletedTransactionStatus.COMMITTED : CompletedTransactionStatus.ABORTED; } // Transaction ids are allocated in sequence, so any transaction with a smaller id must have been started // before a transaction that was already removed from the completed transactions map because it was too old. // We assume that the transaction was either committed, or it was rolled back (e.g. because the prepare // RPC timed out. // Note: We must check the id *after* verifying that the tx doesn't exist in the map. if (gtx.getId() > globalMaxPrunedTxId) return CompletedTransactionStatus.NOT_COMPLETED; Long nodeMaxPrunedTxId = nodeMaxPrunedTxIds.get(gtx.getAddress()); if (nodeMaxPrunedTxId == null) { // We haven't removed any transaction for this node return CompletedTransactionStatus.NOT_COMPLETED; } else if (gtx.getId() > nodeMaxPrunedTxId) { // We haven't removed this particular transaction yet return CompletedTransactionStatus.NOT_COMPLETED; } else { // We already removed the status of this transaction from the completed transactions map return CompletedTransactionStatus.EXPIRED; } } void cleanupCompletedTransactions() { if (completedTransactions.isEmpty()) return; try { if (log.isTraceEnabled()) log.tracef("About to cleanup completed transaction. Initial size is %d", completedTransactions.size()); long beginning = timeService.time(); long minCompleteTimestamp = timeService.time() - TimeUnit.MILLISECONDS.toNanos(configuration.transaction().completedTxTimeout()); int removedEntries = 0; // Collect the leavers. They will be removed at the end. Set<Address> leavers = new HashSet<>(); for (Map.Entry<Address, Long> e : nodeMaxPrunedTxIds.entrySet()) { if (!rpcManager.getMembers().contains(e.getKey())) { leavers.add(e.getKey()); } } // Remove stale completed transactions. Iterator<Map.Entry<GlobalTransaction, CompletedTransactionInfo>> txIterator = completedTransactions.entrySet().iterator(); while (txIterator.hasNext()) { Map.Entry<GlobalTransaction, CompletedTransactionInfo> e = txIterator.next(); CompletedTransactionInfo completedTx = e.getValue(); if (minCompleteTimestamp - completedTx.timestamp > 0) { // Need to update lastPrunedTxId *before* removing the tx from the map // Don't need atomic operations, there can't be more than one thread updating lastPrunedTxId. final long txId = e.getKey().getId(); final Address address = e.getKey().getAddress(); updateLastPrunedTxId(txId, address); txIterator.remove(); removedEntries++; } else { // Nodes with "active" completed transactions are not removed.. leavers.remove(e.getKey().getAddress()); } } // Finally, remove nodes that are no longer members and don't have any "active" completed transactions. leavers.forEach(nodeMaxPrunedTxIds::remove); long duration = timeService.timeDuration(beginning, TimeUnit.MILLISECONDS); if (log.isTraceEnabled()) log.tracef("Finished cleaning up completed transactions in %d millis, %d transactions were removed, " + "current number of completed transactions is %d", removedEntries, duration, completedTransactions.size()); if (log.isTraceEnabled()) log.tracef("Last pruned transaction ids were updated: %d, %s", globalMaxPrunedTxId, nodeMaxPrunedTxIds); } catch (Exception e) { log.errorf(e, "Failed to cleanup completed transactions: %s", e.getMessage()); } } private void updateLastPrunedTxId(final long txId, Address address) { if (txId > globalMaxPrunedTxId) { globalMaxPrunedTxId = txId; } nodeMaxPrunedTxIds.compute(address, (a, nodeMaxPrunedTxId) -> { if (nodeMaxPrunedTxId != null && txId <= nodeMaxPrunedTxId) { return nodeMaxPrunedTxId; } return txId; }); } } public CompletionStage<Integer> beforeCompletion(LocalTransaction localTransaction) { if (log.isTraceEnabled()) log.tracef("beforeCompletion called for %s", localTransaction); return txCoordinator.prepare(localTransaction) .exceptionally(t -> { throw new CacheException("Could not prepare. ", t); }); } public CompletionStage<Void> afterCompletion(LocalTransaction localTransaction, int status) { if (log.isTraceEnabled()) { log.tracef("afterCompletion(%s) called for %s.", (Integer) status, localTransaction); } if (status == Status.STATUS_COMMITTED) { return txCoordinator.commit(localTransaction, false).handle((isOnePhase, t) -> { if (t != null) { throw new CacheException("Could not commit.", t); } releaseLocksForCompletedTransaction(localTransaction, isOnePhase); return null; }); } else if (status == Status.STATUS_ROLLEDBACK) { localTransaction.markForRollback(true); //make sure writes no longer succeed return txCoordinator.rollback(localTransaction).exceptionally(t -> { throw new CacheException("Could not commit.", t); }); } else { throw new IllegalArgumentException("Unknown status: " + status); } } protected final void releaseLocksForCompletedTransaction(LocalTransaction localTransaction, boolean committedInOnePhase) { final GlobalTransaction gtx = localTransaction.getGlobalTransaction(); if ((!committedInOnePhase || !isOptimisticCache()) && isClustered()) { removeTransactionInfoRemotely(localTransaction, gtx); } // Perform local transaction removal last to prevent exceptions during shutDownGracefully() removeLocalTransaction(localTransaction); if (log.isTraceEnabled()) log.tracef("Committed in onePhase? %s isOptimistic? %s", committedInOnePhase, isOptimisticCache()); } private void removeTransactionInfoRemotely(LocalTransaction localTransaction, GlobalTransaction gtx) { if (mayHaveRemoteLocks(localTransaction) && !partitionHandlingManager.isTransactionPartiallyCommitted(gtx)) { TxCompletionNotificationCommand command = commandsFactory.buildTxCompletionNotificationCommand(null, gtx); LocalizedCacheTopology cacheTopology = clusteringLogic.getCacheTopology(); Collection<Address> owners = cacheTopology.getWriteOwners(localTransaction.getAffectedKeys()); Collection<Address> commitNodes = cacheTopology.getReadConsistentHash().isReplicated() ? null : owners; commitNodes = localTransaction.getCommitNodes(commitNodes, cacheTopology); if (log.isTraceEnabled()) log.tracef("About to invoke tx completion notification on commitNodes: %s", commitNodes); rpcManager.sendToMany(commitNodes, command, DeliverOrder.NONE); } } private boolean mayHaveRemoteLocks(LocalTransaction lt) { return (lt.getRemoteLocksAcquired() != null && !lt.getRemoteLocksAcquired().isEmpty() || lt.hasModifications() || isPessimisticLocking && lt.getTopologyId() != rpcManager.getTopologyId()); } private boolean isClustered() { return rpcManager != null; } private boolean isOptimisticCache() { //a transactional cache that is neither total order nor pessimistic must be optimistic. return !isPessimisticLocking; } private static class CompletedTransactionInfo { public final long timestamp; public final boolean successful; private CompletedTransactionInfo(long timestamp, boolean successful) { this.timestamp = timestamp; this.successful = successful; } } }
45,065
45.411946
374
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/FakeJTATransaction.java
package org.infinispan.transaction.impl; import java.util.concurrent.atomic.AtomicLong; import org.infinispan.commons.tx.TransactionImpl; import org.infinispan.commons.tx.XidImpl; import org.infinispan.commons.util.Util; public class FakeJTATransaction extends TransactionImpl { // Make it different from embedded txs (1) static final int FORMAT_ID = 2; static AtomicLong id = new AtomicLong(0); public FakeJTATransaction() { byte[] bytes = new byte[8]; Util.longToBytes(id.incrementAndGet(), bytes, 0); XidImpl xid = XidImpl.create(FORMAT_ID, bytes, bytes); setXid(xid); } }
619
28.52381
60
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/AbstractCacheTransaction.java
package org.infinispan.transaction.impl; import static org.infinispan.commons.util.Util.toStr; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; 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.Flag; import org.infinispan.transaction.xa.CacheTransaction; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import net.jcip.annotations.GuardedBy; /** * Base class for local and remote transaction. Impl note: The aggregated modification list and lookedUpEntries are not * instantiated here but in subclasses. This is done in order to take advantage of the fact that, for remote * transactions we already know the size of the modifications list at creation time. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño * @since 4.2 */ public abstract class AbstractCacheTransaction implements CacheTransaction { protected final GlobalTransaction tx; private static final Log log = LogFactory.getLog(AbstractCacheTransaction.class); private static final int INITIAL_LOCK_CAPACITY = 4; protected volatile ModificationList modifications; protected Map<Object, CacheEntry> lookedUpEntries; /** Holds all the locked keys that were acquired by the transaction allover the cluster. */ protected Set<Object> affectedKeys = null; /** Holds all the keys that were actually locked on the local node. */ private final AtomicReference<Set<Object>> lockedKeys = new AtomicReference<>(); /** * Holds all the locks for which the local node is a secondary data owner. * <p> * A {@link CompletableFuture} is created for each key and it is completed when the backup lock is release for that * key. A transaction, before acquiring the locks, must wait for all the backup locks (i.e. the {@link * CompletableFuture}) is released, for all transaction created in the previous topology. */ @GuardedBy("this") private Map<Object, CompletableFuture<Void>> backupKeyLocks; //should we merge the locked and backup locked keys in a single map? protected final int topologyId; private Map<Object, IncrementableEntryVersion> updatedEntryVersions; private Map<Object, IncrementableEntryVersion> versionsSeenMap; /** mark as volatile as this might be set from the tx thread code on view change*/ private volatile boolean isMarkedForRollback; /** * Mark the time this tx object was created */ private final long txCreationTime; private volatile Flag stateTransferFlag; private final CompletableFuture<Void> txCompleted; public final boolean isMarkedForRollback() { return isMarkedForRollback; } public void markForRollback(boolean markForRollback) { isMarkedForRollback = markForRollback; } public AbstractCacheTransaction(GlobalTransaction tx, int topologyId, long txCreationTime) { this.tx = tx; this.topologyId = topologyId; this.txCreationTime = txCreationTime; txCompleted = new CompletableFuture<>(); modifications = new ModificationList(); } @Override public GlobalTransaction getGlobalTransaction() { return tx; } @Override public final List<WriteCommand> getModifications() { return modifications.getModifications(); } @Override public final List<WriteCommand> getAllModifications() { return modifications.getAllModifications(); } public final void setModifications(List<WriteCommand> modifications) { this.modifications = ModificationList.fromCollection(modifications); } public final boolean hasModifications() { return modifications.hasNonLocalModifications(); } @Override public void freezeModifications() { modifications.freeze(); } @Override public Map<Object, CacheEntry> getLookedUpEntries() { return lookedUpEntries; } @Override public CacheEntry lookupEntry(Object key) { if (lookedUpEntries == null) return null; return lookedUpEntries.get(key); } @Override public void removeLookedUpEntry(Object key) { if (lookedUpEntries != null) lookedUpEntries.remove(key); } @Override public void clearLookedUpEntries() { lookedUpEntries = null; } @Override public boolean ownsLock(Object key) { final Set<Object> keys = lockedKeys.get(); return keys != null && keys.contains(key); } @Override public void notifyOnTransactionFinished() { if (log.isTraceEnabled()) log.tracef("Transaction %s has completed, notifying listening threads.", tx); if (!txCompleted.isDone()) { txCompleted.complete(null); cleanupBackupLocks(); } } @Override public int getTopologyId() { return topologyId; } @Override public synchronized void addBackupLockForKey(Object key) { if (backupKeyLocks == null) { backupKeyLocks = new HashMap<>(); } if (log.isTraceEnabled()) log.tracef("Transaction %s added backup lock: %s", tx, toStr(key)); backupKeyLocks.put(key, new CompletableFuture<>()); } public void registerLockedKey(Object key) { // we need a synchronized collection to be able to get a valid snapshot from another thread during state transfer final Set<Object> keys = lockedKeys.updateAndGet((value) -> value == null ? Collections.synchronizedSet(new HashSet<>(INITIAL_LOCK_CAPACITY)) : value); if (log.isTraceEnabled()) log.tracef("Transaction %s added lock: %s", tx, toStr(key)); keys.add(key); } @Override public Set<Object> getLockedKeys() { final Set<Object> keys = lockedKeys.get(); return keys == null ? Collections.emptySet() : keys; } public synchronized Set<Object> getBackupLockedKeys() { //Testing and toString only! return backupKeyLocks == null ? Collections.emptySet() : new HashSet<>(backupKeyLocks.keySet()); } @Override public void clearLockedKeys() { if (log.isTraceEnabled()) log.tracef("Clearing locked keys: %s", toStr(lockedKeys.get())); lockedKeys.set(null); } public Set<Object> getAffectedKeys() { return affectedKeys == null ? Collections.emptySet() : affectedKeys; } public void addAffectedKey(Object key) { initAffectedKeys(); affectedKeys.add(key); } public void addAllAffectedKeys(Collection<?> keys) { initAffectedKeys(); affectedKeys.addAll(keys); } private void initAffectedKeys() { if (affectedKeys == null) affectedKeys = new HashSet<>(INITIAL_LOCK_CAPACITY); } @Override public Map<Object, IncrementableEntryVersion> getUpdatedEntryVersions() { return updatedEntryVersions; } @Override public void setUpdatedEntryVersions(Map<Object, IncrementableEntryVersion> updatedEntryVersions) { this.updatedEntryVersions = updatedEntryVersions; } @Override public void addVersionRead(Object key, EntryVersion version) { if (version == null) { return; } if (versionsSeenMap == null) { versionsSeenMap = new HashMap<>(); } if (!versionsSeenMap.containsKey(key)) { if (log.isTraceEnabled()) { log.tracef("Transaction %s read %s with version %s", getGlobalTransaction().globalId(), key, version); } versionsSeenMap.put(key, (IncrementableEntryVersion) version); } } @Override public Map<Object, IncrementableEntryVersion> getVersionsRead() { return versionsSeenMap == null ? new HashMap<>() : versionsSeenMap; } public final boolean isFromStateTransfer() { return stateTransferFlag != null; } public final Flag getStateTransferFlag() { return stateTransferFlag; } public abstract void setStateTransferFlag(Flag stateTransferFlag); @Override public long getCreationTime() { return txCreationTime; } @Override public final void addListener(TransactionCompletedListener listener) { txCompleted.thenRun(listener::onCompletion); } @Override public CompletableFuture<Void> getReleaseFutureForKey(Object key) { if (getLockedKeys().contains(key)) { return txCompleted; } else { return findBackupLock(key); } } @Override public Map<Object, CompletableFuture<Void>> getReleaseFutureForKeys(Collection<Object> keys) { Set<Object> locked = getLockedKeys(); Map<Object, CompletableFuture<Void>> result = null; for (Object key : keys) { if (locked.contains(key)) { return Collections.singletonMap(key, txCompleted); } else { CompletableFuture<Void> cf = findBackupLock(key); if (cf != null) { if (result == null) { result = new HashMap<>(); } result.put(key, cf); } } } return result == null ? Collections.emptyMap() : result; } @Override public synchronized void cleanupBackupLocks() { if (backupKeyLocks != null) { if (log.isTraceEnabled()) log.tracef("Transaction %s removing all backup locks: %s", tx, toStr(backupKeyLocks.keySet())); for (CompletableFuture<Void> cf : backupKeyLocks.values()) { cf.complete(null); } backupKeyLocks.clear(); } } @Override public synchronized void removeBackupLocks(Collection<?> keys) { if (backupKeyLocks != null) { for (Object key : keys) { CompletableFuture<Void> cf = backupKeyLocks.remove(key); if (cf != null) { if (log.isTraceEnabled()) log.tracef("Transaction %s removed backup lock: %s", tx, toStr(key)); cf.complete(null); } } } } public synchronized void removeBackupLock(Object key) { if (backupKeyLocks != null) { CompletableFuture<Void> cf = backupKeyLocks.remove(key); if (cf != null) { if (log.isTraceEnabled()) log.tracef("Transaction %s removed backup lock: %s", tx, toStr(key)); cf.complete(null); } } } @Override public void forEachLock(Consumer<Object> consumer) { Set<Object> locked = lockedKeys.get(); if (locked != null) { locked.forEach(consumer); } } @Override public synchronized void forEachBackupLock(Consumer<Object> consumer) { if (backupKeyLocks != null) { backupKeyLocks.keySet().forEach(consumer); } } protected final void checkIfRolledBack() { if (isMarkedForRollback()) { throw log.transactionAlreadyRolledBack(getGlobalTransaction()); } } final void internalSetStateTransferFlag(Flag stateTransferFlag) { this.stateTransferFlag = stateTransferFlag; } private synchronized CompletableFuture<Void> findBackupLock(Object key) { return backupKeyLocks == null ? null : backupKeyLocks.get(key); } }
11,440
30.780556
157
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/TransactionCoordinator.java
package org.infinispan.transaction.impl; import static javax.transaction.xa.XAResource.XA_OK; import static javax.transaction.xa.XAResource.XA_RDONLY; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.function.Function; import jakarta.transaction.Transaction; import javax.transaction.xa.XAException; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.tx.RollbackCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.Configurations; import org.infinispan.context.InvocationContextFactory; import org.infinispan.context.impl.LocalTxInvocationContext; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.transaction.xa.GlobalTransaction; 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; /** * Coordinates transaction prepare/commits as received from the {@link javax.transaction.TransactionManager}. * Integrates with the TM through either {@link org.infinispan.transaction.xa.TransactionXaAdapter} or * through {@link org.infinispan.transaction.synchronization.SynchronizationAdapter}. * * @author Mircea.Markus@jboss.com * @author Pedro Ruivo * @since 5.0 */ @Scope(Scopes.NAMED_CACHE) public class TransactionCoordinator { private static final Log log = LogFactory.getLog(TransactionCoordinator.class); @Inject CommandsFactory commandsFactory; @Inject ComponentRef<InvocationContextFactory> icf; @Inject ComponentRef<AsyncInterceptorChain> invoker; @Inject ComponentRef<TransactionTable> txTable; @Inject ComponentRef<RecoveryManager> recoveryManager; @Inject Configuration configuration; private CommandCreator commandCreator; private volatile boolean shuttingDown = false; private boolean defaultOnePhaseCommit; private boolean use1PcForAutoCommitTransactions; private static final CompletableFuture<Integer> XA_OKAY_STAGE = CompletableFuture.completedFuture(XA_OK); private static final Function<Object, Integer> XA_RDONLY_APPLY = ignore -> XA_RDONLY; @Start(priority = 1) void setStartStatus() { shuttingDown = false; } @Stop(priority = 1) void setStopStatus() { shuttingDown = true; } @Start public void start() { use1PcForAutoCommitTransactions = configuration.transaction().use1PcForAutoCommitTransactions(); defaultOnePhaseCommit = Configurations.isOnePhaseCommit(configuration); if (Configurations.isTxVersioned(configuration)) { // We need to create versioned variants of PrepareCommand and CommitCommand commandCreator = new CommandCreator() { @Override public CommitCommand createCommitCommand(GlobalTransaction gtx) { return commandsFactory.buildVersionedCommitCommand(gtx); } @Override public PrepareCommand createPrepareCommand(GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhaseCommit) { return commandsFactory.buildVersionedPrepareCommand(gtx, modifications, onePhaseCommit); } }; } else { commandCreator = new CommandCreator() { @Override public CommitCommand createCommitCommand(GlobalTransaction gtx) { return commandsFactory.buildCommitCommand(gtx); } @Override public PrepareCommand createPrepareCommand(GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhaseCommit) { return commandsFactory.buildPrepareCommand(gtx, modifications, onePhaseCommit); } }; } } public final CompletionStage<Integer> prepare(LocalTransaction localTransaction) { return prepare(localTransaction, false); } public final CompletionStage<Integer> prepare(LocalTransaction localTransaction, boolean replayEntryWrapping) { CompletionStage<Integer> markRollbackStage = validateNotMarkedForRollback(localTransaction); if (markRollbackStage != null) { return markRollbackStage; } if (isOnePhaseCommit(localTransaction)) { if (log.isTraceEnabled()) log.tracef("Received prepare for tx: %s. Skipping call as 1PC will be used.", localTransaction); return XA_OKAY_STAGE; } PrepareCommand prepareCommand = commandCreator.createPrepareCommand(localTransaction.getGlobalTransaction(), localTransaction.getModifications(), false); if (log.isTraceEnabled()) log.tracef("Sending prepare command through the chain: %s", prepareCommand); LocalTxInvocationContext ctx = icf.running().createTxInvocationContext(localTransaction); prepareCommand.setReplayEntryWrapping(replayEntryWrapping); CompletionStage<Object> prepareStage = invoker.running().invokeAsync(ctx, prepareCommand); return CompletionStages.handleAndCompose(prepareStage, (ignore, prepareThrowable) -> { if (prepareThrowable != null) { if (shuttingDown) log.trace("Exception while preparing back, probably because we're shutting down."); else log.errorProcessingPrepare(prepareThrowable); //rollback transaction before throwing the exception as there's no guarantee the TM calls XAResource.rollback //after prepare failed. return CompletionStages.handleAndCompose(rollback(localTransaction), (ignore2, rollbackThrowable) -> { // XA_RBROLLBACK tells the TM that we've rolled back already: the TM shouldn't call rollback after this. XAException xe = new XAException(XAException.XA_RBROLLBACK); if (rollbackThrowable != null) { rollbackThrowable.addSuppressed(prepareThrowable); xe.initCause(rollbackThrowable); } else { xe.initCause(prepareThrowable); } return CompletableFuture.failedFuture(xe); }); } if (localTransaction.isReadOnly()) { if (log.isTraceEnabled()) log.tracef("Readonly transaction: %s", localTransaction.getGlobalTransaction()); // force a cleanup to release any objects held. Some TMs don't call commit if it is a READ ONLY tx. See ISPN-845 return commitInternal(ctx) .thenApply(XA_RDONLY_APPLY); } else { txTable.running().localTransactionPrepared(localTransaction); return XA_OKAY_STAGE; } }); } public CompletionStage<Boolean> commit(LocalTransaction localTransaction, boolean isOnePhase) { if (log.isTraceEnabled()) log.tracef("Committing transaction %s", localTransaction.getGlobalTransaction()); LocalTxInvocationContext ctx = icf.running().createTxInvocationContext(localTransaction); if (isOnePhaseCommit(localTransaction) || isOnePhase) { CompletionStage<Boolean> markRollbackStage = validateNotMarkedForRollback(localTransaction); if (markRollbackStage != null) { return markRollbackStage; } if (log.isTraceEnabled()) log.trace("Doing an 1PC prepare call on the interceptor chain"); List<WriteCommand> modifications = localTransaction.getModifications(); PrepareCommand command = commandCreator.createPrepareCommand(localTransaction.getGlobalTransaction(), modifications, true); return CompletionStages.handleAndCompose(invoker.running().invokeAsync(ctx, command), (ignore, t) -> { if (t != null) { return handleCommitFailure(t, true, ctx); } return CompletableFutures.completedTrue(); }); } else if (!localTransaction.isReadOnly()) { return commitInternal(ctx); } return CompletableFutures.completedFalse(); } public CompletionStage<Void> rollback(LocalTransaction localTransaction) { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); } return CompletableFutures.completedNull(); }); } private <T> CompletionStage<T> handleRollbackFailure(Throwable t, LocalTransaction localTransaction) { if (shuttingDown) log.trace("Exception while rolling back, probably because we're shutting down."); else log.errorRollingBack(t); final Transaction transaction = localTransaction.getTransaction(); //this might be possible if the cache has stopped and TM still holds a reference to the XAResource if (transaction != null) { txTable.running().failureCompletingTransaction(transaction); } XAException xe = new XAException(XAException.XAER_RMERR); xe.initCause(t); return CompletableFuture.failedFuture(t); } private <T> CompletionStage<T> handleCommitFailure(Throwable e, boolean onePhaseCommit, LocalTxInvocationContext ctx) { if (log.isTraceEnabled()) log.tracef("Couldn't commit transaction %s, trying to rollback.", ctx.getCacheTransaction()); if (onePhaseCommit) { log.errorProcessing1pcPrepareCommand(e); } else { log.errorProcessing2pcCommitCommand(e); } boolean isRecoveryEnabled = recoveryManager.running() != null; CompletionStage<Void> stage; if (!isRecoveryEnabled) { //the rollback is not needed any way, because if one node aborts the transaction, then all the nodes will //abort too. stage = rollbackInternal(ctx); } else { stage = CompletableFutures.completedNull(); } return stage.handle((ignore, t) -> { txTable.running().failureCompletingTransaction(ctx.getTransaction()); if (t != null) { log.couldNotRollbackPrepared1PcTransaction(ctx.getCacheTransaction(), t); // inform the TM that a resource manager error has occurred in the transaction branch (XAER_RMERR). XAException xe = new XAException(XAException.XAER_RMERR); xe.initCause(t); xe.addSuppressed(e); throw new CompletionException(xe); } XAException xe = new XAException(XAException.XA_HEURRB); xe.initCause(e); throw new CompletionException(xe); //this is a heuristic rollback }); } private CompletionStage<Boolean> commitInternal(LocalTxInvocationContext ctx) { CommitCommand commitCommand = commandCreator.createCommitCommand(ctx.getGlobalTransaction()); CompletableFuture<Object> commitStage = invoker.running().invokeAsync(ctx, commitCommand); return CompletionStages.handleAndCompose(commitStage, (ignore, t) -> { if (t != null) { return handleCommitFailure(t, false, ctx); } txTable.running().removeLocalTransaction(ctx.getCacheTransaction()); return CompletableFutures.completedFalse(); }); } private CompletionStage<Void> rollbackInternal(LocalTxInvocationContext ctx) { if (log.isTraceEnabled()) log.tracef("rollback transaction %s ", ctx.getGlobalTransaction()); RollbackCommand rollbackCommand = commandsFactory.buildRollbackCommand(ctx.getGlobalTransaction()); return invoker.running().invokeAsync(ctx, rollbackCommand) .thenRun(() -> txTable.running().removeLocalTransaction(ctx.getCacheTransaction()) ); } private <T> CompletionStage<T> validateNotMarkedForRollback(LocalTransaction localTransaction) { if (localTransaction.isMarkedForRollback()) { if (log.isTraceEnabled()) log.tracef("Transaction already marked for rollback. Forcing rollback for %s", localTransaction); return rollback(localTransaction).thenApply(ignore -> { throw CompletableFutures.asCompletionException(new XAException(XAException.XA_RBROLLBACK)); }); } return null; } public boolean is1PcForAutoCommitTransaction(LocalTransaction localTransaction) { return use1PcForAutoCommitTransactions && localTransaction.isImplicitTransaction(); } private interface CommandCreator { CommitCommand createCommitCommand(GlobalTransaction gtx); PrepareCommand createPrepareCommand(GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhaseCommit); } private boolean isOnePhaseCommit(LocalTransaction localTransaction) { return defaultOnePhaseCommit || is1PcForAutoCommitTransaction(localTransaction); } }
13,437
45.020548
159
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/ModificationList.java
package org.infinispan.transaction.impl; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.infinispan.commands.write.WriteCommand; import org.infinispan.context.Flag; import org.infinispan.context.impl.FlagBitSets; import net.jcip.annotations.GuardedBy; /** * A list of {@link WriteCommand} for a transaction * <p> * {@link WriteCommand} can only be appended and the methods {@link #getAllModifications()} and {@link * #getModifications()} return a snapshot of the current list. {@link WriteCommand} appended after those methods are * invoked, are not visible. * * @since 14.0 */ public final class ModificationList { private static final int DEFAULT_ARRAY_LENGTH = 16; @GuardedBy("this") private WriteCommand[] mods; @GuardedBy("this") private int nextInsertIndex; @GuardedBy("this") private int[] nonLocalIndexes; @GuardedBy("this") private int nextNonLocalInsertIndex; private volatile boolean frozen; public ModificationList() { mods = new WriteCommand[DEFAULT_ARRAY_LENGTH]; nonLocalIndexes = new int[DEFAULT_ARRAY_LENGTH]; } public ModificationList(int capacity) { if (capacity < 1) { throw new IllegalArgumentException("Capacity must be greater than 1 but is " + capacity); } mods = new WriteCommand[capacity]; nonLocalIndexes = new int[capacity]; } public static ModificationList fromCollection(Collection<WriteCommand> mods) { if (mods == null || mods.size() == 0) { return new ModificationList(); } ModificationList modificationList = new ModificationList(mods.size()); for (WriteCommand command : mods) { modificationList.append(command); } return modificationList; } /** * Appends the {@link WriteCommand} to this list. * * @param command The {@link WriteCommand} instance to append. * @throws IllegalStateException If this list is frozen. * @see #freeze() */ public synchronized void append(WriteCommand command) { checkNotFrozen(); if (nextInsertIndex == mods.length) { growAllMods(); } assert nextInsertIndex < mods.length; if (!command.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL)) { if (nextNonLocalInsertIndex == nonLocalIndexes.length) { growNonLocalIndexMap(); } assert nextNonLocalInsertIndex < nonLocalIndexes.length; nonLocalIndexes[nextNonLocalInsertIndex++] = nextInsertIndex; } mods[nextInsertIndex++] = command; } /** * Freezes this list. * <p> * After invoked, no more {@link WriteCommand} can be appended to this list. {@link #append(WriteCommand)} will throw * a {@link IllegalStateException}. */ public void freeze() { frozen = true; } /** * Returns a snapshot of this list. * <p> * This snapshot does not contain {@link WriteCommand} with flag {@link Flag#CACHE_MODE_LOCAL} and it cannot be * modified. * * @return A snapshot of this list. */ public synchronized List<WriteCommand> getModifications() { return new NonLocalModificationsList(mods, nonLocalIndexes, nextNonLocalInsertIndex); } /** * @return {@code true} if it contains one or more {@link WriteCommand} without {@link Flag#CACHE_MODE_LOCAL}. */ public synchronized boolean hasNonLocalModifications() { return nextNonLocalInsertIndex != 0; } /** * @return A snapshot of this list with all {@link WriteCommand}. The {@link List} cannot be modified. * @see #getModifications() */ public synchronized List<WriteCommand> getAllModifications() { return new AllModsList(mods, nextInsertIndex); } /** * @return The number of {@link WriteCommand} stored this list. */ public synchronized int size() { return nextInsertIndex; } /** * @return {@code true} if this list is empty. */ public synchronized boolean isEmpty() { return nextInsertIndex == 0; } @Override public synchronized String toString() { return "ModificationList{" + "mods=" + Arrays.toString(mods) + '}'; } private void checkNotFrozen() { if (frozen) { throw new IllegalStateException(); } } @GuardedBy("this") private void growAllMods() { int newCapacity = mods.length == 1 ? 2 : mods.length + (mods.length >> 1); mods = Arrays.copyOf(mods, newCapacity); } @GuardedBy("this") private void growNonLocalIndexMap() { int newCapacity = nonLocalIndexes.length == 1 ? 2 : nonLocalIndexes.length + (nonLocalIndexes.length >> 1); nonLocalIndexes = Arrays.copyOf(nonLocalIndexes, newCapacity); } private static void checkIndex(int index, int size) { if (index < 0 || index >= size) { throw new ArrayIndexOutOfBoundsException("Range check failed: " + index + " not in [0," + size + "[."); } } private static class AllModsList extends AbstractList<WriteCommand> { private final WriteCommand[] mods; private final int size; private AllModsList(WriteCommand[] mods, int size) { this.mods = mods; this.size = size; } @Override public WriteCommand get(int index) { checkIndex(index, size); return mods[index]; } @Override public int size() { return size; } } private static class NonLocalModificationsList extends AbstractList<WriteCommand> { private final WriteCommand[] mods; private final int[] indexMappings; private final int size; private NonLocalModificationsList(WriteCommand[] mods, int[] indexMappings, int size) { this.mods = mods; this.indexMappings = indexMappings; this.size = size; } @Override public WriteCommand get(int index) { checkIndex(index, size); return mods[indexMappings[index]]; } @Override public int size() { return size; } } }
6,123
27.751174
120
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/WriteSkewHelper.java
package org.infinispan.transaction.impl; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import org.infinispan.commands.SegmentSpecificCommand; import org.infinispan.commands.tx.VersionedPrepareCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.VersionedRepeatableReadEntry; import org.infinispan.container.versioning.IncrementableEntryVersion; import org.infinispan.container.versioning.VersionGenerator; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.persistence.util.EntryLoader; import org.infinispan.remoting.responses.PrepareResponse; import org.infinispan.remoting.responses.Response; import org.infinispan.transaction.WriteSkewException; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; /** * Encapsulates write skew logic in maintaining version maps, etc. * * @author Manik Surtani * @since 5.1 */ public class WriteSkewHelper { public static void mergePrepareResponses(Response r, PrepareResponse aggregateResponse) { if (r instanceof PrepareResponse && aggregateResponse != null) { PrepareResponse remoteRsp = (PrepareResponse) r; aggregateResponse.merge(remoteRsp); } } public static PrepareResponse mergeInPrepareResponse(Map<Object, IncrementableEntryVersion> versionsMap, PrepareResponse response) { response.mergeEntryVersions(versionsMap); return response; } public static Map<Object, IncrementableEntryVersion> mergeEntryVersions(Map<Object, IncrementableEntryVersion> entryVersions, Map<Object, IncrementableEntryVersion> updatedEntryVersions) { if (updatedEntryVersions != null && !updatedEntryVersions.isEmpty()){ updatedEntryVersions.putAll(entryVersions); return updatedEntryVersions; } return entryVersions; } public static CompletionStage<Map<Object, IncrementableEntryVersion>> performWriteSkewCheckAndReturnNewVersions(VersionedPrepareCommand prepareCommand, EntryLoader<?, ?> entryLoader, VersionGenerator versionGenerator, TxInvocationContext<?> context, KeySpecificLogic ksl, KeyPartitioner keyPartitioner) { if (prepareCommand.getVersionsSeen() == null) { // Do not perform the write skew check if this prepare command is being replayed for state transfer return CompletableFutures.completedEmptyMap(); } Map<Object, IncrementableEntryVersion> uv = new HashMap<>(); AggregateCompletionStage<Map<Object, IncrementableEntryVersion>> aggregateCompletionStage = CompletionStages.aggregateCompletionStage(uv); for (WriteCommand c : prepareCommand.getModifications()) { for (Object k : c.getAffectedKeys()) { int segment = SegmentSpecificCommand.extractSegment(c, k, keyPartitioner); if (ksl.performCheckOnSegment(segment)) { CacheEntry<?, ?> cacheEntry = context.lookupEntry(k); if (!(cacheEntry instanceof VersionedRepeatableReadEntry)) { continue; } VersionedRepeatableReadEntry entry = (VersionedRepeatableReadEntry) cacheEntry; CompletionStage<Boolean> skewStage = entry.performWriteSkewCheck(entryLoader, segment, context, prepareCommand.getVersionsSeen().get(k), versionGenerator, c.hasAnyFlag(FlagBitSets.ROLLING_UPGRADE)); aggregateCompletionStage.dependsOn(skewStage.thenAccept(passSkew -> { if (!passSkew) { throw new WriteSkewException("Write skew detected on key " + entry.getKey() + " for transaction " + context.getCacheTransaction(), entry.getKey()); } IncrementableEntryVersion newVersion = incrementVersion(entry,versionGenerator); // Have to synchronize as we could have returns on different threads due to notifications/loaders etc synchronized (uv) { uv.put(entry.getKey(), newVersion); } })); } } } return aggregateCompletionStage.freeze(); } public static IncrementableEntryVersion versionFromEntry(CacheEntry<?, ?> entry) { if (entry == null) { return null; } PrivateMetadata metadata = entry.getInternalMetadata(); return metadata == null ? null : metadata.entryVersion(); } public static IncrementableEntryVersion incrementVersion(CacheEntry<?, ?> entry, VersionGenerator versionGenerator) { IncrementableEntryVersion oldVersion = versionFromEntry(entry); return entry.isCreated() || oldVersion == null ? versionGenerator.generateNew() : versionGenerator.increment(oldVersion); } public static void addVersionRead(TxInvocationContext<?> ctx, CacheEntry<? ,?> entry, Object key, VersionGenerator versionGenerator, Log log) { IncrementableEntryVersion version = versionFromEntry(entry); if (version == null) { version = versionGenerator.nonExistingVersion(); if (log.isTraceEnabled()) { log.tracef("Adding non-existent version read for key %s", key); } } else if (log.isTraceEnabled()) { log.tracef("Adding version read %s for key %s", version, key); } ctx.getCacheTransaction().addVersionRead(key, version); } @FunctionalInterface public interface KeySpecificLogic { boolean performCheckOnSegment(int segment); } public static final KeySpecificLogic ALWAYS_TRUE_LOGIC = k -> true; }
6,632
48.5
154
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/TransactionOriginatorChecker.java
package org.infinispan.transaction.impl; import java.util.Collection; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.xa.GlobalTransaction; /** * An interface to check if the transaction originator is left or not. * * @author Pedro Ruivo * @since 9.1 */ @Scope(Scopes.NAMED_CACHE) public interface TransactionOriginatorChecker { /** * A Local mode implementation. */ TransactionOriginatorChecker LOCAL = new TransactionOriginatorChecker() { @Override public boolean isOriginatorMissing(GlobalTransaction gtx) { return false; } @Override public boolean isOriginatorMissing(GlobalTransaction gtx, Collection<Address> liveMembers) { return false; } }; /** * @return {@code true} if the member who executed {@code gtx} is missing. */ boolean isOriginatorMissing(GlobalTransaction gtx); /** * @return {@code true} if the member who executed {@code gtx} is missing using the {@code liveMembers}. */ boolean isOriginatorMissing(GlobalTransaction gtx, Collection<Address> liveMembers); }
1,221
26.155556
107
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/ClusteredTransactionOriginatorChecker.java
package org.infinispan.transaction.impl; import java.util.Collection; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.xa.GlobalTransaction; /** * A {@link TransactionOriginatorChecker} implementation for clustered caches. * <p> * It uses the current topology to fetch the live members to check if the transaction's originator is alive. * * @author Pedro Ruivo * @since 9.1 */ @Scope(Scopes.NAMED_CACHE) public class ClusteredTransactionOriginatorChecker implements TransactionOriginatorChecker { @Inject RpcManager rpcManager; @Override public boolean isOriginatorMissing(GlobalTransaction gtx) { return isOriginatorMissing(gtx, rpcManager.getMembers()); } @Override public boolean isOriginatorMissing(GlobalTransaction gtx, Collection<Address> liveMembers) { return !liveMembers.contains(gtx.getAddress()); } }
1,086
30.057143
108
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/RemoteTransaction.java
package org.infinispan.transaction.impl; import static org.infinispan.commons.util.Util.toStr; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.commands.write.WriteCommand; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.Flag; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Defines the state of a remotely originated transaction. * * @author Mircea.Markus@jboss.com * @since 4.0 */ public class RemoteTransaction extends AbstractCacheTransaction { private static final Log log = LogFactory.getLog(RemoteTransaction.class); private static final CompletableFuture<Void> INITIAL_FUTURE = CompletableFutures.completedNull(); /** * This int should be set to the highest topology id for transactions received via state transfer. During state * transfer we do not migrate lookedUpEntries to save bandwidth. If lookedUpEntriesTopology is less than the * topology of the CommitCommand that is received this indicates the preceding PrepareCommand was received by * previous owner before state transfer or the data has now changed owners and the current owner * now has to re-execute prepare to populate lookedUpEntries (and acquire the locks). */ // Default value of MAX_VALUE basically means it hasn't yet received what topology id this is for the entries private volatile int lookedUpEntriesTopology = Integer.MAX_VALUE; private final AtomicReference<CompletableFuture<Void>> synchronization = new AtomicReference<>(INITIAL_FUTURE); public RemoteTransaction(List<WriteCommand> modifications, GlobalTransaction tx, int topologyId, long txCreationTime) { super(tx, topologyId, txCreationTime); lookedUpEntries = new HashMap<>(modifications.size()); setModifications(modifications); } public RemoteTransaction(GlobalTransaction tx, int topologyId, long txCreationTime) { super(tx, topologyId, txCreationTime); lookedUpEntries = new HashMap<>(4); } @Override public void setStateTransferFlag(Flag stateTransferFlag) { if (getStateTransferFlag() == null && stateTransferFlag == Flag.PUT_FOR_X_SITE_STATE_TRANSFER) { internalSetStateTransferFlag(Flag.PUT_FOR_X_SITE_STATE_TRANSFER); } } @Override public void putLookedUpEntry(Object key, CacheEntry e) { checkIfRolledBack(); if (log.isTraceEnabled()) { log.tracef("Adding key %s to tx %s", toStr(key), getGlobalTransaction()); } lookedUpEntries.put(key, e); } @Override public void putLookedUpEntries(Map<Object, CacheEntry> entries) { checkIfRolledBack(); if (log.isTraceEnabled()) { log.tracef("Adding keys %s to tx %s", entries.keySet(), getGlobalTransaction()); } lookedUpEntries.putAll(entries); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RemoteTransaction)) return false; RemoteTransaction that = (RemoteTransaction) o; return tx.equals(that.tx); } @Override public int hashCode() { return tx.hashCode(); } @Override public String toString() { return "RemoteTransaction{" + "modifications=" + modifications + ", lookedUpEntries=" + lookedUpEntries + ", lockedKeys=" + toStr(getLockedKeys()) + ", backupKeyLocks=" + toStr(getBackupLockedKeys()) + ", lookedUpEntriesTopology=" + lookedUpEntriesTopology + ", isMarkedForRollback=" + isMarkedForRollback() + ", tx=" + tx + '}'; } public void setLookedUpEntriesTopology(int lookedUpEntriesTopology) { this.lookedUpEntriesTopology = lookedUpEntriesTopology; } public int lookedUpEntriesTopology() { return lookedUpEntriesTopology; } public final CompletableFuture<Void> enterSynchronizationAsync(CompletableFuture<Void> releaseFuture) { CompletableFuture<Void> currentFuture; do { currentFuture = synchronization.get(); } while (!synchronization.compareAndSet(currentFuture, releaseFuture)); return currentFuture; } }
4,451
35.793388
122
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/impl/LocalTransaction.java
package org.infinispan.transaction.impl; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import jakarta.transaction.Transaction; import org.infinispan.commands.write.WriteCommand; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.Flag; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.remoting.transport.Address; import org.infinispan.topology.CacheTopology; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import net.jcip.annotations.GuardedBy; /** * Object that holds transaction's state on the node where it originated; as opposed to {@link RemoteTransaction}. * * @author Mircea.Markus@jboss.com * @author Pedro Ruivo * @since 5.0 */ public abstract class LocalTransaction extends AbstractCacheTransaction { private static final Log log = LogFactory.getLog(LocalTransaction.class); private Set<Address> remoteLockedNodes; private final Transaction transaction; private final boolean implicitTransaction; private volatile boolean isFromRemoteSite; private boolean prepareSent; @GuardedBy("this") private Map<Object, CompletionStage<IracMetadata>> iracMetadata; public LocalTransaction(Transaction transaction, GlobalTransaction tx, boolean implicitTransaction, int topologyId, long txCreationTime) { super(tx, topologyId, txCreationTime); this.transaction = transaction; this.implicitTransaction = implicitTransaction; } public final void addModification(WriteCommand mod) { if (log.isTraceEnabled()) log.tracef("Adding modification %s. Mod list is %s", mod, modifications); modifications.append(mod); } public void locksAcquired(Collection<Address> nodes) { if (log.isTraceEnabled()) log.tracef("Adding remote locks on %s. Remote locks are %s", nodes, remoteLockedNodes); if (remoteLockedNodes == null) remoteLockedNodes = new HashSet<>(nodes); else remoteLockedNodes.addAll(nodes); } public Collection<Address> getRemoteLocksAcquired(){ if (remoteLockedNodes == null) return Collections.emptySet(); return remoteLockedNodes; } public void clearRemoteLocksAcquired() { if (remoteLockedNodes != null) remoteLockedNodes.clear(); } public Transaction getTransaction() { return transaction; } @Override public Map<Object, CacheEntry> getLookedUpEntries() { return lookedUpEntries == null ? Collections.emptyMap() : lookedUpEntries; } public boolean isImplicitTransaction() { return implicitTransaction; } @Override public void putLookedUpEntry(Object key, CacheEntry e) { checkIfRolledBack(); if (lookedUpEntries == null) lookedUpEntries = new HashMap<>(4); lookedUpEntries.put(key, e); } @Override public void putLookedUpEntries(Map<Object, CacheEntry> entries) { checkIfRolledBack(); if (lookedUpEntries == null) { lookedUpEntries = new HashMap<>(entries); } else { lookedUpEntries.putAll(entries); } } public boolean isReadOnly() { return modifications.isEmpty(); } public abstract boolean isEnlisted(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LocalTransaction that = (LocalTransaction) o; return tx.getId() == that.tx.getId(); } @Override public int hashCode() { long id = tx.getId(); return (int)(id ^ (id >>> 32)); } @Override public String toString() { return "LocalTransaction{" + "remoteLockedNodes=" + remoteLockedNodes + ", isMarkedForRollback=" + isMarkedForRollback() + ", lockedKeys=" + getLockedKeys() + ", backupKeyLocks=" + getBackupLockedKeys() + ", topologyId=" + topologyId + ", stateTransferFlag=" + getStateTransferFlag() + "} " + super.toString(); } public void setStateTransferFlag(Flag stateTransferFlag) { if (this.getStateTransferFlag() == null && (stateTransferFlag == Flag.PUT_FOR_STATE_TRANSFER || stateTransferFlag == Flag.PUT_FOR_X_SITE_STATE_TRANSFER)) { internalSetStateTransferFlag(stateTransferFlag); } } /** * When x-site replication is used, this returns when this operation * happens as a result of backing up data from a remote site. */ public boolean isFromRemoteSite() { return isFromRemoteSite; } /** * @see #isFromRemoteSite() */ public void setFromRemoteSite(boolean fromRemoteSite) { isFromRemoteSite = fromRemoteSite; } /** * Calculates the list of nodes to which a commit/rollback needs to be sent based on the nodes to which prepare * was sent. If the commit/rollback is to be sent in the same topologyId, then the 'recipients' param is returned back. * If the current topologyId is different than the topologyId of this transaction ({@link #getTopologyId()} then * this method returns the reunion between 'recipients' and {@link #getRemoteLocksAcquired()} from which it discards * the members that left. */ public Collection<Address> getCommitNodes(Collection<Address> recipients, CacheTopology cacheTopology) { int currentTopologyId = cacheTopology.getTopologyId(); List<Address> members = cacheTopology.getMembers(); if (log.isTraceEnabled()) log.tracef("getCommitNodes recipients=%s, currentTopologyId=%s, members=%s, txTopologyId=%s", recipients, currentTopologyId, members, getTopologyId()); if (recipients == null) { return null; } // Include all the nodes we sent a LockControlCommand to and are not in the recipients list now // either because the topology changed, or because the lock failed. // Also include nodes that are no longer in the cluster, so if JGroups retransmits a lock/prepare command // after a merge, it also retransmits the commit/rollback. Set<Address> allRecipients = new HashSet<>(getRemoteLocksAcquired()); allRecipients.addAll(recipients); if (log.isTraceEnabled()) log.tracef("The merged list of nodes to send commit/rollback is %s", allRecipients); return allRecipients; } /** * Sets the prepare sent for this transaction */ public final void markPrepareSent() { prepareSent = true; } /** * @return true if the prepare was sent to the other nodes */ public final boolean isPrepareSent() { return prepareSent; } /** * @return {@code true} if there is an {@link IracMetadata} stored for {@code key}. */ public synchronized boolean hasIracMetadata(Object key) { return iracMetadata != null && iracMetadata.containsKey(key); } /** * Stores the {@link IracMetadata} associated with {@code key}. * * @param key The key. * @param metadata The {@link CompletionStage} that will be completed with {@link IracMetadata} to associate. */ public synchronized void storeIracMetadata(Object key, CompletionStage<IracMetadata> metadata) { if (iracMetadata == null) { iracMetadata = new HashMap<>(); } CompletionStage<IracMetadata> old = iracMetadata.put(key, metadata); assert old == null : "[IRAC] irac metadata replaced!"; } /** * @return The {@link IracMetadata} associated with {@code key}. */ public synchronized CompletionStage<IracMetadata> getIracMetadata(Object key) { return iracMetadata == null ? null : iracMetadata.get(key); } }
7,946
32.673729
125
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/tm/package-info.java
/** * Infinispan's bare-bones internal transaction manager, used for batching calls as well as as a dummy, unit-test-only * transaction manager. */ package org.infinispan.transaction.tm;
190
30.833333
118
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/tm/EmbeddedTransactionManager.java
package org.infinispan.transaction.tm; import javax.transaction.xa.XAResource; /** * Simple transaction manager implementation that maintains transaction state in memory only. * <p> * See {@link EmbeddedBaseTransactionManager} for details about which features are supported. * * @author bela * @author Pedro Ruivo * @see EmbeddedBaseTransactionManager * @since 9.0 */ public class EmbeddedTransactionManager extends EmbeddedBaseTransactionManager { private EmbeddedTransactionManager() { } public static EmbeddedTransactionManager getInstance() { return LazyInitializeHolder.TM_INSTANCE; } public static EmbeddedUserTransaction getUserTransaction() { return LazyInitializeHolder.USER_TX_INSTANCE; } public static void destroy() { dissociateTransaction(); } public XAResource firstEnlistedResource() { return getTransaction().firstEnlistedResource(); } private static class LazyInitializeHolder { static final EmbeddedTransactionManager TM_INSTANCE = new EmbeddedTransactionManager(); static final EmbeddedUserTransaction USER_TX_INSTANCE = new EmbeddedUserTransaction(TM_INSTANCE); } }
1,174
28.375
103
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/tm/BatchModeTransactionManager.java
package org.infinispan.transaction.tm; /** * Not really a transaction manager in the truest sense of the word. Only used to batch up operations. Proper * transactional semantics of rollbacks and recovery are NOT used here. * * @author bela * @since 4.0 */ public class BatchModeTransactionManager extends EmbeddedBaseTransactionManager { private static BatchModeTransactionManager INSTANCE = null; private BatchModeTransactionManager() { } public static BatchModeTransactionManager getInstance() { if (INSTANCE == null) { INSTANCE = new BatchModeTransactionManager(); } return INSTANCE; } public static void destroy() { if (INSTANCE == null) { return; } dissociateTransaction(); INSTANCE = null; } }
795
23.121212
111
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/tm/EmbeddedTransaction.java
package org.infinispan.transaction.tm; import static org.infinispan.commons.util.Util.longToBytes; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import jakarta.transaction.Transaction; import javax.transaction.xa.XAResource; import org.infinispan.commons.tx.TransactionImpl; import org.infinispan.commons.tx.XidImpl; /** * A {@link Transaction} implementation used by {@link EmbeddedBaseTransactionManager}. * <p> * See {@link EmbeddedBaseTransactionManager} for more details. * * @author Bela Ban * @author Pedro Ruivo * @see EmbeddedBaseTransactionManager * @since 9.0 */ public final class EmbeddedTransaction extends TransactionImpl { //format can be anything except: //-1: means a null Xid // 0: means OSI CCR format //I would like ot use 0x4953504E (ISPN in hex) for the format, but keep it to 1 to be consistent with DummyXid. private static final int FORMAT = 1; private static final AtomicLong GLOBAL_ID_GENERATOR = new AtomicLong(1); private static final AtomicLong BRANCH_QUALIFIER_GENERATOR = new AtomicLong(1); public EmbeddedTransaction(EmbeddedBaseTransactionManager tm) { super(); setXid(createXid(tm.getTransactionManagerId())); } public XAResource firstEnlistedResource() { return getEnlistedResources().iterator().next(); } public static XidImpl createXid(UUID transactionManagerId) { return XidImpl.create(FORMAT, create(transactionManagerId, GLOBAL_ID_GENERATOR), create(transactionManagerId, BRANCH_QUALIFIER_GENERATOR)); } private static byte[] create(UUID transactionManagerId, AtomicLong generator) { byte[] field = new byte[24]; //size of 3 longs longToBytes(transactionManagerId.getLeastSignificantBits(), field, 0); longToBytes(transactionManagerId.getMostSignificantBits(), field, 8); longToBytes(generator.incrementAndGet(), field, 16); return field; } }
1,940
33.052632
114
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/tm/EmbeddedUserTransaction.java
package org.infinispan.transaction.tm; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.UserTransaction; /** * A {@link UserTransaction} implementation that uses {@link EmbeddedTransactionManager}. * <p> * This implementation does not support transaction timeout and it does not cancel long running transactions. * <p> * See {@link EmbeddedBaseTransactionManager} for more details about its implementation. * * @author Bela Ban * @author Pedro Ruivo * @see EmbeddedBaseTransactionManager * @since 9.0 */ public class EmbeddedUserTransaction implements UserTransaction { private final EmbeddedTransactionManager tm; EmbeddedUserTransaction(EmbeddedTransactionManager tm) { this.tm = tm; } @Override public void begin() throws NotSupportedException, SystemException { tm.begin(); } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException { tm.commit(); } @Override public void rollback() throws IllegalStateException, SystemException { tm.rollback(); } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { tm.setRollbackOnly(); } @Override public int getStatus() throws SystemException { return tm.getStatus(); } @Override public void setTransactionTimeout(int seconds) throws SystemException { throw new SystemException("not supported"); } }
1,735
26.555556
109
java
null
infinispan-main/core/src/main/java/org/infinispan/transaction/tm/EmbeddedBaseTransactionManager.java
package org.infinispan.transaction.tm; import java.util.UUID; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.commons.tx.TransactionManagerImpl; /** * A simple {@link TransactionManager} implementation. * <p> * It provides the basic to handle {@link Transaction}s and supports any {@link javax.transaction.xa.XAResource}. * <p> * Implementation notes: <ul> <li>The state is kept in memory only.</li> <li>Does not support recover.</li> <li>Does not * support multi-thread transactions. Although it is possible to execute the transactions in multiple threads, this * transaction manager does not wait for them to complete. It is the application responsibility to wait before invoking * {@link #commit()} or {@link #rollback()}</li> <li>The transaction should not block. It is no possible to {@link * #setTransactionTimeout(int)} and this transaction manager won't rollback the transaction if it takes too long.</li> * </ul> * <p> * If you need any of the requirements above, please consider use another implementation. * <p> * Also, it does not implement any 1-phase-commit optimization. * * @author Bela Ban * @author Pedro Ruivo * @since 9.0 */ public class EmbeddedBaseTransactionManager extends TransactionManagerImpl { UUID getTransactionManagerId() { return transactionManagerId; } @Override protected EmbeddedTransaction createTransaction() { return new EmbeddedTransaction(this); } @Override public EmbeddedTransaction getTransaction() { return (EmbeddedTransaction) super.getTransaction(); } }
1,631
33.723404
120
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/package-info.java
/** * Functional API package * * @api.public */ @Experimental package org.infinispan.functional; import org.infinispan.commons.util.Experimental;
151
14.2
48
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/EntryView.java
package org.infinispan.functional; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import org.infinispan.commons.util.Experimental; import org.infinispan.metadata.Metadata; /** * Entry views expose cached entry information to the user. Depending on the * type of entry view, different operations are available. Currently, three * type of entry views are supported: * * <ul> * <il>{@link ReadEntryView}: read-only entry view</il> * <il>{@link WriteEntryView}: write-only entry view</il> * <il>{@link ReadWriteEntryView}: read-write entry view</il> * </ul> * * @since 8.0 */ @Experimental public final class EntryView { private EntryView() { // Cannot be instantiated, it's just a holder class } /** * Expose read-only information about a cache entry potentially associated * with a key in the functional map. Typically, if the key is associated * with a cache entry, that information will include value and optional * {@link MetaParam} information. * * <p>It exposes both {@link #get()} and {@link #find()} methods for * convenience. If the caller knows for sure that the value will be * present, {@link #get()} offers the convenience of retrieving the value * directly without having to get an {@link Optional} first. As a result * of this, {@link #get()} throws {@link NoSuchElementException} if * there's no value associated with the entry. If the caller is unsure * of whether the value is present, {@link #find()} should be used. * This approach avoids the user having to do null checks. * * @since 8.0 */ @Experimental public interface ReadEntryView<K, V> extends MetaParam.Lookup { /** * Key of the read-only entry view. Guaranteed to return a non-null value. * The instance of the key must not be mutated. */ K key(); /** * Returns a non-null value if the key has a value associated with it or * throws {@link NoSuchElementException} if no value is associated with * the entry. * * <p>The value instance is read-only and must not be mutated. If the function * accessing this value is about to update the entry, it has to create * a defensive copy (or completely new instance) and store it using * {@link WriteEntryView#set(Object, MetaParam.Writable[])}. * * @throws NoSuchElementException if no value is associated with the key. */ V get() throws NoSuchElementException; /** * Optional value. It'll return a non-empty value when the value is present, * and empty when the value is not present. * * <p>The value instance is read-only and must not be mutated. If the function * accessing this value is about to update the entry, it has to create * a defensive copy (or completely new instance) and store it using * {@link WriteEntryView#set(Object, MetaParam.Writable[])}. */ Optional<V> find(); /** * The same as {@link #find()} but does not update any hit/miss statistics. * @return */ default Optional<V> peek() { return find(); } } /** * Expose a write-only facade for a cache entry potentially associated with a key * in the functional map which allows the cache entry to be written with * new value and/or new metadata parameters. * * @since 8.0 */ @Experimental public interface WriteEntryView<K, V> { /** * Key of the write-only entry view. Guaranteed to return a non-null value. * The instance of the key must not be mutated. */ K key(); /** * Set this value along with optional metadata parameters. * * <p>This method returns {@link Void} instead of 'void' to avoid * having to add overloaded methods in functional map that take * {@link Consumer} instead of {@link Function}. This is an * unfortunate side effect of the Java language itself which does * not consider 'void' to be an {@link Object}. */ Void set(V value, MetaParam.Writable... metas); /** * Set this value along with metadata object. * * <p>This method returns {@link Void} instead of 'void' to avoid * having to add overloaded methods in functional map that take * {@link Consumer} instead of {@link Function}. This is an * unfortunate side effect of the Java language itself which does * not consider 'void' to be an {@link Object}. */ Void set(V value, Metadata metadata); /** * Removes the value and any metadata parameters associated with it. * * <p>This method returns {@link Void} instead of 'void' to avoid * having to add overloaded methods in functional map that take * {@link Consumer} instead of {@link Function}. This is an * unfortunate side effect of the Java language itself which does * not consider 'void' to be an {@link Object}. */ Void remove(); } /** * Expose information about a cache entry potentially associated with a key * in the functional map, and allows that cache entry to be written with * new value and/or new metadata parameters. * * @since 8.0 */ @Experimental public interface ReadWriteEntryView<K, V> extends ReadEntryView<K, V>, WriteEntryView<K, V> {} }
5,534
35.9
97
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/ParamIds.java
package org.infinispan.functional; import org.infinispan.commons.util.Experimental; /** * Parameter identifiers. * * @since 8.0 */ @Experimental public final class ParamIds { public static final int PERSISTENCE_MODE_ID = 0; public static final int LOCKING_MODE_ID = 1; public static final int EXECUTION_MODE_ID = 2; public static final int STATS_MODE_ID = 3; public static final int REPLICATION_MODE_ID = 4; private ParamIds() { // Cannot be instantiated, it's just a holder class } }
521
20.75
57
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/MetaParam.java
package org.infinispan.functional; import java.util.Optional; import org.infinispan.commons.util.Experimental; import org.infinispan.container.versioning.EntryVersion; /** * An easily extensible metadata parameter that's stored along with the value * in the the functional map. * * <p>Some metadata parameters can be provided by the user in which case they * need to implement {@link MetaParam.Writable}. Examples of writable metadata * parameters are version information, lifespan of the cached value...etc. * * <p>Those metadata parameters not extending {@link MetaParam.Writable} are * created by internal logic and hence can only be queried, for example: * time when value was added into the functional map, or last time value * was accessed or modified. * * <p>What makes {@link MetaParam} different from {@link Param} is that {@link MetaParam} * values are designed to be stored along with key/value pairs in the functional map, * to provide extra information. On the other hand, {@link Param} instances * merely act as ways to tweak how operations are executed, and their contents * are never stored permanently. * * <p>This interface replaces Infinispan's Metadata interface providing * a more flexible way to add new metadata parameters to be stored with * the cached entries. * * <p>{@link MetaParam} design has been geared towards making a clear * separation between the metadata that can be provided by the user on * per-entry basis, e.g. lifespan, maxIdle, version...etc, as opposed to * metadata that's produced by the internal logic that cannot be modified * directly by the user, e.g. cache entry created time, last time cache entry * was modified or accessed ...etc. * * @param <T> type of MetaParam instance, implementations should assign it to * the implementation's type. * @since 8.0 */ @Experimental public interface MetaParam<T> { /** * Returns the value of the meta parameter. */ T get(); /** * Provides metadata parameter lookup capabilities using {@link Class} as * lookup key. * * <p>When the {@link MetaParam} type is generic, e.g. {@link MetaEntryVersion}, * passing the correct {@link Class} information so that the return of * {@link #findMetaParam} is of the expected type can be a bit tricky. * {@link MetaEntryVersion#type()} offers an easy way to retrieve the * expected {@link MetaParam} type from {@link #findMetaParam} at the * expense of some type safety: * * <pre>{@code * Class<MetaEntryVersion<Long>> type = MetaEntryVersion.type(); * Optional<MetaEntryVersion<Long>> metaVersion = * metaParamLookup.findMetaParam(type); * }</pre> * * In the future, the API might be adjusted to provide additional lookup * methods where this situation is improved. Also, if the {@link MetaParam} * type is not generic, e.g. {@link MetaLifespan}, the problem is avoided * altogether: * * <pre>{@code * Optional<MetaLifespan<Long>> metaLifespan = * metaParamLookup.findMetaParam(MetaLifespan.class); * }</pre> * * <p>A user that queries meta parameters can never assume that the * meta parameter will always exist because some of them depends on the * cache usage. * * @since 8.0 */ @Experimental interface Lookup { /** * Returns a non-empty {@link Optional} instance containing a metadata * parameter instance that can be assigned to the type {@link Class} * passed in, or an empty {@link Optional} if no metadata can be assigned * to that type. * * @param <T> metadata parameter type */ <T extends MetaParam> Optional<T> findMetaParam(Class<T> type); } /** * Writable {@link MetaParam} instances are those that the user can provide * to be stored as part of the cache entry. RESTful HTTTP MIME metadata, version * information or lifespan are examples. * * @param <T> type of MetaParam instance, implementations should assign it to * the implementation's type. * @since 8.0 */ @Experimental interface Writable<T> extends MetaParam<T> {} /** * Writable metadata parameter representing a cached entry's millisecond lifespan. * * @since 8.0 */ @Experimental final class MetaLifespan extends MetaLong implements Writable<Long> { private static final MetaLifespan DEFAULT = new MetaLifespan(-1); public MetaLifespan(long lifespan) { super(lifespan); } @Override public String toString() { return "MetaLifespan=" + value; } public static MetaLifespan defaultValue() { return DEFAULT; } } /** * Read only metadata parameter representing a cached entry's created time * in milliseconds. * * @since 8.0 */ @Experimental final class MetaCreated extends MetaLong { public MetaCreated(long created) { super(created); } @Override public String toString() { return "MetaCreated=" + value; } } /** * Writable metadata parameter representing a cached entry's millisecond * max idle time. * * @since 8.0 */ @Experimental final class MetaMaxIdle extends MetaLong implements Writable<Long> { private static final MetaMaxIdle DEFAULT = new MetaMaxIdle(-1); public MetaMaxIdle(long maxIdle) { super(maxIdle); } @Override public String toString() { return "MetaMaxIdle=" + value; } public static MetaMaxIdle defaultValue() { return DEFAULT; } } /** * Read only metadata parameter representing a cached entry's last used time * in milliseconds. * * @since 8.0 */ @Experimental final class MetaLastUsed extends MetaLong { public MetaLastUsed(long lastUsed) { super(lastUsed); } @Override public String toString() { return "MetaLastUsed=" + value; } } /** * Writable metadata parameter representing a cached entry's generic version. * * @since 8.0 */ @Experimental class MetaEntryVersion implements Writable<EntryVersion> { private final EntryVersion entryVersion; public MetaEntryVersion(EntryVersion entryVersion) { this.entryVersion = entryVersion; } @Override public EntryVersion get() { return entryVersion; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetaEntryVersion that = (MetaEntryVersion) o; return entryVersion.equals(that.entryVersion); } @Override public int hashCode() { return entryVersion.hashCode(); } @Override public String toString() { return "MetaEntryVersion=" + entryVersion; } } /** * Abstract class for numeric long-based metadata parameter instances. * * @since 8.0 */ @Experimental abstract class MetaLong implements MetaParam<Long> { protected final long value; public MetaLong(long value) { this.value = value; } public Long get() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetaLong longMeta = (MetaLong) o; return value == longMeta.value; } @Override public int hashCode() { return (int) (value ^ (value >>> 32)); } } @Experimental abstract class MetaBoolean implements MetaParam<Boolean> { protected final boolean value; public MetaBoolean(boolean value) { this.value = value; } public Boolean get() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetaBoolean metaBoolean = (MetaBoolean) o; return value == metaBoolean.value; } @Override public int hashCode() { return value ? 1 : 0; } } /** * Non-writable parameter telling if the entry was loaded from a persistence tier * ({@link org.infinispan.persistence.spi.CacheLoader}) or not. * This information may be available only to write commands due to implementation reasons. */ @Experimental final class MetaLoadedFromPersistence extends MetaBoolean { public static final MetaLoadedFromPersistence LOADED = new MetaLoadedFromPersistence(true); public static final MetaLoadedFromPersistence NOT_LOADED = new MetaLoadedFromPersistence(false); private MetaLoadedFromPersistence(boolean loaded) { super(loaded); } public static MetaLoadedFromPersistence of(boolean loaded) { return loaded ? LOADED : NOT_LOADED; } } /** * A parameter to tell if the creation timestamp should be updated for modified entries. * <p> * Created entries will always update its creation timestamp. */ @Experimental final class MetaUpdateCreationTime extends MetaBoolean implements Writable<Boolean> { private static final MetaUpdateCreationTime UPDATE = new MetaUpdateCreationTime(true); private static final MetaUpdateCreationTime NOT_UPDATE = new MetaUpdateCreationTime(false); public MetaUpdateCreationTime(boolean value) { super(value); } public static MetaUpdateCreationTime of(boolean update) { return update ? UPDATE : NOT_UPDATE; } } }
9,783
28.46988
102
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/FunctionalMap.java
package org.infinispan.functional; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.commons.util.Experimental; import org.infinispan.functional.EntryView.ReadEntryView; import org.infinispan.functional.EntryView.ReadWriteEntryView; import org.infinispan.functional.EntryView.WriteEntryView; import org.infinispan.functional.Listeners.ReadWriteListeners; import org.infinispan.functional.Listeners.WriteListeners; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.marshall.core.MarshallableFunctions; import org.infinispan.util.function.SerializableBiConsumer; import org.infinispan.util.function.SerializableBiFunction; import org.infinispan.util.function.SerializableConsumer; import org.infinispan.util.function.SerializableFunction; /** * Top level functional map interface offering common functionality for the * read-only, read-write, and write-only operations that can be run against a * functional map asynchronously. * * <p>Lambdas passed in as parameters to functional map methods define the * type of operation that is executed, but since lambdas are transparent to * the internal logic, it was decided to separate the API into three types * of operation: read-only, write-only, and read-write. This separation helps * the user understand the group of functions and their possibilities. * * <p>This conscious decision to separate read-only, write-only and * read-write interfaces helps type safety. So, if a user gets a read-only * map, it can't write to it by mistake since no such APIs are exposed. * The same happens with write-only maps, the user can only write and cannot * make the mistake of reading from the entry view because read operations * are not exposed. * * <p>Lambdas passed in to read-write and write-only operations, when * running in a cluster, must be marshallable. One option to do so is to * mark them as being {@link java.io.Serializable} but this is expensive * in terms of payload size. Alternatively, you can provide an Infinispan * {@link org.infinispan.commons.marshall.Externalizer} for it which * drastically reduces the payload size. Marshallable lambdas for some of * the most popular lambda functions used by {@link ConcurrentMap} are * available via the {@link MarshallableFunctions} helper class. * * <p>Being an asynchronous API, all methods that return a single result, * return a {@link CompletableFuture} which wraps the result. To avoid * blocking, it offers the possibility to receive callbacks when the * {@link CompletableFuture} has completed, or it can be chained or composes * with other {@link CompletableFuture} instances. * * <p>For those operations that return multiple results, the API returns * instances of a {@link Traversable} interface which offers a lazy pull­style * API for working with multiple results. Although push­style interfaces for * handling multiple results, such as RxJava, are fully asynchronous, they're * harder to use from a user’s perspective. {@link Traversable},​ being a lazy * pull­style API, can still be asynchronous underneath since the user can * decide to work on the {@link Traversable} at a later stage, and the * implementation itself can decide when to compute those results. * * @since 8.0 */ @Experimental public interface FunctionalMap<K, V> extends AutoCloseable { /** * Tweak functional map executions providing {@link Param} instances. */ FunctionalMap<K, V> withParams(Param<?>... ps); /** * Functional map's name. */ String getName(); /** * Functional map's status. */ ComponentStatus getStatus(); /** * Tells if the underlying cache is using encoding or not * * @return true if the underlying cache is encoded */ default boolean isEncoded() { return false; } Cache<K, V> cache(); /** * Exposes read-only operations that can be executed against the functional map. * The information that can be read per entry in the functional map is * exposed by {@link ReadEntryView}. * * <p>Read-only operations have the advantage that no locks are acquired * for the duration of the operation and so it makes sense to have them * a top-level interface dedicated to them. * * <p>Browsing methods that provide a read-only view of the cached data * are available via {@link #keys()} and {@link #entries()}. * Having {@link #keys()} makes sense since that way keys can be traversed * without having to bring values. Having {@link #entries()} makes sense * since it allows traversing both keys, values and any meta parameters * associated with them, but this is no extra cost to exposing just values * since keys are the main index and hence will always be available. * Hence, adding a method to only browse values offers nothing extra to * the API. * * @since 8.0 */ @Experimental interface ReadOnlyMap<K, V> extends FunctionalMap<K, V> { /** * Tweak read-only functional map executions providing {@link Param} instances. */ ReadOnlyMap<K, V> withParams(Param<?>... ps); /** * Evaluate a read-only function on the value associated with the key * and return a {@link CompletableFuture} with the return type of the function. * If the user is not sure if the key is present, {@link ReadEntryView#find()} * can be used to find out for sure. Typically, function implementations * would return value or {@link MetaParam} information from the cache * entry in the functional map. * * <p>By returning {@link CompletableFuture} instead of the function's * return type directly, the method hints at the possibility that to * execute the function might require to go remote to retrieve data in * persistent store or another clustered node. * * <p>This method can be used to implement read-only single-key based * operations in {@link ConcurrentMap} such as: * * <ul> * <li>{@link ConcurrentMap#get(Object)}</li> * <li>{@link ConcurrentMap#containsKey(Object)}</li> * </ul> * * <p>The function must not mutate neither the key returned through * {@link ReadEntryView#key()} nor the internally stored value provided * through {@link ReadEntryView#get()} or {@link ReadEntryView#find()}. * * @param key the key associated with the {@link ReadEntryView} to be * passed to the function. * @param f function that takes a {@link ReadEntryView} associated with * the key, and returns a value. * @param <R> function return type * @return a {@link CompletableFuture} which will be completed with the * returned value from the function */ <R> CompletableFuture<R> eval(K key, Function<ReadEntryView<K, V>, R> f); /** * Same as {@link #eval(Object, Function)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <R> CompletableFuture<R> eval(K key, SerializableFunction<ReadEntryView<K, V>, R> f) { return eval(key, (Function<ReadEntryView<K, V>, R>) f); } /** * Evaluate a read-only function on a key and potential value associated in * the functional map, for each of the keys in the set passed in, and * returns an {@link Traversable} to work on each computed function's result. * * <p>The function passed in will be executed for as many keys * present in keys collection set. Similar to {@link #eval(Object, Function)}, * if the user is not sure whether a particular key is present, * {@link ReadEntryView#find()} can be used to find out for sure. * * DESIGN RATIONALE: * <ul> * <li>It makes sense to expose global operation like this instead of * forcing users to iterate over the keys to lookup and call get * individually since Infinispan can do things more efficiently. * </li> * </ul> * * <p>The function must not mutate neither the key returned through * {@link ReadEntryView#key()} nor the internally stored value provided * through {@link ReadEntryView#get()} or {@link ReadEntryView#find()}. * * @param keys the keys associated with each of the {@link ReadEntryView} * passed in the function callbacks * @param f function that takes a {@link ReadEntryView} associated with * the key, and returns a value. It'll be invoked once for each key * passed in * @param <R> function return type * @return a sequential {@link Traversable} that can be navigated to * retrieve each function return value */ <R> Traversable<R> evalMany(Set<? extends K> keys, Function<ReadEntryView<K, V>, R> f); /** * Same as {@link #evalMany(Set, Function)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <R> Traversable<R> evalMany(Set<? extends K> keys, SerializableFunction<ReadEntryView<K, V>, R> f) { return evalMany(keys, (Function<ReadEntryView<K, V>, R>) f); } /** * Provides a {@link Traversable} that allows clients to navigate all cached keys. * * <p>This method can be used to implement operations such as: * <ul> * <li>{@link ConcurrentMap#size()}</li> * <li>{@link ConcurrentMap#keySet()}</li> * <li>{@link ConcurrentMap#isEmpty()}</li> * </ul> * * @return a sequential {@link Traversable} to navigate each cached key */ Traversable<K> keys(); /** * Provides a {@link Traversable} that allows clients to navigate all cached entries. * * <p>This method can be used to implement operations such as: * <ul> * <li>{@link ConcurrentMap#containsValue(Object)}</li> * <li>{@link ConcurrentMap#values()}</li> * <li>{@link ConcurrentMap#entrySet()}</li> * </ul> * * @return a sequential {@link Traversable} to navigate each cached entry */ Traversable<ReadEntryView<K, V>> entries(); } /** * Exposes write-only operations that can be executed against the functional map. * The write operations that can be applied per entry are exposed by * {@link WriteEntryView}. * * <p>Write-only operations require locks to be acquired but crucially * they do not require reading previous value or metadata parameter * information associated with the cached entry, which sometimes can be * expensive since they involve talking to a remote node in the cluster * or the persistence layer So, exposing write-only operations makes it * easy to take advantage of this important optimisation. * * <p>Method parameters for write-only operations, including lambdas, * must be marshallable when running in a cluster. * * @since 8.0 */ @Experimental interface WriteOnlyMap<K, V> extends FunctionalMap<K, V> { /** * Tweak write-only functional map executions providing {@link Param} instances. */ WriteOnlyMap<K, V> withParams(Param<?>... ps); /** * Evaluate a write-only {@link BiConsumer} operation, with an argument * passed in and a {@link WriteEntryView} of the value associated with * the key, and return a {@link CompletableFuture} which will be * completed when the operation completes. * * <p>Since this is a write-only operation, no entry attributes can be * queried, hence the only reasonable thing can be returned is Void. * * <p>This method can be used to implement single-key write-only operations * which do not need to query the previous value. * * <p>This operation is very similar to {@link #eval(Object, Consumer)} * and in fact, the functionality provided by this function could indeed * be implemented with {@link #eval(Object, Consumer)}, but there's a * crucial difference. If you want to store a value and reference the * value to be stored from the passed in operation, * {@link #eval(Object, Consumer)} needs to capture that value. * Capturing means that each time the operation is called, a new lambda * needs to be instantiated. By offering a {@link BiConsumer} that * takes user provided value as first parameter, the operation does not * capture any external objects when implementing simple operations, * and hence, the {@link BiConsumer} could be cached and reused each * time it's invoked. * * <p>Note that when {@link org.infinispan.commons.dataconversion.Encoder encoders} * are in place despite the argument type and value type don't have to match * the argument will use value encoding. * * @param key the key associated with the {@link WriteEntryView} to be * passed to the operation * @param argument argument passed in as first parameter to the * {@link BiConsumer} operation. * @param f operation that takes a user defined value, and a * {@link WriteEntryView} associated with the key, and writes * to the {@link WriteEntryView} passed in without returning anything * @return a {@link CompletableFuture} which will be completed when the * operation completes */ <T> CompletableFuture<Void> eval(K key, T argument, BiConsumer<T, WriteEntryView<K, V>> f); /** * Same as {@link #eval(Object, Object, BiConsumer)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <T> CompletableFuture<Void> eval(K key, T argument, SerializableBiConsumer<T, WriteEntryView<K, V>> f) { return eval(key, argument, (BiConsumer<T, WriteEntryView<K, V>>) f); } /** * Evaluate a write-only {@link Consumer} operation with a * {@link WriteEntryView} of the value associated with the key, * and return a {@link CompletableFuture} which will be * completed with the object returned by the operation. * * <p>Since this is a write-only operation, no entry attributes can be * queried, hence the only reasonable thing can be returned is Void. * * <p>This operation can be used to either remove a cached entry, * or to write a constant value along with optional metadata parameters. * * @param key the key associated with the {@link WriteEntryView} to be * passed to the operation * @param f operation that takes a {@link WriteEntryView} associated with * the key and writes to the it without returning anything * @return a {@link CompletableFuture} which will be completed when the * operation completes */ CompletableFuture<Void> eval(K key, Consumer<WriteEntryView<K, V>> f); /** * Same as {@link #eval(Object, Consumer)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default CompletableFuture<Void> eval(K key, SerializableConsumer<WriteEntryView<K, V>> f) { return eval(key, (Consumer<WriteEntryView<K, V>>) f); } /** * Evaluate a write-only {@link BiConsumer} operation, with an argument * passed in and a {@link WriteEntryView} of the value associated with * the key, for each of the keys in the set passed in, and returns a * {@link CompletableFuture} that will be completed when the write-only * operation has been executed against all the entries. * * <p>These kind of operations are preferred to traditional end user * iterations because the internal logic can often iterate more * efficiently since it knows more about the system. * * <p>Since this is a write-only operation, no entry attributes can be * queried, hence the only reasonable thing can be returned is Void. * * <p>Note that when {@link org.infinispan.commons.dataconversion.Encoder encoders} * are in place despite the argument type and value type don't have to match * the argument will use value encoding. * * @param arguments the key/value pairs associated with each of the * {@link WriteEntryView} passed in the function callbacks * @param f operation that consumes a value associated with a key in the * entries collection and the {@link WriteEntryView} associated * with that key in the cache * @return a {@link CompletableFuture} which will be completed when * the {@link BiConsumer} operation has been executed against * all entries */ <T> CompletableFuture<Void> evalMany(Map<? extends K, ? extends T> arguments, BiConsumer<T, WriteEntryView<K, V>> f); /** * Same as {@link #evalMany(Map, BiConsumer)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <T> CompletableFuture<Void> evalMany(Map<? extends K, ? extends T> arguments, SerializableBiConsumer<T, WriteEntryView<K, V>> f) { return evalMany(arguments, (BiConsumer<T, WriteEntryView<K, V>>) f); } /** * Evaluate a write-only {@link Consumer} operation with the * {@link WriteEntryView} of the value associated with the key, for each * of the keys in the set passed in, and returns a * {@link CompletableFuture} that will be completed when the write-only * operation has been executed against all the entries. * * <p>These kind of operations are preferred to traditional end user * iterations because the internal logic can often iterate more * efficiently since it knows more about the system. * * <p>Since this is a write-only operation, no entry attributes can be * queried, hence the only reasonable thing can be returned is Void. * * @param keys the keys associated with each of the {@link WriteEntryView} * passed in the function callbacks * @param f operation that the {@link WriteEntryView} associated with * one of the keys passed in * @return a {@link CompletableFuture} which will be completed when * the {@link Consumer} operation has been executed against all * entries */ CompletableFuture<Void> evalMany(Set<? extends K> keys, Consumer<WriteEntryView<K, V>> f); /** * Same as {@link #evalMany(Set, Consumer)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default CompletableFuture<Void> evalMany(Set<? extends K> keys, SerializableConsumer<WriteEntryView<K, V>> f) { return evalMany(keys, (Consumer<WriteEntryView<K, V>>) f); } /** * Evaluate a write-only {@link Consumer} operation with the * {@link WriteEntryView} of the value associated with the key, for all * existing keys in functional map, and returns a {@link CompletableFuture} * that will be completed when the write-only operation has been executed * against all the entries. * * @param f operation that the {@link WriteEntryView} associated with * one of the keys passed in * @return a {@link CompletableFuture} which will be completed when * the {@link Consumer} operation has been executed against all * entries */ CompletableFuture<Void> evalAll(Consumer<WriteEntryView<K, V>> f); /** * Same as {@link #evalAll(Consumer)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default CompletableFuture<Void> evalAll(SerializableConsumer<WriteEntryView<K, V>> f) { return evalAll((Consumer<WriteEntryView<K, V>>) f); } /** * Truncate the contents of the cache, returning a {@link CompletableFuture} * that will be completed when the truncate process completes. * * This method can be used to implement: * * <ul> * <li>{@link ConcurrentMap#clear()}</li> * </ul> * * @return a {@link CompletableFuture} that completes when the truncat * has finished */ CompletableFuture<Void> truncate(); /** * Allows to write-only listeners to be registered. */ WriteListeners<K, V> listeners(); } /** * Exposes read-write operations that can be executed against the functional map. * The read-write operations that can be applied per entry are exposed by * {@link ReadWriteEntryView}. * * <p>Read-write operations offer the possibility of writing values or * metadata parameters, and returning previously stored information. * Read-write operations are also crucial for implementing conditional, * compare-and-swap (CAS) like operations. * * <p>Locks are acquired before executing the read-write lambda. * * <p>Method parameters for read-write operations, including lambdas, * must be marshallable when running in a cluster. * * @since 8.0 */ @Experimental interface ReadWriteMap<K, V> extends FunctionalMap<K, V> { /** * Tweak read-write functional map executions providing {@link Param} instances. */ ReadWriteMap<K, V> withParams(Param<?>... ps); /** * Evaluate a read-write function on the value and metadata associated * with the key and return a {@link CompletableFuture} with the return * type of the function. If the user is not sure if the key is present, * {@link ReadWriteEntryView#find()} can be used to find out for sure. * * This method can be used to implement single-key read-write operations * in {@link ConcurrentMap} that do not depend on value information given * by the user such as: * * <ul> * <li>{@link ConcurrentMap#remove(Object)}</li> * </ul> * * <p>The function must not mutate neither the key returned through * {@link ReadEntryView#key()} nor the internally stored value provided * through {@link ReadEntryView#get()} or {@link ReadEntryView#find()}. * * @param key the key associated with the {@link ReadWriteEntryView} to be * passed to the function. * @param f function that takes a {@link ReadWriteEntryView} associated with * the key, and returns a value. * @param <R> function return type * @return a {@link CompletableFuture} which will be completed with the * returned value from the function */ <R> CompletableFuture<R> eval(K key, Function<ReadWriteEntryView<K, V>, R> f); /** * Same as {@link #eval(Object, Function)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <R> CompletableFuture<R> eval(K key, SerializableFunction<ReadWriteEntryView<K, V>, R> f) { return eval(key, (Function<ReadWriteEntryView<K, V>, R>) f); } /** * Evaluate a read-write function, with an argument passed in and a * {@link WriteEntryView} of the value associated with the key, and * return a {@link CompletableFuture} which will be completed with the * returned value by the function. * * <p>This method provides the the capability to both update the value and * metadata associated with that key, and return previous value or metadata. * * <p>This method can be used to implement the vast majority of single-key * read-write operations in {@link ConcurrentMap} such as: * * <ul> * <li>{@link ConcurrentMap#put(Object, Object)}</li> * <li>{@link ConcurrentMap#putIfAbsent(Object, Object)}</li> * <li>{@link ConcurrentMap#replace(Object, Object)}</li> * <li>{@link ConcurrentMap#replace(Object, Object, Object)}</li> * <li>{@link ConcurrentMap#remove(Object, Object)}</li> * </ul> * * <p> The functionality provided by this function could indeed be * implemented with {@link #eval(Object, Function)}, but there's a * crucial difference. If you want to store a value and reference the * value to be stored from the passed in operation, * {@link #eval(Object, Function)} needs to capture that value. * Capturing means that each time the operation is called, a new lambda * needs to be instantiated. By offering a {@link BiFunction} that * takes user provided value as first parameter, the operation does * not capture any external objects when implementing * simple operations, and hence, the {@link BiFunction} could be cached * and reused each time it's invoked. * * <p>Note that when {@link org.infinispan.commons.dataconversion.Encoder encoders} * are in place despite the argument type and value type don't have to match * the argument will use value encoding. * * <p>The function must not mutate neither the key returned through * {@link ReadEntryView#key()} nor the internally stored value provided * through {@link ReadEntryView#get()} or {@link ReadEntryView#find()}. * * @param key the key associated with the {@link ReadWriteEntryView} to be * passed to the operation * @param argument argument passed in as first parameter to the {@link BiFunction}. * @param f operation that takes a user defined value, and a * {@link ReadWriteEntryView} associated with the key, and writes * to the {@link ReadWriteEntryView} passed in, possibly * returning previously stored value or metadata information * @param <R> type of the function's return * @return a {@link CompletableFuture} which will be completed with the * returned value from the function */ <T, R> CompletableFuture<R> eval(K key, T argument, BiFunction<T, ReadWriteEntryView<K, V>, R> f); /** * Same as {@link #eval(Object, Object, BiFunction)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <T, R> CompletableFuture<R> eval(K key, T argument, SerializableBiFunction<T, ReadWriteEntryView<K, V>, R> f) { return eval(key, argument, (BiFunction<T, ReadWriteEntryView<K, V>, R>) f); } /** * Evaluate a read-write {@link BiFunction}, with an argument passed in and * a {@link ReadWriteEntryView} of the value associated with * the key, for each of the keys in the set passed in, and * returns an {@link Traversable} to navigate each of the * {@link BiFunction} invocation returns. * * <p>This method can be used to implement operations that store a set of * keys and return previous values or metadata parameters. * * <p>These kind of operations are preferred to traditional end user * iterations because the internal logic can often iterate more * efficiently since it knows more about the system. * * <p>Note that when {@link org.infinispan.commons.dataconversion.Encoder encoders} * are in place despite the argument type and value type don't have to match * the argument will use value encoding. * * <p>The function must not mutate neither the key returned through * {@link ReadEntryView#key()} nor the internally stored value provided * through {@link ReadEntryView#get()} or {@link ReadEntryView#find()}. * * @param arguments the key/value pairs associated with each of the * {@link ReadWriteEntryView} passed in the function callbacks * @param f function that takes in a value associated with a key in the * entries collection and the {@link ReadWriteEntryView} associated * with that key in the cache * @return a {@link Traversable} to navigate each {@link BiFunction} return */ <T, R> Traversable<R> evalMany(Map<? extends K, ? extends T> arguments, BiFunction<T, ReadWriteEntryView<K, V>, R> f); /** * Same as {@link #evalMany(Map, BiFunction)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <T, R> Traversable<R> evalMany(Map<? extends K, ? extends T> arguments, SerializableBiFunction<T, ReadWriteEntryView<K, V>, R> f) { return evalMany(arguments, (BiFunction<T, ReadWriteEntryView<K, V>, R>) f); } /** * Evaluate a read-write {@link Function} operation with the * {@link ReadWriteEntryView} of the value associated with the key, for each * of the keys in the set passed in, and returns a {@link Traversable} * to navigate each of the {@link Function} invocation returns. * * <p>This method can be used to a remove a set of keys returning * previous values or metadata parameters. * * <p>The function must not mutate neither the key returned through * {@link ReadEntryView#key()} nor the internally stored value provided * through {@link ReadEntryView#get()} or {@link ReadEntryView#find()}. * * @param keys the keys associated with each of the {@link ReadWriteEntryView} * passed in the function callbacks * @param f function that the {@link ReadWriteEntryView} associated with * one of the keys passed in, and returns a value * @return a {@link Traversable} to navigate each {@link Function} return */ <R> Traversable<R> evalMany(Set<? extends K> keys, Function<ReadWriteEntryView<K, V>, R> f); /** * Same as {@link #evalMany(Set, Function)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <R> Traversable<R> evalMany(Set<? extends K> keys, SerializableFunction<ReadWriteEntryView<K, V>, R> f) { return evalMany(keys, (Function<ReadWriteEntryView<K, V>, R>) f); } /** * Evaluate a read-write {@link Function} operation with the * {@link ReadWriteEntryView} of the value associated with the key, for all * existing keys, and returns a {@link Traversable} to navigate each of * the {@link Function} invocation returns. * * <p>This method can be used to an operation that removes all cached * entries individually, and returns previous value and/or metadata * parameters. * * <p>The function must not mutate neither the key returned through * {@link ReadEntryView#key()} nor the internally stored value provided * through {@link ReadEntryView#get()} or {@link ReadEntryView#find()}. * * @return a {@link Traversable} to navigate each {@link Function} return */ <R> Traversable<R> evalAll(Function<ReadWriteEntryView<K, V>, R> f); /** * Same as {@link #evalAll(Function)} except that the function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> */ default <R> Traversable<R> evalAll(SerializableFunction<ReadWriteEntryView<K, V>, R> f) { return evalAll((Function<ReadWriteEntryView<K, V>, R>) f); } /** * Allows to read-write listeners to be registered. */ ReadWriteListeners<K, V> listeners(); } }
33,597
46.860399
145
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/Traversable.java
package org.infinispan.functional; import java.util.Comparator; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; import org.infinispan.commons.util.Experimental; /** * Unsorted traversable stream for sequential and aggregating operations. * * <p>Traversable contains two type of operations: * <ol> * <li>Intermediate operations which transform a traversable, into another, * e.g. {@link #filter(Predicate)}. * </li> * <li>Terminal operations which produce a side effect, e.g. {@link #forEach(Consumer)}. * Once a terminal operation is completed, the resources taken by the * traversable are released. * </li> * </ol> * * <p>Traversable cannot be reused and hence is designed to be used only once * via its intermediate and terminal operations. * * <p>In distributed environments, unless individually specified, all lambdas * passed to methods are executed where data is located. For example, if * executing {@link #forEach(Consumer)}, the {@link Consumer} function is * executed wherever a particular key resides. To execute a for-each operation * where the side effects are executed locally, all the {@link Traversable}'s * data needs to be collected and iterated over manually. * * @param <T> * @since 8.0 */ @Experimental public interface Traversable<T> { /** * An intermediate operation that returns a traversable containing elements * matching the given predicate. */ Traversable<T> filter(Predicate<? super T> p); /** * An intermediate operation that returns a traversable containing the * results of applying the given function over the elements of the * traversable. */ <R> Traversable<R> map(Function<? super T, ? extends R> f); /** * An intermediate operation that returns a traversable containing the * results of replacing each element of this traversable with the contents * of a traversable produced by applying the provided function to each element. * * <p>From a functional map perspective, this operation is particularly handy * when the values are collections. */ <R> Traversable<R> flatMap(Function<? super T, ? extends Traversable<? extends R>> f); /** * A terminal operation that applies an operation to all elements of this * traversable. */ void forEach(Consumer<? super T> c); /** * A terminal operation that applies a binary folding operation to a start * value and all elements of this traversable. */ T reduce(T z, BinaryOperator<T> folder); /** * A terminal operation that applies a binary folding operation to all * elements of this traversable, and wraps the result in an optional. * If the traversable is empty, it returns an empty optional. */ Optional<T> reduce(BinaryOperator<T> folder); /** * A terminal operation that applies a binary folding operation to a start * value and the result of each element having a mapping function applied. * * <p>This is a combined map/reduce which could potentially be done more * efficiently than if a map is executed and then reduce. */ <U> U reduce(U z, BiFunction<U, ? super T, U> mapper, BinaryOperator<U> folder); /** * A terminal operation that transforms the traversable into a result * container, first constructed with the given supplier, and then * accumulating elements over it with the given consumer. * * <p>The combiner can be used to combine accumulated results executed in * parallel or coming from different nodes in a distributed environment. * * <p>In distributed environments where some keys are remote, the * {@link Supplier} and {@link BiConsumer} instances passed in are sent to * other nodes and hence they need to be marshallable. If the collect * operation can be defined using the helper methods in * {@link java.util.stream.Collectors}, it is recommended that those are * used, which can easily be made marshalled using the * {@code org.infinispan.stream.CacheCollectors#serializableCollector} method. */ <R> R collect(Supplier<R> s, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner); /** * A terminal operation that transforms the traversable into a result * container using a {@code Collector}. * * <p>In distributed environments where some keys are remote, the * {@link Collector} instance passed in is sent other nodes and hence it * needs to be marshallable. This can easily be made achieved using the * {@code org.infinispan.stream.CacheCollectors#serializableCollector} method. */ <R, A> R collect(Collector<? super T, A, R> collector); /** * A terminal operation that returns an optional containing the minimum * element of this traversable based on the comparator passed in. * If the traversable is empty, it returns an empty optional. */ default Optional<T> min(Comparator<? super T> comparator) { return reduce(BinaryOperator.minBy(comparator)); } /** * A terminal operation that returns an optional containing the maximum * element of this traversable based on the comparator passed in. * If the traversable is empty, it returns an empty optional. */ default Optional<T> max(Comparator<? super T> comparator) { return reduce(BinaryOperator.maxBy(comparator)); } /** * A terminal operation that returns the number of elements in the traversable. */ long count(); /** * A terminal operation that returns whether any elements of this * traversable match the provided predicate. * * <p>An important reason to keep this method is the fact as opposed * to a reduction which must evaluate all elements in the traversable, this * method could stop as soon as it has found an element that matches. */ boolean anyMatch(Predicate<? super T> p); /** * A terminal operation that returns whether all elements of this * traversable match the provided predicate. * * <p>An important reason to keep this method is the fact as opposed * to a reduction which must evaluate all elements in the traversable, this * method could stop as soon as it has found an element that does not match * the predicate. */ boolean allMatch(Predicate<? super T> p); /** * A terminal operation that returns whether no elements of this * traversable match the provided predicate. * * <p>An important reason to keep this method is the fact as opposed * to a reduction which must evaluate all elements in the traversable, this * method could stop as soon as it has found an element that does matches * the predicate. */ boolean noneMatch(Predicate<? super T> predicate); /** * A terminal operation that returns an optional containing an element of * the traversable, or an empty optional if empty. */ Optional<T> findAny(); }
7,223
37.425532
97
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/Param.java
package org.infinispan.functional; import org.infinispan.commons.util.Experimental; import org.infinispan.functional.impl.Params; /** * An easily extensible parameter that allows functional map operations to be * tweaked. Examples would include local-only parameter, skip-cache-store parameter and others. * * <p>What makes {@link Param} different from {@link MetaParam} is that {@link Param} * values are never stored in the functional map. They merely act as ways to * tweak how operations are executed. * * <p>Since {@link Param} instances control how the internals work, only * {@link Param} implementations by Infinispan will be supported. * * <p>This interface is equivalent to Infinispan's Flag, but it's more * powerful because it allows to pass a flag along with a value. Infinispan's * Flag are enum based which means no values can be passed along with value. * * <p>Since each param is an independent entity, it's easy to create * public versus private parameter distinction. When parameters are stored in * enums, it's more difficult to make such distinction. * * @param <P> type of parameter * @since 8.0 */ @Experimental public interface Param<P> { /** * A parameter's identifier. Each parameter must have a different id. * * <p>A numeric id makes it flexible enough to be stored in collections that * take up low resources, such as arrays. */ int id(); /** * Parameter's value. */ P get(); /** * When a persistence store is attached to a cache, by default all write * operations, regardless of whether they are inserts, updates or removes, * are persisted to the store. Using {@link #SKIP}, the write operations * can skip the persistence store modification, applying the effects of * the write operation only in the in-memory contents of the caches in * the cluster. * * @apiNote Previously this flag had only two options; PERSIST and SKIP * since it was assumed that an implementation can use write-only command * when it is not interested in the previous value. However sometimes * we are interested in the memory-only data but cannot afford to load it * from persistence. * * @since 8.0 */ @Experimental enum PersistenceMode implements Param<PersistenceMode> { LOAD_PERSIST, SKIP_PERSIST, SKIP_LOAD, SKIP; public static final int ID = ParamIds.PERSISTENCE_MODE_ID; private static final PersistenceMode[] CACHED_VALUES = values(); @Override public int id() { return ID; } @Override public PersistenceMode get() { return this; } /** * Provides default persistence mode. */ public static PersistenceMode defaultValue() { return LOAD_PERSIST; } public static PersistenceMode valueOf(int ordinal) { return CACHED_VALUES[ordinal]; } } /** * Normally the cache has to acquire locks during any write operation to guarantee * its correctness. If the application is sure that no concurrent operation occurs, * it is possible to increase performance by setting this param to {@link #SKIP}. * The result of any operation without locking is undefined under presence of concurrent * writes. */ @Experimental enum LockingMode implements Param<LockingMode> { LOCK, SKIP, /** * The operation fails when it is not possible to acquire the lock without waiting. */ TRY_LOCK; public static final int ID = ParamIds.LOCKING_MODE_ID; private static final LockingMode[] CACHED_VALUES = values(); @Override public int id() { return ID; } @Override public LockingMode get() { return this; } public static LockingMode defaultValue() { return LOCK; } public static LockingMode valueOf(int ordinal) { return CACHED_VALUES[ordinal]; } } /** * Defines where is the command executed. */ @Experimental enum ExecutionMode implements Param<ExecutionMode> { /** * Command is executed on its owners, in transactional mode in the context, too, but there it is not persisted. * The result of the command is backed up to all sites configured for backup. * Note: under some circumstances it may be necessary to transfer full value instead of executing the command * on some owners; the application must not rely on any side effects of command execution. */ ALL, /** * Command is executed only locally, it is not sent to remote nodes. If the command is a write and this node * is not an owner of given entry, the entry is not stored in the cache; if the node is an owner the entry is * stored (even without contacting the primary owner, if this is a backup). If the command reads a value and * the entry is not available locally, null entry is provided instead. */ LOCAL, /** * Command is executed only in the current site (same as {@link #ALL}, but it is not sent for backup * to other sites) */ LOCAL_SITE; // Other options: context-only write, write without remote read (SKIP_REMOTE_LOOKUP)... public static final int ID = ParamIds.EXECUTION_MODE_ID; private static final ExecutionMode[] CACHED_VALUES = values(); @Override public int id() { return ID; } @Override public ExecutionMode get() { return this; } public static ExecutionMode defaultValue() { return ALL; } public static ExecutionMode valueOf(int ordinal) { return CACHED_VALUES[ordinal]; } } /** * Defines how statistics are gathered for this command. */ @Experimental enum StatisticsMode implements Param<StatisticsMode> { /** * Statistics from this command are recorded */ GATHER, /** * Statistics from this command are not recorded */ SKIP; public static final int ID = ParamIds.STATS_MODE_ID; private static final StatisticsMode[] CACHED_VALUES = values(); @Override public int id() { return ID; } @Override public StatisticsMode get() { return this; } public static StatisticsMode defaultValue() { return GATHER; } public static StatisticsMode valueOf(int ordinal) { return CACHED_VALUES[ordinal]; } public static boolean isSkip(Params params) { return params.<StatisticsMode>get(ID).get() == SKIP; } } @Experimental enum ReplicationMode implements Param<ReplicationMode> { /** * Command is completed when all owners are updated. */ SYNC, /** * Invoking node does not know when the owners are updated nor if the command fails. */ ASYNC; public static final int ID = ParamIds.REPLICATION_MODE_ID; public static final ReplicationMode[] CACHED_VALUES = values(); @Override public int id() { return ID; } @Override public ReplicationMode get() { return this; } public static ReplicationMode defaultValue() { return SYNC; } public static ReplicationMode valueOf(int ordinal) { return CACHED_VALUES[ordinal]; } } }
7,473
28.776892
117
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/Listeners.java
package org.infinispan.functional; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.infinispan.functional.EntryView.ReadEntryView; import org.infinispan.commons.util.Experimental; /** * Holder class for functional listener definitions. * * @since 8.0 */ @Experimental public final class Listeners { private Listeners() { // Cannot be instantiated, it's just a holder class } /** * Read-write listeners enable users to register listeners for cache * entry created, modified and removed events, and also register listeners * for any cache entry write events. * * <p>Entry created, modified and removed events can only be fired when these * originate on a read-write functional map, since this is the only one * that guarantees that the previous value has been read, and hence the * differentiation between create, modified and removed can be fully * guaranteed. * * @since 8.0 */ @Experimental public interface ReadWriteListeners<K, V> extends WriteListeners<K, V> { /** * Add a create event specific listener by passing in a * {@link Consumer} to be called back each time a new cache entry is * created, passing in a {@link ReadEntryView} of that new entry. * * <p>This method is shortcut for users who are only interested in * create events. If interested in multiple event types, calling * {@link #add(ReadWriteListener)} is recommended instead. * * @param f operation to be called each time a new cache entry is created * @return an {@link AutoCloseable} instance that can be used to * unregister the listener */ AutoCloseable onCreate(Consumer<ReadEntryView<K, V>> f); /** * Add a modify/update event specific listener by passing in a * {@link BiConsumer} to be called back each time an entry is * modified or updated, passing in a {@link ReadEntryView} of the * previous entry as first parameter, and a {@link ReadEntryView} of the * new value as second parameter. * * <p>This method is shortcut for users who are only interested in * update events. If interested in multiple event types, calling * {@link #add(ReadWriteListener)} is recommended instead. * * @param f operation to be called each time a new cache entry is modified or updated, * with the first parameter the {@link ReadEntryView} of the previous * entry value, and the second parameter the new {@link ReadEntryView} * @return an {@link AutoCloseable} instance that can be used to * unregister the listener */ AutoCloseable onModify(BiConsumer<ReadEntryView<K, V>, ReadEntryView<K, V>> f); /** * Add a remove event specific listener by passing in a * {@link Consumer} to be called back each time an entry is * removed, passing in the {@link ReadEntryView} of the removed entry. * * <p>This method is shortcut for users who are only interested in * remove events. If interested in multiple event types, calling * {@link #add(ReadWriteListener)} is recommended instead. * * @param f operation to be called each time a new cache entry is removed, * with the old cached entry's {@link ReadEntryView} as parameter. * @return an {@link AutoCloseable} instance that can be used to * unregister the listener */ AutoCloseable onRemove(Consumer<ReadEntryView<K, V>> f); /** * Add a read-write listener, and return an {@link AutoCloseable} * instance that can be used to remove the listener registration. * * @param l the read-write functional map event listener * @return an {@link AutoCloseable} instance that can be used to * unregister the listener */ AutoCloseable add(ReadWriteListener<K, V> l); /** * Read-write listener */ interface ReadWriteListener<K, V> { /** * Entry created event callback that receives a {@link ReadEntryView} * of the created entry. * * @param created created entry view */ default void onCreate(ReadEntryView<K, V> created) {} /** * Entry modify/update event callback that receives {@link ReadEntryView} * of the previous entry as first parameter, and the {@link ReadEntryView} * of the new entry. * * @param before previous entry view * @param after new entry view */ default void onModify(ReadEntryView<K, V> before, ReadEntryView<K, V> after) {} /** * Entry removed event callback that receives a {@link ReadEntryView} * of the removed entry. * * @param removed removed entry view */ default void onRemove(ReadEntryView<K, V> removed) {} } } /** * Write listeners enable user to register listeners for any cache entry * write events that happen in either a read-write or write-only * functional map. * * <p>Listeners for write events cannot distinguish between cache entry * created and cache entry modify/update events because they don't have * access to the previous value. All they know is that a new non-null * entry has been written. * * <p>However, write event listeners can distinguish between entry removals * and cache entry create/modify-update events because they can query * what the new entry's value via {@link ReadEntryView#find()}. * * @since 8.0 */ @Experimental public interface WriteListeners<K, V> { /** * Add a write event listener by passing in a {@link Consumer} to be * called each time a cache entry is created, modified/updated or * removed. * * <p>For created or modified/updated events, the * {@link ReadEntryView} passed in will represent the newly stored * entry, hence implementations will not be available to differentiate * between created events vs modified/updated events. * * <p>For removed events, {@link ReadEntryView} passed in will represent * an empty entry view, hence {@link ReadEntryView#find()} will return * an empty {@link java.util.Optional} instance, and * {@link ReadEntryView#get()} will throw * {@link java.util.NoSuchElementException}. * * @param f operation to be called each time a cache entry is written * @return an {@link AutoCloseable} instance that can be used to * unregister the listener */ AutoCloseable onWrite(Consumer<ReadEntryView<K, V>> f); /** * Add a write-only listener, and return an {@link AutoCloseable} * instance that can be used to remove the listener registration. * * @param l the write-only functional map event listener * @return an {@link AutoCloseable} instance that can be used to * unregister the listener */ AutoCloseable add(WriteListener<K, V> l); /** * Write-only listener. * * @since 8.0 */ @Experimental interface WriteListener<K, V> { /** * Entry write event callback that receives a {@link ReadEntryView} * of the written entry. * * <p>For created or modified/updated events, the * {@link ReadEntryView} passed in will represent the newly stored * entry, hence implementations will not be available to differentiate * between created events vs modified/updated events. * * <p>For removed events, {@link ReadEntryView} passed in will represent * an empty entry view, hence {@link ReadEntryView#find()} will return * an empty {@link java.util.Optional} instance, and * {@link ReadEntryView#get()} will throw * {@link java.util.NoSuchElementException}. * * @param write written entry view */ void onWrite(ReadEntryView<K, V> write); } } }
8,272
38.966184
92
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/EntryViews.java
package org.infinispan.functional.impl; import static org.infinispan.metadata.Metadatas.updateMetadata; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.Experimental; import org.infinispan.commons.util.Util; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.MVCCEntry; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.encoding.DataConversion; import org.infinispan.functional.EntryView.ReadEntryView; import org.infinispan.functional.EntryView.ReadWriteEntryView; import org.infinispan.functional.EntryView.WriteEntryView; import org.infinispan.functional.MetaParam; import org.infinispan.marshall.core.Ids; import org.infinispan.metadata.Metadata; /** * Entry views implementation class holder. * * @since 8.0 */ @Experimental public final class EntryViews { private EntryViews() { // Cannot be instantiated, it's just a holder class } public static <K, V> ReadEntryView<K, V> readOnly(CacheEntry<K, V> entry, DataConversion keyDataConversion, DataConversion valueDataConversion) { return new EntryBackedReadOnlyView<>(entry, keyDataConversion, valueDataConversion); } public static <K, V> ReadEntryView<K, V> readOnly(CacheEntry entry) { return new EntryBackedReadOnlyView<>(entry, DataConversion.IDENTITY_KEY, DataConversion.IDENTITY_VALUE); } public static <K, V> ReadEntryView<K, V> readOnly(K key, V value, Metadata metadata) { return new ReadOnlySnapshotView<>(key, value, metadata); } public static <K, V> WriteEntryView<K, V> writeOnly(CacheEntry entry, DataConversion valueDataConversion) { return new EntryBackedWriteOnlyView<>(entry, valueDataConversion); } public static <K, V> AccessLoggingReadWriteView<K, V> readWrite(MVCCEntry entry, DataConversion keyDataConversion, DataConversion valueDataConversion) { return new EntryBackedReadWriteView<>(entry, keyDataConversion, valueDataConversion); } public static <K, V> AccessLoggingReadWriteView<K, V> readWrite(MVCCEntry entry, Object prevValue, Metadata prevMetadata, DataConversion keyDataConversion, DataConversion valueDataConversion) { return new EntryAndPreviousReadWriteView<>(entry, prevValue, prevMetadata, keyDataConversion, valueDataConversion); } public static <K, V> ReadEntryView<K, V> noValue(Object key) { return new NoValueReadOnlyView<>(key, null); } public static <K, V> ReadEntryView<K, V> noValue(Object key, DataConversion keyDataConversion) { return new NoValueReadOnlyView<>(key, keyDataConversion); } /** * For convenience, a lambda might decide to return the entry view it received as parameter, because that makes easy * to return both value and meta parameters back to the client. * <p> * If the lambda function decides to return an view, launder it into an immutable view to avoid the user trying apply * any modifications to the entry view from outside the lambda function. * <p> * If the view is read-only, capture its data into a snapshot from the cached entry and avoid changing underneath. */ @SuppressWarnings("unchecked") public static <R> R snapshot(R ret) { if (ret instanceof EntryBackedReadWriteView) { EntryBackedReadWriteView view = (EntryBackedReadWriteView) ret; return (R) new ReadWriteSnapshotView(view.key(), view.find().orElse(null), view.entry.getMetadata()); } else if (ret instanceof EntryAndPreviousReadWriteView) { EntryAndPreviousReadWriteView view = (EntryAndPreviousReadWriteView) ret; return (R) new ReadWriteSnapshotView(view.key(), view.getCurrentValue(), view.entry.getMetadata()); } else if (ret instanceof EntryBackedReadOnlyView) { EntryBackedReadOnlyView view = (EntryBackedReadOnlyView) ret; return (R) new ReadOnlySnapshotView(view.key(), view.find().orElse(null), view.entry.getMetadata()); } else if (ret instanceof NoValueReadOnlyView) { NoValueReadOnlyView view = (NoValueReadOnlyView) ret; return (R) new ReadOnlySnapshotView(view.key(), null, null); } return ret; } public interface AccessLoggingReadWriteView<K, V> extends ReadWriteEntryView<K, V> { boolean isRead(); } private static final class EntryBackedReadOnlyView<K, V> implements ReadEntryView<K, V> { final CacheEntry<K, V> entry; private final DataConversion keyDataConversion; private final DataConversion valueDataConversion; private EntryBackedReadOnlyView(CacheEntry<K, V> entry, DataConversion keyDataConversion, DataConversion valueDataConversion) { this.entry = entry; this.keyDataConversion = keyDataConversion; this.valueDataConversion = valueDataConversion; } @Override public K key() { return (K) keyDataConversion.fromStorage(entry.getKey()); } @Override public Optional<V> find() { return entry == null ? Optional.empty() : Optional.ofNullable((V) valueDataConversion.fromStorage(entry.getValue())); } @Override public V get() throws NoSuchElementException { if (entry == null || entry.getValue() == null) throw new NoSuchElementException("No value present"); return (V) valueDataConversion.fromStorage(entry.getValue()); } @Override public <T extends MetaParam> Optional<T> findMetaParam(Class<T> type) { Metadata metadata = entry.getMetadata(); if (metadata instanceof MetaParamsInternalMetadata) { MetaParamsInternalMetadata metaParamsMetadata = (MetaParamsInternalMetadata) metadata; return metaParamsMetadata.findMetaParam(type); } // TODO: Add interoperability support, e.g. able to retrieve lifespan for data stored in Cache via lifespan API return Optional.empty(); } @Override public String toString() { return "EntryBackedReadOnlyView{" + "entry=" + entry + '}'; } } private static final class ReadOnlySnapshotView<K, V> implements ReadEntryView<K, V> { final K key; final V value; final Metadata metadata; private ReadOnlySnapshotView(K key, V value, Metadata metadata) { this.key = key; this.value = value; this.metadata = metadata; } @Override public K key() { return key; } @Override public V get() throws NoSuchElementException { if (value == null) throw new NoSuchElementException("No value"); return value; } @Override public Optional<V> find() { return Optional.ofNullable(value); } // TODO: Duplication @Override public <T extends MetaParam> Optional<T> findMetaParam(Class<T> type) { if (metadata instanceof MetaParamsInternalMetadata) { MetaParamsInternalMetadata metaParamsMetadata = (MetaParamsInternalMetadata) metadata; return metaParamsMetadata.findMetaParam(type); } // TODO: Add interoperability support, e.g. able to retrieve lifespan for data stored in Cache via lifespan API return Optional.empty(); } @Override public String toString() { return "ReadOnlySnapshotView{" + "key=" + key + ", value=" + value + ", metadata=" + metadata + '}'; } } private static final class EntryBackedWriteOnlyView<K, V> implements WriteEntryView<K, V> { final CacheEntry entry; private final DataConversion valueDataConversion; private EntryBackedWriteOnlyView(CacheEntry entry, DataConversion valueDataConversion) { this.entry = entry; this.valueDataConversion = valueDataConversion; } @Override public Void set(V value, MetaParam.Writable... metas) { setValue(value); updateMetaParams(entry, metas); return null; } @Override public Void set(V value, Metadata metadata) { setValue(value); updateMetadata(entry, metadata); return null; } private void setValue(V value) { Object encodedValue = valueDataConversion.toStorage(value); entry.setValue(encodedValue); entry.setChanged(true); entry.setRemoved(value == null); } @Override public K key() { return (K) entry.getKey(); } @Override public Void remove() { entry.setRemoved(true); entry.setChanged(true); entry.setValue(null); return null; } @Override public String toString() { return "EntryBackedWriteOnlyView{" + "entry=" + entry + '}'; } } private static final class EntryBackedReadWriteView<K, V> implements AccessLoggingReadWriteView<K, V> { final MVCCEntry entry; private final DataConversion keyDataConversion; private final DataConversion valueDataConversion; private final boolean existsBefore; private K decodedKey; private V decodedValue; private boolean isRead; private EntryBackedReadWriteView(MVCCEntry entry, DataConversion keyDataConversion, DataConversion valueDataConversion) { this.entry = entry; this.keyDataConversion = keyDataConversion; this.valueDataConversion = valueDataConversion; this.existsBefore = entry.getValue() != null; } @Override public K key() { if (entry == null) { return null; } if (decodedKey == null) { decodedKey = (K) keyDataConversion.fromStorage(entry.getKey()); } return decodedKey; } @Override public Optional<V> find() { isRead = true; return peek(); } @Override public Optional<V> peek() { if (entry == null) { return Optional.empty(); } if (decodedValue == null) { decodedValue = (V) valueDataConversion.fromStorage(entry.getValue()); } return Optional.ofNullable(decodedValue); } @Override public Void set(V value, MetaParam.Writable... metas) { setOnly(value, metas); return null; } @Override public Void set(V value, Metadata metadata) { setEntry(value); updateMetadata(entry, metadata); return null; } private void setOnly(V value, MetaParam.Writable[] metas) { setEntry(value); updateMetaParams(entry, metas); } private void setEntry(V value) { decodedValue = value; Object valueEncoded = valueDataConversion.toStorage(value); entry.setCreated(entry.getValue() == null && valueEncoded != null); entry.setValue(valueEncoded); entry.setChanged(true); entry.setRemoved(valueEncoded == null); } @Override public Void remove() { decodedValue = null; entry.setRemoved(existsBefore); entry.setChanged(existsBefore); entry.setValue(null); entry.setCreated(false); return null; } @Override public <T extends MetaParam> Optional<T> findMetaParam(Class<T> type) { Metadata metadata = entry.getMetadata(); if (type == MetaParam.MetaLoadedFromPersistence.class) { return Optional.of((T) MetaParam.MetaLoadedFromPersistence.of(entry.isLoaded())); } if (metadata instanceof MetaParamsInternalMetadata) { MetaParamsInternalMetadata metaParamsMetadata = (MetaParamsInternalMetadata) metadata; return metaParamsMetadata.findMetaParam(type); } // TODO: Add interoperability support, e.g. able to retrieve lifespan for data stored in Cache via lifespan API return Optional.empty(); } @Override public V get() throws NoSuchElementException { isRead = true; if (entry == null || entry.getValue() == null) throw new NoSuchElementException("No value present"); decodedValue = decodedValue == null ? (V) valueDataConversion.fromStorage(entry.getValue()) : decodedValue; return decodedValue; } @Override public String toString() { return "EntryBackedReadWriteView{" + "entry=" + entry + '}'; } @Override public boolean isRead() { return isRead; } } private static final class EntryAndPreviousReadWriteView<K, V> implements AccessLoggingReadWriteView<K, V> { final MVCCEntry entry; final Object prevValue; final Metadata prevMetadata; private final DataConversion keyDataConversion; private final DataConversion valueDataConversion; private K decodedKey; private V decodedPrevValue; private V decodedValue; private boolean isRead; private EntryAndPreviousReadWriteView(MVCCEntry entry, Object prevValue, Metadata prevMetadata, DataConversion keyDataConversion, DataConversion valueDataConversion) { this.entry = entry; this.prevValue = prevValue; this.prevMetadata = prevMetadata; this.keyDataConversion = keyDataConversion; this.valueDataConversion = valueDataConversion; } @Override public K key() { if (decodedKey == null) { decodedKey = (K) keyDataConversion.fromStorage(entry.getKey()); } return decodedKey; } @Override public Optional<V> find() { isRead = true; return peek(); } @Override public Optional<V> peek() { if (decodedPrevValue == null) { decodedPrevValue = (V) valueDataConversion.fromStorage(prevValue); } return Optional.ofNullable(decodedPrevValue); } public V getCurrentValue() { isRead = true; if (decodedValue == null) { decodedValue = (V) valueDataConversion.fromStorage(entry.getValue()); } return decodedValue; } @Override public Void set(V value, MetaParam.Writable... metas) { setOnly(value, metas); return null; } @Override public Void set(V value, Metadata metadata) { setValue(value); updateMetadata(entry, metadata); return null; } private void setOnly(V value, MetaParam.Writable[] metas) { setValue(value); updateMetaParams(entry, metas); } private void setValue(V value) { decodedValue = value; Object valueEncoded = valueDataConversion.toStorage(value); entry.setValue(valueEncoded); entry.setChanged(true); entry.setRemoved(valueEncoded == null); entry.setCreated(prevValue == null && valueEncoded != null); } @Override public Void remove() { decodedValue = null; entry.setRemoved(prevValue != null); entry.setCreated(false); entry.setChanged(prevValue != null); entry.setValue(null); return null; } @Override public <T extends MetaParam> Optional<T> findMetaParam(Class<T> type) { isRead = true; if (type == MetaParam.MetaLoadedFromPersistence.class) { return Optional.of((T) MetaParam.MetaLoadedFromPersistence.of(entry.isLoaded())); } Metadata metadata = prevMetadata; // Use previous metadata if (metadata instanceof MetaParamsInternalMetadata) { MetaParamsInternalMetadata metaParamsMetadata = (MetaParamsInternalMetadata) metadata; return metaParamsMetadata.findMetaParam(type); } // TODO: Add interoperability support, e.g. able to retrieve lifespan for data stored in Cache via lifespan API return Optional.empty(); } @Override public V get() throws NoSuchElementException { isRead = true; if (prevValue == null) throw new NoSuchElementException(); if (decodedPrevValue == null) { decodedPrevValue = (V) valueDataConversion.fromStorage(prevValue); } return decodedPrevValue; } @Override public String toString() { return "EntryAndPreviousReadWriteView{" + "entry=" + entry + ", prevValue=" + prevValue + ", prevMetadata=" + prevMetadata + '}'; } @Override public boolean isRead() { return isRead; } } private static final class NoValueReadOnlyView<K, V> implements ReadEntryView<K, V> { final Object key; private final DataConversion keyDataConversion; public NoValueReadOnlyView(Object key, DataConversion keyDataConversion) { this.key = key; this.keyDataConversion = keyDataConversion; } @Override public K key() { return (K) keyDataConversion.fromStorage(key); } @Override public V get() throws NoSuchElementException { throw new NoSuchElementException("No value for key " + key()); } @Override public Optional<V> find() { return Optional.empty(); } @Override public <T extends MetaParam> Optional<T> findMetaParam(Class<T> type) { return Optional.empty(); } @Override public String toString() { return "NoValueReadOnlyView{" + "key=" + key() + '}'; } } private static final class ReadWriteSnapshotView<K, V> implements ReadWriteEntryView<K, V> { final K key; final V value; final Metadata metadata; public ReadWriteSnapshotView(K key, V value, Metadata metadata) { this.key = key; this.value = value; this.metadata = metadata; } @Override public K key() { return key; } @Override public V get() throws NoSuchElementException { if (value == null) throw new NoSuchElementException("No value present"); return value; } @Override public Optional<V> find() { return Optional.ofNullable(value); } // TODO: Duplication @Override public <T extends MetaParam> Optional<T> findMetaParam(Class<T> type) { if (metadata instanceof MetaParamsInternalMetadata) { MetaParamsInternalMetadata metaParamsMetadata = (MetaParamsInternalMetadata) metadata; return metaParamsMetadata.findMetaParam(type); } // TODO: Add interoperability support, e.g. able to retrieve lifespan for data stored in Cache via lifespan API return Optional.empty(); } @Override public Void set(V value, MetaParam.Writable... metas) { throw new IllegalStateException( "A read-write entry view cannot be modified outside the scope of a lambda"); } @Override public Void set(V value, Metadata metadata) { throw new IllegalStateException( "A read-write entry view cannot be modified outside the scope of a lambda"); } @Override public Void remove() { throw new IllegalStateException( "A read-write entry view cannot be modified outside the scope of a lambda"); } @Override public String toString() { return "ReadWriteSnapshotView{" + "key=" + key + ", value=" + value + ", metadata=" + metadata + '}'; } } private static <K, V> void updateMetaParams(CacheEntry<K, V> entry, MetaParam.Writable[] metas) { // TODO: Deal with entry instances that are MetaParamsCacheEntry and merge meta params // e.g. check if meta params exist and if so, merge, but also check for old metadata // information and merge it individually Optional<EntryVersion> version = Optional.ofNullable(entry.getMetadata()).map(m -> m.version()); MetaParams metaParams = MetaParams.empty(); if (version.isPresent()) { metaParams.add(new MetaParam.MetaEntryVersion(version.get())); } if (metas.length != 0) { metaParams.addMany(metas); } updateMetadata(entry, MetaParamsInternalMetadata.from(metaParams)); } private static <K, V> MetaParams extractMetaParams(CacheEntry<K, V> entry) { // TODO: Deal with entry instances that are MetaParamsCacheEntry and merge meta params // e.g. check if meta params exist and if so, merge, but also check for old metadata // information and merge it individually Metadata metadata = entry.getMetadata(); if (metadata instanceof MetaParamsInternalMetadata) { MetaParamsInternalMetadata metaParamsMetadata = (MetaParamsInternalMetadata) metadata; return metaParamsMetadata.params; } return MetaParams.empty(); } public static final class ReadOnlySnapshotViewExternalizer implements AdvancedExternalizer<ReadOnlySnapshotView> { @Override public Set<Class<? extends ReadOnlySnapshotView>> getTypeClasses() { return Util.asSet(ReadOnlySnapshotView.class); } @Override public Integer getId() { return Ids.READ_ONLY_SNAPSHOT_VIEW; } @Override public void writeObject(ObjectOutput output, ReadOnlySnapshotView object) throws IOException { output.writeObject(object.key); output.writeObject(object.value); output.writeObject(object.metadata); } @Override public ReadOnlySnapshotView readObject(ObjectInput input) throws IOException, ClassNotFoundException { Object key = input.readObject(); Object value = input.readObject(); Metadata metadata = (Metadata) input.readObject(); return new ReadOnlySnapshotView<>(key, value, metadata); } } public static final class NoValueReadOnlyViewExternalizer implements AdvancedExternalizer<NoValueReadOnlyView> { @Override public Set<Class<? extends NoValueReadOnlyView>> getTypeClasses() { return Util.asSet(NoValueReadOnlyView.class); } @Override public Integer getId() { return Ids.NO_VALUE_READ_ONLY_VIEW; } @Override public void writeObject(ObjectOutput output, NoValueReadOnlyView object) throws IOException { output.writeObject(object.key); } @Override public NoValueReadOnlyView readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new NoValueReadOnlyView(input.readObject(), null); } } // Externalizer class defined outside of externalized class to avoid having // to making externalized class public, since that would leak internal impl. public static final class ReadWriteSnapshotViewExternalizer extends AbstractExternalizer<ReadWriteSnapshotView> { @Override public Integer getId() { return Ids.READ_WRITE_SNAPSHOT_VIEW; } @Override @SuppressWarnings("unchecked") public Set<Class<? extends ReadWriteSnapshotView>> getTypeClasses() { return Util.asSet(ReadWriteSnapshotView.class); } @Override public void writeObject(ObjectOutput output, ReadWriteSnapshotView obj) throws IOException { output.writeObject(obj.key); output.writeObject(obj.value); output.writeObject(obj.metadata); } @Override @SuppressWarnings("unchecked") public ReadWriteSnapshotView readObject(ObjectInput input) throws IOException, ClassNotFoundException { Object key = input.readObject(); Object value = input.readObject(); Metadata metadata = (Metadata) input.readObject(); return new ReadWriteSnapshotView(key, value, metadata); } } }
24,437
32.941667
196
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/FunctionalNotifier.java
package org.infinispan.functional.impl; import java.util.function.Supplier; import org.infinispan.commons.util.Experimental; import org.infinispan.container.entries.CacheEntry; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.functional.EntryView.ReadEntryView; import org.infinispan.functional.Listeners.ReadWriteListeners; import org.infinispan.metadata.Metadata; /** * Listener notifier. * * @since 8.0 */ @Scope(Scopes.NAMED_CACHE) @Experimental public interface FunctionalNotifier<K, V> extends ReadWriteListeners<K, V> { /** * Notify registered {@link ReadWriteListener} instances of the created entry. */ void notifyOnCreate(CacheEntry<K, V> entry); /** * Notify registered {@link ReadWriteListener} instances of the modified * entry passing the previous and new value. */ void notifyOnModify(CacheEntry<K, V> entry, V previousValue, Metadata previousMetadata); /** * Notify registered {@link ReadWriteListener} instances of the removed * entry passing in the removed entry. */ void notifyOnRemove(ReadEntryView<K, V> removed); /** * Notify registered {@link WriteListener} instances of the written entry. * * @apiNote By using a {@link Supplier} the entry view can be computed lazily * only if any listeners has been registered. */ void notifyOnWriteRemove(K key); void notifyOnWrite(CacheEntry<K, V> entry); }
1,477
28.56
91
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/AbstractFunctionalMap.java
package org.infinispan.functional.impl; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.batch.BatchContainer; import org.infinispan.commands.VisitableCommand; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.Configuration; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.encoding.DataConversion; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.Param; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Abstract functional map, providing implementations for some of the shared methods. * * @since 8.0 */ abstract class AbstractFunctionalMap<K, V> implements FunctionalMap<K, V> { private static final Log log = LogFactory.getLog(FunctionalMap.class); protected final FunctionalMapImpl<K, V> fmap; protected final Params params; private final boolean transactional; private final boolean autoCommit; private final BatchContainer batchContainer; private final TransactionManager transactionManager; protected final DataConversion keyDataConversion; protected final DataConversion valueDataConversion; private final BlockingManager blockingManager; protected AbstractFunctionalMap(Params params, FunctionalMapImpl<K, V> fmap) { this.fmap = fmap; Configuration config = fmap.cache.getCacheConfiguration(); transactional = config.transaction().transactionMode().isTransactional(); autoCommit = config.transaction().autoCommit(); transactionManager = transactional ? fmap.cache.getTransactionManager() : null; batchContainer = transactional && config.invocationBatching().enabled() ? fmap.cache.getBatchContainer() : null; this.params = config.statistics().available() ? params : params.addAll(Param.StatisticsMode.SKIP); this.keyDataConversion = fmap.cache.getKeyDataConversion(); this.valueDataConversion = fmap.cache.getValueDataConversion(); this.blockingManager = fmap.cache.getComponentRegistry().getComponent(BlockingManager.class); } @Override public String getName() { return ""; } @Override public ComponentStatus getStatus() { return fmap.getStatus(); } @Override public void close() throws Exception { fmap.close(); } @Override public Cache<K, V> cache() { return fmap.cache(); } protected InvocationContext getInvocationContext(boolean isWrite, int keyCount) { InvocationContext invocationContext; boolean txInjected = false; if (transactional) { Transaction transaction = getOngoingTransaction(); if (transaction == null && autoCommit && transactionManager != null) { try { transactionManager.begin(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new CacheException("Unable to begin implicit transaction.", e); } transaction = getOngoingTransaction(); txInjected = true; } invocationContext = fmap.invCtxFactory.createInvocationContext(transaction, txInjected); } else { invocationContext = fmap.invCtxFactory.createInvocationContext(isWrite, keyCount); } // Functional map has no way to lock key so we only have to add lock owner for writes if (isWrite && fmap.lockOwner != null) { invocationContext.setLockOwner(fmap.lockOwner); } return invocationContext; } private Transaction getOngoingTransaction() { try { Transaction transaction = null; if (transactionManager != null) { transaction = transactionManager.getTransaction(); if (transaction == null && batchContainer != null) { transaction = batchContainer.getBatchTransaction(); } } return transaction; } catch (SystemException e) { throw new CacheException("Unable to get transaction", e); } } protected <T> CompletableFuture<T> invokeAsync(InvocationContext ctx, VisitableCommand cmd) { CompletableFuture<T> cf; boolean isImplicitTx = ctx.isInTxScope() && ((TxInvocationContext) ctx).isImplicitTransaction(); final Transaction implicitTransaction; try { // interceptors must not access thread-local transaction anyway if (isImplicitTx) { implicitTransaction = transactionManager.suspend(); assert implicitTransaction != null; } else { implicitTransaction = null; } cf = (CompletableFuture<T>) fmap.chain.invokeAsync(ctx, cmd); } catch (SystemException e) { throw new CacheException("Cannot suspend implicit transaction", e); } catch (Throwable t) { if (isImplicitTx) { try { if (transactionManager != null) transactionManager.rollback(); } catch (Throwable t2) { log.trace("Could not rollback", t2);//best effort t.addSuppressed(t2); } } throw t; } if (isImplicitTx) { return blockingManager.handleBlocking(cf, (result, throwable) -> { if (throwable != null) { try { implicitTransaction.rollback(); } catch (SystemException e) { log.trace("Could not rollback", e); throwable.addSuppressed(e); } throw CompletableFutures.asCompletionException(throwable); } try { implicitTransaction.commit(); } catch (Exception e) { log.couldNotCompleteInjectedTransaction(e); throw CompletableFutures.asCompletionException(e); } return result; }, ctx.getLockOwner()).toCompletableFuture(); } else { return cf; } } protected Set<?> encodeKeys(Set<? extends K> keys) { return keys.stream().map(k -> keyDataConversion.toStorage(k)).collect(Collectors.toSet()); } protected Map<?, ?> encodeEntries(Map<? extends K, ?> entries) { Map encodedEntries = new HashMap<>(); entries.entrySet().forEach(e -> { Object keyEncoded = keyDataConversion.toStorage(e.getKey()); Object valueEncoded = valueDataConversion.toStorage(e.getValue()); encodedEntries.put(keyEncoded, valueEncoded); }); return encodedEntries; } }
7,046
36.285714
118
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/WriteOnlyMapImpl.java
package org.infinispan.functional.impl; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; 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.commons.util.Experimental; import org.infinispan.context.InvocationContext; import org.infinispan.functional.EntryView.WriteEntryView; import org.infinispan.functional.FunctionalMap.WriteOnlyMap; import org.infinispan.functional.Listeners.WriteListeners; import org.infinispan.functional.Param; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Write-only map implementation. * * @since 8.0 */ @Experimental public final class WriteOnlyMapImpl<K, V> extends AbstractFunctionalMap<K, V> implements WriteOnlyMap<K, V> { private static final Log log = LogFactory.getLog(WriteOnlyMapImpl.class); private WriteOnlyMapImpl(Params params, FunctionalMapImpl<K, V> functionalMap) { super(params, functionalMap); } public static <K, V> WriteOnlyMap<K, V> create(FunctionalMapImpl<K, V> functionalMap) { return create(Params.from(functionalMap.params.params), functionalMap); } private static <K, V> WriteOnlyMap<K, V> create(Params params, FunctionalMapImpl<K, V> functionalMap) { return new WriteOnlyMapImpl<>(params, functionalMap); } @Override public CompletableFuture<Void> eval(K key, Consumer<WriteEntryView<K, V>> f) { log.tracef("Invoked eval(k=%s, %s)", key, params); Object keyEncoded = keyDataConversion.toStorage(key); WriteOnlyKeyCommand<K, V> cmd = fmap.commandsFactory.buildWriteOnlyKeyCommand(keyEncoded, f, fmap.keyPartitioner.getSegment(keyEncoded), params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, 1); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return invokeAsync(ctx, cmd); } @Override public <T> CompletableFuture<Void> eval(K key, T argument, BiConsumer<T, WriteEntryView<K, V>> f) { log.tracef("Invoked eval(k=%s, v=%s, %s)", key, argument, params); Object keyEncoded = keyDataConversion.toStorage(key); Object argumentEncoded = valueDataConversion.toStorage(argument); WriteOnlyKeyValueCommand<K, V, T> cmd = fmap.commandsFactory.buildWriteOnlyKeyValueCommand(keyEncoded, argumentEncoded, (BiConsumer) f, fmap.keyPartitioner.getSegment(keyEncoded), params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, 1); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return invokeAsync(ctx, cmd); } @Override public <T> CompletableFuture<Void> evalMany(Map<? extends K, ? extends T> arguments, BiConsumer<T, WriteEntryView<K, V>> f) { log.tracef("Invoked evalMany(entries=%s, %s)", arguments, params); Map<?, ?> argumentsEncoded = encodeEntries(arguments); WriteOnlyManyEntriesCommand<K, V, T> cmd = fmap.commandsFactory.buildWriteOnlyManyEntriesCommand(argumentsEncoded, f, params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, arguments.size()); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return invokeAsync(ctx, cmd); } @Override public CompletableFuture<Void> evalMany(Set<? extends K> keys, Consumer<WriteEntryView<K, V>> f) { log.tracef("Invoked evalMany(keys=%s, %s)", keys, params); Set<?> encodedKeys = encodeKeys(keys); WriteOnlyManyCommand<K, V> cmd = fmap.commandsFactory.buildWriteOnlyManyCommand(encodedKeys, f, params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, keys.size()); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return invokeAsync(ctx, cmd); } @Override public CompletableFuture<Void> evalAll(Consumer<WriteEntryView<K, V>> f) { log.tracef("Invoked evalAll(%s)", params); // TODO: during commmand execution the set is iterated multiple times, and can execute remote operations // therefore we should rather have separate command (or different semantics for keys == null) Set<K> keys = new HashSet<>(fmap.cache.keySet()); Set<?> encodedKeys = encodeKeys(keys); WriteOnlyManyCommand<K, V> cmd = fmap.commandsFactory.buildWriteOnlyManyCommand(encodedKeys, f, params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, encodedKeys.size()); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return invokeAsync(ctx, cmd); } @Override public CompletableFuture<Void> truncate() { log.tracef("Invoked truncate(%s)", params); return fmap.cache.clearAsync(); } @Override public WriteOnlyMap<K, V> withParams(Param<?>... ps) { if (ps == null || ps.length == 0) return this; if (params.containsAll(ps)) return this; // We already have all specified params return create(params.addAll(ps), fmap); } @Override public WriteListeners<K, V> listeners() { return fmap.notifier; } }
5,629
41.330827
172
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/CounterConfigurationMetaParam.java
package org.infinispan.functional.impl; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.functional.MetaParam; /** * Stores the {@link CounterConfiguration}. * <p> * The metadata is static and doesn't change. It is sent when initializing a counter and it is kept locally in all the * nodes. This avoids transfer information about the counter in every operation (e.g. boundaries/reset). * * @author Pedro Ruivo * @since 11.0 */ public class CounterConfigurationMetaParam implements MetaParam.Writable<CounterConfiguration> { private final CounterConfiguration configuration; public CounterConfigurationMetaParam(CounterConfiguration configuration) { this.configuration = configuration; } @Override public CounterConfiguration get() { return configuration; } @Override public String toString() { return "CounterConfigurationMetaParam{" + "configuration=" + configuration + '}'; } }
993
26.611111
118
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/StatsEnvelope.java
package org.infinispan.functional.impl; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.infinispan.commands.VisitableCommand; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.util.Util; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.InvocationContext; import org.infinispan.marshall.core.Ids; /** * Responses for functional commands that allow to record statistics. */ public class StatsEnvelope<T> { // hit and miss are exclusive flags since the command might not read the entry at all public static final byte HIT = 1; public static final byte MISS = 2; public static final byte CREATE = 4; public static final byte UPDATE = 8; public static final byte DELETE = 16; private final T value; private final byte flags; public static <T> StatsEnvelope<T> create(T returnValue, CacheEntry<?, ?> e, boolean exists, boolean isRead) { byte flags = 0; if (isRead) { if (exists) flags |= HIT; else flags |= MISS; } if (exists) { if (e.getValue() == null) { flags |= DELETE; } else if (e.isChanged()) { flags |= UPDATE; } } else if (e.getValue() != null) { flags |= CREATE; } return new StatsEnvelope(returnValue, flags); } public static <R> StatsEnvelope create(R ret, boolean isNull) { return new StatsEnvelope(ret, isNull ? MISS : HIT); } public static Object unpack(InvocationContext ctx, VisitableCommand command, Object o) { return ((StatsEnvelope<?>) o).value; } public static Object unpackCollection(InvocationContext ctx, VisitableCommand command, Object o) { return ((Collection<StatsEnvelope<?>>) o).stream().map(StatsEnvelope::value).collect(Collectors.toList()); } public static Object unpackStream(InvocationContext ctx, VisitableCommand command, Object o) { return ((Stream<StatsEnvelope<?>>) o).map(StatsEnvelope::value); } private StatsEnvelope(T value, byte flags) { this.value = value; this.flags = flags; } public T value() { return value; } public byte flags() { return flags; } @Override public String toString() { return "StatsEnvelope{value=" + value + ", flags=" + ((flags & HIT) != 0 ? 'H' : '_') + ((flags & MISS) != 0 ? 'M' : '_') + ((flags & CREATE) != 0 ? 'C' : '_') + ((flags & UPDATE) != 0 ? 'U' : '_') + ((flags & DELETE) != 0 ? 'D' : '_') + "}"; } public boolean isHit() { return (flags & HIT) != 0; } public boolean isMiss() { return (flags & MISS) != 0; } public boolean isDelete() { return (flags & DELETE) != 0; } public static class Externalizer implements AdvancedExternalizer<StatsEnvelope> { @Override public Set<Class<? extends StatsEnvelope>> getTypeClasses() { return Util.asSet(StatsEnvelope.class); } @Override public Integer getId() { return Ids.STATS_ENVELOPE; } @Override public void writeObject(ObjectOutput output, StatsEnvelope object) throws IOException { output.writeObject(object.value); output.writeByte(object.flags); } @Override public StatsEnvelope readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new StatsEnvelope(input.readObject(), input.readByte()); } } }
3,685
28.488
113
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/FunctionalMapImpl.java
package org.infinispan.functional.impl; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.cache.impl.AbstractDelegatingCache; import org.infinispan.cache.impl.DecoratedCache; import org.infinispan.commands.CommandsFactory; import org.infinispan.commons.util.Experimental; import org.infinispan.context.InvocationContextFactory; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.factories.ComponentRegistry; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.Param; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.lifecycle.ComponentStatus; /** * Functional map implementation. * * @since 8.0 */ @Experimental public final class FunctionalMapImpl<K, V> implements FunctionalMap<K, V> { final Params params; final AdvancedCache<K, V> cache; final AsyncInterceptorChain chain; final CommandsFactory commandsFactory; final InvocationContextFactory invCtxFactory; final Object lockOwner; final FunctionalNotifier notifier; final KeyPartitioner keyPartitioner; public static <K, V> FunctionalMapImpl<K, V> create(Params params, AdvancedCache<K, V> cache) { params = params.addAll(Params.fromFlagsBitSet(getFlagsBitSet(cache))); return new FunctionalMapImpl<>(params, cache); } public static <K, V> FunctionalMapImpl<K, V> create(AdvancedCache<K, V> cache) { Params params = Params.fromFlagsBitSet(getFlagsBitSet(cache)); return new FunctionalMapImpl<>(params, cache); } private static <K, V> long getFlagsBitSet(Cache<K, V> cache) { long flagsBitSet = 0; for (; ; ) { if (cache instanceof DecoratedCache) { flagsBitSet |= ((DecoratedCache) cache).getFlagsBitSet(); } if (cache instanceof AbstractDelegatingCache) { cache = ((AbstractDelegatingCache) cache).getDelegate(); } else { break; } } // By default the commands have Param.ReplicationMode.SYNC and this forces synchronous execution // We could either have third replication mode (USE_CACHE_MODE) or we enforce that here. if (!cache.getCacheConfiguration().clustering().cacheMode().isSynchronous()) { flagsBitSet |= FlagBitSets.FORCE_ASYNCHRONOUS; } return flagsBitSet; } // Finds the first decorated cache if there are delegates surrounding it otherwise null private DecoratedCache<K, V> findDecoratedCache(Cache<K, V> cache) { if (cache instanceof AbstractDelegatingCache) { if (cache instanceof DecoratedCache) { return ((DecoratedCache<K, V>) cache); } return findDecoratedCache(((AbstractDelegatingCache<K, V>) cache).getDelegate()); } return null; } private FunctionalMapImpl(Params params, AdvancedCache<K, V> cache) { this.params = params; this.cache = cache; ComponentRegistry componentRegistry = cache.getComponentRegistry(); chain = componentRegistry.getComponent(AsyncInterceptorChain.class); invCtxFactory = componentRegistry.getComponent(InvocationContextFactory.class); DecoratedCache<K, V> decoratedCache = findDecoratedCache(cache); lockOwner = decoratedCache == null ? null : decoratedCache.getLockOwner(); commandsFactory = componentRegistry.getComponent(CommandsFactory.class); notifier = componentRegistry.getComponent(FunctionalNotifier.class); keyPartitioner = componentRegistry.getComponent(KeyPartitioner.class); } @Override public FunctionalMapImpl<K, V> withParams(Param<?>... ps) { if (ps == null || ps.length == 0) return this; if (params.containsAll(ps)) return this; // We already have all specified params return create(params.addAll(ps), cache); } @Override public String getName() { return cache.getName(); } @Override public ComponentStatus getStatus() { return cache.getStatus(); } @Override public void close() throws Exception { cache.stop(); } @Override public Cache<K, V> cache() { return cache; } }
4,224
34.208333
102
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/FunctionalNotifierImpl.java
package org.infinispan.functional.impl; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.infinispan.commons.util.Experimental; import org.infinispan.container.entries.CacheEntry; import org.infinispan.functional.EntryView.ReadEntryView; import org.infinispan.metadata.Metadata; /** * @since 8.0 */ @Experimental public final class FunctionalNotifierImpl<K, V> implements FunctionalNotifier<K, V> { final List<Consumer<ReadEntryView<K, V>>> onCreates = new CopyOnWriteArrayList<>(); final List<BiConsumer<ReadEntryView<K, V>, ReadEntryView<K, V>>> onModifies = new CopyOnWriteArrayList<>(); final List<Consumer<ReadEntryView<K, V>>> onRemoves = new CopyOnWriteArrayList<>(); final List<Consumer<ReadEntryView<K, V>>> onWrites = new CopyOnWriteArrayList<>(); final List<ReadWriteListener<K, V>> rwListeners = new CopyOnWriteArrayList<>(); final List<WriteListener<K, V>> writeListeners = new CopyOnWriteArrayList<>(); @Override public AutoCloseable add(WriteListener<K, V> l) { writeListeners.add(l); return new ListenerCloseable<>(l, writeListeners); } @Override public AutoCloseable add(ReadWriteListener<K, V> l) { rwListeners.add(l); return new ListenerCloseable<>(l, rwListeners); } @Override public AutoCloseable onCreate(Consumer<ReadEntryView<K, V>> f) { onCreates.add(f); return new ListenerCloseable<>(f, onCreates); } @Override public AutoCloseable onModify(BiConsumer<ReadEntryView<K, V>, ReadEntryView<K, V>> f) { onModifies.add(f); return new ListenerCloseable<>(f, onModifies); } @Override public AutoCloseable onRemove(Consumer<ReadEntryView<K, V>> f) { onRemoves.add(f); return new ListenerCloseable<>(f, onRemoves); } @Override public AutoCloseable onWrite(Consumer<ReadEntryView<K, V>> f) { onWrites.add(f); return new ListenerCloseable<>(f, onWrites); } @Override public void notifyOnCreate(CacheEntry entry) { if (!onCreates.isEmpty() || !rwListeners.isEmpty()) { ReadEntryView<K, V> created = EntryViews.readOnly(entry); onCreates.forEach(c -> c.accept(created)); rwListeners.forEach(rwl -> rwl.onCreate(created)); } } @Override public void notifyOnModify(CacheEntry<K, V> entry, V previousValue, Metadata previousMetadata) { if (!onModifies.isEmpty() || !rwListeners.isEmpty()) { ReadEntryView<K, V> before = EntryViews.readOnly(entry.getKey(), previousValue, previousMetadata); ReadEntryView<K, V> after = EntryViews.readOnly(entry); onModifies.forEach(c -> c.accept(before, after)); rwListeners.forEach(rwl -> rwl.onModify(before, after)); } } @Override public void notifyOnRemove(ReadEntryView<K, V> removed) { onRemoves.forEach(c -> c.accept(removed)); rwListeners.forEach(rwl -> rwl.onRemove(removed)); } @Override public void notifyOnWrite(CacheEntry<K, V> entry) { if (!onWrites.isEmpty() || !writeListeners.isEmpty()) { ReadEntryView<K, V> wrote = EntryViews.readOnly(entry); onWrites.forEach(c -> c.accept(wrote)); writeListeners.forEach(wl -> wl.onWrite(wrote)); } } @Override public void notifyOnWriteRemove(K key) { if (!onWrites.isEmpty() || !writeListeners.isEmpty()) { ReadEntryView<K, V> wrote = EntryViews.noValue(key); onWrites.forEach(c -> c.accept(wrote)); writeListeners.forEach(wl -> wl.onWrite(wrote)); } } private static final class ListenerCloseable<T> implements AutoCloseable { final T f; final List<T> list; private ListenerCloseable(T f, List<T> list) { this.f = f; this.list = list; } @Override public void close() throws Exception { list.remove(f); } } }
3,979
31.622951
110
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/MetaParams.java
package org.infinispan.functional.impl; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Function; import java.util.stream.Stream; import org.infinispan.commons.util.Experimental; import org.infinispan.functional.MetaParam; import net.jcip.annotations.NotThreadSafe; /** * Represents a {@link MetaParam} collection. * * <p>In {@link Params}, the internal array where each parameter was * stored is indexed by an integer. This worked fine because the available * parameters are exclusively controlled by the Infinispan. This is not the * case with {@link MetaParam} instances where users are expected to add their * own types. So, for {@link MetaParams}, an array is still used but the lookup * is done sequentially comparing the type of the {@link MetaParam} looked for * against the each individual {@link MetaParam} instance stored in * {@link MetaParams}. * * <p>Having sequential {@link MetaParam} lookups over an array is O(n), * but this is not problematic since the number of {@link MetaParam} to be * stored with each cached entry is expected to be small, less than 10 per * {@link MetaParams} collection. So, the performance impact is quite small. * * <p>Storing {@link MetaParam} instances in an array adds the least * amount of overhead to keeping a collection of {@link MetaParam} in memory * along with each cached entry, while retaining flexibility to add or remove * {@link MetaParam} instances. * * <p>This {@link MetaParams} collection is not thread safe because * it is expected that any updates will be done having acquired write locks * on the entire {@link org.infinispan.container.entries.CacheEntry} which * references the {@link MetaParams} collection. Hence, any updates could be * done without the need to keep {@link MetaParams} concurrently safe. * Also, although users can retrieve or update individual {@link MetaParam} * instances, they cannot act on the globally at the {@link MetaParams} level, * and hence there is no risk of users misusing {@link MetaParams}. * * This class should not be accessible from user code, therefore it is package-protected. * * @since 8.0 */ @NotThreadSafe @Experimental public final class MetaParams implements Iterable<MetaParam<?>> { static final MetaParam<?>[] EMPTY_ARRAY = {}; private MetaParam<?>[] metas; private int length; MetaParams(MetaParam<?>[] metas, int length) { this.metas = metas; this.length = length; assert checkLength(); } public boolean isEmpty() { return length == 0; } public int size() { return length; } public MetaParams copy() { if (length == 0) { return empty(); } else { return new MetaParams(Arrays.copyOf(metas, metas.length), length); } } public <T extends MetaParam> Optional<T> find(Class<T> type) { return Optional.ofNullable(findNullable(type)); } @SuppressWarnings("unchecked") private <T extends MetaParam> T findNullable(Class<T> type) { for (MetaParam<?> meta : metas) { if (meta != null && meta.getClass().isAssignableFrom(type)) return (T) meta; } return null; } public void add(MetaParam meta) { assert meta != null; if (metas.length == 0) { metas = new MetaParam[]{meta}; length = 1; } else { int hole = -1; for (int i = 0; i < metas.length; i++) { MetaParam<?> m = metas[i]; if (m == null) { hole = i; } else if (m.getClass().isAssignableFrom(meta.getClass())) { metas[i] = meta; assert checkLength(); return; } } ++length; if (hole < 0) { MetaParam<?>[] newMetas = Arrays.copyOf(metas, metas.length + 1); newMetas[newMetas.length - 1] = meta; metas = newMetas; } else { metas[hole] = meta; } assert checkLength(); } } private boolean checkLength() { int l = 0; for (MetaParam meta : metas) { if (meta != null) ++l; } return l == length; } public void addMany(MetaParam... metaParams) { if (metas.length == 0) { // Arrays in Java are covariant, therefore someone could pass MetaParam.Writable[] and // we could try to store non-writable meta param in that array (or its copy) later. if (metaParams.getClass().getComponentType() == MetaParam.class) { metas = metaParams; } else { metas = Arrays.copyOf(metaParams, metaParams.length, MetaParam[].class); } length = (int) Stream.of(metas).filter(Objects::nonNull).count(); } else { List<MetaParam<?>> notFound = new ArrayList<>(metaParams.length); for (MetaParam newMeta : metaParams) { updateExisting(newMeta, notFound); } if (!notFound.isEmpty()) { MetaParam<?>[] newMetas = Arrays.copyOf(metas, metas.length + notFound.size()); int i = metas.length; for (MetaParam<?> meta : notFound) { newMetas[i++] = meta; } metas = newMetas; } } assert checkLength(); } private void updateExisting(MetaParam newMeta, List<MetaParam<?>> notFound) { int hole = -1; for (int i = 0; i < metas.length; i++) { MetaParam<?> m = metas[i]; if (m == null) { hole = i; } else if (m.getClass().isAssignableFrom(newMeta.getClass())) { metas[i] = newMeta; return; } } ++length; if (hole < 0) { notFound.add(newMeta); } else { metas[hole] = newMeta; } } public <T extends MetaParam> void remove(Class<T> type) { for (int i = 0; i < metas.length; ++i) { MetaParam<?> m = metas[i]; if (m != null && m.getClass().isAssignableFrom(type)) { metas[i] = null; --length; assert checkLength(); return; } } } public <T extends MetaParam> void replace(Class<T> type, Function<T, T> f) { int hole = -1; for (int i = 0; i < metas.length; ++i) { MetaParam<?> m = metas[i]; if (m == null) { hole = i; } else if (m.getClass().isAssignableFrom(type)) { T newMeta = f.apply((T) m); assert newMeta == null || type.isInstance(newMeta); if (newMeta == null) { --length; } metas[i] = newMeta; assert checkLength(); return; } } T newMeta = f.apply(null); if (newMeta == null) { assert checkLength(); return; } else if (hole < 0) { ++length; MetaParam<?>[] newMetas = Arrays.copyOf(metas, metas.length + 1); newMetas[newMetas.length - 1] = newMeta; metas = newMetas; } else { ++length; metas[hole] = newMeta; } assert checkLength(); } @Override public String toString() { return "MetaParams{length=" + length + ", metas=" + Arrays.toString(metas) + '}'; } /** * Construct a collection of {@link MetaParam} instances. If multiple * instances of the same {@link MetaParam} are present, the last value is * only considered since there can only be one instance per type in the * {@link MetaParams} collection. * * @param metas Meta parameters to create the collection with * @return a collection of meta parameters without type duplicates */ static MetaParams of(MetaParam... metas) { metas = filterDuplicates(metas); return new MetaParams(metas, metas.length); } static MetaParams of(MetaParam meta) { assert meta != null; return new MetaParams(new MetaParam[]{meta}, 1); } static MetaParams empty() { return new MetaParams(EMPTY_ARRAY, 0); } private static MetaParam[] filterDuplicates(MetaParam... metas) { Map<Class<?>, MetaParam<?>> all = new HashMap<>(); for (MetaParam meta : metas) { if (meta == null) continue; all.put(meta.getClass(), meta); } return all.values().toArray(new MetaParam[all.size()]); } void merge(MetaParams other) { Map<Class<?>, MetaParam<?>> all = new HashMap<>(); // Add other's metadata first, because we don't want to override those already present for (MetaParam meta : other.metas) { if (meta == null) continue; all.put(meta.getClass(), meta); } for (MetaParam meta : metas) { if (meta == null) continue; all.put(meta.getClass(), meta); } metas = all.values().toArray(new MetaParam[all.size()]); } @Override public Iterator<MetaParam<?>> iterator() { return new It(); } @Override public Spliterator<MetaParam<?>> spliterator() { return Spliterators.spliterator(iterator(), length, Spliterator.DISTINCT | Spliterator.NONNULL); } public static MetaParams readFrom(ObjectInput input) throws IOException, ClassNotFoundException { int length = input.readInt(); MetaParam[] metas = new MetaParam[length]; for (int i = 0; i < length; i++) metas[i] = (MetaParam) input.readObject(); return new MetaParams(metas, metas.length); } public static void writeTo(ObjectOutput output, MetaParams params) throws IOException { output.writeInt(params.size()); for (MetaParam meta : params) output.writeObject(meta); } private class It implements Iterator<MetaParam<?>> { private int i = 0; public It() { skipNulls(); } private void skipNulls() { while (i < metas.length && metas[i] == null) ++i; } @Override public boolean hasNext() { return i < metas.length; } @Override public MetaParam<?> next() { if (i >= metas.length) { throw new NoSuchElementException(); } MetaParam<?> meta = metas[i++]; skipNulls(); return meta; } } }
10,585
30.227139
102
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/Params.java
package org.infinispan.functional.impl; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.List; import org.infinispan.functional.Param; import org.infinispan.functional.Param.ExecutionMode; import org.infinispan.functional.Param.LockingMode; import org.infinispan.functional.Param.PersistenceMode; import org.infinispan.functional.Param.ReplicationMode; import org.infinispan.functional.Param.StatisticsMode; import org.infinispan.commons.util.Experimental; import org.infinispan.context.impl.FlagBitSets; /** * Internal class that encapsulates collection of parameters used to tweak * functional map operations. * * <p>Internally, parameters are stored in an array which is indexed by * a parameter's {@link Param#id()} * * <p>All parameters have default values which are stored in a static * array field in {@link Params} class, which are used to as base collection * when adding or overriding parameters. * * @since 8.0 */ @Experimental public final class Params { private static final Param<?>[] DEFAULTS = new Param<?>[]{ PersistenceMode.defaultValue(), LockingMode.defaultValue(), ExecutionMode.defaultValue(), StatisticsMode.defaultValue(), ReplicationMode.defaultValue() }; // TODO: as Params are immutable and there's only limited number of them, // there could be a table with all the possible combinations and we // wouldn't have to allocate at all private static final Params DEFAULT_INSTANCE = new Params(DEFAULTS); final Param<?>[] params; private Params(Param<?>[] params) { this.params = params; } /** * Checks whether all the parameters passed in are already present in the * current parameters. This method can be used to optimise the decision on * whether the parameters collection needs updating at all. */ public boolean containsAll(Param<?>... ps) { List<Param<?>> paramsToCheck = Arrays.asList(ps); List<Param<?>> paramsCurrent = Arrays.asList(params); return paramsCurrent.containsAll(paramsToCheck); } /** * Adds all parameters and returns a new parameter collection. */ public Params addAll(Param<?>... ps) { List<Param<?>> paramsToAdd = Arrays.asList(ps); Param<?>[] paramsAll = Arrays.copyOf(params, params.length); paramsToAdd.forEach(p -> paramsAll[p.id()] = p); return new Params(paramsAll); } public Params add(Param<?> p) { Param<?>[] paramsAll = Arrays.copyOf(params, params.length); paramsAll[p.id()] = p; return new Params(paramsAll); } public Params addAll(Params ps) { if (ps == DEFAULT_INSTANCE) { return this; } Param<?>[] paramsAll = Arrays.copyOf(params, params.length); for (int i = 0; i < this.params.length; ++i) { if (!ps.params[i].equals(DEFAULTS[i])) { paramsAll[i] = ps.params[i]; } } return new Params(paramsAll); } /** * Retrieve a param given its identifier. Callers are expected to know the * exact type of parameter that will be returned. Such assumption is * possible because as indicated in {@link Param} implementations will * only come from Infinispan itself. */ @SuppressWarnings("unchecked") public <T> Param<T> get(int index) { // TODO: Provide a more type safe API. E.g. make index a pojo typed on T which is aligned with the Param<T> return (Param<T>) params[index]; } @Override public String toString() { return "Params=" + Arrays.toString(params); } /** * Bridging method between flags and params, provided for efficient checks. */ public long toFlagsBitSet() { PersistenceMode persistenceMode = (PersistenceMode) params[PersistenceMode.ID].get(); LockingMode lockingMode = (LockingMode) params[LockingMode.ID].get(); ExecutionMode executionMode = (ExecutionMode) params[ExecutionMode.ID].get(); StatisticsMode statisticsMode = (StatisticsMode) params[StatisticsMode.ID].get(); ReplicationMode replicationMode = (ReplicationMode) params[ReplicationMode.ID].get(); long flagsBitSet = 0; switch (persistenceMode) { case SKIP_PERSIST: flagsBitSet |= FlagBitSets.SKIP_CACHE_STORE; break; case SKIP_LOAD: flagsBitSet |= FlagBitSets.SKIP_CACHE_LOAD; break; case SKIP: flagsBitSet |= FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_CACHE_STORE; break; } switch (lockingMode) { case SKIP: flagsBitSet |= FlagBitSets.SKIP_LOCKING; break; case TRY_LOCK: flagsBitSet |= FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT | FlagBitSets.FAIL_SILENTLY; break; } switch (executionMode) { case LOCAL: flagsBitSet |= FlagBitSets.CACHE_MODE_LOCAL; break; case LOCAL_SITE: flagsBitSet |= FlagBitSets.SKIP_XSITE_BACKUP; break; } if (statisticsMode == StatisticsMode.SKIP) { flagsBitSet |= FlagBitSets.SKIP_STATISTICS; } switch (replicationMode) { case SYNC: flagsBitSet |= FlagBitSets.FORCE_SYNCHRONOUS; break; case ASYNC: flagsBitSet |= FlagBitSets.FORCE_ASYNCHRONOUS; break; } return flagsBitSet; } public static Params fromFlagsBitSet(long flagsBitSet) { if (flagsBitSet == 0) { return DEFAULT_INSTANCE; } Param<?>[] paramsAll = Arrays.copyOf(DEFAULTS, DEFAULTS.length); if ((flagsBitSet & (FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_CACHE_STORE)) != 0) { paramsAll[PersistenceMode.ID] = PersistenceMode.SKIP; } else if ((flagsBitSet & FlagBitSets.SKIP_CACHE_STORE) != 0) { paramsAll[PersistenceMode.ID] = PersistenceMode.SKIP_PERSIST; } else if ((flagsBitSet & FlagBitSets.SKIP_CACHE_LOAD) != 0) { paramsAll[PersistenceMode.ID] = PersistenceMode.SKIP_LOAD; } if ((flagsBitSet & FlagBitSets.SKIP_LOCKING) != 0) { paramsAll[LockingMode.ID] = LockingMode.SKIP; } else if ((flagsBitSet & FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT) != 0) { paramsAll[LockingMode.ID] = LockingMode.TRY_LOCK; } if ((flagsBitSet & FlagBitSets.CACHE_MODE_LOCAL) != 0) { paramsAll[ExecutionMode.ID] = ExecutionMode.LOCAL; } else if ((flagsBitSet & FlagBitSets.SKIP_XSITE_BACKUP) != 0) { paramsAll[ExecutionMode.ID] = ExecutionMode.LOCAL_SITE; } if ((flagsBitSet & FlagBitSets.SKIP_STATISTICS) != 0) { paramsAll[StatisticsMode.ID] = StatisticsMode.SKIP; } if ((flagsBitSet & FlagBitSets.FORCE_ASYNCHRONOUS) != 0) { paramsAll[ReplicationMode.ID] = ReplicationMode.ASYNC; } else if ((flagsBitSet & FlagBitSets.FORCE_SYNCHRONOUS) != 0) { paramsAll[ReplicationMode.ID] = ReplicationMode.SYNC; } return new Params(paramsAll); } public static Params create() { return DEFAULT_INSTANCE; } public static Params from(Param<?>... ps) { List<Param<?>> paramsToAdd = Arrays.asList(ps); List<Param<?>> paramsDefaults = Arrays.asList(DEFAULTS); if (paramsDefaults.containsAll(paramsToAdd)) return create(); // All parameters are defaults, don't do more work Param<?>[] paramsAll = Arrays.copyOf(DEFAULTS, DEFAULTS.length); paramsToAdd.forEach(p -> paramsAll[p.id()] = p); return new Params(paramsAll); } static { // make sure that bit-set marshalling will work if (PersistenceMode.values().length > 4) throw new IllegalStateException(); if (LockingMode.values().length > 4) throw new IllegalStateException(); if (ExecutionMode.values().length > 4) throw new IllegalStateException(); if (StatisticsMode.values().length > 2) throw new IllegalStateException(); if (ReplicationMode.values().length > 2) throw new IllegalStateException(); } public static void writeObject(ObjectOutput output, Params params) throws IOException { PersistenceMode persistenceMode = (PersistenceMode) params.get(PersistenceMode.ID).get(); LockingMode lockingMode = (LockingMode) params.get(LockingMode.ID).get(); ExecutionMode executionMode = (ExecutionMode) params.get(ExecutionMode.ID).get(); StatisticsMode statisticsMode = (StatisticsMode) params.get(StatisticsMode.ID).get(); ReplicationMode replicationMode = (ReplicationMode) params.get(ReplicationMode.ID).get(); int paramBits = persistenceMode.ordinal() | (lockingMode.ordinal() << 2) | (executionMode.ordinal() << 4) | (statisticsMode.ordinal() << 6) | (replicationMode.ordinal() << 7); output.writeByte(paramBits); } public static Params readObject(ObjectInput input) throws IOException { int paramBits = input.readByte(); PersistenceMode persistenceMode = PersistenceMode.valueOf(paramBits & 3); LockingMode lockingMode = LockingMode.valueOf((paramBits >>> 2) & 3); ExecutionMode executionMode = ExecutionMode.valueOf((paramBits >>> 4) & 3); StatisticsMode statisticsMode = StatisticsMode.valueOf((paramBits >>> 6) & 1); ReplicationMode replicationMode = ReplicationMode.valueOf((paramBits >>> 7) & 1); if (persistenceMode == PersistenceMode.defaultValue() && lockingMode == LockingMode.defaultValue() && executionMode == ExecutionMode.defaultValue() && statisticsMode == StatisticsMode.defaultValue() && replicationMode == ReplicationMode.defaultValue()) { return DEFAULT_INSTANCE; } else { Param[] params = Arrays.copyOf(DEFAULTS, DEFAULTS.length); params[PersistenceMode.ID] = persistenceMode; params[LockingMode.ID] = lockingMode; params[ExecutionMode.ID] = executionMode; params[StatisticsMode.ID] = statisticsMode; params[ReplicationMode.ID] = replicationMode; return new Params(params); } } }
10,171
39.365079
113
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/ReadOnlyMapImpl.java
package org.infinispan.functional.impl; import java.util.Iterator; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.infinispan.commands.functional.ReadOnlyKeyCommand; import org.infinispan.commands.functional.ReadOnlyManyCommand; import org.infinispan.commons.util.Experimental; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.InvocationContext; import org.infinispan.functional.EntryView.ReadEntryView; import org.infinispan.functional.FunctionalMap.ReadOnlyMap; import org.infinispan.functional.Param; import org.infinispan.functional.Traversable; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Read-only map implementation. * * @since 8.0 */ @Experimental public final class ReadOnlyMapImpl<K, V> extends AbstractFunctionalMap<K, V> implements ReadOnlyMap<K, V> { private static final Log log = LogFactory.getLog(ReadOnlyMapImpl.class); private ReadOnlyMapImpl(Params params, FunctionalMapImpl<K, V> functionalMap) { super(params, functionalMap); } public static <K, V> ReadOnlyMap<K, V> create(FunctionalMapImpl<K, V> functionalMap) { return create(Params.from(functionalMap.params.params), functionalMap); } private static <K, V> ReadOnlyMap<K, V> create(Params params, FunctionalMapImpl<K, V> functionalMap) { return new ReadOnlyMapImpl<>(params, functionalMap); } @Override public <R> CompletableFuture<R> eval(K key, Function<ReadEntryView<K, V>, R> f) { log.tracef("Invoked eval(k=%s, %s)", key, params); Object keyEncoded = keyDataConversion.toStorage(key); ReadOnlyKeyCommand<K, V, R> cmd = fmap.commandsFactory.buildReadOnlyKeyCommand(keyEncoded, f, fmap.keyPartitioner.getSegment(keyEncoded), params, keyDataConversion, valueDataConversion); InvocationContext ctx = fmap.invCtxFactory.createInvocationContext(false, 1); return (CompletableFuture<R>) fmap.chain.invokeAsync(ctx, cmd); } @Override public <R> Traversable<R> evalMany(Set<? extends K> keys, Function<ReadEntryView<K, V>, R> f) { log.tracef("Invoked evalMany(m=%s, %s)", keys, params); Set<?> encodedKeys = encodeKeys(keys); ReadOnlyManyCommand<K, V, R> cmd = fmap.commandsFactory.buildReadOnlyManyCommand(encodedKeys, f, params, keyDataConversion, valueDataConversion); InvocationContext ctx = fmap.invCtxFactory.createInvocationContext(false, keys.size()); return Traversables.of((Stream<R>) fmap.chain.invokeAsync(ctx, cmd).join()); } @Override public Traversable<K> keys() { log.tracef("Invoked keys(%s)", params); return Traversables.of(fmap.cache.keySet().stream()); } @Override public Traversable<ReadEntryView<K, V>> entries() { log.tracef("Invoked entries(%s)", params); Iterator<CacheEntry<K, V>> it = fmap.cache.cacheEntrySet().iterator(); // TODO: Don't really need a Stream here... Stream<CacheEntry<K, V>> stream = StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, Spliterator.IMMUTABLE), false); return Traversables.of(stream.map(EntryViews::readOnly)); } @Override public ReadOnlyMap<K, V> withParams(Param<?>... ps) { if (ps == null || ps.length == 0) return this; if (params.containsAll(ps)) return this; // We already have all specified params return create(params.addAll(ps), fmap); } }
3,637
38.543478
151
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/MetaParamsInternalMetadata.java
package org.infinispan.functional.impl; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Experimental; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.container.versioning.SimpleClusteredVersion; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.functional.MetaParam; import org.infinispan.functional.MetaParam.MetaCreated; import org.infinispan.functional.MetaParam.MetaEntryVersion; import org.infinispan.functional.MetaParam.MetaLastUsed; import org.infinispan.functional.MetaParam.MetaLifespan; import org.infinispan.functional.MetaParam.MetaMaxIdle; import org.infinispan.metadata.InternalMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * Metadata parameters backed internal metadata representation. * * @since 8.0 */ @Experimental @ProtoTypeId(ProtoStreamTypeIds.META_PARAMS_INTERNAL_METADATA) public final class MetaParamsInternalMetadata implements InternalMetadata, MetaParam.Lookup { private static final MetaParamsInternalMetadata EMPTY = new MetaParamsInternalMetadata(MetaParams.empty()); final MetaParams params; public static Metadata from(MetaParams params) { return new MetaParamsInternalMetadata(params); } @ProtoFactory MetaParamsInternalMetadata(NumericVersion numericVersion, SimpleClusteredVersion clusteredVersion, long created, long lastUsed, long lifespan, long maxIdle, CounterConfiguration counterConfiguration, boolean updateCreationTimestamp) { this.params = new MetaParams(MetaParams.EMPTY_ARRAY, 0); if (numericVersion != null || clusteredVersion != null) { this.params.add(new MetaEntryVersion(numericVersion == null ? clusteredVersion : numericVersion)); } if (created > -1) params.add(new MetaCreated(created)); if (lastUsed > -1) params.add(new MetaLastUsed(lastUsed)); if (lifespan > -1) params.add(new MetaLifespan(lifespan)); if (maxIdle > -1) params.add(new MetaMaxIdle(maxIdle)); if (counterConfiguration != null) { params.add(new CounterConfigurationMetaParam(counterConfiguration)); } // Default is always true, so no need to set the param unless it is false if (!updateCreationTimestamp) { params.add(MetaParam.MetaUpdateCreationTime.of(false)); } } private MetaParamsInternalMetadata(MetaParams params) { this.params = params; } @ProtoField(1) NumericVersion getNumericVersion() { EntryVersion version = version(); return version instanceof NumericVersion ? (NumericVersion) version : null; } @ProtoField(2) SimpleClusteredVersion getClusteredVersion() { EntryVersion version = version(); return version instanceof SimpleClusteredVersion ? (SimpleClusteredVersion) version : null; } @ProtoField(number = 3, defaultValue = "-1") @Override public long created() { return params.find(MetaCreated.class).map(MetaParam.MetaLong::get).orElse(0L); } @ProtoField(number = 4, defaultValue = "-1") @Override public long lastUsed() { return params.find(MetaLastUsed.class).map(MetaParam.MetaLong::get).orElse(0L); } @Override public boolean isExpired(long now) { long expiryTime = expiryTime(); return expiryTime >= 0 && expiryTime <= now; } @Override public long expiryTime() { long deadline = -1; long lifespan = lifespan(); if (lifespan >= 0) { deadline = created() + lifespan; } long maxIdle = maxIdle(); if (maxIdle >= 0) { if (deadline < 0) { deadline = lastUsed() + maxIdle; } else { deadline = Math.min(deadline, lastUsed() + maxIdle); } } return deadline; } @ProtoField(number = 5, defaultValue = "-1") @Override public long lifespan() { return params.find(MetaLifespan.class) .orElse(MetaLifespan.defaultValue()).get(); } @ProtoField(number = 6, defaultValue = "-1") @Override public long maxIdle() { return params.find(MetaMaxIdle.class) .orElse(MetaMaxIdle.defaultValue()).get(); } @ProtoField(7) public CounterConfiguration counterConfiguration() { return params.find(CounterConfigurationMetaParam.class).map(CounterConfigurationMetaParam::get).orElse(null); } @ProtoField(value = 8, defaultValue = "true") @Override public boolean updateCreationTimestamp() { return params.find(MetaParam.MetaUpdateCreationTime.class).map(MetaParam.MetaBoolean::get).orElse(true); } @Override public EntryVersion version() { return params.find(MetaEntryVersion.class).map(MetaEntryVersion::get).orElse(null); } @Override public Builder builder() { return new Builder(params.copy()); } @Override public <T extends MetaParam> Optional<T> findMetaParam(Class<T> type) { return params.find(type); } public boolean isEmpty() { return params.isEmpty(); } @Override public String toString() { return "MetaParamsInternalMetadata{params=" + params + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MetaParamsInternalMetadata that = (MetaParamsInternalMetadata) o; return created() == that.created() && lastUsed() == that.lastUsed() && lifespan() == that.lifespan() && maxIdle() == that.maxIdle() && Objects.equals(version(), that.version()) && Objects.equals(counterConfiguration(), that.counterConfiguration()); } @Override public int hashCode() { return Objects.hash(created(), lastUsed(), lastUsed(), maxIdle(), version(), counterConfiguration()); } public static MetaParamsInternalMetadata.Builder getBuilder(MetaParamsInternalMetadata metadata) { return metadata == null ? new MetaParamsInternalMetadata.Builder() : metadata.builder(); } public static MetaParamsInternalMetadata empty() { return EMPTY; } public static class Builder implements Metadata.Builder { private final MetaParams params; public Builder() { this.params = MetaParams.empty(); } Builder(MetaParams params) { this.params = params; } @Override public Builder lifespan(long time, TimeUnit unit) { params.add(new MetaLifespan(unit.toMillis(time))); return this; } @Override public Builder lifespan(long time) { params.add(new MetaLifespan(time)); return this; } @Override public Builder maxIdle(long time, TimeUnit unit) { params.add(new MetaMaxIdle(unit.toMillis(time))); return this; } @Override public Builder maxIdle(long time) { params.add(new MetaMaxIdle(time)); return this; } @Override public Builder version(EntryVersion version) { params.add(new MetaEntryVersion(version)); return this; } @Override public Metadata.Builder updateCreationTimestamp(boolean enabled) { params.add(new MetaParam.MetaUpdateCreationTime(enabled)); return this; } @Override public MetaParamsInternalMetadata build() { return new MetaParamsInternalMetadata(params); } public Builder add(MetaParam<?> metaParam) { params.add(metaParam); return this; } @Override public Builder merge(Metadata metadata) { if (metadata instanceof MetaParamsInternalMetadata) { params.merge(((MetaParamsInternalMetadata) metadata).params); } else { if (!params.find(MetaLifespan.class).isPresent()) { lifespan(metadata.lifespan()); } if (!params.find(MetaMaxIdle.class).isPresent()) { maxIdle(metadata.maxIdle()); } if (!params.find(MetaEntryVersion.class).isPresent()) { version(metadata.version()); } if (!params.find(MetaParam.MetaUpdateCreationTime.class).isPresent()) { updateCreationTimestamp(metadata.updateCreationTimestamp()); } } return this; } } }
8,812
31.047273
130
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/Traversables.java
package org.infinispan.functional.impl; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Stream; import org.infinispan.functional.Traversable; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; public final class Traversables { public static <T> Traversable<T> of(Stream<T> stream) { return new StreamTraversable<>(stream); } public static <T> CloseableIterator<T> asIterator(Traversable<T> traversable) { if (traversable instanceof StreamTraversable) return Closeables.iterator(((StreamTraversable<T>) traversable).stream); else { List<T> collected = traversable.collect(ArrayList::new, ArrayList::add, ArrayList::addAll); return Closeables.iterator(collected.iterator()); } } private Traversables() { // Cannot be instantiated, it's just a holder class } // TODO: Attention! This is a very rudimentary/simplistic implementation! private static final class StreamTraversable<T> implements Traversable<T> { final Stream<T> stream; private StreamTraversable(Stream<T> stream) { this.stream = stream; } @Override public Traversable<T> filter(Predicate<? super T> p) { return new StreamTraversable<>(stream.filter(p)); } @Override public <R> Traversable<R> map(Function<? super T, ? extends R> f) { return new StreamTraversable<>(stream.map(f)); } @Override public <R> Traversable<R> flatMap(Function<? super T, ? extends Traversable<? extends R>> f) { Function<? super T, ? extends Stream<? extends R>> mapper = new Function<T, Stream<? extends R>>() { @Override public Stream<? extends R> apply(T t) { StreamTraversable<? extends R> applied = (StreamTraversable<? extends R>) f.apply(t); return applied.stream; } }; return new StreamTraversable<>(stream.flatMap(mapper)); } @Override public void forEach(Consumer<? super T> c) { stream.forEach(c); } @Override public T reduce(T z, BinaryOperator<T> folder) { return stream.reduce(z, folder); } @Override public Optional<T> reduce(BinaryOperator<T> folder) { return stream.reduce(folder); } @Override public <U> U reduce(U z, BiFunction<U, ? super T, U> mapper, BinaryOperator<U> folder) { return stream.reduce(z, mapper, folder); } @Override public <R> R collect(Supplier<R> s, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) { return stream.collect(s, accumulator, combiner); } @Override public <R, A> R collect(Collector<? super T, A, R> collector) { return stream.collect(collector); } @Override public long count() { return stream.count(); } @Override public boolean anyMatch(Predicate<? super T> p) { return stream.anyMatch(p); } @Override public boolean allMatch(Predicate<? super T> p) { return stream.allMatch(p); } @Override public boolean noneMatch(Predicate<? super T> predicate) { return stream.noneMatch(predicate); } @Override public Optional<T> findAny() { return stream.findAny(); } } }
3,767
28.669291
109
java
null
infinispan-main/core/src/main/java/org/infinispan/functional/impl/ReadWriteMapImpl.java
package org.infinispan.functional.impl; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Function; 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.commons.util.Experimental; import org.infinispan.context.InvocationContext; import org.infinispan.functional.EntryView.ReadWriteEntryView; import org.infinispan.functional.FunctionalMap.ReadWriteMap; import org.infinispan.functional.Listeners.ReadWriteListeners; import org.infinispan.functional.Param; import org.infinispan.functional.Traversable; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Read-write map implementation. * * @since 8.0 */ @Experimental public final class ReadWriteMapImpl<K, V> extends AbstractFunctionalMap<K, V> implements ReadWriteMap<K, V> { private static final Log log = LogFactory.getLog(ReadWriteMapImpl.class); private ReadWriteMapImpl(Params params, FunctionalMapImpl<K, V> functionalMap) { super(params, functionalMap); } public static <K, V> ReadWriteMap<K, V> create(FunctionalMapImpl<K, V> functionalMap) { return create(Params.from(functionalMap.params.params), functionalMap); } private static <K, V> ReadWriteMap<K, V> create(Params params, FunctionalMapImpl<K, V> functionalMap) { return new ReadWriteMapImpl<>(params, functionalMap); } @Override public <R> CompletableFuture<R> eval(K key, Function<ReadWriteEntryView<K, V>, R> f) { log.tracef("Invoked eval(k=%s, %s)", key, params); Object keyEncoded = keyDataConversion.toStorage(key); ReadWriteKeyCommand<K, V, R> cmd = fmap.commandsFactory.buildReadWriteKeyCommand(keyEncoded, (Function) f, fmap.keyPartitioner.getSegment(keyEncoded), params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, 1); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return invokeAsync(ctx, cmd); } @Override public <T, R> CompletableFuture<R> eval(K key, T argument, BiFunction<T, ReadWriteEntryView<K, V>, R> f) { log.tracef("Invoked eval(k=%s, v=%s, %s)", key, argument, params); Object keyEncoded = keyDataConversion.toStorage(key); Object argumentEncoded = valueDataConversion.toStorage(argument); ReadWriteKeyValueCommand<K, V, T, R> cmd = fmap.commandsFactory.buildReadWriteKeyValueCommand(keyEncoded, argumentEncoded, (BiFunction) f, fmap.keyPartitioner.getSegment(keyEncoded), params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, 1); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return invokeAsync(ctx, cmd); } @Override public <T, R> Traversable<R> evalMany(Map<? extends K, ? extends T> arguments, BiFunction<T, ReadWriteEntryView<K, V>, R> f) { log.tracef("Invoked evalMany(entries=%s, %s)", arguments, params); Map<?, ?> argumentsEncoded = encodeEntries(arguments); ReadWriteManyEntriesCommand<K, V, T, R> cmd = fmap.commandsFactory.buildReadWriteManyEntriesCommand(argumentsEncoded, f, params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, arguments.size()); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return Traversables.of(((List<R>) invokeAsync(ctx, cmd).join()).stream()); } @Override public <R> Traversable<R> evalMany(Set<? extends K> keys, Function<ReadWriteEntryView<K, V>, R> f) { log.tracef("Invoked evalMany(keys=%s, %s)", keys, params); Set<?> encodedKeys = encodeKeys(keys); ReadWriteManyCommand<K, V, R> cmd = fmap.commandsFactory.buildReadWriteManyCommand(encodedKeys, f, params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, keys.size()); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return Traversables.of(((List<R>) invokeAsync(ctx, cmd).join()).stream()); } @Override public <R> Traversable<R> evalAll(Function<ReadWriteEntryView<K, V>, R> f) { log.tracef("Invoked evalAll(%s)", params); // TODO: during commmand execution the set is iterated multiple times, and can execute remote operations // therefore we should rather have separate command (or different semantics for keys == null) Set<K> keys = new HashSet<>(fmap.cache.keySet()); Set<?> encodedKeys = encodeKeys(keys); ReadWriteManyCommand<K, V, R> cmd = fmap.commandsFactory.buildReadWriteManyCommand(encodedKeys, f, params, keyDataConversion, valueDataConversion); InvocationContext ctx = getInvocationContext(true, encodedKeys.size()); if (ctx.getLockOwner() == null) { ctx.setLockOwner(cmd.getKeyLockOwner()); } return Traversables.of(((List<R>) invokeAsync(ctx, cmd).join()).stream()); } @Override public ReadWriteListeners<K, V> listeners() { return fmap.notifier; } @Override public ReadWriteMap<K, V> withParams(Param<?>... ps) { if (ps == null || ps.length == 0) return this; if (params.containsAll(ps)) return this; // We already have all specified params return create(params.addAll(ps), fmap); } }
5,737
43.48062
175
java
null
infinispan-main/archetypes/client/src/main/resources/archetype-resources/src/main/java/Application.java
package ${package}; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; /** * Sample client application code. For more examples please see our client documentation * (https://infinispan.org/docs/stable/titles/hotrod_java/hotrod_java.html). * <p> * In order to run this application, it's necessary for a Infinispan server to be executing on your localhost with the * HotRod endpoint available on port 11222. The easiest way to achieve this, is by utilising our server docker image: * <p> * <code>docker run -p 11222:11222 -e USER="user" -e PASS="pass" infinispan/server</code> */ public class Application { public void propertyConfiguration() { System.out.println("\n\n1. Demonstrating basic usage of Infinispan Client using 'hotrod-client.properties' configuration."); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager()) { // Retrieve the cache defined by `infinispan.client.hotrod.cache.my-cache.template_name=` RemoteCache<String, String> cache = remoteCacheManager.getCache("my-cache"); helloWord(cache); } } public void programmaticConfiguration() { System.out.println("\n\n2. Demonstrating basic usage of the Infinispan Client using programmatic configuration."); ConfigurationBuilder cb = new ConfigurationBuilder(); // Configure security cb.security() .authentication() .username("user") .password("pass"); // Configure the server(s) to connect to cb.addServer() .host("127.0.0.1") .port(11222); // Configure the caches to create on first access cb.remoteCache("my-cache") .templateName("org.infinispan.DIST_SYNC"); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(cb.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache("my-cache"); helloWord(cache); } } private void helloWord(RemoteCache<String, String> cache) { System.out.println(" Storing value 'World' under key 'Hello'"); String oldValue = cache.put("Hello", "World"); System.out.printf(" Done. Saw old value as '%s'\n", oldValue); System.out.println(" Replacing 'World' with 'Mars'."); boolean worked = cache.replace("Hello", "World", "Mars"); System.out.printf(" Successful? %s\n", worked); assert oldValue == null; assert worked; } public void asyncOperations() { System.out.println("\n\n3. Demonstrating asynchronous operations - where writes can be done in a non-blocking fashion."); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager()) { // Retrieve the cache defined by `infinispan.client.hotrod.cache.wine-cache.template_name=` RemoteCache<String, Integer> cache = remoteCacheManager.getCache("wine-cache"); System.out.println(" Put #1"); CompletableFuture<Integer> f1 = cache.putAsync("Pinot Noir", 300); System.out.println(" Put #1"); CompletableFuture<Integer> f2 = cache.putAsync("Merlot", 120); System.out.println(" Put #1"); CompletableFuture<Integer> f3 = cache.putAsync("Chardonnay", 180); // now poll the futures to make sure any remote calls have completed! for (CompletableFuture<Integer> f : Arrays.asList(f1, f2, f3)) { try { System.out.println(" Checking future... "); f.get(); } catch (Exception e) { throw new RuntimeException("Operation failed!", e); } } System.out.println(" Everything stored!"); } } public void registeringListeners() throws InterruptedException { System.out.println("\n\n4. Demonstrating use of listeners."); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager()) { // Retrieve the cache defined by `infinispan.client.hotrod.cache.listener-cache.template_name=` RemoteCache<Integer, String> cache = remoteCacheManager.getCache("listener-cache"); System.out.println(" Attaching listener"); cache.addClientListener(new MyListener()); System.out.println(" Put #1"); cache.put(1, "One"); System.out.println(" Remove #1"); cache.remove(1); System.out.println(" Put #2"); cache.put(2, "Two"); System.out.println(" Put #3"); cache.put(3, "Three"); System.out.println(" Update #3"); cache.put(3, "3"); Thread.sleep(1000); } } public static void main(String[] args) throws Exception { System.out.println("\n\n\n ******************************** \n\n\n"); System.out.println("Hello. This is a sample application making use of Infinispan."); Application a = new Application(); a.propertyConfiguration(); a.programmaticConfiguration(); a.asyncOperations(); a.registeringListeners(); System.out.println("Sample complete."); System.out.println("\n\n\n ******************************** \n\n\n"); } @ClientListener @SuppressWarnings("unused") public static class MyListener { @ClientCacheEntryCreated public void handleCreatedEvent(ClientCacheEntryCreatedEvent<Integer> e) { System.out.printf("Thread %s has created an entry in the cache under key %s!\n", Thread.currentThread().getName(), e.getKey()); } @ClientCacheEntryModified public void handleModifiedEvent(ClientCacheEntryModifiedEvent<Integer> e) { System.out.printf("Thread %s has modified an entry in the cache under key %s!\n", Thread.currentThread().getName(), e.getKey()); } @ClientCacheEntryRemoved public void handleRemovedEvent(ClientCacheEntryRemovedEvent<Integer> e) { System.out.printf("Thread %s has removed an entry in the cache under key %s!\n", Thread.currentThread().getName(), e.getKey()); } } }
6,740
42.211538
131
java
null
infinispan-main/archetypes/server-task/src/main/resources/archetype-resources/src/main/java/CustomServerTask.java
package ${package}; import java.util.EnumSet; import java.util.Set; import java.util.concurrent.CompletionStage; import org.infinispan.commons.configuration.ConfiguredBy; import org.infinispan.tasks.ServerTask; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecutionMode; import java.nio.charset.StandardCharsets; import org.kohsuke.MetaInfServices; @MetaInfServices public class CustomServerTask<Object> implements ServerTask<Object> { private TaskContext ctx; /** * Allows access to execution context information including task parameters, cache references on * which tasks are executed, and so on. In most cases, implementations store this information * locally in all cases as it is set on each node. */ @Override public void setTaskContext(TaskContext ctx) { this.ctx = ctx; } /** * Computes a result. This method is defined in the java.util.concurrent.Callable interface and * is invoked with server tasks. */ @Override public Object call() { // TODO add task logic here. return null; } /** * Returns unique names for tasks. Clients invoke tasks with these names. */ @Override public String getName() { // TODO update to return the name of the task return null; } /** * Returns the execution mode for tasks. * * TaskExecutionMode.ONE_NODE only the node that handles the request executes the script. * Although scripts can still invoke clustered operations. * * TaskExecutionMode.ALL_NODES Infinispan uses clustered executors to run scripts across nodes. * For example, server tasks that invoke stream processing need to be executed on a single node * because stream processing is distributed to all nodes. */ @Override public TaskExecutionMode getExecutionMode() { // TODO update return TaskExecutionMode.ONE_NODE; } }
1,927
29.125
99
java
null
infinispan-main/archetypes/embedded/src/main/resources/archetype-resources/src/main/java/Application.java
package ${package}; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; /** * Sample application code. For more examples please see our documentation (https://infinispan.org/docs/stable/index.html) * and tutorials (https://infinispan.org/tutorials). */ public class Application { /** * This should point to the Infinispan configuration file. Either an absolute path or the name of a config * file in your classpath could be used. See https://infinispan.org/docs/stable/titles/configuring/configuring.html#declarative-configuring * for more details. * <p> * This skeleton project ships with 4 different Infinispan configurations. Uncomment the one most appropriate to you. */ private static final String INFINISPAN_CONFIGURATION = "infinispan-local.xml"; // private static final String INFINISPAN_CONFIGURATION = "infinispan-clustered-kubernetes.xml"; // private static final String INFINISPAN_CONFIGURATION = "infinispan-clustered-tcp.xml"; // private static final String INFINISPAN_CONFIGURATION = "infinispan-clustered-udp.xml"; private final EmbeddedCacheManager cacheManager; public Application(EmbeddedCacheManager cacheManager) { this.cacheManager = cacheManager; } public void basicUse() { System.out.println("\n\n1. Demonstrating basic usage of Infinispan. This cache stores arbitrary Strings."); Cache<String, String> cache = cacheManager.getCache(); System.out.println(" Storing value 'World' under key 'Hello'"); String oldValue = cache.put("Hello", "World"); System.out.printf(" Done. Saw old value as '%s'\n", oldValue); System.out.println(" Replacing 'World' with 'Mars'."); boolean worked = cache.replace("Hello", "World", "Mars"); System.out.printf(" Successful? %s\n", worked); assert oldValue == null; assert worked == true; } public void lifespans() throws InterruptedException { System.out.println("\n\n2. Demonstrating usage of Infinispan with expirable entries."); Cache<String, Float> stocksCache = cacheManager.getCache("stockTickers"); System.out.println(" Storing key 'RHT' for 10 seconds."); stocksCache.put("RHT", 45.0f, 10, TimeUnit.SECONDS); System.out.printf(" Checking for existence of key. Is it there? %s\n", stocksCache.containsKey("RHT")); System.out.println(" Sleeping for 10 seconds..."); Thread.sleep(10000); System.out.printf(" Checking for existence of key. Is it there? %s\n", stocksCache.containsKey("RHT")); assert stocksCache.get("RHT") == null; } public void asyncOperations() { System.out.println("\n\n3. Demonstrating asynchronous operations - where writes can be done in a non-blocking fashion."); Cache<String, Integer> wineCache = cacheManager.getCache("wineCache"); System.out.println(" Put #1"); CompletableFuture<Integer> f1 = wineCache.putAsync("Pinot Noir", 300); System.out.println(" Put #1"); CompletableFuture<Integer> f2 = wineCache.putAsync("Merlot", 120); System.out.println(" Put #1"); CompletableFuture<Integer> f3 = wineCache.putAsync("Chardonnay", 180); // now poll the futures to make sure any remote calls have completed! for (CompletableFuture<Integer> f : Arrays.asList(f1, f2, f3)) { try { System.out.println(" Checking future... "); f.get(); } catch (Exception e) { throw new RuntimeException("Operation failed!", e); } } System.out.println(" Everything stored!"); // TIP: For more examples on using the asynchronous API, visit https://infinispan.org/docs/stable/titles/developing/developing.html#cache_asynchronous_api } public void registeringListeners() { System.out.println("\n\n4. Demonstrating use of listeners."); Cache<Integer, String> anotherCache = cacheManager.getCache("another"); System.out.println(" Attaching listener"); MyListener l = new MyListener(); anotherCache.addListener(l); System.out.println(" Put #1"); anotherCache.put(1, "One"); System.out.println(" Put #2"); anotherCache.put(2, "Two"); System.out.println(" Put #3"); anotherCache.put(3, "Three"); // TIP: For more examples on using listeners visit https://infinispan.org/docs/stable/titles/developing/developing.html#listeners_and_notifications } public static void main(String[] args) throws Exception { try (EmbeddedCacheManager cacheManager = new DefaultCacheManager(INFINISPAN_CONFIGURATION)) { System.out.println("\n\n\n ******************************** \n\n\n"); System.out.println("Hello. This is a sample application making use of Infinispan."); Application a = new Application(cacheManager); a.basicUse(); a.lifespans(); a.asyncOperations(); a.registeringListeners(); System.out.println("Sample complete."); System.out.println("\n\n\n ******************************** \n\n\n"); } } @Listener @SuppressWarnings("unused") public class MyListener { @CacheEntryCreated @CacheEntryModified @CacheEntryRemoved public void printDetailsOnChange(CacheEntryEvent e) { System.out.printf("Thread %s has modified an entry in the cache named %s under key %s!\n", Thread.currentThread().getName(), e.getCache().getName(), e.getKey()); } @CacheEntryVisited public void printDetailsOnVisit(CacheEntryVisitedEvent e) { System.out.printf("Thread %s has visited an entry in the cache named %s under key %s!\n", Thread.currentThread().getName(), e.getCache().getName(), e.getKey()); } } }
6,502
43.848276
160
java
null
infinispan-main/archetypes/store/src/main/resources/archetype-resources/src/main/java/CustomStoreConfigurationBuilder.java
package ${package}; import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; public class CustomStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<CustomStoreConfiguration, CustomStoreConfigurationBuilder> { public CustomStoreConfigurationBuilder( PersistenceConfigurationBuilder builder) { super(builder, CustomStoreConfiguration.attributeDefinitionSet()); // TODO Auto-generated constructor stub } public CustomStoreConfigurationBuilder sampleAttribute(String sampleAttribute) { // TODO Auto-generated method stub attributes.attribute(CustomStoreConfiguration.SAMPLE_ATTRIBUTE).set(sampleAttribute); return this; } @Override public void validate() { super.validate(); /* * Perform any validation checks required. Throwing a Runtime Exception will prevent your store from being * created and cache startup will fail. * * The call to <code>super.validate();</code> should be kept to ensure that the attributes inherited from * {@link AbstractStoreConfigurationBuilder} are still validated. If no additional validation is required by your * store implementation, then this overridden method can be removed. */ } @Override public CustomStoreConfiguration create() { return new CustomStoreConfiguration(attributes.protect(), async.create()); } @Override public CustomStoreConfigurationBuilder self() { return this; } }
1,586
35.906977
147
java
null
infinispan-main/archetypes/store/src/main/resources/archetype-resources/src/main/java/CustomStoreConfiguration.java
package ${package}; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.AsyncStoreConfiguration; import org.infinispan.configuration.cache.CustomStoreConfigurationBuilder; @BuiltBy(CustomStoreConfigurationBuilder.class) @ConfigurationFor(CustomStore.class) public class CustomStoreConfiguration extends AbstractStoreConfiguration { static final AttributeDefinition<String> SAMPLE_ATTRIBUTE = AttributeDefinition.builder("sampleAttribute", null, String.class).immutable().build(); public static AttributeSet attributeDefinitionSet() { return new AttributeSet(CustomStoreConfiguration.class, AbstractStoreConfiguration.attributeDefinitionSet(), SAMPLE_ATTRIBUTE); } public CustomStoreConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(attributes, async); // TODO Auto-generated constructor stub } }
1,182
44.5
150
java
null
infinispan-main/archetypes/store/src/main/resources/archetype-resources/src/main/java/CustomStoreConfigurationParser.java
package ${package}; import static org.infinispan.commons.util.StringPropertyReplacer.replaceProperties; import java.util.HashMap; import java.util.Map; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ConfigurationParser; import org.infinispan.configuration.parsing.Namespace; import org.infinispan.configuration.parsing.Namespaces; import org.infinispan.configuration.parsing.ParseUtils; @Namespaces({ // A version-specific parser for a cache store. If a parser is capable of parsing configuration for multiple versions // just add multiple @Namespace annotations, one for each version @Namespace(uri = "urn:infinispan:config:my-custom-store:0.0", root = "my-custom-store"), // The default parser. This namespace should be applied to the latest version of the parser @Namespace(root = "my-custom-store") }) public class CustomStoreConfigurationParser implements ConfigurationParser { @Override public Namespace[] getNamespaces() { /* * Return the namespaces for which this parser should be used. */ return ParseUtils.getNamespaceAnnotations(this.getClass()); } @Override public void readElement(ConfigurationReader reader, ConfigurationBuilderHolder configurationHolder) { ConfigurationBuilder builder = configurationHolder.getCurrentConfigurationBuilder(); Element element = Element.forName(reader.getLocalName()); switch (element) { case SAMPLE_ELEMENT: { parseSampleElement(reader, builder.persistence()); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } private void parseSampleElement(ConfigurationReader reader, PersistenceConfigurationBuilder persistenceBuilder) { CustomStoreConfigurationBuilder storeBuilder = new CustomStoreConfigurationBuilder(persistenceBuilder); for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = replaceProperties(reader.getAttributeValue(i)); Attribute attribute = Attribute.forName(reader.getAttributeName(i)); switch (attribute) { case SAMPLE_ATTRIBUTE: { storeBuilder.sampleAttribute(value); break; } default: { throw ParseUtils.unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); } enum Element { // must be first UNKNOWN(null), SAMPLE_ELEMENT("sample-element"); private final String name; Element(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Element> MAP; static { final Map<String, Element> map = new HashMap<>(8); for (Element element : values()) { final String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static Element forName(final String localName) { final Element element = MAP.get(localName); return element == null ? UNKNOWN : element; } } enum Attribute { // must be first UNKNOWN(null), SAMPLE_ATTRIBUTE("sample-attribute"); // Other enums to be placed here private final String name; Attribute(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, Attribute> attributes; static { final Map<String, Attribute> map = new HashMap<>(); for (Attribute attribute : values()) { final String name = attribute.getLocalName(); if (name != null) { map.put(name, attribute); } } attributes = map; } public static Attribute forName(final String localName) { final Attribute attribute = attributes.get(localName); return attribute == null ? UNKNOWN : attribute; } } }
4,711
29.797386
123
java
null
infinispan-main/archetypes/store/src/main/resources/archetype-resources/src/main/java/CustomStore.java
package ${package}; import java.util.EnumSet; import java.util.Set; import java.util.concurrent.CompletionStage; import org.infinispan.commons.configuration.ConfiguredBy; import org.infinispan.configuration.cache.CustomStoreConfiguration; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.NonBlockingStore; import org.kohsuke.MetaInfServices; @MetaInfServices @ConfiguredBy(CustomStoreConfiguration.class) /** * This is an example {@link NonBlockingStore} implementation that provides basic */ public class CustomStore<K, V> implements NonBlockingStore<K, V> { /* * Mandatory method implementations. */ @Override public CompletionStage<Void> start(InitializationContext ctx) { /** * This method will be invoked by the PersistenceManager during initialization. See the {@link InitializationContext} * JavaDocs for details of the provided components. * <p> * This method is guaranteed not to be invoked concurrently with other operations. This means other methods are * not invoked on this store until after the returned Stage completes. */ return null; // TODO: Customise this generated block } @Override public CompletionStage<Void> stop() { return null; // TODO: Customise this generated block } @Override public CompletionStage<MarshallableEntry<K, V>> load(int segment, Object key) { /** * If the store provides the {@link NonBlockingStore.Characteristic.WRITE_ONLY} characteristic via a * {@link #characteristics()} implementation, then this can simply return null. */ return null; // TODO: Customise this generated block } @Override public CompletionStage<Void> write(int segment, MarshallableEntry<? extends K, ? extends V> entry) { /** * If the store provides the {@link NonBlockingStore.Characteristic.READ_ONLY} characteristic via a * {@link #characteristics()} implementation, then this can simply return null. */ return null; // TODO: Customise this generated block } @Override public CompletionStage<Boolean> delete(int segment, Object key) { /** * If the store provides the {@link NonBlockingStore.Characteristic.READ_ONLY} characteristic via a * {@link #characteristics()} implementation, then this can simply return null. */ return null; // TODO: Customise this generated block } @Override public CompletionStage<Void> clear() { /** * If the store provides the {@link NonBlockingStore.Characteristic.READ_ONLY} characteristic via a * {@link #characteristics()} implementation, then this can simply return null. */ return null; // TODO: Customise this generated block } @Override public Set<Characteristic> characteristics() { /** * If your store implementation wants to support one or more of the {@link NonBlockingStore.Characteristic}s, * then it's necessary to update this method to return a {@link Set} of the supported characteristics. * <p> * For example: * If your store is read-only, the following should be returned: * <code>return EnumSet.of(Characteristic.READ_ONLY);</code> * <p> * Conversely, if your store only accepts writes and is shareable, the following is required: * <code>return EnumSet.of(Characteristic.WRITE_ONLY, Characteristic.SHAREABLE);</code> */ return EnumSet.noneOf(Characteristic.class); } }
3,612
37.43617
123
java
null
infinispan-main/commons/spi/src/main/java/org/infinispan/commons/spi/ThreadCreator.java
package org.infinispan.commons.spi; /** * @since 15.0 **/ public interface ThreadCreator { Thread createThread(ThreadGroup threadGroup, Runnable target, boolean lightweight); }
183
19.444444
86
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/hash/MurmurHash3StringCompatTest.java
package org.infinispan.commons.hash; import java.util.Random; import org.junit.Assert; import org.junit.Test; /** * @author Dan Berindei * @since 9.0 */ public class MurmurHash3StringCompatTest { private static final long NUM_KEYS = 100000; private static final int MAX_KEY_SIZE = 5; @Test public void compareHashes() { Random random = new Random(9005); for (int i = 0; i < NUM_KEYS; i++) { int cpLen = Math.abs(random.nextInt(MAX_KEY_SIZE) - random.nextInt(MAX_KEY_SIZE)) + 1; int[] codePoints = random.ints(cpLen, 0, 0x110000).filter(Character::isDefined).toArray(); String s = new String(codePoints, 0, codePoints.length); testString(s); } } private void testString(String s) { int h1 = MurmurHash3Old.getInstance().hash(s); int h2 = MurmurHash3.getInstance().hash(s); Assert.assertEquals(h1, h2); } }
906
26.484848
99
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/hash/MurmurHash3Old.java
package org.infinispan.commons.hash; import java.io.ObjectInput; import java.nio.charset.StandardCharsets; import java.util.Set; import org.infinispan.commons.marshall.Ids; import org.infinispan.commons.marshall.exts.NoStateExternalizer; import org.infinispan.commons.util.Util; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; /** * MurmurHash3 implementation in Java, based on Austin Appleby's <a href= * "https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp" * >original in C</a> * * Only implementing x64 version, because this should always be faster on 64 bit * native processors, even 64 bit being ran with a 32 bit OS; this should also * be as fast or faster than the x86 version on some modern 32 bit processors. * * @author Patrick McFarland * @see <a href="http://sites.google.com/site/murmurhash/">MurmurHash website</a> * @see <a href="http://en.wikipedia.org/wiki/MurmurHash">MurmurHash entry on Wikipedia</a> */ @ThreadSafe @Immutable public class MurmurHash3Old implements Hash { private final static MurmurHash3Old instance = new MurmurHash3Old(); public static MurmurHash3Old getInstance() { return instance; } private MurmurHash3Old() { } static class State { long h1; long h2; long k1; long k2; long c1; long c2; } static long getblock(byte[] key, int i) { return ((key[i + 0] & 0x00000000000000FFL)) | ((key[i + 1] & 0x00000000000000FFL) << 8) | ((key[i + 2] & 0x00000000000000FFL) << 16) | ((key[i + 3] & 0x00000000000000FFL) << 24) | ((key[i + 4] & 0x00000000000000FFL) << 32) | ((key[i + 5] & 0x00000000000000FFL) << 40) | ((key[i + 6] & 0x00000000000000FFL) << 48) | ((key[i + 7] & 0x00000000000000FFL) << 56); } static void bmix(State state) { state.k1 *= state.c1; state.k1 = (state.k1 << 23) | (state.k1 >>> 64 - 23); state.k1 *= state.c2; state.h1 ^= state.k1; state.h1 += state.h2; state.h2 = (state.h2 << 41) | (state.h2 >>> 64 - 41); state.k2 *= state.c2; state.k2 = (state.k2 << 23) | (state.k2 >>> 64 - 23); state.k2 *= state.c1; state.h2 ^= state.k2; state.h2 += state.h1; state.h1 = state.h1 * 3 + 0x52dce729; state.h2 = state.h2 * 3 + 0x38495ab5; state.c1 = state.c1 * 5 + 0x7b7d159c; state.c2 = state.c2 * 5 + 0x6bce6396; } static long fmix(long k) { k ^= k >>> 33; k *= 0xff51afd7ed558ccdL; k ^= k >>> 33; k *= 0xc4ceb9fe1a85ec53L; k ^= k >>> 33; return k; } /** * Hash a value using the x64 128 bit variant of MurmurHash3 * * @param key value to hash * @param seed random value * @return 128 bit hashed key, in an array containing two longs */ public static long[] MurmurHash3_x64_128(final byte[] key, final int seed) { State state = new State(); state.h1 = 0x9368e53c2f6af274L ^ seed; state.h2 = 0x586dcd208f7cd3fdL ^ seed; state.c1 = 0x87c37b91114253d5L; state.c2 = 0x4cf5ad432745937fL; for (int i = 0; i < key.length / 16; i++) { state.k1 = getblock(key, i * 2 * 8); state.k2 = getblock(key, (i * 2 + 1) * 8); bmix(state); } state.k1 = 0; state.k2 = 0; int tail = (key.length >>> 4) << 4; switch (key.length & 15) { case 15: state.k2 ^= (long) key[tail + 14] << 48; case 14: state.k2 ^= (long) key[tail + 13] << 40; case 13: state.k2 ^= (long) key[tail + 12] << 32; case 12: state.k2 ^= (long) key[tail + 11] << 24; case 11: state.k2 ^= (long) key[tail + 10] << 16; case 10: state.k2 ^= (long) key[tail + 9] << 8; case 9: state.k2 ^= key[tail + 8]; case 8: state.k1 ^= (long) key[tail + 7] << 56; case 7: state.k1 ^= (long) key[tail + 6] << 48; case 6: state.k1 ^= (long) key[tail + 5] << 40; case 5: state.k1 ^= (long) key[tail + 4] << 32; case 4: state.k1 ^= (long) key[tail + 3] << 24; case 3: state.k1 ^= (long) key[tail + 2] << 16; case 2: state.k1 ^= (long) key[tail + 1] << 8; case 1: state.k1 ^= key[tail + 0]; bmix(state); } state.h2 ^= key.length; state.h1 += state.h2; state.h2 += state.h1; state.h1 = fmix(state.h1); state.h2 = fmix(state.h2); state.h1 += state.h2; state.h2 += state.h1; return new long[] { state.h1, state.h2 }; } /** * Hash a value using the x64 64 bit variant of MurmurHash3 * * @param key value to hash * @param seed random value * @return 64 bit hashed key */ public static long MurmurHash3_x64_64(final byte[] key, final int seed) { // Exactly the same as MurmurHash3_x64_128, except it only returns state.h1 State state = new State(); state.h1 = 0x9368e53c2f6af274L ^ seed; state.h2 = 0x586dcd208f7cd3fdL ^ seed; state.c1 = 0x87c37b91114253d5L; state.c2 = 0x4cf5ad432745937fL; for (int i = 0; i < key.length / 16; i++) { state.k1 = getblock(key, i * 2 * 8); state.k2 = getblock(key, (i * 2 + 1) * 8); bmix(state); } state.k1 = 0; state.k2 = 0; int tail = (key.length >>> 4) << 4; switch (key.length & 15) { case 15: state.k2 ^= (long) key[tail + 14] << 48; case 14: state.k2 ^= (long) key[tail + 13] << 40; case 13: state.k2 ^= (long) key[tail + 12] << 32; case 12: state.k2 ^= (long) key[tail + 11] << 24; case 11: state.k2 ^= (long) key[tail + 10] << 16; case 10: state.k2 ^= (long) key[tail + 9] << 8; case 9: state.k2 ^= key[tail + 8]; case 8: state.k1 ^= (long) key[tail + 7] << 56; case 7: state.k1 ^= (long) key[tail + 6] << 48; case 6: state.k1 ^= (long) key[tail + 5] << 40; case 5: state.k1 ^= (long) key[tail + 4] << 32; case 4: state.k1 ^= (long) key[tail + 3] << 24; case 3: state.k1 ^= (long) key[tail + 2] << 16; case 2: state.k1 ^= (long) key[tail + 1] << 8; case 1: state.k1 ^= key[tail + 0]; bmix(state); } state.h2 ^= key.length; state.h1 += state.h2; state.h2 += state.h1; state.h1 = fmix(state.h1); state.h2 = fmix(state.h2); state.h1 += state.h2; state.h2 += state.h1; return state.h1; } /** * Hash a value using the x64 32 bit variant of MurmurHash3 * * @param key value to hash * @param seed random value * @return 32 bit hashed key */ public static int MurmurHash3_x64_32(final byte[] key, final int seed) { return (int) (MurmurHash3_x64_64(key, seed) >>> 32); } /** * Hash a value using the x64 128 bit variant of MurmurHash3 * * @param key value to hash * @param seed random value * @return 128 bit hashed key, in an array containing two longs */ public static long[] MurmurHash3_x64_128(final long[] key, final int seed) { State state = new State(); state.h1 = 0x9368e53c2f6af274L ^ seed; state.h2 = 0x586dcd208f7cd3fdL ^ seed; state.c1 = 0x87c37b91114253d5L; state.c2 = 0x4cf5ad432745937fL; for (int i = 0; i < key.length / 2; i++) { state.k1 = key[i * 2]; state.k2 = key[i * 2 + 1]; bmix(state); } long tail = key[key.length - 1]; // Key length is odd if ((key.length & 1) == 1) { state.k1 ^= tail; bmix(state); } state.h2 ^= key.length * 8; state.h1 += state.h2; state.h2 += state.h1; state.h1 = fmix(state.h1); state.h2 = fmix(state.h2); state.h1 += state.h2; state.h2 += state.h1; return new long[] { state.h1, state.h2 }; } /** * Hash a value using the x64 64 bit variant of MurmurHash3 * * @param key value to hash * @param seed random value * @return 64 bit hashed key */ public static long MurmurHash3_x64_64(final long[] key, final int seed) { // Exactly the same as MurmurHash3_x64_128, except it only returns state.h1 State state = new State(); state.h1 = 0x9368e53c2f6af274L ^ seed; state.h2 = 0x586dcd208f7cd3fdL ^ seed; state.c1 = 0x87c37b91114253d5L; state.c2 = 0x4cf5ad432745937fL; for (int i = 0; i < key.length / 2; i++) { state.k1 = key[i * 2]; state.k2 = key[i * 2 + 1]; bmix(state); } long tail = key[key.length - 1]; if (key.length % 2 != 0) { state.k1 ^= tail; bmix(state); } state.h2 ^= key.length * 8; state.h1 += state.h2; state.h2 += state.h1; state.h1 = fmix(state.h1); state.h2 = fmix(state.h2); state.h1 += state.h2; state.h2 += state.h1; return state.h1; } /** * Hash a value using the x64 32 bit variant of MurmurHash3 * * @param key value to hash * @param seed random value * @return 32 bit hashed key */ public static int MurmurHash3_x64_32(final long[] key, final int seed) { return (int) (MurmurHash3_x64_64(key, seed) >>> 32); } @Override public int hash(byte[] payload) { return MurmurHash3_x64_32(payload, 9001); } /** * Hashes a byte array efficiently. * * @param payload a byte array to hash * @return a hash code for the byte array */ public static int hash(long[] payload) { return MurmurHash3_x64_32(payload, 9001); } @Override public int hash(int hashcode) { // Obtained by inlining MurmurHash3_x64_32(byte[], 9001) and removing all the unused code // (since we know the input is always 4 bytes and we only need 4 bytes of output) byte b0 = (byte) hashcode; byte b1 = (byte) (hashcode >>> 8); byte b2 = (byte) (hashcode >>> 16); byte b3 = (byte) (hashcode >>> 24); State state = new State(); state.h1 = 0x9368e53c2f6af274L ^ 9001; state.h2 = 0x586dcd208f7cd3fdL ^ 9001; state.c1 = 0x87c37b91114253d5L; state.c2 = 0x4cf5ad432745937fL; state.k1 = 0; state.k2 = 0; state.k1 ^= (long) b3 << 24; state.k1 ^= (long) b2 << 16; state.k1 ^= (long) b1 << 8; state.k1 ^= b0; bmix(state); state.h2 ^= 4; state.h1 += state.h2; state.h2 += state.h1; state.h1 = fmix(state.h1); state.h2 = fmix(state.h2); state.h1 += state.h2; state.h2 += state.h1; return (int) (state.h1 >>> 32); } @Override public int hash(Object o) { if (o instanceof byte[]) return hash((byte[]) o); else if (o instanceof long[]) return hash((long[]) o); else if (o instanceof String) return hash(((String) o).getBytes(StandardCharsets.UTF_8)); else return hash(o.hashCode()); } @Override public boolean equals(Object other) { return other != null && other.getClass() == getClass(); } @Override public int hashCode() { return 0; } @Override public String toString() { return "MurmurHash3"; } public static class Externalizer extends NoStateExternalizer<MurmurHash3Old> { @Override @SuppressWarnings("unchecked") public Set<Class<? extends MurmurHash3Old>> getTypeClasses() { return Util.asSet(MurmurHash3Old.class); } @Override public MurmurHash3Old readObject(ObjectInput input) { return instance; } @Override public Integer getId() { return Ids.MURMURHASH_3; } } }
11,775
26.386047
95
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/configuration/io/NamingStrategyTest.java
package org.infinispan.commons.configuration.io; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public class NamingStrategyTest { @Test public void testNamingStrategyConversion() { assertEquals("l1-lifespan", NamingStrategy.KEBAB_CASE.convert("l1Lifespan")); assertEquals("thisIsAnIdentifier", NamingStrategy.CAMEL_CASE.convert("this-is-an-identifier")); assertEquals("yet-another-identifier", NamingStrategy.KEBAB_CASE.convert("yetAnotherIdentifier")); assertEquals("sock_conn_timeout", NamingStrategy.SNAKE_CASE.convert("sockConnTimeout")); assertEquals("enabled-ciphersuites-tls13", NamingStrategy.KEBAB_CASE.convert("enabledCiphersuitesTls13")); } }
800
35.409091
112
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/configuration/io/yaml/YamlConfigurationReaderTest.java
package org.infinispan.commons.configuration.io.yaml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.commons.configuration.io.ConfigurationReaderException; import org.infinispan.commons.configuration.io.NamingStrategy; import org.infinispan.commons.configuration.io.PropertyReplacer; import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.Version; import org.junit.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public class YamlConfigurationReaderTest { public static final String DEFAULT_NAMESPACE = "urn:infinispan:config:" + Version.getSchemaVersion(); @Test public void testLine() { YamlConfigurationReader yaml = new YamlConfigurationReader(new StringReader(""), new URLConfigurationResourceResolver(null), new Properties(), PropertyReplacer.DEFAULT, NamingStrategy.KEBAB_CASE); YamlConfigurationReader.Parsed p = yaml.parseLine(" key: value"); assertEquals(4, p.indent); assertEquals("key", p.name); assertEquals("value", p.value); p = yaml.parseLine("'key': 'value'"); assertEquals(0, p.indent); assertEquals("key", p.name); assertEquals("value", p.value); p = yaml.parseLine(" key: value "); assertEquals(4, p.indent); assertEquals("key", p.name); assertEquals("value", p.value); p = yaml.parseLine(" key:"); assertEquals(2, p.indent); assertEquals("key", p.name); assertNull(p.value); p = yaml.parseLine(" key: # Comment"); assertEquals(2, p.indent); assertEquals("key", p.name); assertNull(p.value); p = yaml.parseLine(" key: value # Comment"); assertEquals(2, p.indent); assertEquals("key", p.name); assertEquals("value", p.value); p = yaml.parseLine(" # Comment"); assertEquals(2, p.indent); assertNull(p.name); assertNull(p.value); p = yaml.parseLine(" - value"); assertEquals(4, p.indent); assertTrue(p.list); assertNull(p.name); assertEquals("value", p.value); p = yaml.parseLine(" - key: value"); assertEquals(4, p.indent); assertTrue(p.list); assertEquals("key", p.name); assertEquals("value", p.value); // Test null values assertNull(yaml.parseLine("key: ~").value); assertNull(yaml.parseLine("key: {}").value); assertNull(yaml.parseLine("key: null").value); assertNull(yaml.parseLine("key: Null").value); assertNull(yaml.parseLine("key: NULL").value); assertEquals("null", yaml.parseLine("key: \"null\"").value); assertEquals("nullAndSome", yaml.parseLine("key: \"nullAndSome\"").value); assertEquals("Null", yaml.parseLine("key: \"Null\"").value); assertEquals("NULL", yaml.parseLine("key: \"NULL\"").value); assertEquals("NUll", yaml.parseLine("key: NUll").value); Exceptions.expectException(ConfigurationReaderException.class, () -> yaml.parseLine(" key # comment")); } @Test public void testYamlFile() throws IOException { URL url = YamlConfigurationReaderTest.class.getResource("/yaml.yaml"); try (Reader r = new InputStreamReader(url.openStream())) { Properties properties = new Properties(); properties.put("opinion", "YAML is awful"); properties.put("fact", "YAML is really awful"); YamlConfigurationReader yaml = new YamlConfigurationReader(r, new URLConfigurationResourceResolver(url), properties, PropertyReplacer.DEFAULT, NamingStrategy.KEBAB_CASE); yaml.require(ConfigurationReader.ElementType.START_DOCUMENT); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item1"); assertEquals(3, yaml.getAttributeCount()); assertAttribute(yaml, "item5", "v5"); assertAttribute(yaml, "item6", "v6"); assertAttribute(yaml, "item10", "some idiot thought this was a good idea"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item2"); assertEquals(4, yaml.getAttributeCount()); assertAttribute(yaml, "a", "1"); assertAttribute(yaml, "b", "2"); assertAttribute(yaml, "c", "3"); assertAttribute(yaml, "d", "4"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "camel-item3"); assertEquals("camel-attribute", yaml.getAttributeName(0)); assertEquals("YAML is awful", yaml.getAttributeValue(0)); assertEquals("another-camel-attribute", yaml.getAttributeName(1)); assertEquals("YAML is really awful", yaml.getAttributeValue(1)); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "camel-item3"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item2"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item7"); assertEquals("v7", yaml.getElementText()); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item7"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item7"); assertEquals("v8", yaml.getElementText()); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item7"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item8"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item8"); assertEquals(2, yaml.getAttributeCount()); assertAttribute(yaml, "a", "1"); assertAttribute(yaml, "b", "2"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item8"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item8"); assertEquals(2, yaml.getAttributeCount()); assertAttribute(yaml, "a", "3"); assertAttribute(yaml, "b", "4"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item8"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item8"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item9"); assertEquals(2, yaml.getAttributeCount()); assertAttribute(yaml, "a", "true"); assertAttribute(yaml, "b", "1 2 3 "); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "c"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "c"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item9"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item11"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item11"); assertEquals(1, yaml.getAttributeCount()); assertAttribute(yaml, "e", "3"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "a"); assertEquals(1, yaml.getAttributeCount()); assertAttribute(yaml, "b", "1"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "a"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "c"); assertEquals(1, yaml.getAttributeCount()); assertAttribute(yaml, "d", "2"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "c"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item11"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item11"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item1"); yaml.nextElement(); yaml.require(ConfigurationReader.ElementType.END_DOCUMENT); } } private void assertAttribute(YamlConfigurationReader yaml, String name, String value) { for (int i = 0; i < yaml.getAttributeCount(); i++) { if (name.equals(yaml.getAttributeName(i))) { assertEquals(value, yaml.getAttributeValue(i)); return; } } fail("Could not find attribute '" + name + " in element '" + yaml.getLocalName() + "'"); } @Test public void testYamlMapper() throws IOException { URL url = YamlConfigurationReaderTest.class.getResource("/identities.yaml"); try (Reader r = new InputStreamReader(url.openStream())) { YamlConfigurationReader yaml = new YamlConfigurationReader(r, new URLConfigurationResourceResolver(url), new Properties(), PropertyReplacer.DEFAULT, NamingStrategy.KEBAB_CASE); Map<String, Object> identities = yaml.asMap(); assertEquals(1, identities.size()); List<Object> credentials = (List<Object>) identities.get("credentials"); assertNotNull(credentials); assertEquals(3, credentials.size()); for (Object o : credentials) { Map<String, Object> credential = (Map<String, Object>) o; assertTrue(credential.containsKey("username")); assertTrue(credential.containsKey("password")); assertEquals("changeme", credential.get("password")); if ("my-user-1".equals(credential.get("username"))) { assertTrue(credential.containsKey("roles")); assertEquals(Collections.singletonList("admin"), credential.get("roles")); } else if ("my-user-2".equals(credential.get("username"))) { assertTrue(credential.containsKey("roles")); assertEquals(Arrays.asList("monitor", "writer"), credential.get("roles")); } else { assertEquals("admin", credential.get("username")); assertFalse(credential.containsKey("roles")); } } } } }
11,432
47.858974
202
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/configuration/io/json/JsonConfigurationReaderTest.java
package org.infinispan.commons.configuration.io.json; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; import org.infinispan.commons.configuration.io.ConfigurationReader; import org.infinispan.commons.configuration.io.Location; import org.infinispan.commons.configuration.io.NamingStrategy; import org.infinispan.commons.configuration.io.PropertyReplacer; import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver; import org.infinispan.commons.util.Version; import org.junit.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ public class JsonConfigurationReaderTest { public static final String DEFAULT_NAMESPACE = "urn:infinispan:config:" + Version.getSchemaVersion(); @Test public void testJsonFile() throws IOException { try (BufferedReader r = new BufferedReader(new InputStreamReader(JsonConfigurationReaderTest.class.getResourceAsStream("/json.json")))) { Properties properties = new Properties(); properties.put("opinion", "JSON is pretty nice"); properties.put("fact", "JSON is ok"); JsonConfigurationReader json = new JsonConfigurationReader(r, new URLConfigurationResourceResolver(null), properties, PropertyReplacer.DEFAULT, NamingStrategy.KEBAB_CASE); json.require(ConfigurationReader.ElementType.START_DOCUMENT); json.nextElement(); json.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item1"); assertLocation(json, 3, 5); assertEquals(3, json.getAttributeCount()); assertAttribute(json, "item5", "v5"); assertAttribute(json, "item6", "v6"); assertAttribute(json, "item7", new String[] {"v7", "v8"}); json.nextElement(); json.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "item2"); assertLocation(json, 4, 7); assertEquals(4, json.getAttributeCount()); assertAttribute(json, "a", "1"); assertAttribute(json, "b", "2"); assertAttribute(json, "c", "3"); assertAttribute(json, "d", "4"); json.nextElement(); json.require(ConfigurationReader.ElementType.START_ELEMENT, DEFAULT_NAMESPACE, "camel-item3"); assertLocation(json, 8, 9); assertEquals("camel-attribute", json.getAttributeName(0)); assertEquals(properties.getProperty("opinion"), json.getAttributeValue(0)); assertEquals("another-camel-attribute", json.getAttributeName(1)); assertEquals(properties.getProperty("fact"), json.getAttributeValue(1)); json.nextElement(); json.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "camel-item3"); json.nextElement(); json.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item2"); json.nextElement(); json.require(ConfigurationReader.ElementType.END_ELEMENT, DEFAULT_NAMESPACE, "item1"); json.nextElement(); json.require(ConfigurationReader.ElementType.END_DOCUMENT); } } private void assertLocation(JsonConfigurationReader json, int line, int col) { Location location = json.getLocation(); assertEquals("Line", line, location.getLineNumber()); assertEquals("Column", col, location.getColumnNumber()); System.out.println(location); } private void assertAttribute(JsonConfigurationReader json, String name, String value) { for (int i = 0; i < json.getAttributeCount(); i++) { if (name.equals(json.getAttributeName(i))) { assertEquals(value, json.getAttributeValue(i)); return; } } fail("Could not find attribute '" + name + " in element '" + json.getLocalName() + "'"); } private void assertAttribute(JsonConfigurationReader json, String name, String value[]) { for (int i = 0; i < json.getAttributeCount(); i++) { if (name.equals(json.getAttributeName(i))) { assertArrayEquals(value, json.getListAttributeValue(i)); return; } } fail("Could not find attribute '" + name + " in element '" + json.getLocalName() + "'"); } }
4,406
45.389474
180
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/configuration/io/json/JsonConfigurationWriterTest.java
package org.infinispan.commons.configuration.io.json; import static org.junit.Assert.assertEquals; import java.io.StringWriter; import org.junit.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ public class JsonConfigurationWriterTest { @Test public void testWriteJson() { StringWriter sw = new StringWriter(); JsonConfigurationWriter w = new JsonConfigurationWriter(sw, false, false); w.writeStartDocument(); w.writeStartElement("e1"); w.writeAttribute("a1", "v1"); w.writeAttribute("a2", "v2"); w.writeEndElement(); // e1 w.writeStartListElement("e2", true); w.writeStartElement("e2"); w.writeAttribute("a3", "v3"); w.writeAttribute("a4", "v4"); w.writeEndElement(); w.writeStartElement("e2"); w.writeAttribute("a3", "v3"); w.writeAttribute("a4", "v4"); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.close(); String json = sw.toString(); assertEquals("{\"e1\":{\"a1\":\"v1\",\"a2\":\"v2\"},\"e2\":[{\"a3\":\"v3\",\"a4\":\"v4\"},{\"a3\":\"v3\",\"a4\":\"v4\"}]}", json); } }
1,174
28.375
136
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/configuration/attributes/AttributeTest.java
package org.infinispan.commons.configuration.attributes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.util.TypedProperties; import org.junit.Test; public class AttributeTest { @Test public void testAttributeDefinitionType() { AttributeDefinition<Long> def = AttributeDefinition.builder("long", 10l).build(); assertEquals(Long.class, def.getType()); AttributeDefinition<String> def2 = AttributeDefinition.builder("string", null, String.class).build(); assertEquals(String.class, def2.getType()); } @Test public void testAttributeSetProtection() { AttributeDefinition<String> immutable = AttributeDefinition.builder("immutable", "").immutable().build(); AttributeDefinition<String> mutable = AttributeDefinition.builder("mutable", "").build(); AttributeSet set = new AttributeSet(getClass(), immutable, mutable); set.attribute(immutable).set("an immutable string"); set.attribute(mutable).set("a mutable string"); set = set.protect(); try { set.attribute(immutable).set("this should fail"); fail("Changing an immutable attribute on a protected set should fail"); } catch (Exception e) { // Expected } set.attribute(mutable).set("this should work"); } @Test public void testAttributeChanges() { AttributeDefinition<Boolean> def = AttributeDefinition.builder("test", false).build(); Attribute<Boolean> attribute = def.toAttribute(); assertFalse(attribute.isModified()); attribute.set(true); assertEquals(true, attribute.get()); assertTrue(attribute.isModified()); } @Test public void testAttributeInitializer() { AttributeDefinition<Properties> def = AttributeDefinition.builder("props", null, Properties.class).initializer(Properties::new).build(); Attribute<Properties> attribute1 = def.toAttribute(); Attribute<Properties> attribute2 = def.toAttribute(); assertNotSame(attribute1.get(), attribute2.get()); } @Test public void testDefaultAttributeCopy() { AttributeDefinition<Boolean> def = AttributeDefinition.builder("test", false).build(); AttributeSet set1 = new AttributeSet("set", def); set1.attribute(def).set(true); AttributeSet set2 = new AttributeSet("set", def); set2.read(set1, Combine.DEFAULT); assertEquals(set1.attribute(def).get(), set2.attribute(def).get()); } @Test public void testAttributeOverride() { AttributeDefinition<Boolean> one = AttributeDefinition.builder("one", false).build(); AttributeDefinition<Boolean> two = AttributeDefinition.builder("two", false).build(); AttributeSet set1 = new AttributeSet("set", one, two); set1.attribute(one).set(true); AttributeSet set2 = new AttributeSet("set", one, two); set2.attribute(two).set(true); set2.read(set1, new Combine(Combine.RepeatedAttributes.OVERRIDE, Combine.Attributes.OVERRIDE)); assertEquals(set1.attribute(one).get(), set2.attribute(one).get()); assertFalse(set2.attribute(two).isModified()); } @Test public void testCollectionAttributeCopy() { AttributeDefinition<TypedProperties> def = AttributeDefinition.builder("properties", null, TypedProperties.class).copier(TypedPropertiesAttributeCopier.INSTANCE).initializer(TypedProperties::new).build(); AttributeSet set1 = new AttributeSet("set", def); TypedProperties typedProperties = set1.attribute(def).get(); typedProperties.setProperty("key", "value"); set1.attribute(def).set(typedProperties); set1 = set1.protect(); typedProperties = set1.attribute(def).get(); typedProperties.setProperty("key", "anotherValue"); AttributeSet set2 = new AttributeSet("set", def); set2.read(set1, Combine.DEFAULT); } @Test public void testCustomAttributeCopier() { AttributeDefinition<List<String>> def = AttributeDefinition.builder("test", Arrays.asList("a", "b")).copier(attribute -> { if (attribute == null) return null; else return new ArrayList<>(attribute); }).build(); AttributeSet set1 = new AttributeSet("set", def); set1.attribute(def).set(Arrays.asList("b", "a")); AttributeSet set2 = new AttributeSet("set", def); set2.read(set1, Combine.DEFAULT); assertEquals(set1.attribute(def).get(), set2.attribute(def).get()); assertFalse(set1.attribute(def).get() == set2.attribute(def).get()); } @Test public void testAttributeListener() { AttributeDefinition<Boolean> def = AttributeDefinition.builder("test", false).build(); Attribute<Boolean> attribute = def.toAttribute(); final Holder<Boolean> listenerInvoked = new Holder<>(false); attribute.addListener((attribute1, oldValue) -> { assertTrue(attribute1.get()); assertFalse(oldValue); listenerInvoked.set(true); }); attribute.set(true); assertTrue("Attribute listener was not invoked", listenerInvoked.get()); } @Test public void testAttributeSetMatches() { AttributeDefinition<String> local = AttributeDefinition.builder("local", "").global(false).build(); AttributeDefinition<String> global = AttributeDefinition.builder("global", "").build(); AttributeSet setA = new AttributeSet(getClass(), local, global); AttributeSet setB = new AttributeSet(getClass(), local, global); setA.attribute("local").set("A"); setA.attribute("global").set("A"); setB.attribute("local").set("B"); setB.attribute("global").set("A"); assertTrue(setA.matches(setB)); assertNotEquals(setA, setB); setB.attribute("global").set("B"); assertFalse(setA.matches(setB)); assertNotEquals(setA, setB); setA = new AttributeSet(getClass(), local); setB = new AttributeSet(getClass(), local, global); setA.attribute("local").set("A"); setB.attribute("local").set("A"); setB.attribute("global").set("A"); assertFalse(setA.matches(setB)); assertNotEquals(setA, setB); AttributeDefinition<String> global2 = AttributeDefinition.builder("global2", "").build(); setA = new AttributeSet(getClass(), local, global); setB = new AttributeSet(getClass(), local, global2); setA.attribute("local").set("A"); setA.attribute("global").set("A"); setB.attribute("local").set("A"); setB.attribute("global2").set("A"); assertFalse(setA.matches(setB)); assertNotEquals(setA, setB); } static class Holder<T> { T object; Holder(T object) { this.object = object; } Holder() { this.object = null; } T get() { return object; } void set(T object) { this.object = object; } } }
7,264
37.850267
210
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/io/SignedNumericTest.java
package org.infinispan.commons.io; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; /** * @author gustavonalle * @since 8.0 */ public class SignedNumericTest { @Test public void testEncodeDecode() throws Exception { encodeDecode(-Integer.MAX_VALUE, 5); encodeDecode(-2500000, 4); encodeDecode(-15000, 3); encodeDecode(-100, 2); encodeDecode(-1, 1); encodeDecode(0, 1); encodeDecode(1, 1); encodeDecode(60, 1); encodeDecode(128, 2); encodeDecode(1300, 2); encodeDecode(15000, 3); encodeDecode(2500000, 4); encodeDecode(Integer.MAX_VALUE - 1, 5); } private void encodeDecode(int value, int expectedSize) throws IOException { try (ByteArrayOutputStream os = new ByteArrayOutputStream(5)) { SignedNumeric.writeSignedInt(os, value); byte[] bytes = os.toByteArray(); try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) { int read = SignedNumeric.readSignedInt(is); assertEquals(read, value); } assertEquals(bytes.length, expectedSize); } } }
1,254
25.702128
78
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/HashMapTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import org.junit.Test; public class HashMapTest { @Test public void testCreateHopscotch() { testCreate(new HopscotchHashMap<>(32)); } @Test public void testCreateHopscotchWithRemovals() { testCreateWithRemovals(new HopscotchHashMap<>(32)); } private void testCreate(Map<Integer, Integer> testedMap) { HashMap<Integer, Integer> map = new HashMap<>(); ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 0; i < 10000; ++i) { Integer key; do { key = random.nextInt(); } while (map.containsKey(key)); Integer value = random.nextInt(); testedMap.put(key, value); assertEquals("Contents differs with " + (i + 1) + " entries", value, testedMap.get(key)); assertEquals(i + 1, testedMap.size()); map.put(key, value); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { Integer actual = testedMap.get(entry.getKey()); assertEquals(entry.getValue(), actual); } } assertEquals(map, testedMap); // test re-inserts for (Map.Entry<Integer, Integer> entry : map.entrySet()) { testedMap.put(entry.getKey(), entry.getValue()); assertEquals(map.size(), testedMap.size()); } assertEquals(map, testedMap); } private void testCreateWithRemovals(Map<Integer, Integer> testedMap) { HashMap<Integer, Integer> map = new HashMap<>(); ThreadLocalRandom random = ThreadLocalRandom.current(); int[] keys = new int[10000]; Arrays.fill(keys, -1); for (int i = 0; i < 10000; ++i) { if (map.size() > 0 && random.nextInt(5) == 0) { int ki, key; do { key = keys[ki = random.nextInt(i)]; } while (key < 0); keys[ki] = -1; Integer value = map.remove(key); assertNotNull(value); Integer removed = testedMap.remove(key); assertEquals(value, removed); assertEquals(map.size(), testedMap.size()); } else { int key; do { key = Math.abs(random.nextInt()); } while (map.containsKey(key)); Integer value = random.nextInt(); keys[i] = key; testedMap.put(key, value); assertEquals("Contents differs with " + (i + 1) + " entries", value, testedMap.get(key)); map.put(key, value); assertEquals(map.size(), testedMap.size()); } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { assertEquals(entry.getValue(), testedMap.get(entry.getKey())); } } assertEquals(map, testedMap); } }
3,001
33.505747
101
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/SingletonIntSetTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.PrimitiveIterator; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.IntConsumer; import org.junit.Test; /** * @author wburns * @since 9.3 */ public class SingletonIntSetTest { @Test public void testSize() { IntSet rs = new SingletonIntSet(3); assertEquals(1, rs.size()); } @Test public void testIsEmpty() { IntSet rs = new SingletonIntSet(3); assertFalse(rs.isEmpty()); } @Test public void testContains() throws Exception { IntSet sis = new SingletonIntSet(3); assertFalse(sis.contains(5)); assertTrue(sis.contains(3)); } @Test public void testContains1() throws Exception { IntSet sis = new SingletonIntSet(3); assertFalse(sis.contains(Integer.valueOf(5))); assertTrue(sis.contains(Integer.valueOf(3))); } @Test public void testIterator() throws Exception { IntSet sis = new SingletonIntSet(3); PrimitiveIterator.OfInt iterator = sis.iterator(); assertEquals(3, iterator.nextInt()); assertFalse(iterator.hasNext()); } @Test public void testToArray() throws Exception { IntSet sis = new SingletonIntSet(3); Object[] array = sis.toArray(); assertEquals(1, array.length); assertEquals(3, array[0]); } @Test public void testToArray1() throws Exception { IntSet sis = new SingletonIntSet(3); Object[] array = sis.toArray(new Integer[1]); assertEquals(1, array.length); assertEquals(3, array[0]); } @Test public void testToIntArray() throws Exception { IntSet sis = new SingletonIntSet(3); int[] array = sis.toIntArray(); assertArrayEquals(new int[]{3}, array); } @Test(expected = UnsupportedOperationException.class) public void testAdd() throws Exception { IntSet sis = new SingletonIntSet(3); sis.add(1); } @Test(expected = UnsupportedOperationException.class) public void testAdd1() throws Exception { IntSet sis = new SingletonIntSet(3); sis.add(Integer.valueOf(1)); } @Test(expected = UnsupportedOperationException.class) public void testSet() throws Exception { IntSet sis = new SingletonIntSet(3); sis.set(1); } @Test(expected = UnsupportedOperationException.class) public void testRemove() throws Exception { IntSet sis = new SingletonIntSet(3); sis.remove(3); } @Test(expected = UnsupportedOperationException.class) public void testRemove1() throws Exception { IntSet sis = new SingletonIntSet(3); sis.remove(Integer.valueOf(3)); } @Test public void testContainsAll() throws Exception { IntSet sis = new SingletonIntSet(3); IntSet sis2 = new SingletonIntSet(3); assertTrue(sis.containsAll(sis2)); assertTrue(sis2.containsAll(sis)); IntSet sis3 = new RangeSet(4); assertTrue(sis3.containsAll(sis)); assertFalse(sis.containsAll(sis3)); } @Test public void testContainsAll1() throws Exception { IntSet sis = new SingletonIntSet(3); Set<Integer> hashSet = new HashSet<>(Arrays.asList(3)); assertTrue(sis.containsAll(hashSet)); assertTrue(hashSet.containsAll(sis)); hashSet.add(0); assertTrue(hashSet.containsAll(sis)); assertFalse(sis.containsAll(hashSet)); } @Test(expected = UnsupportedOperationException.class) public void testAddAll() throws Exception { IntSet sis = new SingletonIntSet(3); IntSet rs = new RangeSet(5); sis.addAll(rs); } @Test(expected = UnsupportedOperationException.class) public void testAddAll1() throws Exception { IntSet sis = new SingletonIntSet(3); SmallIntSet sis2 = new SmallIntSet(); sis.addAll(sis2); } @Test(expected = UnsupportedOperationException.class) public void testAddAll2() throws Exception { Set<Integer> hashSet = Util.asSet(1, 4); IntSet sis = new SingletonIntSet(3); sis.addAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAll() throws Exception { IntSet sis = new SingletonIntSet(3); IntSet rs = new RangeSet(6); sis.removeAll(rs); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAll1() throws Exception { IntSet sis = new SingletonIntSet(3); Set<Integer> hashSet = new HashSet<>(); sis.removeAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void testRetainAll() throws Exception { IntSet sis = new SingletonIntSet(3); IntSet rs = new RangeSet(5); sis.retainAll(rs); } @Test(expected = UnsupportedOperationException.class) public void testRetainAll1() throws Exception { IntSet sis = new SingletonIntSet(3); IntSet sis2 = new SingletonIntSet(3); sis.retainAll(sis2); } @Test(expected = UnsupportedOperationException.class) public void testRetainAll2() throws Exception { IntSet sis = new SingletonIntSet(3); Set<Integer> hashSet = new HashSet<>(); sis.retainAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void testClear() throws Exception { IntSet sis = new SingletonIntSet(3); sis.clear(); } @Test public void testIntStream() throws Exception { IntSet sis = new SingletonIntSet(3); assertEquals(1, sis.intStream().count()); } @Test public void testEquals() throws Exception { IntSet sis = new SingletonIntSet(3); IntSet sis2 = new SingletonIntSet(4); // Verify equals both ways assertNotEquals(sis, sis2); assertNotEquals(sis2, sis); IntSet sis3 = SmallIntSet.of(3); assertEquals(sis3, sis); assertEquals(sis, sis3); } @Test public void testEquals1() throws Exception { IntSet sis = new SingletonIntSet(3); SmallIntSet sis2 = new SmallIntSet(); sis2.add(2); sis2.add(3); // Verify equals both ways assertNotEquals(sis, sis2); assertNotEquals(sis2, sis); sis2.remove(2); assertEquals(sis, sis2); assertEquals(sis2, sis); } @Test public void testEquals2() throws Exception { IntSet sis = new SingletonIntSet(3); Set<Integer> hashSet = new HashSet<>(); hashSet.add(2); hashSet.add(3); // Verify equals both ways assertNotEquals(sis, hashSet); assertNotEquals(hashSet, sis); hashSet.remove(2); assertEquals(sis, hashSet); assertEquals(hashSet, sis); } @Test public void testForEachPrimitive() { IntSet sis = new SingletonIntSet(3); Set<Integer> results = new HashSet<>(); sis.forEach((IntConsumer) results::add); assertEquals(1, results.size()); assertTrue(results.contains(3)); } @Test public void testForEachObject() { IntSet sis = new SingletonIntSet(3); Set<Integer> results = new HashSet<>(); sis.forEach((Consumer<? super Integer>) results::add); assertEquals(1, results.size()); assertTrue(results.contains(3)); } @Test(expected = UnsupportedOperationException.class) public void testRemoveIfPrimitive() { IntSet sis = new SingletonIntSet(3); sis.removeIf((int i) -> i == 3); } @Test(expected = UnsupportedOperationException.class) public void testRemoveIfObject() { IntSet sis = new SingletonIntSet(3); sis.removeIf((Integer i) -> i == 3); } @Test public void testIntSpliteratorForEachRemaining() { IntSet sis = new SingletonIntSet(3); Set<Integer> results = new HashSet<>(); sis.intSpliterator().forEachRemaining((IntConsumer) results::add); assertEquals(1, results.size()); assertTrue(results.contains(3)); } @Test public void testIntSpliteratorSplitTryAdvance() { IntSet sis = new SingletonIntSet(3); Set<Integer> results = new HashSet<>(); Spliterator.OfInt spliterator = sis.intSpliterator(); Spliterator.OfInt split = spliterator.trySplit(); assertNull(split); IntConsumer consumer = results::add; while (spliterator.tryAdvance(consumer)) { } assertEquals(1, results.size()); assertTrue(results.contains(3)); } @Test public void testToBitSet() { testToArray(0); testToArray(12); testToArray(16); testToArray(43); testToArray(5); } private void testToArray(int bitToSet) { BitSet bitSet = new BitSet(); bitSet.set(bitToSet); IntSet sis = new SingletonIntSet(bitToSet); assertArrayEquals(bitSet.toByteArray(), sis.toBitSet()); } }
9,153
24.287293
72
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/MyBrokenSampleSPI.java
package org.infinispan.commons.util; public class MyBrokenSampleSPI implements SampleSPI { public MyBrokenSampleSPI() { throw new RuntimeException("I am broken"); } }
180
21.625
53
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/FeaturesTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class FeaturesTest { @Test public void testFeatures() { Features features = new Features(); assertFalse(features.isAvailable("A")); assertTrue(features.isAvailable("B")); } @Test public void featureSysOverride() { Features features = new Features(); assertFalse(features.isAvailable("A")); System.setProperty("org.infinispan.feature.A", "true"); System.setProperty("org.infinispan.feature.B", "false"); boolean a = features.isAvailable("A"); boolean b = features.isAvailable("B"); System.clearProperty("org.infinispan.feature.A"); System.clearProperty("org.infinispan.feature.B"); assertTrue(a); assertFalse(b); } }
871
27.129032
62
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/CallerIdTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import org.infinispan.commons.jdkspecific.CallerId; import org.infinispan.commons.test.categories.Java11; import org.junit.Test; import org.junit.experimental.categories.Category; public class CallerIdTest { @Test @Category(Java11.class) public void testCaller() { assertEquals(this.getClass(), CallerId.getCallerClass(1)); } }
432
23.055556
64
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/MarshallUtilTest.java
package org.infinispan.commons.util; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.UUID; import org.infinispan.commons.marshall.MarshallUtil; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link org.infinispan.commons.marshall.MarshallUtil} * * @author Pedro Ruivo * @since 8.2 */ public class MarshallUtilTest { private static final int NR_RANDOM = 1000; private static void positiveRange(int min, int max, int bytesExpected, ObjectInputOutput io) throws IOException { for (int i = min; i > 0 && i < max; i <<= 1) { checkIntAndByteArray(i, bytesExpected, io); } } private static void checkIntAndByteArray(int i, int bytesExpected, ObjectInputOutput io) throws IOException { io.reset(); MarshallUtil.marshallSize(io, i); Assert.assertEquals("Error for i=" + i, bytesExpected, io.buffer.size()); Assert.assertEquals("Error for i=" + i, i, MarshallUtil.unmarshallSize(io)); Assert.assertEquals("Error for i=" + i, 0, io.buffer.size()); } private static void checkNegativeInt(int i, ObjectInputOutput io) throws IOException { io.reset(); MarshallUtil.marshallSize(io, i); Assert.assertEquals("Error for i=" + i, 1, io.buffer.size()); Assert.assertEquals("Error for i=" + i, -1, MarshallUtil.unmarshallSize(io)); Assert.assertEquals("Error for i=" + i, 0, io.buffer.size()); } @Test public void testPositiveRange() throws IOException { ObjectInputOutput io = new ObjectInputOutput(); checkIntAndByteArray(0, 1, io); //zero positiveRange(1, 1 << 6, 1, io); positiveRange(1 << 6, 1 << 13, 2, io); positiveRange(1 << 13, 1 << 20, 3, io); positiveRange(1 << 20, 1 << 27, 4, io); positiveRange(1 << 27, Integer.MAX_VALUE, 5, io); checkIntAndByteArray(Integer.MAX_VALUE, 5, io); } @Test public void testNegativeRange() throws IOException { ObjectInputOutput io = new ObjectInputOutput(); for (int i = 1; i < Integer.MAX_VALUE; i <<= 1) { int v = -i; if (v >= 0) { break; } checkNegativeInt(v, io); } checkNegativeInt(Integer.MIN_VALUE, io); } @Test public void testRandomPositiveInt() throws IOException { Random random = new Random(System.nanoTime()); ObjectInputOutput io = new ObjectInputOutput(); for (int i = 0; i < NR_RANDOM; ++i) { int v = random.nextInt(); if (v < 0) { v = -v; } io.reset(); MarshallUtil.marshallSize(io, v); Assert.assertEquals("Error for v=" + v, v, MarshallUtil.unmarshallSize(io)); } } @Test public void testRandomNegativeInt() throws IOException { Random random = new Random(System.nanoTime()); ObjectInputOutput io = new ObjectInputOutput(); for (int i = 0; i < NR_RANDOM; ++i) { int v = random.nextInt(); if (v > 0) { v = -v; } else if (v == 0) { i--; continue; } io.reset(); MarshallUtil.marshallSize(io, v); Assert.assertEquals("Error for v=" + v, -1, MarshallUtil.unmarshallSize(io)); } } @Test public void testEnum() throws IOException { ObjectInputOutput io = new ObjectInputOutput(); MarshallUtil.marshallEnum(null, io); Assert.assertNull(MarshallUtil.unmarshallEnum(io, ordinal -> TestEnum.values()[ordinal])); Assert.assertEquals(0, io.buffer.size()); for (TestEnum e : TestEnum.values()) { io.reset(); MarshallUtil.marshallEnum(e, io); Assert.assertEquals(e, MarshallUtil.unmarshallEnum(io, ordinal -> TestEnum.values()[ordinal])); Assert.assertEquals(0, io.buffer.size()); } } @Test public void testUUID() throws IOException { ObjectInputOutput io = new ObjectInputOutput(); MarshallUtil.marshallUUID(null, io, true); Assert.assertNull(MarshallUtil.unmarshallUUID(io, true)); Assert.assertEquals(0, io.buffer.size()); for (int i = 0; i < NR_RANDOM; ++i) { io.reset(); UUID uuid = Util.threadLocalRandomUUID(); MarshallUtil.marshallUUID(uuid, io, false); Assert.assertEquals(uuid, MarshallUtil.unmarshallUUID(io, false)); Assert.assertEquals(0, io.buffer.size()); } for (int i = 0; i < NR_RANDOM; ++i) { io.reset(); UUID uuid = Util.threadLocalRandomUUID(); MarshallUtil.marshallUUID(uuid, io, true); Assert.assertEquals(uuid, MarshallUtil.unmarshallUUID(io, true)); Assert.assertEquals(0, io.buffer.size()); } } @Test public void testArray() throws IOException, ClassNotFoundException { ObjectInputOutput io = new ObjectInputOutput(); MarshallUtil.marshallArray(null, io); Assert.assertNull(MarshallUtil.unmarshallArray(io, null)); Assert.assertEquals(0, io.buffer.size()); io.reset(); String[] array = new String[0]; MarshallUtil.marshallArray(array, io); Assert.assertTrue(Arrays.equals(array, MarshallUtil.unmarshallArray(io, Util::stringArray))); Assert.assertEquals(0, io.buffer.size()); io.reset(); array = new String[] {"a", "b", "c"}; MarshallUtil.marshallArray(array, io); Assert.assertTrue(Arrays.equals(array, MarshallUtil.unmarshallArray(io, Util::stringArray))); Assert.assertEquals(0, io.buffer.size()); io.reset(); } @Test public void testByteArray() throws IOException, ClassNotFoundException { ObjectInputOutput io = new ObjectInputOutput(); MarshallUtil.marshallByteArray(null, io); Assert.assertNull(MarshallUtil.unmarshallByteArray(io)); Assert.assertEquals(0, io.buffer.size()); io.reset(); byte[] array = Util.EMPTY_BYTE_ARRAY; MarshallUtil.marshallByteArray(array, io); Assert.assertTrue(Arrays.equals(array, MarshallUtil.unmarshallByteArray(io))); Assert.assertEquals(0, io.buffer.size()); io.reset(); array = new byte[] {1, 2, 3}; MarshallUtil.marshallByteArray(array, io); Assert.assertTrue(Arrays.equals(array, MarshallUtil.unmarshallByteArray(io))); Assert.assertEquals(0, io.buffer.size()); io.reset(); } private enum TestEnum { ONE, TWO, THREE } private static class ObjectInputOutput implements ObjectOutput, ObjectInput { private final Queue<Object> buffer = new LinkedList<>(); @Override public void writeByte(int v) throws IOException { buffer.add((byte) v); } @Override public void writeShort(int v) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeChar(int v) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeInt(int v) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeLong(long v) throws IOException { buffer.add(v); } @Override public void writeFloat(float v) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeDouble(double v) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeBytes(String s) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeChars(String s) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeUTF(String s) throws IOException { throw new UnsupportedOperationException(); } public void reset() { buffer.clear(); } @Override public Object readObject() throws ClassNotFoundException, IOException { return buffer.poll(); } @Override public int read() throws IOException { throw new UnsupportedOperationException(); } @Override public int read(byte[] b) throws IOException { throw new UnsupportedOperationException(); } @Override public int read(byte[] b, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public long skip(long n) throws IOException { throw new UnsupportedOperationException(); } @Override public int available() throws IOException { throw new UnsupportedOperationException(); } @Override public void readFully(byte[] b) throws IOException { byte[] array = (byte[]) buffer.poll(); Assert.assertEquals(array.length, b.length); System.arraycopy(array, 0, b, 0, b.length); } @Override public void readFully(byte[] b, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public int skipBytes(int n) throws IOException { throw new UnsupportedOperationException(); } @Override public boolean readBoolean() throws IOException { return (boolean) buffer.poll(); } @Override public byte readByte() throws IOException { return (byte) buffer.poll(); } @Override public int readUnsignedByte() throws IOException { throw new UnsupportedOperationException(); } @Override public short readShort() throws IOException { throw new UnsupportedOperationException(); } @Override public int readUnsignedShort() throws IOException { throw new UnsupportedOperationException(); } @Override public char readChar() throws IOException { throw new UnsupportedOperationException(); } @Override public int readInt() throws IOException { throw new UnsupportedOperationException(); } @Override public long readLong() throws IOException { return (long) buffer.poll(); } @Override public float readFloat() throws IOException { throw new UnsupportedOperationException(); } @Override public double readDouble() throws IOException { throw new UnsupportedOperationException(); } @Override public String readLine() throws IOException { throw new UnsupportedOperationException(); } @Override public String readUTF() throws IOException { throw new UnsupportedOperationException(); } @Override public void writeObject(Object obj) throws IOException { buffer.add(obj); } @Override public void write(int b) throws IOException { throw new UnsupportedOperationException(); } @Override public void write(byte[] b) throws IOException { buffer.add(b); } @Override public void write(byte[] b, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public void writeBoolean(boolean v) throws IOException { buffer.add(v); } @Override public void flush() throws IOException { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { throw new UnsupportedOperationException(); } } }
11,731
28.77665
116
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/RangeSetTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.BitSet; import java.util.HashSet; import java.util.PrimitiveIterator; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.IntConsumer; import org.junit.Test; /** * @author wburns * @since 9.0 */ public class RangeSetTest { @Test public void testSize() { RangeSet rs = new RangeSet(4); assertEquals(4, rs.size()); } @Test public void testIsEmpty() { RangeSet rs = new RangeSet(0); assertTrue(rs.isEmpty()); rs = new RangeSet(3); assertFalse(rs.isEmpty()); } @Test public void contains() throws Exception { RangeSet rs = new RangeSet(4); assertFalse(rs.contains(5)); assertTrue(rs.contains(1)); } @Test public void contains1() throws Exception { RangeSet rs = new RangeSet(4); assertFalse(rs.contains(Integer.valueOf(5))); assertTrue(rs.contains(Integer.valueOf(1))); } @Test public void iterator() throws Exception { RangeSet rs = new RangeSet(4); PrimitiveIterator.OfInt iterator = rs.iterator(); assertEquals(0, iterator.nextInt()); assertEquals(1, iterator.nextInt()); assertEquals(2, iterator.nextInt()); assertEquals(3, iterator.nextInt()); } @Test public void toArray() throws Exception { RangeSet rs = new RangeSet(4); Object[] array = rs.toArray(); assertEquals(4, array.length); assertEquals(0, array[0]); assertEquals(1, array[1]); assertEquals(2, array[2]); assertEquals(3, array[3]); } @Test public void toArray1() throws Exception { RangeSet rs = new RangeSet(4); Object[] array = rs.toArray(new Integer[4]); assertEquals(4, array.length); assertEquals(0, array[0]); assertEquals(1, array[1]); assertEquals(2, array[2]); assertEquals(3, array[3]); } @Test public void toIntArray() throws Exception { RangeSet rs = new RangeSet(4); int[] array = rs.toIntArray(); assertArrayEquals(new int[]{0, 1, 2, 3}, array); } @Test(expected = UnsupportedOperationException.class) public void add() throws Exception { RangeSet rs = new RangeSet(4); rs.add(1); } @Test(expected = UnsupportedOperationException.class) public void add1() throws Exception { RangeSet rs = new RangeSet(4); rs.add(Integer.valueOf(1)); } @Test(expected = UnsupportedOperationException.class) public void set() throws Exception { RangeSet rs = new RangeSet(4); rs.set(1); } @Test(expected = UnsupportedOperationException.class) public void remove() throws Exception { RangeSet rs = new RangeSet(4); rs.remove(1); } @Test(expected = UnsupportedOperationException.class) public void remove1() throws Exception { RangeSet rs = new RangeSet(4); rs.remove(Integer.valueOf(1)); } @Test public void containsAll() throws Exception { RangeSet rs = new RangeSet(4); RangeSet rs2 = new RangeSet(4); assertTrue(rs.containsAll(rs2)); RangeSet rs3 = new RangeSet(3); assertTrue(rs.containsAll(rs3)); assertFalse(rs3.containsAll(rs)); } @Test public void containsAll1() throws Exception { RangeSet rs = new RangeSet(5); Set<Integer> hashSet = new HashSet<>(); hashSet.add(1); hashSet.add(4); assertFalse(hashSet.containsAll(rs)); assertTrue(rs.containsAll(hashSet)); } @Test(expected = UnsupportedOperationException.class) public void addAll() throws Exception { RangeSet rs = new RangeSet(4); RangeSet rs2 = new RangeSet(5); rs.addAll(rs2); } @Test(expected = UnsupportedOperationException.class) public void addAll1() throws Exception { RangeSet rs = new RangeSet(4); SmallIntSet sis = new SmallIntSet(); rs.addAll(sis); } @Test(expected = UnsupportedOperationException.class) public void addAll2() throws Exception { Set<Integer> hashSet = new HashSet<>(); hashSet.add(1); hashSet.add(4); RangeSet rs = new RangeSet(4); rs.addAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void removeAll() throws Exception { RangeSet rs = new RangeSet(4); RangeSet rs2 = new RangeSet(6); rs.removeAll(rs2); } @Test(expected = UnsupportedOperationException.class) public void removeAll1() throws Exception { RangeSet rs = new RangeSet(5); SmallIntSet sis = new SmallIntSet(); rs.removeAll(sis); } @Test(expected = UnsupportedOperationException.class) public void removeAll2() throws Exception { RangeSet rs = new RangeSet(4); Set<Integer> hashSet = new HashSet<>(); rs.removeAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void retainAll() throws Exception { RangeSet rs = new RangeSet(4); RangeSet rs2 = new RangeSet(5); rs.retainAll(rs2); } @Test(expected = UnsupportedOperationException.class) public void retainAll1() throws Exception { IntSet rs = new RangeSet(5); SmallIntSet sis = new SmallIntSet(); rs.retainAll(sis); } @Test(expected = UnsupportedOperationException.class) public void retainAll2() throws Exception { RangeSet rs = new RangeSet(4); Set<Integer> hashSet = new HashSet<>(); rs.retainAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void clear() throws Exception { RangeSet rs = new RangeSet(5); rs.clear(); } @Test public void intStream() throws Exception { IntSet rs = new RangeSet(5); assertEquals(10, rs.intStream().sum()); } @Test public void equals() throws Exception { RangeSet rs = new RangeSet(4); RangeSet rs2 = new RangeSet(5); // Verify equals both ways assertNotEquals(rs, rs2); assertNotEquals(rs2, rs); RangeSet rs3 = new RangeSet(4); assertEquals(rs3, rs); assertEquals(rs, rs3); } @Test public void equals1() throws Exception { IntSet intSet = new RangeSet(4); SmallIntSet sis = new SmallIntSet(); sis.add(0); sis.add(1); sis.add(2); // Verify equals both ways assertNotEquals(sis, intSet); assertNotEquals(intSet, sis); sis.add(3); assertEquals(sis, intSet); assertEquals(intSet, sis); } @Test public void equals2() throws Exception { IntSet rs = new RangeSet(4); Set<Integer> hashSet = new HashSet<>(); hashSet.add(0); hashSet.add(1); hashSet.add(2); // Verify equals both ways assertNotEquals(rs, hashSet); assertNotEquals(hashSet, rs); hashSet.add(3); assertEquals(rs, hashSet); assertEquals(hashSet, rs); } @Test public void forEachPrimitive() { IntSet rs = new RangeSet(4); Set<Integer> results = new HashSet<>(); rs.forEach((IntConsumer) results::add); assertEquals(4, results.size()); assertTrue(results.contains(0)); assertTrue(results.contains(1)); assertTrue(results.contains(2)); assertTrue(results.contains(3)); } @Test public void forEachObject() { IntSet rs = new RangeSet(4); Set<Integer> results = new HashSet<>(); rs.forEach((Consumer<? super Integer>) results::add); assertEquals(4, results.size()); assertTrue(results.contains(0)); assertTrue(results.contains(1)); assertTrue(results.contains(2)); assertTrue(results.contains(3)); } @Test(expected = UnsupportedOperationException.class) public void removeIfPrimitive() { RangeSet rs = new RangeSet(4); rs.removeIf((int i) -> i == 3); } @Test(expected = UnsupportedOperationException.class) public void removeIfObject() { RangeSet rs = new RangeSet(4); rs.removeIf((Integer i) -> i == 3); } @Test public void intSpliteratorForEachRemaining() { IntSet rs = new RangeSet(4); Set<Integer> results = new HashSet<>(); rs.intSpliterator().forEachRemaining((IntConsumer) results::add); assertEquals(4, results.size()); assertTrue(results.contains(0)); assertTrue(results.contains(1)); assertTrue(results.contains(2)); assertTrue(results.contains(3)); } @Test public void intSpliteratorSplitTryAdvance() { IntSet rs = new RangeSet(4); Set<Integer> results = new HashSet<>(); Spliterator.OfInt spliterator = rs.intSpliterator(); Spliterator.OfInt split = spliterator.trySplit(); assertNotNull(split); IntConsumer consumer = results::add; while (spliterator.tryAdvance(consumer)) { } while (split.tryAdvance(consumer)) { } assertEquals(4, results.size()); assertTrue(results.contains(0)); assertTrue(results.contains(1)); assertTrue(results.contains(2)); assertTrue(results.contains(3)); } @Test public void testToBitSet() { testToArray(13); testToArray(12); testToArray(0); testToArray(16); testToArray(43); testToArray(5); } private void testToArray(int bitToSet) { BitSet bitSet = new BitSet(); for (int i = 0; i < bitToSet; ++i) { bitSet.set(i); } IntSet sis = new RangeSet(bitToSet); assertArrayEquals(bitSet.toByteArray(), sis.toBitSet()); } }
9,839
23.723618
71
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/MutableIntSetTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.HashSet; import java.util.PrimitiveIterator; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.IntConsumer; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * @author wburns * @since 9.0 */ @RunWith(Parameterized.class) public class MutableIntSetTest { @Parameterized.Parameters public static Object[] data() { return new Object[] { new SmallIntSet(), new ConcurrentSmallIntSet(64), }; } @Parameterized.Parameter public IntSet intSet; @After public void after() { intSet.clear(); } @Test public void testSize() { intSet.add(1); intSet.add(4); assertEquals(2, intSet.size()); intSet.add(4); assertEquals(2, intSet.size()); } @Test public void testIsEmpty() { assertTrue(intSet.isEmpty()); intSet.add(1); intSet.add(4); assertFalse(intSet.isEmpty()); } @Test public void testContains() throws Exception { assertFalse(intSet.contains(1)); intSet.add(1); assertTrue(intSet.contains(1)); assertFalse(intSet.contains(1832131)); } @Test public void testContains1() throws Exception { Integer intValue = 1; assertFalse(intSet.contains(intValue)); intSet.add(1); assertTrue(intSet.contains(intValue)); assertFalse(intSet.contains(1832131)); } @Test public void testIterator() throws Exception { intSet.add(1); intSet.add(4); PrimitiveIterator.OfInt iterator = intSet.iterator(); assertEquals(1, iterator.nextInt()); assertEquals(4, iterator.nextInt()); } @Test public void testToIntArray() throws Exception { intSet.add(1); intSet.add(4); int[] array = intSet.toIntArray(); assertArrayEquals(new int[]{1, 4}, array); } @Test public void testToIntArray64() throws Exception { addRange64(); int[] array = intSet.toIntArray(); assertArrayEquals(new RangeSet(64).toIntArray(), array); } @Test public void testToArray() throws Exception { intSet.add(1); intSet.add(4); Object[] array = intSet.toArray(); assertArrayEquals(new Object[]{1, 4}, array); } @Test public void testToArray1() throws Exception { intSet.add(1); intSet.add(4); Integer[] array = intSet.toArray(new Integer[2]); assertArrayEquals(new Integer[]{1, 4}, array); } @Test public void testAdd() throws Exception { assertTrue(intSet.add(1)); assertFalse(intSet.add(1)); } @Test public void testAdd1() throws Exception { assertTrue(intSet.add(Integer.valueOf(1))); assertFalse(intSet.add(Integer.valueOf(1))); } @Test public void testSet() throws Exception { intSet.set(1); assertTrue(intSet.contains(1)); } @Test public void testRemove() throws Exception { assertFalse(intSet.remove(1)); intSet.add(1); assertTrue(intSet.remove(1)); } @Test public void testRemove1() throws Exception { assertFalse(intSet.remove(Integer.valueOf(1))); intSet.add(1); assertTrue(intSet.remove(Integer.valueOf(1))); } @Test public void testContainsAll() throws Exception { IntSet intSet2 = new SmallIntSet(); intSet.add(1); intSet.add(4); intSet2.add(1); intSet2.add(4); intSet2.add(7); assertFalse(intSet.containsAll(intSet2)); assertTrue(intSet2.containsAll(intSet)); } @Test public void testContainsAll1() throws Exception { intSet.add(1); intSet.add(4); Set<Integer> set = Util.asSet(1, 4, 7); assertFalse(intSet.containsAll(set)); assertTrue(set.containsAll(intSet)); } @Test public void testAddAll() throws Exception { intSet.add(1); intSet.add(4); IntSet intSet2 = new SmallIntSet(); intSet2.addAll(intSet); assertEquals(2, intSet2.size()); } @Test public void testAddAll1() throws Exception { IntSet rangeSet = new RangeSet(4); intSet.addAll(rangeSet); assertEquals(4, intSet.size()); } @Test public void testAddAll2() throws Exception { intSet.addAll(Util.asSet(1, 4)); assertEquals(2, intSet.size()); } @Test public void testRemoveAll() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); IntSet intSet2 = new SmallIntSet(); intSet2.add(4); intSet2.add(5); intSet2.add(7); assertTrue(intSet.removeAll(intSet2)); assertEquals(1, intSet.size()); assertTrue(intSet.contains(1)); } @Test public void testRemoveAll1() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); // (1 - 4) IntSet rs = new RangeSet(5); assertTrue(intSet.removeAll(rs)); assertEquals(Util.asSet((Object) 7), intSet); } @Test public void testRemoveAll2() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); assertTrue(intSet.removeAll(Util.asSet(4, 5, 7))); assertEquals(Util.asSet((Object) 1), intSet); } @Test public void testRetainAll() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); IntSet intSet2 = new SmallIntSet(); intSet2.add(4); intSet2.add(5); intSet2.add(7); intSet.retainAll(intSet2); assertEquals(Util.asSet(4, 7), intSet); } @Test public void testRetainAll1() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); // (0 - 4) IntSet rs = new RangeSet(5); assertTrue(intSet.retainAll(rs)); assertEquals(Util.asSet(1, 4), intSet); } @Test public void testRetainAll2() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); assertTrue(intSet.retainAll(Util.asSet(4, 5, 7))); assertEquals(Util.asSet(4, 7), intSet); } @Test public void testClear() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); intSet.clear(); assertEquals(0, intSet.size()); } @Test public void testClear64() { addRange64(); assertEquals(64, intSet.size()); intSet.clear(); assertEquals(0, intSet.size()); } public void addRange64() { for (int i = 0; i < 64; i++) { intSet.add(i); } } @Test public void testIntStream() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(12, intSet.intStream().sum()); } @Test public void testEquals() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); IntSet intSet2 = new SmallIntSet(); intSet2.add(1); intSet2.add(4); // Verify equals both ways assertNotEquals(intSet, intSet2); assertNotEquals(intSet2, intSet); intSet2.add(7); assertEquals(intSet, intSet2); assertEquals(intSet2, intSet); } @Test public void testEquals1() throws Exception { intSet.add(0); intSet.add(1); intSet.add(2); // (0 - 3) IntSet rangeSet = new RangeSet(4); // Verify equals both ways assertNotEquals(rangeSet, intSet); assertNotEquals(intSet, rangeSet); intSet.add(3); assertEquals(intSet, intSet); assertEquals(intSet, intSet); } @Test public void testEquals2() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); Set<Integer> hashSet = Util.asSet(1, 4); // Verify equals both ways assertNotEquals(intSet, hashSet); assertNotEquals(hashSet, intSet); hashSet.add(7); assertEquals(intSet, hashSet); assertEquals(hashSet, intSet); } @Test public void testForEachPrimitive() { intSet.add(0); intSet.add(4); intSet.add(7); Set<Integer> results = new HashSet<>(); intSet.forEach((IntConsumer) results::add); assertEquals(Util.asSet(0, 4, 7), results); } @Test public void testForEachPrimitive64() { addRange64(); Set<Integer> results = new HashSet<>(); intSet.forEach((IntConsumer) results::add); assertEquals(new RangeSet(64), results); } @Test public void testForEachObject() { intSet.add(0); intSet.add(4); intSet.add(7); Set<Integer> results = new HashSet<>(); intSet.forEach((Consumer<? super Integer>) results::add); assertEquals(Util.asSet(0, 4, 7), results); } @Test public void testRemoveIfPrimitive() { intSet.add(1); intSet.add(4); intSet.add(7); assertFalse(intSet.removeIf((int i) -> i > 10)); assertEquals(3, intSet.size()); assertTrue(intSet.removeIf((int i) -> true)); assertEquals(0, intSet.size()); assertEquals(Collections.emptySet(), intSet); } @Test public void testRemoveIf64() { addRange64(); assertFalse(intSet.removeIf((int i) -> i > 64)); assertEquals(64, intSet.size()); assertTrue(intSet.removeIf((int i) -> true)); assertEquals(0, intSet.size()); assertEquals(Collections.emptySet(), intSet); } @Test public void testRemoveIfObject() { intSet.add(1); intSet.add(4); intSet.add(7); assertFalse(intSet.removeIf((Integer i) -> i / 10 > 0)); assertEquals(3, intSet.size()); assertTrue(intSet.removeIf((Integer i) -> i > 3)); assertEquals(Util.asSet((Object) 1), intSet); } @Test public void testIntSpliteratorForEachRemaining() { intSet.add(1); intSet.add(4); intSet.add(7); Set<Integer> results = new HashSet<>(); intSet.intSpliterator().forEachRemaining((IntConsumer) results::add); assertEquals(Util.asSet(1, 4, 7), results); } @Test public void testIntSpliteratorSplitTryAdvance() { intSet.add(1); intSet.add(4); intSet.add(7); Set<Integer> results = new HashSet<>(); Spliterator.OfInt spliterator = intSet.intSpliterator(); Spliterator.OfInt split = spliterator.trySplit(); assertNotNull(split); IntConsumer consumer = results::add; while (spliterator.tryAdvance(consumer)) { } while (split.tryAdvance(consumer)) { } assertEquals(Util.asSet(1, 4, 7), results); } @Test public void testToByteSet() { intSet.add(3); intSet.add(16); intSet.add(35); intSet.add(34); intSet.add(33); byte[] bytes = intSet.toBitSet(); byte[] expectedBytes = new byte[] { 8, 0, 1, 0, 14}; if (bytes.length == expectedBytes.length) { assertArrayEquals(expectedBytes, bytes); } else { for (int i = 0; i < expectedBytes.length; ++i) { assertEquals("Byte at pos: " + i + " didn't match", expectedBytes[i], bytes[i]); } // Any extra bytes should be all 0 for (int i = expectedBytes.length; i < bytes.length; ++i) { assertEquals("Byte at pos: " + i + " didn't match", 0, bytes[i]); } } } }
11,902
21.543561
92
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/ByteQuantityParserTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import org.junit.Test; public class ByteQuantityParserTest { @Test public void testParse() { assertIllegal(""); assertIllegal("-1"); assertIllegal("1.23.5"); assertIllegal("1,23"); assertIllegal("10.2"); assertIllegal("10.2 kB"); assertIllegal("0.0000001 MB"); assertIllegal("100000000000000000000 GB"); assertEquals(0, ByteQuantity.parse("0")); assertEquals(250_000, ByteQuantity.parse("250000 B")); assertEquals(1_000, ByteQuantity.parse("1000")); assertEquals(1_000, ByteQuantity.parse("1KB")); assertEquals(1_024, ByteQuantity.parse("1KiB")); assertEquals(1_000, ByteQuantity.parse("1 KB")); assertEquals(1_000, ByteQuantity.parse("1 KB")); assertEquals(1_000_000, ByteQuantity.parse("1 MB")); assertEquals(1_048_576, ByteQuantity.parse("1 MiB")); assertEquals(1_523_000, ByteQuantity.parse("1.523 MB")); assertEquals(100_000, ByteQuantity.parse("0.1 MB")); assertEquals(1, ByteQuantity.parse("0.000001 MB")); assertEquals(10_000_000_000L, ByteQuantity.parse("10GB")); assertEquals(1_000_000_000_000L, ByteQuantity.parse("1TB")); assertEquals(1_099_511_627_776L, ByteQuantity.parse("1TiB")); assertEquals(100_000_000_000_000L, ByteQuantity.parse("100TB")); } private void assertIllegal(String text) { assertThrows(IllegalArgumentException.class, () -> ByteQuantity.parse(text)); } }
1,584
37.658537
83
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/StringPropertyReplacerTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import java.io.File; import java.util.Properties; import org.junit.Test; public class StringPropertyReplacerTest { @Test public void testReplaceProperties() { Properties properties = new Properties(); properties.put("one", "1"); properties.put("two", "2"); assertEquals("V1", StringPropertyReplacer.replaceProperties("V${one}", properties)); assertEquals("VX", StringPropertyReplacer.replaceProperties("V${void:X}", properties)); assertEquals("V1", StringPropertyReplacer.replaceProperties("V${void,one}", properties)); assertEquals("VX", StringPropertyReplacer.replaceProperties("V${void1,void2:X}", properties)); assertEquals(System.getenv("PATH"), StringPropertyReplacer.replaceProperties("${env.PATH}", properties)); assertEquals(File.separator, StringPropertyReplacer.replaceProperties("${/}")); assertEquals(File.pathSeparator, StringPropertyReplacer.replaceProperties("${:}")); } }
1,046
37.777778
111
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/TimedThreadDumpTest.java
package org.infinispan.commons.util; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; import org.junit.Assert; import org.junit.Test; public class TimedThreadDumpTest { static { Configurator.setLevel("org.infinispan.commons.util.TimedThreadDump", Level.TRACE); } @Test public void dumpThreadsOnlyOnce() { Assert.assertTrue(TimedThreadDump.generateThreadDump()); Assert.assertFalse(TimedThreadDump.generateThreadDump()); } }
509
24.5
88
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/ProcessorInfoTest.java
package org.infinispan.commons.util; import org.infinispan.commons.test.categories.Java11; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.assertTrue; public class ProcessorInfoTest { @Test @Category(Java11.class) public void testCPUCount() { assertTrue(ProcessorInfo.availableProcessors() <= Runtime.getRuntime().availableProcessors()); } }
421
23.823529
100
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/TypedPropertiesTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import java.util.Properties; import org.junit.Test; /** * Test for {@link TypedProperties}. * * @author Diego Lovison * @since 12.1 **/ public class TypedPropertiesTest { @Test public void testIntProperty() { TypedProperties p = createProperties(); assertEquals(1, p.getIntProperty("int", 999)); assertEquals(10, p.getIntProperty("int_put_str", 999)); assertEquals(1, p.getIntProperty("int_invalid", 1)); assertEquals(1, p.getIntProperty("int_null", 1)); System.setProperty("fooVar", "100"); assertEquals(100, p.getIntProperty("int_key_value_replacement", 1, true)); System.clearProperty("fooVar"); } @Test public void testLongProperty() { TypedProperties p = createProperties(); assertEquals(2L, p.getLongProperty("long", 999L)); assertEquals(20L, p.getLongProperty("long_put_str", 999L)); assertEquals(2L, p.getLongProperty("long_invalid", 2L)); assertEquals(2L, p.getLongProperty("long_null", 2L)); } @Test public void testBooleanProperty() { TypedProperties p = createProperties(); assertEquals(true, p.getBooleanProperty("boolean", false)); assertEquals(true, p.getBooleanProperty("boolean_put_str", false)); assertEquals(true, p.getBooleanProperty("boolean_invalid", true)); assertEquals(true, p.getBooleanProperty("boolean_null", true)); } @Test public void testEnumProperty() { TypedProperties p = createProperties(); assertEquals(COLOR.BLUE, p.getEnumProperty("enum_cast", COLOR.class, COLOR.BLUE)); assertEquals(COLOR.RED, p.getEnumProperty("enum", COLOR.class, COLOR.BLUE)); assertEquals(COLOR.RED, p.getEnumProperty("enum_put_str", COLOR.class, COLOR.BLUE)); assertEquals(COLOR.BLUE, p.getEnumProperty("enum_invalid", COLOR.class, COLOR.BLUE)); assertEquals(COLOR.BLUE, p.getEnumProperty("enum_null", COLOR.class, COLOR.BLUE)); assertEquals(COLOR.BLUE, p.getEnumProperty("enum_other", COLOR.class, COLOR.BLUE)); } private enum COLOR { RED, BLUE } private enum NUMBER { NUMBER_1 } private TypedProperties createProperties() { Properties p = new Properties(); p.put("int", 1); p.put("int_put_str", Integer.toString(10)); p.put("int_invalid", false); p.put("int_key_value_replacement", "${fooVar}"); p.put("long", 2L); p.put("long_put_str", Long.toString(20L)); p.put("long_invalid", false); p.put("boolean", true); p.put("boolean_put_str", Boolean.toString(true)); p.put("boolean_invalid", COLOR.RED); p.put("enum", COLOR.RED); p.put("enum_put_str", COLOR.RED.toString()); p.put("enum_invalid", false); p.put("enum_other", NUMBER.NUMBER_1); return new TypedProperties(p); } }
2,901
31.244444
91
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/ServiceFinderTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import java.util.Collection; import org.junit.Test; /** * @author Tristan Tarrant * @since 9.0 */ public class ServiceFinderTest { @Test public void testDuplicateServiceFinder() { ClassLoader mainClassLoader = this.getClass().getClassLoader(); ClassLoader otherClassLoader = new ClonedClassLoader(mainClassLoader); Collection<SampleSPI> spis = ServiceFinder.load(SampleSPI.class, mainClassLoader, otherClassLoader); assertEquals(1, spis.size()); } public static class ClonedClassLoader extends ClassLoader { public ClonedClassLoader(ClassLoader cl) { super(cl); } } }
721
22.290323
106
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/MemoryUnitTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import org.junit.Test; public class MemoryUnitTest { @Test public void testMemoryUnitParser() { assertEquals(1000, MemoryUnit.parseBytes("1000")); assertEquals(1000, MemoryUnit.parseBytes("1K")); assertEquals(1024, MemoryUnit.parseBytes("1Ki")); assertEquals(1_000_000l, MemoryUnit.parseBytes("1M")); assertEquals(1_048_576l, MemoryUnit.parseBytes("1Mi")); assertEquals(1_000_000_000l, MemoryUnit.parseBytes("1G")); assertEquals(1_073_741_824l, MemoryUnit.parseBytes("1Gi")); assertEquals(1_000_000_000_000l, MemoryUnit.parseBytes("1T")); assertEquals(1_099_511_627_776l, MemoryUnit.parseBytes("1Ti")); } }
756
33.409091
69
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/EmptyIntSetTest.java
package org.infinispan.commons.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.HashSet; import java.util.PrimitiveIterator; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.IntConsumer; import org.junit.Test; /** * @author wburns * @since 9.3 */ public class EmptyIntSetTest { IntSet es = EmptyIntSet.getInstance(); @Test public void testSize() { assertEquals(0, es.size()); } @Test public void testIsEmpty() { assertTrue(es.isEmpty()); } @Test public void testContains() throws Exception { assertFalse(es.contains(5)); assertFalse(es.contains(3)); } @Test public void testContains1() throws Exception { assertFalse(es.contains(Integer.valueOf(5))); assertFalse(es.contains(Integer.valueOf(3))); } @Test public void testIterator() throws Exception { PrimitiveIterator.OfInt iterator = es.iterator(); assertFalse(iterator.hasNext()); } @Test public void testToArray() throws Exception { Object[] array = es.toArray(); assertEquals(0, array.length); } @Test public void testToArray1() throws Exception { Object[] array = es.toArray(new Integer[1]); assertEquals(1, array.length); assertEquals(null, array[0]); array = es.toArray(new Integer[0]); assertEquals(0, array.length); } @Test public void testToIntArray() throws Exception { int[] array = es.toIntArray(); assertEquals(0, array.length); } @Test(expected = UnsupportedOperationException.class) public void testAdd() throws Exception { es.add(1); } @Test(expected = UnsupportedOperationException.class) public void testAdd1() throws Exception { es.add(Integer.valueOf(1)); } @Test(expected = UnsupportedOperationException.class) public void testSet() throws Exception { es.set(1); } @Test(expected = UnsupportedOperationException.class) public void testRemove() throws Exception { es.remove(3); } @Test(expected = UnsupportedOperationException.class) public void testRemove1() throws Exception { es.remove(Integer.valueOf(3)); } @Test public void testContainsAll() throws Exception { IntSet sis2 = new SingletonIntSet(3); assertFalse(es.containsAll(sis2)); assertTrue(sis2.containsAll(es)); IntSet sis3 = new RangeSet(0); assertTrue(sis3.containsAll(es)); assertTrue(es.containsAll(sis3)); } @Test public void testContainsAll1() throws Exception { Set<Integer> hashSet = new HashSet<>(); hashSet.add(3); assertFalse(es.containsAll(hashSet)); assertTrue(hashSet.containsAll(es)); hashSet.remove(3); assertTrue(hashSet.containsAll(es)); assertTrue(es.containsAll(hashSet)); } @Test(expected = UnsupportedOperationException.class) public void testAddAll() throws Exception { IntSet rs = new RangeSet(5); es.addAll(rs); } @Test(expected = UnsupportedOperationException.class) public void testAddAll1() throws Exception { SmallIntSet sis2 = new SmallIntSet(); es.addAll(sis2); } @Test(expected = UnsupportedOperationException.class) public void testAddAll2() throws Exception { Set<Integer> hashSet = new HashSet<>(); hashSet.add(1); hashSet.add(4); es.addAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAll() throws Exception { IntSet rs = new RangeSet(6); es.removeAll(rs); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAll1() throws Exception { Set<Integer> hashSet = Collections.emptySet(); es.removeAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void testRetainAll() throws Exception { IntSet rs = new RangeSet(5); es.retainAll(rs); } @Test(expected = UnsupportedOperationException.class) public void testRetainAll1() throws Exception { Set<Integer> hashSet = Collections.emptySet(); es.retainAll(hashSet); } @Test(expected = UnsupportedOperationException.class) public void testClear() throws Exception { es.clear(); } @Test public void testIntStream() throws Exception { assertEquals(0, es.intStream().count()); } @Test public void testEquals() throws Exception { IntSet sis2 = new SingletonIntSet(4); // Verify equals both ways assertNotEquals(es, sis2); assertNotEquals(sis2, es); // This is empty, just sets the range IntSet sis3 = new SmallIntSet(2); assertEquals(sis3, es); assertEquals(es, sis3); } @Test public void testEquals1() throws Exception { SmallIntSet sis2 = new SmallIntSet(); sis2.add(2); // Verify equals both ways assertNotEquals(es, sis2); assertNotEquals(sis2, es); sis2.remove(2); assertEquals(es, sis2); assertEquals(sis2, es); } @Test public void testEquals2() throws Exception { Set<Integer> hashSet = new HashSet<>(); hashSet.add(2); // Verify equals both ways assertNotEquals(es, hashSet); assertNotEquals(hashSet, es); hashSet.remove(2); assertEquals(es, hashSet); assertEquals(hashSet, es); } @Test public void testForEachPrimitive() { Set<Integer> results = new HashSet<>(); es.forEach((IntConsumer) results::add); assertEquals(0, results.size()); } @Test public void testForEachObject() { Set<Integer> results = new HashSet<>(); es.forEach((Consumer<? super Integer>) results::add); assertEquals(0, results.size()); } @Test(expected = UnsupportedOperationException.class) public void testRemoveIfPrimitive() { es.removeIf((int i) -> i == 3); } @Test(expected = UnsupportedOperationException.class) public void testRemoveIfObject() { es.removeIf((Integer i) -> i == 3); } @Test public void testIntSpliteratorForEachRemaining() { Set<Integer> results = new HashSet<>(); es.intSpliterator().forEachRemaining((IntConsumer) results::add); assertEquals(0, results.size()); } @Test public void testIntSpliteratorSplitTryAdvance() { Set<Integer> results = new HashSet<>(); Spliterator.OfInt spliterator = es.intSpliterator(); Spliterator.OfInt split = spliterator.trySplit(); assertNull(split); IntConsumer consumer = results::add; while (spliterator.tryAdvance(consumer)) { } assertEquals(0, results.size()); } }
6,936
23.255245
71
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/SampleSPI.java
package org.infinispan.commons.util; public interface SampleSPI { }
69
13
36
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/util/MySampleSPI.java
package org.infinispan.commons.util; public class MySampleSPI implements SampleSPI { }
88
16.8
47
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/jmx/TestMBeanServerLookup.java
package org.infinispan.commons.jmx; import java.util.Properties; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; /** * A lazy implementations of MBeanServerLookup. The MBeanServer is created only on first call to {@link * MBeanServerLookup#getMBeanServer}. The MBeanServer is cached and the same instance is returned on subsequent calls. * * @author anistor@redhat.com * @since 10.0 */ public final class TestMBeanServerLookup implements MBeanServerLookup { private MBeanServer mBeanServer; /** * Factory method */ public static MBeanServerLookup create() { return new TestMBeanServerLookup(); } @Override public synchronized MBeanServer getMBeanServer(Properties properties) { if (mBeanServer == null) { mBeanServer = MBeanServerFactory.newMBeanServer(); } return mBeanServer; } }
889
25.176471
118
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/time/ControlledTimeService.java
package org.infinispan.commons.time; import java.time.Instant; import java.util.concurrent.TimeUnit; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; /** * TimeService that allows for wall clock time to be adjust manually. */ public class ControlledTimeService extends DefaultTimeService { private static final Log log = LogFactory.getLog(ControlledTimeService.class); private final Object id; private TimeService actualTimeService; protected volatile long currentMillis; public ControlledTimeService() { this(null); } public ControlledTimeService(Object id) { this(id, 1_000_000L); } public ControlledTimeService(Object id, ControlledTimeService other) { this(id, other.currentMillis); } public ControlledTimeService(Object id, long currentMillis) { this.id = id; this.currentMillis = currentMillis; } @Override public long wallClockTime() { return currentMillis; } @Override public long time() { return TimeUnit.MILLISECONDS.toNanos(currentMillis); } @Override public Instant instant() { return Instant.ofEpochMilli(currentMillis); } public void advance(long delta, TimeUnit timeUnit) { advance(timeUnit.toMillis(delta)); } public TimeService getActualTimeService() { return actualTimeService; } public void setActualTimeService(TimeService actualTimeService) { this.actualTimeService = actualTimeService; } public synchronized void advance(long deltaMillis) { if (deltaMillis <= 0) { throw new IllegalArgumentException("Argument must be greater than 0"); } currentMillis += deltaMillis; log.tracef("Current time for %s is now %d", id, currentMillis); } }
1,805
24.43662
81
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/dataconversion/BinaryTranscoderTest.java
package org.infinispan.commons.dataconversion; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.net.URLEncoder; import java.util.Base64; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.util.KeyValueWithPrevious; import org.junit.BeforeClass; import org.junit.Test; public class BinaryTranscoderTest { private static BinaryTranscoder binaryTranscoder; private static JavaSerializationMarshaller marshaller; @BeforeClass public static void prepare() { final ClassAllowList allowList = new ClassAllowList(); allowList.addRegexps(".*"); marshaller = new JavaSerializationMarshaller(allowList); binaryTranscoder = new BinaryTranscoder(marshaller); } @Test public void testToFromUnknown() { testWithContentTypes(APPLICATION_UNKNOWN, APPLICATION_UNKNOWN); } @Test public void testToFromOctetStream() { testWithContentTypes(APPLICATION_UNKNOWN, APPLICATION_OCTET_STREAM); testWithContentTypes(APPLICATION_OCTET_STREAM, APPLICATION_UNKNOWN); } @Test public void testToFromTextPlain() { testWithContentTypes(APPLICATION_UNKNOWN, TEXT_PLAIN); testWithContentTypes(TEXT_PLAIN, APPLICATION_UNKNOWN); } @Test public void testToFromUrlEncoded() throws Exception { String data = "word1 word2"; byte[] dataBinary = data.getBytes(UTF_8); final String encoded = URLEncoder.encode(data, "utf-8"); final byte[] dataEncoded = encoded.getBytes(UTF_8); Object toBinary = binaryTranscoder.transcode(dataEncoded, APPLICATION_WWW_FORM_URLENCODED, APPLICATION_UNKNOWN); Object toBinaryHex = binaryTranscoder.transcode(dataEncoded, APPLICATION_WWW_FORM_URLENCODED, hexEncoded(APPLICATION_UNKNOWN)); Object toBinaryBase64 = binaryTranscoder.transcode(dataEncoded, APPLICATION_WWW_FORM_URLENCODED, base64Encoded(APPLICATION_UNKNOWN)); assertArrayEquals(dataBinary, (byte[]) toBinary); assertEquals(Base16Codec.encode(dataBinary), toBinaryHex); assertSame(Base64.getEncoder().encode(dataBinary), toBinaryBase64); Object fromBinary = binaryTranscoder.transcode(toBinary, APPLICATION_UNKNOWN, APPLICATION_WWW_FORM_URLENCODED); Object fromBinaryHex = binaryTranscoder.transcode(toBinaryHex, hexEncoded(APPLICATION_UNKNOWN), APPLICATION_WWW_FORM_URLENCODED); Object fromBinaryBase64 = binaryTranscoder.transcode(toBinaryBase64, base64Encoded(APPLICATION_UNKNOWN), APPLICATION_WWW_FORM_URLENCODED); assertSame(dataEncoded, fromBinary); assertSame(dataEncoded, fromBinaryHex); assertSame(dataEncoded, fromBinaryBase64); } @Test public void testToFromObject() throws Exception { testToFromObject("string-data"); testToFromObject(new KeyValueWithPrevious<>("string", 1L, 0L)); testToFromObject(new byte[]{1, 2, 3}); } private void testToFromObject(Object data) throws Exception { byte[] binaryForm = marshaller.objectToByteBuffer(data); Object toBinary = binaryTranscoder.transcode(data, APPLICATION_OBJECT, APPLICATION_UNKNOWN); Object toBinaryHex = binaryTranscoder.transcode(data, APPLICATION_OBJECT, hexEncoded(APPLICATION_UNKNOWN)); Object toBinaryBase64 = binaryTranscoder.transcode(data, APPLICATION_OBJECT, base64Encoded(APPLICATION_UNKNOWN)); assertArrayEquals(binaryForm, (byte[]) toBinary); assertEquals(Base16Codec.encode(binaryForm), toBinaryHex); assertSame(Base64.getEncoder().encode(binaryForm), toBinaryBase64); Object fromBinary = binaryTranscoder.transcode(toBinary, APPLICATION_UNKNOWN, APPLICATION_OBJECT); Object fromBinaryHex = binaryTranscoder.transcode(toBinaryHex, hexEncoded(APPLICATION_UNKNOWN), APPLICATION_OBJECT); Object fromBinaryBase64 = binaryTranscoder.transcode(toBinaryBase64, base64Encoded(APPLICATION_UNKNOWN), APPLICATION_OBJECT); assertSame(data, fromBinary); assertSame(data, fromBinaryHex); assertSame(data, fromBinaryBase64); } private void assertSame(Object expected, Object obtained) { if (expected instanceof byte[]) { assertArrayEquals((byte[]) expected, (byte[]) obtained); } else { assertEquals(expected, obtained); } } private void testWithContentTypes(MediaType sourceType, MediaType targetType) { byte[] data = {1, 2, 3}; MediaType[] sourceTypes = {sourceType, hexEncoded(sourceType), base64Encoded(sourceType)}; MediaType[] targetTypes = {targetType, hexEncoded(targetType), base64Encoded(targetType)}; for (MediaType source : sourceTypes) { for (MediaType target : targetTypes) { Object dataIn = encodeIfNeeded(data, source); Object expected = encodeIfNeeded(data, target); Object result = binaryTranscoder.transcode(dataIn, source, target); assertSame(expected, result); } } } private MediaType hexEncoded(MediaType mediaType) { return mediaType.withParameter("encoding", "hex"); } private MediaType base64Encoded(MediaType mediaType) { return mediaType.withParameter("encoding", "base64"); } private Object encodeIfNeeded(Object data, MediaType type) { final String encoding = type.getEncoding(); if (encoding == null || (!(data instanceof byte[]))) return data; return new RFC4648Codec().encodeContent(data, type); } }
6,014
41.659574
144
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/dataconversion/MediaTypeResolverTest.java
package org.infinispan.commons.dataconversion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; /** * @since 10.1 */ public class MediaTypeResolverTest { @Test public void testResolver() { assertNull(MediaTypeResolver.getMediaType(null)); assertNull(MediaTypeResolver.getMediaType("noextension")); assertNull(MediaTypeResolver.getMediaType("124.")); assertEquals("application/javascript", MediaTypeResolver.getMediaType("file.js")); assertEquals("image/jpeg", MediaTypeResolver.getMediaType("file.jpg")); assertEquals("image/jpeg", MediaTypeResolver.getMediaType("file.jpeg")); assertEquals("image/jpeg", MediaTypeResolver.getMediaType("file.jpe")); assertEquals("text/css", MediaTypeResolver.getMediaType("file.css")); assertEquals("text/html", MediaTypeResolver.getMediaType("file.htm")); assertEquals("text/html", MediaTypeResolver.getMediaType("file.html")); assertEquals("application/java-archive", MediaTypeResolver.getMediaType("file.JAR")); } }
1,096
38.178571
91
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/dataconversion/DefaultTranscoderTest.java
package org.infinispan.commons.dataconversion; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Base64; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.util.KeyValueWithPrevious; import org.junit.BeforeClass; import org.junit.Test; public class DefaultTranscoderTest { private static DefaultTranscoder defaultTranscoder; private static JavaSerializationMarshaller marshaller; @BeforeClass public static void prepare() { final ClassAllowList allowList = new ClassAllowList(); allowList.addRegexps(".*"); marshaller = new JavaSerializationMarshaller(allowList); defaultTranscoder = new DefaultTranscoder(marshaller); } @Test public void testObjectOctetStream() throws Exception { final String string = "string-data"; final byte[] byteArray = {1, 2, 3}; final KeyValueWithPrevious<String, Long> pojo = new KeyValueWithPrevious<>("string", 1L, 0L); testObjectOctetStream(string, string.getBytes(UTF_8)); testObjectOctetStream(byteArray, byteArray); testObjectOctetStream(pojo, marshaller.objectToByteBuffer(pojo)); } private void testObjectOctetStream(Object data, byte[] expectOctetStream) { Object toOctetStream = defaultTranscoder.transcode(data, APPLICATION_OBJECT, APPLICATION_OCTET_STREAM); Object toOctetStreamHex = defaultTranscoder.transcode(data, APPLICATION_OBJECT, hexEncoded(APPLICATION_OCTET_STREAM)); Object toOctetStreamBase64 = defaultTranscoder.transcode(data, APPLICATION_OBJECT, base64Encoded(APPLICATION_OCTET_STREAM)); assertSame(expectOctetStream, toOctetStream); assertSame(Base16Codec.encode(expectOctetStream), toOctetStreamHex); assertSame(Base64.getEncoder().encode(expectOctetStream), toOctetStreamBase64); Object fromOctetStream = defaultTranscoder.transcode(toOctetStream, APPLICATION_OCTET_STREAM, APPLICATION_OBJECT); Object fromOctetStreamHex = defaultTranscoder.transcode(toOctetStreamHex, hexEncoded(APPLICATION_OCTET_STREAM), APPLICATION_OBJECT); Object fromOctetStreamBase64 = defaultTranscoder.transcode(toOctetStreamBase64, base64Encoded(APPLICATION_OCTET_STREAM), APPLICATION_OBJECT); assertSame(expectOctetStream, fromOctetStream); assertSame(expectOctetStream, fromOctetStreamHex); assertSame(expectOctetStream, fromOctetStreamBase64); } @Test public void testObjectUrlEncoded() throws Exception { String data = "word1 word2"; final String encoded = URLEncoder.encode(data, "utf-8"); final byte[] encodedUTF = encoded.getBytes(UTF_8); Object toObject = defaultTranscoder.transcode(encodedUTF, APPLICATION_WWW_FORM_URLENCODED, APPLICATION_OBJECT); assertEquals(data, toObject); Object fromObject = defaultTranscoder.transcode(toObject, APPLICATION_OBJECT, APPLICATION_WWW_FORM_URLENCODED); assertSame(encodedUTF, fromObject); } @Test public void testObjectText() throws Exception { String textData = "this is text"; byte[] utf8 = textData.getBytes(UTF_8); Object textPlain = defaultTranscoder.transcode(textData, APPLICATION_OBJECT, TEXT_PLAIN); assertSame(utf8, textPlain); Object object = defaultTranscoder.transcode(textPlain, TEXT_PLAIN, APPLICATION_OBJECT.withClassType(String.class)); assertEquals(textData, object); Object fromText = defaultTranscoder.transcode(textPlain, TEXT_PLAIN, APPLICATION_OBJECT); assertSame(textData, fromText); } @Test public void testOctetStreamUrlEncoded() throws UnsupportedEncodingException { String data = "word1 word2"; byte[] urlEncoded = URLEncoder.encode(data, "utf-8").getBytes(UTF_8); byte[] utf8 = data.getBytes(UTF_8); Object toOctetStream = defaultTranscoder.transcode(urlEncoded, APPLICATION_WWW_FORM_URLENCODED, APPLICATION_OCTET_STREAM); Object toOctetStreamHex = defaultTranscoder.transcode(data, APPLICATION_WWW_FORM_URLENCODED, hexEncoded(APPLICATION_OCTET_STREAM)); Object toOctetStream64 = defaultTranscoder.transcode(data, APPLICATION_WWW_FORM_URLENCODED, base64Encoded(APPLICATION_OCTET_STREAM)); assertSame(utf8, toOctetStream); assertSame(Base16Codec.encode(utf8), toOctetStreamHex); assertSame(Base64.getEncoder().encode(utf8), toOctetStream64); Object fromOctetStream = defaultTranscoder.transcode(toOctetStream, APPLICATION_OCTET_STREAM, APPLICATION_WWW_FORM_URLENCODED); Object fromOctetStreamHex = defaultTranscoder.transcode(toOctetStreamHex, hexEncoded(APPLICATION_OCTET_STREAM), APPLICATION_WWW_FORM_URLENCODED); Object fromOctetStream64 = defaultTranscoder.transcode(toOctetStream64, base64Encoded(APPLICATION_OCTET_STREAM), APPLICATION_WWW_FORM_URLENCODED); assertSame(urlEncoded, fromOctetStream); assertSame(urlEncoded, fromOctetStreamHex); assertSame(urlEncoded, fromOctetStream64); } @Test public void testOctetStreamText() { String text = "word1 word2"; byte[] utf8 = text.getBytes(UTF_8); Object toOctetStream = defaultTranscoder.transcode(text, TEXT_PLAIN, APPLICATION_OCTET_STREAM); Object toOctetStreamHex = defaultTranscoder.transcode(text, TEXT_PLAIN, hexEncoded(APPLICATION_OCTET_STREAM)); Object toOctetStream64 = defaultTranscoder.transcode(text, TEXT_PLAIN, base64Encoded(APPLICATION_OCTET_STREAM)); assertSame(utf8, toOctetStream); assertEquals(Base16Codec.encode(utf8), toOctetStreamHex); assertSame(Base64.getEncoder().encode(utf8), toOctetStream64); Object toOctetStreamFromByteArray = defaultTranscoder.transcode(utf8, TEXT_PLAIN, APPLICATION_OCTET_STREAM); Object toOctetStreamHexFromByteArray = defaultTranscoder.transcode(utf8, TEXT_PLAIN, hexEncoded(APPLICATION_OCTET_STREAM)); Object toOctetStream64FromByteArray = defaultTranscoder.transcode(utf8, TEXT_PLAIN, base64Encoded(APPLICATION_OCTET_STREAM)); assertSame(utf8, toOctetStreamFromByteArray); assertEquals(Base16Codec.encode(utf8), toOctetStreamHexFromByteArray); assertSame(Base64.getEncoder().encode(utf8), toOctetStream64FromByteArray); Object fromOctetStream = defaultTranscoder.transcode(toOctetStream, APPLICATION_OCTET_STREAM, TEXT_PLAIN); Object fromOctetStreamHex = defaultTranscoder.transcode(toOctetStreamHex, hexEncoded(APPLICATION_OCTET_STREAM), TEXT_PLAIN); Object fromOctetStream64 = defaultTranscoder.transcode(toOctetStream64, base64Encoded(APPLICATION_OCTET_STREAM), TEXT_PLAIN); assertSame(utf8, fromOctetStream); assertSame(utf8, fromOctetStreamHex); assertSame(utf8, fromOctetStream64); } @Test public void testTextUrlEncoded() throws Exception { String textData = "this is text"; byte[] urlEncoded = URLEncoder.encode(textData, "utf-8").getBytes(UTF_8); Object encodedText = defaultTranscoder.transcode(textData, TEXT_PLAIN, APPLICATION_WWW_FORM_URLENCODED); assertSame(urlEncoded, encodedText); Object toText = defaultTranscoder.transcode(encodedText, APPLICATION_WWW_FORM_URLENCODED, TEXT_PLAIN); assertSame(textData.getBytes(UTF_8), toText); } private MediaType hexEncoded(MediaType mediaType) { return mediaType.withParameter("encoding", "hex"); } private MediaType base64Encoded(MediaType mediaType) { return mediaType.withParameter("encoding", "base64"); } private void assertSame(Object expected, Object obtained) { if (expected instanceof byte[]) { assertArrayEquals((byte[]) expected, (byte[]) obtained); } else { assertEquals(expected, obtained); } } }
8,264
45.960227
152
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/dataconversion/StandardConversionsTest.java
package org.infinispan.commons.dataconversion; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_16; import static java.nio.charset.StandardCharsets.UTF_16BE; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.infinispan.commons.dataconversion.StandardConversions.bytesToHex; import static org.infinispan.commons.dataconversion.StandardConversions.hexToBytes; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.time.Instant; import java.util.Calendar; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class StandardConversionsTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void textToTextConversion() { String source = "All those moments will be lost in time, like tears in rain."; byte[] sourceAs8859 = source.getBytes(ISO_8859_1); byte[] sourceAsASCII = source.getBytes(US_ASCII); Object result = StandardConversions.convertTextToText(sourceAs8859, TEXT_PLAIN.withCharset(ISO_8859_1), TEXT_PLAIN.withCharset(US_ASCII)); assertArrayEquals(sourceAsASCII, (byte[]) result); } @Test public void testTextToOctetStreamConversion() { String source = "Like our owl?"; byte[] result = StandardConversions.convertTextToOctetStream(source, TEXT_PLAIN); assertArrayEquals(source.getBytes(UTF_8), result); } @Test public void testTextToObjectConversion() { String source = "Can the maker repair what he makes?"; String source2 = "I had your job once. I was good at it."; byte[] sourceBytes = source2.getBytes(US_ASCII); Object result = StandardConversions.convertTextToObject(source, APPLICATION_OBJECT); Object result2 = StandardConversions.convertTextToObject(sourceBytes, TEXT_PLAIN.withCharset(US_ASCII)); assertEquals(source, result); assertEquals(source2, result2); } @Test public void testTextToURLEncodedConversion() throws UnsupportedEncodingException { String source = "They're either a benefit or a hazard. If they're a benefit, it's not my problem."; String result = StandardConversions.convertTextToUrlEncoded(source, TEXT_PLAIN.withCharset(UTF_16)); assertEquals(URLEncoder.encode(source, "UTF-16"), result); } @Test public void testOctetStreamToTextConversion() { String text = "Have you ever retired a human by mistake?"; byte[] bytes1 = text.getBytes(); byte[] bytes2 = new byte[]{1, 2, 3}; byte[] result1 = StandardConversions.convertOctetStreamToText(bytes1, TEXT_PLAIN.withCharset(US_ASCII)); byte[] result2 = StandardConversions.convertOctetStreamToText(bytes2, TEXT_PLAIN); assertArrayEquals(text.getBytes(US_ASCII), result1); assertArrayEquals(new String(bytes2).getBytes(UTF_8), result2); } @Test public void testOctetStreamToJavaConversion() { String value = "It's not an easy thing to meet your maker."; byte[] textStream = value.getBytes(UTF_8); byte[] randomBytes = new byte[]{23, 23, 34, 1, -1, -123}; Marshaller marshaller = new ProtoStreamMarshaller(); MediaType stringType = APPLICATION_OBJECT.withParameter("type", "java.lang.String"); Object result = StandardConversions.convertOctetStreamToJava(textStream, stringType, marshaller); assertEquals(value, result); MediaType byteArrayType = APPLICATION_OBJECT.withParameter("type", "ByteArray"); Object result2 = StandardConversions.convertOctetStreamToJava(textStream, byteArrayType, marshaller); assertArrayEquals(textStream, (byte[]) result2); Object result3 = StandardConversions.convertOctetStreamToJava(randomBytes, byteArrayType, marshaller); assertArrayEquals(randomBytes, (byte[]) result3); thrown.expect(EncodingException.class); MediaType doubleType = APPLICATION_OBJECT.withParameter("type", "java.lang.Double"); StandardConversions.convertOctetStreamToJava(randomBytes, doubleType, marshaller); System.out.println(thrown); } @Test public void testJavaToTextConversion() { String string = "I've seen things you people wouldn't believe."; Double number = 12.1d; Calendar complex = Calendar.getInstance(); MediaType stringType = APPLICATION_OBJECT.withParameter("type", "java.lang.String"); byte[] result1 = StandardConversions.convertJavaToText(string, stringType, TEXT_PLAIN.withCharset(UTF_16BE)); assertArrayEquals(string.getBytes(UTF_16BE), result1); MediaType doubleType = APPLICATION_OBJECT.withParameter("type", "java.lang.Double"); byte[] result2 = StandardConversions.convertJavaToText(number, doubleType, TEXT_PLAIN.withCharset(US_ASCII)); assertArrayEquals("12.1".getBytes(US_ASCII), result2); MediaType customType = APPLICATION_OBJECT.withParameter("type", complex.getClass().getName()); byte[] bytes = StandardConversions.convertJavaToText(complex, customType, TEXT_PLAIN.withCharset(US_ASCII)); assertEquals(complex.toString(), new String(bytes)); } @Test public void testJavaToOctetStreamConversion() throws IOException, InterruptedException { Marshaller marshaller = new ProtoStreamMarshaller(); String string = "I've seen things you people wouldn't believe."; Double number = 12.1d; Instant complex = Instant.now(); byte[] binary = new byte[]{1, 2, 3}; MediaType stringType = APPLICATION_OBJECT.withParameter("type", "java.lang.String"); byte[] result = StandardConversions.convertJavaToOctetStream(string, stringType, marshaller); assertArrayEquals(marshaller.objectToByteBuffer(string), result); MediaType doubleType = APPLICATION_OBJECT.withParameter("type", "java.lang.Double"); result = StandardConversions.convertJavaToOctetStream(number, doubleType, marshaller); assertArrayEquals(marshaller.objectToByteBuffer(number), result); MediaType customType = APPLICATION_OBJECT.withParameter("type", complex.getClass().getName()); result = StandardConversions.convertJavaToOctetStream(complex, customType, marshaller); assertArrayEquals(marshaller.objectToByteBuffer(complex), result); MediaType byteArrayType = APPLICATION_OBJECT.withParameter("type", "ByteArray"); result = StandardConversions.convertJavaToOctetStream(binary, byteArrayType, marshaller); assertArrayEquals(marshaller.objectToByteBuffer(binary), result); } @Test public void testHexConversion() throws Exception { assertNull(bytesToHex(null)); assertNull(hexToBytes(null)); assertEquals("", bytesToHex(new byte[]{})); assertArrayEquals(new byte[]{}, hexToBytes("")); Marshaller marshaller = new ProtoStreamMarshaller(); byte[] before = marshaller.objectToByteBuffer(Instant.now()); byte[] after = hexToBytes(bytesToHex(before)); assertArrayEquals(before, after); assertEquals("0x010203", bytesToHex(new byte[]{1, 2, 3})); assertEquals("0x808080", bytesToHex(new byte[]{-128, -128, -128})); } }
7,686
42.676136
115
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/dataconversion/MediaTypeTest.java
package org.infinispan.commons.dataconversion; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.stream.Collectors; import java.util.stream.Stream; import org.infinispan.commons.test.Exceptions; import org.junit.Test; /** * @since 9.2 */ public class MediaTypeTest { @Test public void testParsingTypeSubType() { MediaType appJson = MediaType.fromString("application/json"); assertMediaTypeNoParams(appJson, "application", "json"); } @Test(expected = EncodingException.class) public void testParsingMultipleSubType() { MediaType.fromString("application/json/on"); } public void testParsingNoType() { Exceptions.expectException(EncodingException.class, () -> MediaType.fromString("")); Exceptions.expectException(EncodingException.class, () -> MediaType.fromString(";param=value")); } @Test(expected = EncodingException.class) public void testParsingNoSubType() { MediaType.fromString("something"); } @Test(expected = EncodingException.class) public void testParsingNoSubType2() { MediaType.fromString("application; charset=utf-8"); } @Test(expected = EncodingException.class) public void testParsingNull() { MediaType.fromString(null); } @Test(expected = EncodingException.class) public void testParsingWhitespaceInType() { MediaType.fromString("application /json"); } @Test(expected = EncodingException.class) public void testParsingWhitespaceInSubtype() { MediaType.fromString("application/ json"); } @Test(expected = EncodingException.class) public void testParsingWhitespaceInTypeSubtype() { MediaType.fromString("application / json"); } @Test(expected = EncodingException.class) public void testParsingWhitespaceInParamName() { MediaType.fromString("application/json; charset =utf-8"); } @Test public void testQuotedParam() { MediaType mediaType = MediaType.fromString("application/json; charset=\"UTF-8\""); assertMediaTypeWithParam(mediaType, "application", "json", "charset", "\"UTF-8\""); } @Test public void testQuotedParamsWithWhitespace() { MediaType mediaType = MediaType.fromString("application/json; charset=\" UTF-8 \""); assertMediaTypeWithParam(mediaType, "application", "json", "charset", "\" UTF-8 \""); } @Test public void testQuotedParamsEscaping() { MediaType mediaType = MediaType.fromString("application/json; charset=\"\\\"UTF-8\\\"\""); assertMediaTypeWithParam(mediaType, "application", "json", "charset", "\"\\\"UTF-8\\\"\""); MediaType mediaType2 = MediaType.fromString("application/json; charset=\"\\a\\\"\\\\\""); assertMediaTypeWithParam(mediaType2, "application", "json", "charset", "\"\\a\\\"\\\\\""); Exceptions.expectException(EncodingException.class, () -> MediaType.fromString("application/json; charset=\"\\\"")); } @Test public void testUnquotedParamWithSingleQuote() { MediaType mediaType = MediaType.fromString("application/json; charset='UTF-8'"); assertMediaTypeWithParam(mediaType, "application", "json", "charset", "'UTF-8'"); Exceptions.expectException(EncodingException.class, () -> MediaType.fromString("application/json; charset='UTF 8'")); } @Test public void testUnQuotedParam() { MediaType mediaType = MediaType.fromString("application/json; charset=UTF-8"); assertMediaTypeWithParam(mediaType, "application", "json", "charset", "UTF-8"); Exceptions.expectException(EncodingException.class, () -> MediaType.fromString("application/json; charset=utf 8")); } @Test public void testToString() { assertEquals("application/xml; q=0.9", new MediaType("application", "xml", createMap(new MapEntry("q", "0.9"))).toString()); assertEquals("text/csv", new MediaType("text", "csv").toString()); assertEquals("foo/bar; a=2", new MediaType("foo", "bar", createMap(new MapEntry("a", "2"))).toString()); assertEquals("foo/bar; a=2; b=1; c=2", new MediaType("foo", "bar", createMap(new MapEntry("a", "2"), new MapEntry("b", "1"), new MapEntry("c", "2"))).toString()); assertEquals("a/b; p=1", MediaType.fromString("a/b; p=1; q=2").toStringExcludingParam("q")); } @Test public void testToStringQuotedParams() { MediaType mediaType = MediaType.fromString("a/b; p=\"\"; r=\"\\\"\""); assertEquals(mediaType, MediaType.fromString(mediaType.toString())); } @Test(expected = EncodingException.class) public void testUnQuotedParamWithSpaces() { MediaType mediaType = MediaType.fromString("application/json ; charset= UTF-8"); } @Test(expected = EncodingException.class) public void testWrongQuoting() { MediaType.fromString("application/json;charset= \"UTF-8"); } @Test public void testMultipleParameters() { MediaType mediaType = MediaType.fromString("application/json; charset=UTF-8; param1=value1 ;param2=value2"); assertMediaTypeWithParams(mediaType, "application", "json", new String[]{"charset", "param1", "param2"}, new String[]{"UTF-8", "value1", "value2"}); } @Test(expected = EncodingException.class) public void testMultipleParametersWrongSeparator() { MediaType.fromString("application/json; charset=UTF-8; param1=value1, param2=value2"); } @Test public void testParseWeight() { MediaType mediaType = MediaType.fromString("application/json; q=0.8"); assertEquals(0.8, mediaType.getWeight(), 0.0); } @Test(expected = EncodingException.class) public void testParseInvalidWeight() { MediaType.fromString("application/json ; q=high"); } @Test public void testDefaultWeight() { MediaType mediaType = MediaType.fromString("application/json"); assertEquals(1.0, mediaType.getWeight(), 0.0); } @Test public void testWildCard() { MediaType mediaType = MediaType.fromString("*/*"); assertEquals("*", mediaType.getType()); assertEquals("*", mediaType.getSubType()); assertTrue(mediaType.match(MediaType.TEXT_PLAIN)); assertTrue(mediaType.match(MediaType.APPLICATION_PROTOSTREAM)); } @Test public void testWildCard2() { MediaType mediaType = MediaType.fromString("*"); assertEquals("*", mediaType.getType()); assertEquals("*", mediaType.getSubType()); } @Test public void testParseList() { List<MediaType> mediaTypes = MediaType.parseList("text/html, image/png,*/*").collect(Collectors.toList()); assertEquals(asList(MediaType.TEXT_HTML, MediaType.IMAGE_PNG, MediaType.MATCH_ALL), mediaTypes); Exceptions.expectException(EncodingException.class, () -> MediaType.parseList("text/html,")); Exceptions.expectException(EncodingException.class, () -> MediaType.parseList("text/html;a=b,")); Exceptions.expectException(EncodingException.class, () -> MediaType.parseList("text/html;a=b,;b=c")); Exceptions.expectException(EncodingException.class, () -> MediaType.parseList("text/html;a=b,image/png/")); List<MediaType> mediaTypes2 = MediaType.parseList("text/html;a=\"b,\" ,*/*").collect(Collectors.toList()); assertEquals(asList(MediaType.TEXT_HTML.withParameter("a", "\"b,\""), MediaType.MATCH_ALL), mediaTypes2); } @Test public void testParseBrowserRequest() { Stream<MediaType> list = MediaType.parseList("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); Iterator<MediaType> iterator = list.iterator(); assertEquals("text/html", iterator.next().getTypeSubtype()); assertEquals("application/xhtml+xml", iterator.next().getTypeSubtype()); assertEquals("application/xml", iterator.next().getTypeSubtype()); assertEquals("*/*", iterator.next().getTypeSubtype()); } @Test public void testParseSingleAsterix() { List<String> list = MediaType.parseList("text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2") .map(MediaType::getTypeSubtype) .collect(Collectors.toList()); assertEquals(asList("text/html", "image/gif", "image/jpeg", "*/*", "*/*"), list); } @Test public void testNegotiations() { Stream<MediaType> mediaTypes = MediaType.parseList("text/html; q=0.8,*/*;q=0.2,application/json"); Iterator<MediaType> iterator = mediaTypes.iterator(); MediaType preferred = iterator.next(); MediaType secondChoice = iterator.next(); MediaType everythingElse = iterator.next(); assertEquals(MediaType.APPLICATION_JSON, preferred); assertEquals("text/html", secondChoice.getTypeSubtype()); assertEquals("*/*", everythingElse.getTypeSubtype()); } @Test public void testMediaTypeMatch() { MediaType one = MediaType.APPLICATION_JSON; MediaType two = MediaType.APPLICATION_JSON; assertTrue(one.match(two)); assertTrue(two.match(one)); } @Test public void testMediaTypeUnMatch() { MediaType one = MediaType.APPLICATION_JSON; MediaType two = MediaType.APPLICATION_JAVASCRIPT; assertFalse(one.match(two)); assertFalse(two.match(one)); } @Test public void testMediaTypeMatchItself() { MediaType one = MediaType.APPLICATION_JSON; assertTrue(one.match(one)); } @Test public void testMediaTypeExternalizerNoId() throws Exception { ObjectInOut inOutOrig = new ObjectInOut(); MediaType.MediaTypeExternalizer mediaTypeExternalizer = new MediaType.MediaTypeExternalizer(); mediaTypeExternalizer.writeObject(inOutOrig, MediaType.APPLICATION_XML); MediaType mediaType = mediaTypeExternalizer.readObject(inOutOrig); assertMediaTypeNoParams(mediaType, "application", "xml"); } @Test public void testMediaTypeExternalizerId() throws Exception { ObjectInOut inOutOrig = new ObjectInOut(); MediaType.MediaTypeExternalizer mediaTypeExternalizer = new MediaType.MediaTypeExternalizer(); mediaTypeExternalizer.writeObject(inOutOrig, MediaType.TEXT_PLAIN); MediaType mediaType = mediaTypeExternalizer.readObject(inOutOrig); assertMediaTypeNoParams(mediaType, "text", "plain"); } private void assertMediaTypeNoParams(MediaType mediaType, String type, String subType) { assertEquals(type, mediaType.getType()); assertEquals(subType, mediaType.getSubType()); assertFalse(mediaType.hasParameters()); assertEquals(Optional.empty(), mediaType.getParameter("a")); } private void assertMediaTypeWithParam(MediaType mediaType, String type, String subType, String paramName, String paramValue) { assertMediaTypeWithParams(mediaType, type, subType, new String[]{paramName}, new String[]{paramValue}); } private void assertMediaTypeWithParams(MediaType mediaType, String type, String subType, String[] paramNames, String[] paramValues) { assertEquals(type, mediaType.getType()); assertEquals(subType, mediaType.getSubType()); assertTrue(mediaType.hasParameters()); for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; assertEquals(Optional.of(paramValue), mediaType.getParameter(paramName)); } } private static class MapEntry { private final String key; private final String value; String getKey() { return key; } String getValue() { return value; } MapEntry(String key, String value) { this.key = key; this.value = value; } } private static Map<String, String> createMap(MapEntry... entries) { Map<String, String> map = new HashMap<>(); Arrays.stream(entries).forEach(e -> map.put(e.getKey(), e.getValue())); return map; } private static class ObjectInOut implements ObjectInput, ObjectOutput { private final Queue<Object> buffer = new LinkedList<>(); @Override public Object readObject() throws ClassNotFoundException, IOException { return buffer.remove(); } @Override public int read() { throw new UnsupportedOperationException(); } @Override public int read(byte[] b) { throw new UnsupportedOperationException(); } @Override public int read(byte[] b, int off, int len) { throw new UnsupportedOperationException(); } @Override public long skip(long n) { throw new UnsupportedOperationException(); } @Override public int available() { throw new UnsupportedOperationException(); } @Override public void writeObject(Object obj) throws IOException { buffer.add(obj); } @Override public void write(int b) { throw new UnsupportedOperationException(); } @Override public void write(byte[] b) { throw new UnsupportedOperationException(); } @Override public void write(byte[] b, int off, int len) { throw new UnsupportedOperationException(); } @Override public void writeBoolean(boolean v) { buffer.add(v); } @Override public void writeByte(int v) { throw new UnsupportedOperationException(); } @Override public void writeShort(int v) { buffer.add((short) v); } @Override public void writeChar(int v) { throw new UnsupportedOperationException(); } @Override public void writeInt(int v) { throw new UnsupportedOperationException(); } @Override public void writeLong(long v) { throw new UnsupportedOperationException(); } @Override public void writeFloat(float v) { throw new UnsupportedOperationException(); } @Override public void writeDouble(double v) { throw new UnsupportedOperationException(); } @Override public void writeBytes(String s) { throw new UnsupportedOperationException(); } @Override public void writeChars(String s) { throw new UnsupportedOperationException(); } @Override public void writeUTF(String s) { buffer.add(s); } @Override public void flush() { throw new UnsupportedOperationException(); } @Override public void close() { throw new UnsupportedOperationException(); } @Override public void readFully(byte[] b) { throw new UnsupportedOperationException(); } @Override public void readFully(byte[] b, int off, int len) { throw new UnsupportedOperationException(); } @Override public int skipBytes(int n) { throw new UnsupportedOperationException(); } @Override public boolean readBoolean() { return (boolean) buffer.remove(); } @Override public byte readByte() { throw new UnsupportedOperationException(); } @Override public int readUnsignedByte() { throw new UnsupportedOperationException(); } @Override public short readShort() { return (short) buffer.remove(); } @Override public int readUnsignedShort() { throw new UnsupportedOperationException(); } @Override public char readChar() { throw new UnsupportedOperationException(); } @Override public int readInt() { throw new UnsupportedOperationException(); } @Override public long readLong() { throw new UnsupportedOperationException(); } @Override public float readFloat() { throw new UnsupportedOperationException(); } @Override public double readDouble() { throw new UnsupportedOperationException(); } @Override public String readLine() { throw new UnsupportedOperationException(); } @Override public String readUTF() { return (String) buffer.remove(); } } }
16,811
30.542214
136
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/stat/DefaultSimpleStatTest.java
package org.infinispan.commons.stat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * An unit test for {@link DefaultSimpleStat} * * @author Pedro Ruivo * @since 10.0 */ public class DefaultSimpleStatTest { @Test public void testDefaultValues() { SimpleStat stat = new DefaultSimpleStat(); assertEquals(-10, stat.getMin(-10)); assertEquals(-11, stat.getAverage(-11)); assertEquals(-12, stat.getMax(-12)); assertEquals(0, stat.count()); assertTrue(stat.isEmpty()); } @Test public void testValues() { SimpleStat stat = new DefaultSimpleStat(); stat.record(-1); stat.record(0); stat.record(1); assertEquals(-1, stat.getMin(-10)); assertEquals(0, stat.getAverage(-11)); assertEquals(1, stat.getMax(-12)); assertEquals(3, stat.count()); assertFalse(stat.isEmpty()); } }
997
22.761905
48
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/tx/XidUnitTest.java
package org.infinispan.commons.tx; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Random; import javax.transaction.xa.Xid; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.commons.util.Util; import org.junit.Assert; import org.junit.Test; /** * @author Pedro Ruivo * @since 9.1 */ public class XidUnitTest { private static final Log log = LogFactory.getLog(XidUnitTest.class); @Test(expected = IllegalArgumentException.class) public void testInvalidGlobalTransaction() { long seed = System.currentTimeMillis(); log.infof("[testInvalidGlobalTransaction] seed: %s", seed); Random random = new Random(seed); Xid xid = XidImpl.create(random.nextInt(), Util.EMPTY_BYTE_ARRAY, new byte[]{0}); log.debugf("Invalid XID: %s", xid); } @Test(expected = IllegalArgumentException.class) public void testInvalidGlobalTransaction2() { long seed = System.currentTimeMillis(); log.infof("[testInvalidGlobalTransaction2] seed: %s", seed); Random random = new Random(seed); byte[] globalTx = new byte[65]; //max is 64 random.nextBytes(globalTx); Xid xid = XidImpl.create(random.nextInt(), globalTx, new byte[]{0}); log.debugf("Invalid XID: %s", xid); } @Test(expected = IllegalArgumentException.class) public void testInvalidBranch() { long seed = System.currentTimeMillis(); log.infof("[testInvalidBranch] seed: %s", seed); Random random = new Random(seed); Xid xid = XidImpl.create(random.nextInt(), new byte[]{0}, Util.EMPTY_BYTE_ARRAY); log.debugf("Invalid XID: %s", xid); } @Test(expected = IllegalArgumentException.class) public void testInvalidBranch2() { long seed = System.currentTimeMillis(); log.infof("[testInvalidBranch2] seed: %s", seed); Random random = new Random(seed); byte[] branch = new byte[65]; //max is 64 random.nextBytes(branch); Xid xid = XidImpl.create(random.nextInt(), new byte[]{0}, branch); log.debugf("Invalid XID: %s", xid); } @Test public void testCorrectDataStored() { long seed = System.currentTimeMillis(); log.infof("[testCorrectDataStored] seed: %s", seed); Random random = new Random(seed); int formatId = random.nextInt(); byte[] tx = new byte[random.nextInt(64) + 1]; byte[] branch = new byte[random.nextInt(64) + 1]; random.nextBytes(tx); random.nextBytes(branch); Xid xid = XidImpl.create(formatId, tx, branch); log.debugf("XID: %s", xid); Assert.assertEquals(formatId, xid.getFormatId()); Assert.assertArrayEquals(tx, xid.getGlobalTransactionId()); Assert.assertArrayEquals(branch, xid.getBranchQualifier()); Xid sameXid = XidImpl.create(formatId, tx, branch); log.debugf("same XID: %s", sameXid); Assert.assertEquals(xid, sameXid); } @Test public void testCorrectDataStoredMaxSize() { long seed = System.currentTimeMillis(); log.infof("[testCorrectDataStoredMaxSize] seed: %s", seed); Random random = new Random(seed); int formatId = random.nextInt(); byte[] tx = new byte[Xid.MAXGTRIDSIZE]; byte[] branch = new byte[Xid.MAXBQUALSIZE]; random.nextBytes(tx); random.nextBytes(branch); Xid xid = XidImpl.create(formatId, tx, branch); log.debugf("XID: %s", xid); Assert.assertEquals(formatId, xid.getFormatId()); Assert.assertArrayEquals(tx, xid.getGlobalTransactionId()); Assert.assertArrayEquals(branch, xid.getBranchQualifier()); Xid sameXid = XidImpl.create(formatId, tx, branch); log.debugf("same XID: %s", sameXid); Assert.assertEquals(xid, sameXid); } @Test public void testMarshalling() throws IOException, ClassNotFoundException { long seed = System.currentTimeMillis(); log.infof("[testMarshalling] seed: %s", seed); Random random = new Random(seed); int formatId = random.nextInt(); byte[] tx = new byte[random.nextInt(64) + 1]; byte[] branch = new byte[random.nextInt(64) + 1]; random.nextBytes(tx); random.nextBytes(branch); XidImpl xid = XidImpl.create(formatId, tx, branch); log.debugf("XID: %s", xid); ByteArrayOutputStream bos = new ByteArrayOutputStream(256); ObjectOutput oo = new ObjectOutputStream(bos); XidImpl.writeTo(oo, xid); oo.flush(); oo.close(); bos.close(); byte[] marshalled = bos.toByteArray(); log.debugf("Size: %s", marshalled.length); ByteArrayInputStream bis = new ByteArrayInputStream(marshalled); ObjectInput oi = new ObjectInputStream(bis); XidImpl otherXid = XidImpl.readFrom(oi); oi.close(); bis.close(); log.debugf("other XID: %s", xid); Assert.assertEquals(xid, otherXid); } @Test public void testMarshallingMaxSize() throws IOException, ClassNotFoundException { long seed = System.currentTimeMillis(); log.infof("[testMarshallingMaxSize] seed: %s", seed); Random random = new Random(seed); int formatId = random.nextInt(); byte[] tx = new byte[Xid.MAXGTRIDSIZE]; byte[] branch = new byte[Xid.MAXBQUALSIZE]; random.nextBytes(tx); random.nextBytes(branch); XidImpl xid = XidImpl.create(formatId, tx, branch); log.debugf("XID: %s", xid); ByteArrayOutputStream bos = new ByteArrayOutputStream(256); ObjectOutput oo = new ObjectOutputStream(bos); XidImpl.writeTo(oo, xid); oo.flush(); oo.close(); bos.close(); byte[] marshalled = bos.toByteArray(); log.debugf("Size: %s", marshalled.length); ByteArrayInputStream bis = new ByteArrayInputStream(marshalled); ObjectInput oi = new ObjectInputStream(bis); XidImpl otherXid = XidImpl.readFrom(oi); oi.close(); bis.close(); log.debugf("other XID: %s", xid); Assert.assertEquals(xid, otherXid); } }
6,219
32.085106
87
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/marshall/ProtoStreamTypeIdsUniquenessTest.java
package org.infinispan.commons.marshall; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; import org.junit.Test; /** * Ensures there are no duplicate Id values in {@link ProtoStreamTypeIds}. * * @author Ryan Emerson * @since 10.0 */ public class ProtoStreamTypeIdsUniquenessTest { @Test public void testIdUniqueness() throws Exception { Class clazz = ProtoStreamTypeIds.class; Field[] fields = clazz.getFields(); Set<Integer> messageIds = new HashSet<>(); Set<Integer> lowerBounds = new HashSet<>(); for (Field f : fields) { if (f.getName().endsWith("_LOWER_BOUND")) assertTrue(lowerBounds.add(f.getInt(clazz))); else assertTrue(messageIds.add(f.getInt(clazz))); } assertTrue(messageIds.size() > 0); assertTrue(lowerBounds.size() > 0); assertEquals(fields.length - lowerBounds.size(), messageIds.size()); assertEquals(fields.length - messageIds.size(), lowerBounds.size()); } }
1,117
29.216216
74
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/marshall/JavaSerializationMarshallerTest.java
package org.infinispan.commons.marshall; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.Serializable; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Instant; import org.infinispan.commons.CacheException; import org.junit.Assert; import org.junit.Test; public class JavaSerializationMarshallerTest { @Test public void testPrimitiveArrays() throws Exception { JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller(); byte[] bytes = marshaller.objectToByteBuffer(new byte[0]); assertArrayEquals(new byte[0], (byte[]) marshaller.objectFromByteBuffer(bytes)); bytes = marshaller.objectToByteBuffer(new short[0]); assertArrayEquals(new short[0], (short[]) marshaller.objectFromByteBuffer(bytes)); bytes = marshaller.objectToByteBuffer(new int[0]); assertArrayEquals(new int[0], (int[]) marshaller.objectFromByteBuffer(bytes)); bytes = marshaller.objectToByteBuffer(new long[0]); assertArrayEquals(new long[0], (long[]) marshaller.objectFromByteBuffer(bytes)); bytes = marshaller.objectToByteBuffer(new float[0]); assertArrayEquals(new float[0], (float[]) marshaller.objectFromByteBuffer(bytes), 0); bytes = marshaller.objectToByteBuffer(new double[0]); assertArrayEquals(new double[0], (double[]) marshaller.objectFromByteBuffer(bytes), 0); bytes = marshaller.objectToByteBuffer(new char[0]); assertArrayEquals(new char[0], (char[]) marshaller.objectFromByteBuffer(bytes)); bytes = marshaller.objectToByteBuffer(new boolean[0]); assertArrayEquals(new boolean[0], (boolean[]) marshaller.objectFromByteBuffer(bytes)); } @Test public void testBoxedPrimitivesAndArray() throws Exception { JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller(); isMarshallable(marshaller, Byte.MAX_VALUE); isMarshallable(marshaller, Short.MAX_VALUE); isMarshallable(marshaller, Integer.MAX_VALUE); isMarshallable(marshaller, Long.MAX_VALUE); isMarshallable(marshaller, Float.MAX_VALUE); isMarshallable(marshaller, Double.MAX_VALUE); isMarshallable(marshaller, 'c'); isMarshallable(marshaller, "String"); } @Test public void testMath() throws Exception { JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller(); isMarshallable(marshaller, BigDecimal.TEN); isMarshallable(marshaller, BigInteger.TEN); } @Test public void testDate() throws Exception { JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller(); isMarshallable(marshaller, Instant.now()); } @Test public void testCustomClassAndArray() throws Exception { JavaSerializationMarshaller marshaller = new JavaSerializationMarshaller(); byte[] bytes = marshaller.objectToByteBuffer(new CustomClass()); try { marshaller.objectFromByteBuffer(bytes); Assert.fail("Expected an exception to be thrown when reading the Serialization bytes"); } catch (CacheException e) { assertTrue(e.getMessage().contains("blocked by deserialization allow list")); } marshaller.allowList.addClasses(CustomClass.class); assertNotNull(marshaller.objectFromByteBuffer(bytes)); isMarshallable(marshaller, new CustomClass()); } private static <V> void isMarshallable(Marshaller marshaller, V o) throws Exception { byte[] bytes = marshaller.objectToByteBuffer(o); assertEquals(o, marshaller.objectFromByteBuffer(bytes)); V[] array = (V[]) Array.newInstance(o.getClass(), 1); bytes = marshaller.objectToByteBuffer(array); assertArrayEquals(array, (V[]) marshaller.objectFromByteBuffer(bytes)); } private static class CustomClass implements Serializable { @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { return obj instanceof CustomClass; } } }
4,207
36.238938
96
java
null
infinispan-main/commons/all/src/test/java/org/infinispan/commons/marshall/ProtoStreamMarshallerTest.java
package org.infinispan.commons.marshall; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.time.Instant; import java.util.Date; import org.junit.Test; /** * A simple smoke test to ensure BaseProtoStreamMarshaller is able to handle primitive types besides actual protobuf * messages and enums. * * @author anistor@redhat.com */ public class ProtoStreamMarshallerTest { @Test public void testBasicTypesAreMarshallable() throws Exception { roundtrip("a"); roundtrip('a'); roundtrip(0); roundtrip(0L); roundtrip(0.0D); roundtrip(0.0F); roundtrip((byte) 0); roundtrip((short) 0); roundtrip(true); roundtrip(new Date(0)); roundtrip(Instant.now()); roundtrip(new byte[0]); } private void roundtrip(Object in) throws Exception { ProtoStreamMarshaller marshaller = new ProtoStreamMarshaller(); assertTrue(marshaller.isMarshallable(in)); byte[] buffer = marshaller.objectToByteBuffer(in); assertNotNull(buffer); Object out = marshaller.objectFromByteBuffer(buffer); assertNotNull(out); assertEquals(in.getClass(), out.getClass()); if (in instanceof byte[]) { assertArrayEquals((byte[]) in, (byte[]) out); } else { assertEquals(in, out); } } }
1,460
24.631579
116
java