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/commands/irac/IracTouchKeyCommand.java
|
package org.infinispan.commands.irac;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
import org.infinispan.xsite.BackupReceiver;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.irac.IracManager;
/**
* A request that is sent to the remote site by {@link IracManager}.
*
* @author William Burns
* @since 12.0
*/
public class IracTouchKeyCommand extends XSiteReplicateCommand<Boolean> {
public static final byte COMMAND_ID = 29;
private Object key;
@SuppressWarnings("unused")
public IracTouchKeyCommand() {
super(COMMAND_ID, null);
}
public IracTouchKeyCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public IracTouchKeyCommand(ByteString cacheName, Object key) {
super(COMMAND_ID, cacheName);
this.key = key;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
return null;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
}
@Override
public CompletionStage<Boolean> performInLocalSite(BackupReceiver receiver, boolean preserveOrder) {
assert !preserveOrder : "IRAC Touch Command sent asynchronously!";
return receiver.touchEntry(key);
}
}
| 1,649
| 26.5
| 104
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracCleanupKeysCommand.java
|
package org.infinispan.commands.irac;
import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.util.Util;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.xsite.irac.IracManager;
import org.infinispan.xsite.irac.IracManagerKeyInfo;
import org.infinispan.xsite.irac.IracManagerKeyInfoImpl;
/**
* Sends a cleanup request from the primary owner to the backup owners.
* <p>
* Sent after a successful update of all remote sites.
*
* @author Pedro Ruivo
* @since 11.0
*/
public class IracCleanupKeysCommand implements CacheRpcCommand {
public static final byte COMMAND_ID = 122;
private ByteString cacheName;
private Collection<? extends IracManagerKeyInfo> cleanup;
@SuppressWarnings("unused")
public IracCleanupKeysCommand() {
}
public IracCleanupKeysCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
public IracCleanupKeysCommand(ByteString cacheName, Collection<? extends IracManagerKeyInfo> cleanup) {
this.cacheName = cacheName;
this.cleanup = cleanup;
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public CompletableFuture<Object> invokeAsync(ComponentRegistry componentRegistry) {
IracManager manager = componentRegistry.getIracManager().running();
cleanup.forEach(manager::removeState);
return CompletableFutures.completedNull();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
marshallCollection(cleanup, output, IracManagerKeyInfoImpl::writeTo);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cleanup = unmarshallCollection(input, ArrayList::new, IracManagerKeyInfoImpl::readFrom);
}
@Override
public Address getOrigin() {
//not needed
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op
}
@Override
public String toString() {
return "IracCleanupKeyCommand{" +
"cacheName=" + cacheName +
", cleanup=" + Util.toStr(cleanup) +
'}';
}
}
| 2,824
| 26.696078
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracUpdateKeyCommand.java
|
package org.infinispan.commands.irac;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
import org.infinispan.xsite.BackupReceiver;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.irac.IracManager;
/**
* An update request that is sent to the remote site by {@link IracManager}.
*
* @author Pedro Ruivo
* @since 11.0
*/
public abstract class IracUpdateKeyCommand<T> extends XSiteReplicateCommand<T> {
protected IracUpdateKeyCommand(byte commandId, ByteString cacheName) {
super(commandId, cacheName);
}
@Override
public final CompletionStage<T> performInLocalSite(BackupReceiver receiver, boolean preserveOrder) {
assert !preserveOrder : "IRAC Update Command sent asynchronously!";
return executeOperation(receiver);
}
@Override
public final CompletionStage<?> invokeAsync(ComponentRegistry registry) {
throw new IllegalStateException(); //should never be invoked.
}
@Override
public final boolean isReturnValueExpected() {
return false;
}
public abstract CompletionStage<T> executeOperation(BackupReceiver receiver);
public boolean isClear() {
return false; //by default
}
}
| 1,283
| 27.533333
| 103
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracUpdateVersionCommand.java
|
package org.infinispan.commands.irac;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.container.versioning.irac.IracEntryVersion;
import org.infinispan.container.versioning.irac.IracVersionGenerator;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* It transfers the current versions stored in {@link IracVersionGenerator} to the other nodes when joins/leaving events
* occurs.
*
* @author Pedro Ruivo
* @since 12.0
*/
public class IracUpdateVersionCommand implements CacheRpcCommand {
public static final byte COMMAND_ID = 32;
private final ByteString cacheName;
private Map<Integer, IracEntryVersion> versions;
public IracUpdateVersionCommand() {
this(null);
}
public IracUpdateVersionCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
public IracUpdateVersionCommand(ByteString cacheName, Map<Integer, IracEntryVersion> segmentsVersion) {
this(cacheName);
this.versions = segmentsVersion;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
IracVersionGenerator versionGenerator = registry.getIracVersionGenerator().running();
versions.forEach(versionGenerator::updateVersion);
return CompletableFutures.completedNull();
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public Address getOrigin() {
//no-op, not required.
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op, not required.
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallMap(versions, DataOutput::writeInt, ObjectOutput::writeObject, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
versions = MarshallUtil.unmarshallMap(input, DataInput::readInt, IracUpdateVersionCommand::read, HashMap::new);
}
private static IracEntryVersion read(ObjectInput input) throws IOException, ClassNotFoundException {
return (IracEntryVersion) input.readObject();
}
@Override
public String toString() {
return "IracUpdateVersionCommand{" +
"cacheName=" + cacheName +
", versions=" + versions +
'}';
}
}
| 2,937
| 28.089109
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracRequestStateCommand.java
|
package org.infinispan.commands.irac;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSetsExternalization;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Requests the state for a given segments.
*
* @author Pedro Ruivo
* @since 11.0
*/
public class IracRequestStateCommand extends BaseRpcCommand {
public static final byte COMMAND_ID = 121;
private IntSet segments;
@SuppressWarnings("unused")
public IracRequestStateCommand() {
super(null);
}
public IracRequestStateCommand(ByteString cacheName) {
super(cacheName);
}
public IracRequestStateCommand(ByteString cacheName, IntSet segments) {
super(cacheName);
this.segments = segments;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
registry.getIracManager().wired().requestState(getOrigin(), segments);
return CompletableFutures.completedNull();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
IntSetsExternalization.writeTo(output, segments);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
this.segments = IntSetsExternalization.readFrom(input);
}
@Override
public String toString() {
return "IracRequestStateCommand{" +
"segments=" + segments +
", cacheName=" + cacheName +
'}';
}
}
| 1,922
| 24.64
| 87
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracPutManyCommand.java
|
package org.infinispan.commands.irac;
import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSets;
import org.infinispan.commons.util.Util;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.BackupReceiver;
/**
* A multi-key cross-site requests.
* <p>
* This command is used by asynchronous cross-site replication to send multiple keys batched to remote sites. The keys
* in this command can include updates, removal or expirations.
* <p>
* The element order in {@code updateList} is important because the reply will be a {@link IntSet} with the position of
* the failed keys.
*
* @since 14.0
*/
public class IracPutManyCommand extends IracUpdateKeyCommand<IntSet> {
private static final Log log = LogFactory.getLog(IracPutManyCommand.class);
public static final byte COMMAND_ID = 48;
private static final byte WRITE = 0;
private static final byte REMOVE = 1;
private static final byte EXPIRE = 2;
private List<Update> updateList;
@SuppressWarnings("unused")
public IracPutManyCommand() {
super(COMMAND_ID, null);
}
public IracPutManyCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public IracPutManyCommand(ByteString cacheName, int maxCapacity) {
super(COMMAND_ID, cacheName);
updateList = new ArrayList<>(maxCapacity);
}
public CompletionStage<IntSet> executeOperation(BackupReceiver receiver) {
IntSet rsp = IntSets.concurrentSet(updateList.size());
AggregateCompletionStage<IntSet> stage = CompletionStages.aggregateCompletionStage(rsp);
for (int i = 0; i < updateList.size(); ++i) {
int keyIndex = i;
Update update = updateList.get(i);
stage.dependsOn(update.execute(receiver).exceptionally(throwable -> {
if (log.isTraceEnabled()) {
log.tracef(throwable, "[IRAC] Received exception while applying %s", update);
}
rsp.set(keyIndex);
return null;
}));
}
return stage.freeze();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
marshallCollection(updateList, output, IracPutManyCommand::writeUpdateTo);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
updateList = unmarshallCollection(input, ArrayList::new, IracPutManyCommand::readUpdateFrom);
}
@Override
public String toString() {
return "IracPutManyCommand{" +
"cacheName=" + cacheName +
", originSite='" + originSite + '\'' +
", updateList=" + Util.toStr(updateList) +
'}';
}
public void addUpdate(Object key, Object value, Metadata metadata, IracMetadata iracMetadata) {
updateList.add(new Write(key, iracMetadata, value, metadata));
}
public void addRemove(Object key, IracMetadata tombstone) {
updateList.add(new Remove(key, tombstone));
}
public void addExpire(Object key, IracMetadata tombstone) {
updateList.add(new Expire(key, tombstone));
}
private static void writeUpdateTo(ObjectOutput output, Update update) throws IOException {
output.writeByte(update.getType());
update.writeTo(output);
}
private static Update readUpdateFrom(ObjectInput input) throws IOException, ClassNotFoundException {
switch (input.readByte()) {
case WRITE:
return new Write(input.readObject(), IracMetadata.readFrom(input), input.readObject(), (Metadata) input.readObject());
case REMOVE:
return new Remove(input.readObject(), IracMetadata.readFrom(input));
case EXPIRE:
return new Expire(input.readObject(), IracMetadata.readFrom(input));
}
throw new IllegalStateException();
}
public boolean isEmpty() {
return updateList.isEmpty();
}
private interface Update {
byte getType();
CompletionStage<Void> execute(BackupReceiver backupReceiver);
void writeTo(ObjectOutput output) throws IOException;
}
private static class Remove implements Update {
final Object key;
final IracMetadata iracMetadata;
private Remove(Object key, IracMetadata iracMetadata) {
this.key = key;
this.iracMetadata = iracMetadata;
}
@Override
public byte getType() {
return REMOVE;
}
@Override
public CompletionStage<Void> execute(BackupReceiver backupReceiver) {
return backupReceiver.removeKey(key, iracMetadata, false);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
IracMetadata.writeTo(output, iracMetadata);
}
@Override
public String toString() {
return "Remove{" +
"key=" + Util.toStr(key) +
", iracMetadata=" + iracMetadata +
'}';
}
}
private static final class Expire extends Remove {
private Expire(Object key, IracMetadata tombstone) {
super(key, tombstone);
}
@Override
public byte getType() {
return EXPIRE;
}
@Override
public CompletionStage<Void> execute(BackupReceiver backupReceiver) {
return backupReceiver.removeKey(key, iracMetadata, true);
}
@Override
public String toString() {
return "Expire{" +
"key=" + Util.toStr(key) +
", iracMetadata=" + iracMetadata +
'}';
}
}
private static final class Write extends Remove {
private final Object value;
private final Metadata metadata;
private Write(Object key, IracMetadata metadata, Object value, Metadata metadata1) {
super(key, metadata);
this.value = value;
this.metadata = metadata1;
}
@Override
public byte getType() {
return WRITE;
}
@Override
public CompletionStage<Void> execute(BackupReceiver backupReceiver) {
return backupReceiver.putKeyValue(key, value, metadata, iracMetadata);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output);
output.writeObject(value);
output.writeObject(metadata);
}
@Override
public String toString() {
return "Write{" +
"key=" + Util.toStr(key) +
", value=" + Util.toStr(value) +
", iracMetadata=" + iracMetadata +
", metadata=" + metadata +
'}';
}
}
}
| 7,360
| 29.168033
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracClearKeysCommand.java
|
package org.infinispan.commands.irac;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.util.ByteString;
import org.infinispan.xsite.BackupReceiver;
import org.infinispan.xsite.irac.IracManager;
/**
* A clear request that is sent to the remote site by {@link IracManager}.
*
* @author Pedro Ruivo
* @since 11.0
*/
public class IracClearKeysCommand extends IracUpdateKeyCommand<Void> {
public static final byte COMMAND_ID = 17;
@SuppressWarnings("unused")
public IracClearKeysCommand() {
super(COMMAND_ID, null);
}
public IracClearKeysCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public CompletionStage<Void> executeOperation(BackupReceiver receiver) {
return receiver.clearKeys();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) {
}
@Override
public void readFrom(ObjectInput input) {
}
@Override
public boolean isClear() {
return true;
}
@Override
public String toString() {
return "IracClearKeyCommand{" +
"originSite='" + originSite + '\'' +
", cacheName=" + cacheName +
'}';
}
}
| 1,299
| 20.666667
| 75
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracTombstonePrimaryCheckCommand.java
|
package org.infinispan.commands.irac;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.container.versioning.irac.IracTombstoneInfo;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.xsite.irac.IracManager;
/**
* A {@link CacheRpcCommand} to check if one or more tombstones are still valid.
* <p>
* Periodically, the backup owner send this command for the tombstones they have stored if the key is not present in
* {@link IracManager}.
*
* @since 14.0
*/
public class IracTombstonePrimaryCheckCommand implements CacheRpcCommand {
public static final byte COMMAND_ID = 47;
private ByteString cacheName;
private Collection<IracTombstoneInfo> tombstoneToCheck;
@SuppressWarnings("unused")
public IracTombstonePrimaryCheckCommand() {
}
public IracTombstonePrimaryCheckCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
public IracTombstonePrimaryCheckCommand(ByteString cacheName, Collection<IracTombstoneInfo> tombstoneToCheck) {
this.cacheName = cacheName;
this.tombstoneToCheck = tombstoneToCheck;
}
@Override
public CompletionStage<Void> invokeAsync(ComponentRegistry registry) {
registry.getIracTombstoneManager().running().checkStaleTombstone(tombstoneToCheck);
return CompletableFutures.completedNull();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallCollection(tombstoneToCheck, output, IracTombstoneInfo::writeTo);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
tombstoneToCheck = MarshallUtil.unmarshallCollection(input, ArrayList::new, IracTombstoneInfo::readFrom);
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public Address getOrigin() {
//no-op
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op
}
@Override
public String toString() {
return "IracTombstonePrimaryCheckCommand{" +
"cacheName=" + cacheName +
", tombstoneToCheck=" + tombstoneToCheck +
'}';
}
public Collection<IracTombstoneInfo> getTombstoneToCheck() {
return tombstoneToCheck;
}
}
| 2,860
| 27.326733
| 116
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracStateResponseCommand.java
|
package org.infinispan.commands.irac;
import static java.util.Objects.requireNonNull;
import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commons.util.Util;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.xsite.irac.IracManager;
import org.infinispan.xsite.irac.IracManagerKeyInfo;
import org.infinispan.xsite.irac.IracManagerKeyInfoImpl;
/**
* The IRAC state for a given key.
*
* @author Pedro Ruivo
* @since 11.0
*/
public class IracStateResponseCommand implements CacheRpcCommand {
public static final byte COMMAND_ID = 120;
private ByteString cacheName;
private Collection<State> stateCollection;
@SuppressWarnings("unused")
public IracStateResponseCommand() {
}
public IracStateResponseCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
public IracStateResponseCommand(ByteString cacheName, int capacity) {
this(cacheName);
stateCollection = new ArrayList<>(capacity);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) {
IracManager manager = registry.getIracManager().running();
for (State state : stateCollection) {
state.apply(manager);
}
return CompletableFutures.completedNull();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
marshallCollection(stateCollection, output, IracStateResponseCommand::writeStateTo);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
stateCollection = unmarshallCollection(input, ArrayList::new, IracStateResponseCommand::readStateFrom);
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public Address getOrigin() {
//no-op
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op
}
public void add(IracManagerKeyInfo keyInfo, IracMetadata tombstone) {
stateCollection.add(new State(keyInfo, tombstone));
}
@Override
public String toString() {
return "IracStateResponseCommand{" +
"cacheName=" + cacheName +
", state=" + Util.toStr(stateCollection) +
'}';
}
private static void writeStateTo(ObjectOutput output, State state) throws IOException {
IracManagerKeyInfoImpl.writeTo(output, state.keyInfo);
IracMetadata.writeTo(output, state.tombstone);
}
private static State readStateFrom(ObjectInput input) throws IOException, ClassNotFoundException {
return new State(IracManagerKeyInfoImpl.readFrom(input), IracMetadata.readFrom(input));
}
private static class State {
final IracManagerKeyInfo keyInfo;
final IracMetadata tombstone;
State(IracManagerKeyInfo keyInfo, IracMetadata tombstone) {
this.keyInfo = requireNonNull(keyInfo);
this.tombstone = tombstone;
}
void apply(IracManager manager) {
manager.receiveState(keyInfo.getSegment(), keyInfo.getKey(), keyInfo.getOwner(), tombstone);
}
@Override
public String toString() {
return "State{" +
"keyInfo=" + keyInfo +
", tombstone=" + tombstone +
'}';
}
}
}
| 3,998
| 27.769784
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracTombstoneStateResponseCommand.java
|
package org.infinispan.commands.irac;
import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.container.versioning.irac.IracTombstoneInfo;
import org.infinispan.container.versioning.irac.IracTombstoneManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Response for a state request with the tombstones stored in the local node.
*
* @since 14.0
*/
public class IracTombstoneStateResponseCommand implements CacheRpcCommand {
public static final byte COMMAND_ID = 39;
private ByteString cacheName;
private Collection<IracTombstoneInfo> state;
@SuppressWarnings("unused")
public IracTombstoneStateResponseCommand() {
}
public IracTombstoneStateResponseCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
public IracTombstoneStateResponseCommand(ByteString cacheName, Collection<IracTombstoneInfo> state) {
this.cacheName = cacheName;
this.state = state;
}
@Override
public CompletionStage<Void> invokeAsync(ComponentRegistry registry) {
IracTombstoneManager tombstoneManager = registry.getIracTombstoneManager().running();
for (IracTombstoneInfo data : state) {
tombstoneManager.storeTombstoneIfAbsent(data);
}
return CompletableFutures.completedNull();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
marshallCollection(state, output, IracTombstoneInfo::writeTo);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
state = unmarshallCollection(input, ArrayList::new, IracTombstoneInfo::readFrom);
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public Address getOrigin() {
//no-op
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op
}
@Override
public String toString() {
return "IracTombstoneStateResponseCommand{" +
"cacheName=" + cacheName +
", state=" + state +
'}';
}
}
| 2,742
| 26.707071
| 104
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/irac/IracMetadataRequestCommand.java
|
package org.infinispan.commands.irac;
import static java.util.concurrent.CompletableFuture.completedFuture;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.container.versioning.irac.IracEntryVersion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
/**
* A request for a new {@link IracMetadata} for a giver segment.
*
* @author Pedro Ruivo
* @since 11.0
*/
public class IracMetadataRequestCommand implements CacheRpcCommand, TopologyAffectedCommand {
public static final byte COMMAND_ID = 124;
private ByteString cacheName;
private int segment;
private int topologyId = -1;
private IracEntryVersion versionSeen;
public IracMetadataRequestCommand() {
}
public IracMetadataRequestCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
public IracMetadataRequestCommand(ByteString cacheName, int segment, IracEntryVersion versionSeen) {
this.cacheName = cacheName;
this.segment = segment;
this.versionSeen = versionSeen;
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
return completedFuture(registry.getIracVersionGenerator().running().generateNewMetadata(segment, versionSeen));
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeInt(segment);
output.writeObject(versionSeen);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
this.segment = input.readInt();
this.versionSeen = (IracEntryVersion) input.readObject();
}
@Override
public Address getOrigin() {
//not needed
return null;
}
@Override
public void setOrigin(Address origin) {
//no-op
}
@Override
public String toString() {
return "IracMetadataRequestCommand{" +
"cacheName=" + cacheName +
", segment=" + segment +
", topologyId=" + topologyId +
", versionSeen=" + versionSeen +
'}';
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
}
| 2,803
| 24.724771
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/statetransfer/StateTransferCancelCommand.java
|
package org.infinispan.commands.statetransfer;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.util.IntSet;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.statetransfer.StateProvider;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Cancel state transfer.
*
* @author Ryan Emerson
* @since 11.0
*/
public class StateTransferCancelCommand extends AbstractStateTransferCommand {
public static final byte COMMAND_ID = 117;
public StateTransferCancelCommand() {
this(null);
}
public StateTransferCancelCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public StateTransferCancelCommand(ByteString cacheName, int topologyId, IntSet segments) {
super(COMMAND_ID, cacheName, topologyId, segments);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
StateProvider stateProvider = registry.getStateTransferManager().getStateProvider();
stateProvider.cancelOutboundTransfer(origin, topologyId, segments);
return CompletableFutures.completedNull();
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public String toString() {
return "StateTransferCancelCommand{" +
"topologyId=" + topologyId +
", segments=" + segments +
", cacheName=" + cacheName +
'}';
}
}
| 1,511
| 27
| 93
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/statetransfer/StateTransferStartCommand.java
|
package org.infinispan.commands.statetransfer;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.util.IntSet;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.statetransfer.StateProvider;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Start state transfer.
*
* @author Ryan Emerson
* @since 11.0
*/
public class StateTransferStartCommand extends AbstractStateTransferCommand {
public static final byte COMMAND_ID = 116;
// For command id uniqueness test only
public StateTransferStartCommand() {
this(null);
}
public StateTransferStartCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public StateTransferStartCommand(ByteString cacheName, int topologyId, IntSet segments) {
super(COMMAND_ID, cacheName, topologyId, segments);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
StateProvider stateProvider = registry.getStateTransferManager().getStateProvider();
stateProvider.startOutboundTransfer(origin, topologyId, segments, true);
return CompletableFutures.completedNull();
}
@Override
public String toString() {
return "StateTransferStartCommand{" +
"topologyId=" + topologyId +
", segments=" + segments +
", cacheName=" + cacheName +
'}';
}
}
| 1,469
| 28.4
| 92
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/statetransfer/StateTransferGetTransactionsCommand.java
|
package org.infinispan.commands.statetransfer;
import java.util.List;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.util.IntSet;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.statetransfer.StateProvider;
import org.infinispan.statetransfer.TransactionInfo;
import org.infinispan.util.ByteString;
/**
* Get transactions for the specified segments.
*
* @author Ryan Emerson
* @since 11.0
*/
public class StateTransferGetTransactionsCommand extends AbstractStateTransferCommand {
public static final byte COMMAND_ID = 119;
// For command id uniqueness test only
public StateTransferGetTransactionsCommand() {
this(null);
}
public StateTransferGetTransactionsCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public StateTransferGetTransactionsCommand(ByteString cacheName, int topologyId, IntSet segments) {
super(COMMAND_ID, cacheName, topologyId, segments);
}
@Override
public CompletionStage<List<TransactionInfo>> invokeAsync(ComponentRegistry registry) throws Throwable {
StateProvider stateProvider = registry.getStateTransferManager().getStateProvider();
return stateProvider.getTransactionsForSegments(origin, topologyId, segments);
}
@Override
public String toString() {
return "StateTransferGetTransactionsCommand{" +
"topologyId=" + topologyId +
", segments=" + segments +
", cacheName=" + cacheName +
'}';
}
}
| 1,529
| 29.6
| 107
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/statetransfer/ConflictResolutionStartCommand.java
|
package org.infinispan.commands.statetransfer;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.util.IntSet;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.statetransfer.StateProvider;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Start conflict resolution.
*
* @author Ryan Emerson
* @since 11.0
*/
public class ConflictResolutionStartCommand extends AbstractStateTransferCommand {
public static final byte COMMAND_ID = 112;
// For command id uniqueness test only
public ConflictResolutionStartCommand() {
this(null);
}
public ConflictResolutionStartCommand(ByteString cacheName) {
super(COMMAND_ID, cacheName);
}
public ConflictResolutionStartCommand(ByteString cacheName, int topologyId, IntSet segments) {
super(COMMAND_ID, cacheName, topologyId, segments);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
StateProvider stateProvider = registry.getStateTransferManager().getStateProvider();
stateProvider.startOutboundTransfer(origin, topologyId, segments, false);
return CompletableFutures.completedNull();
}
@Override
public String toString() {
return "ConflictResolutionStartCommand{" +
"topologyId=" + topologyId +
", segments=" + segments +
", cacheName=" + cacheName +
'}';
}
}
| 1,500
| 29.02
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/statetransfer/StateResponseCommand.java
|
package org.infinispan.commands.statetransfer;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.conflict.impl.StateReceiver;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.statetransfer.StateChunk;
import org.infinispan.statetransfer.StateConsumer;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* This command is used by a StateProvider to push cache entries to a StateConsumer.
*
* @author anistor@redhat.com
* @since 5.2
*/
public class StateResponseCommand extends BaseRpcCommand implements TopologyAffectedCommand {
private static final Log log = LogFactory.getLog(StateResponseCommand.class);
public static final byte COMMAND_ID = 20;
/**
* The topology id of the sender at send time.
*/
private int topologyId;
/**
* A collections of state chunks to be transferred.
*/
private Collection<StateChunk> stateChunks;
/**
* Whether the returned state should be applied to the underlying cache upon delivery
*/
private boolean applyState;
private StateResponseCommand() {
super(null); // for command id uniqueness test
}
public StateResponseCommand(ByteString cacheName) {
super(cacheName);
}
public StateResponseCommand(ByteString cacheName, int topologyId, Collection<StateChunk> stateChunks,
boolean applyState) {
super(cacheName);
this.topologyId = topologyId;
this.stateChunks = stateChunks;
this.applyState = applyState;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
final boolean trace = log.isTraceEnabled();
LogFactory.pushNDC(cacheName, trace);
try {
if (applyState) {
StateConsumer stateConsumer = componentRegistry.getStateTransferManager().getStateConsumer();
return stateConsumer.applyState(origin, topologyId, stateChunks);
} else {
StateReceiver stateReceiver = componentRegistry.getConflictManager().running().getStateReceiver();
stateReceiver.receiveState(origin, topologyId, stateChunks);
}
return CompletableFutures.completedNull();
} finally {
LogFactory.popNDC(trace);
}
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
public Collection<StateChunk> getStateChunks() {
return stateChunks;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallCollection(stateChunks, output);
output.writeBoolean(applyState);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
stateChunks = MarshallUtil.unmarshallCollection(input, ArrayList::new);
applyState = input.readBoolean();
}
@Override
public String toString() {
return "StateResponseCommand{" +
"cache=" + cacheName +
", stateChunks=" + stateChunks +
", origin=" + origin +
", topologyId=" + topologyId +
", applyState=" + applyState +
'}';
}
}
| 3,874
| 28.807692
| 110
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/statetransfer/AbstractStateTransferCommand.java
|
package org.infinispan.commands.statetransfer;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSetsExternalization;
import org.infinispan.util.ByteString;
/**
* Base class for commands related to state transfer.
*
* @author Ryan Emerson
* @since 11.0
*/
abstract class AbstractStateTransferCommand extends BaseRpcCommand implements TopologyAffectedCommand {
private final byte commandId;
protected int topologyId;
protected IntSet segments;
AbstractStateTransferCommand(byte commandId, ByteString cacheName) {
super(cacheName);
this.commandId = commandId;
}
AbstractStateTransferCommand(byte commandId, ByteString cacheName, int topologyId, IntSet segments) {
this(commandId, cacheName);
this.topologyId = topologyId;
this.segments = segments;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
public IntSet getSegments() {
return segments;
}
@Override
public byte getCommandId() {
return commandId;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
IntSetsExternalization.writeTo(output, segments);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
segments = IntSetsExternalization.readFrom(input);
}
}
| 1,739
| 23.857143
| 104
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/statetransfer/StateTransferGetListenersCommand.java
|
package org.infinispan.commands.statetransfer;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.notifications.cachelistener.cluster.ClusterListenerReplicateCallable;
import org.infinispan.statetransfer.StateProvider;
import org.infinispan.util.ByteString;
/**
* Get the registered cluster listeners.
*
* @author Ryan Emerson
* @since 11.0
*/
public class StateTransferGetListenersCommand extends BaseRpcCommand implements TopologyAffectedCommand {
public static final byte COMMAND_ID = 118;
private int topologyId;
// For command id uniqueness test only
public StateTransferGetListenersCommand() {
this(null);
}
public StateTransferGetListenersCommand(ByteString cacheName) {
super(cacheName);
}
public StateTransferGetListenersCommand(ByteString cacheName, int topologyId) {
super(cacheName);
this.topologyId = topologyId;
}
@Override
public CompletionStage<Collection<ClusterListenerReplicateCallable<Object, Object>>> invokeAsync(ComponentRegistry registry) throws Throwable {
StateProvider stateProvider = registry.getStateTransferManager().getStateProvider();
Collection<ClusterListenerReplicateCallable<Object, Object>> listeners = stateProvider.getClusterListenersToInstall();
return CompletableFuture.completedFuture(listeners);
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
}
@Override
public String toString() {
return "StateTransferGetListenersCommand{" +
"topologyId=" + topologyId +
", cacheName=" + cacheName +
'}';
}
}
| 2,399
| 26.906977
| 146
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/AbstractDataCommand.java
|
package org.infinispan.commands.read;
import static org.infinispan.commons.util.EnumUtil.prettyPrintBitSet;
import static org.infinispan.commons.util.Util.toStr;
import java.util.Objects;
import org.infinispan.commands.DataCommand;
import org.infinispan.commands.SegmentSpecificCommand;
import org.infinispan.context.Flag;
/**
* @author Mircea.Markus@jboss.com
* @author Sanne Grinovero <sanne@hibernate.org> (C) 2011 Red Hat Inc.
* @since 4.0
*/
public abstract class AbstractDataCommand implements DataCommand, SegmentSpecificCommand {
protected Object key;
private long flags;
// These 2 ints have to stay next to each other to ensure they are aligned together
private int topologyId = -1;
protected int segment;
protected AbstractDataCommand(Object key, int segment, long flagsBitSet) {
this.key = key;
if (segment < 0) {
throw new IllegalArgumentException("Segment must be 0 or greater");
}
this.segment = segment;
this.flags = flagsBitSet;
}
protected AbstractDataCommand() {
this.segment = -1;
}
@Override
public int getSegment() {
return segment;
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
@Override
public long getFlagsBitSet() {
return flags;
}
@Override
public void setFlagsBitSet(long bitSet) {
this.flags = bitSet;
}
@Override
public Object getKey() {
return key;
}
public void setKey(Object key) {
this.key = key;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AbstractDataCommand other = (AbstractDataCommand) obj;
return flags == other.flags && Objects.equals(key, other.key);
}
@Override
public int hashCode() {
return (key != null ? key.hashCode() : 0);
}
@Override
public String toString() {
return getClass().getSimpleName() +
" {key=" + toStr(key) +
", flags=" + printFlags() +
"}";
}
@Override
public boolean isReturnValueExpected() {
return true;
}
protected final String printFlags() {
return prettyPrintBitSet(flags, Flag.class);
}
}
| 2,465
| 21.833333
| 90
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/AbstractCloseableIteratorCollection.java
|
package org.infinispan.commands.read;
import java.util.AbstractCollection;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.infinispan.Cache;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.CloseableIteratorCollection;
import org.infinispan.commons.util.CloseableSpliterator;
/**
* Abstract collection that uses an underlying Cache instance to do various operations. This is useful for a backing
* collection such as entrySet, keySet or values from the Map interface. Implementors only need to implement individual
* methods such as {@link Collection#contains(Object)}, {@link Collection#remove(Object)} and
* {@link org.infinispan.commons.util.CloseableIteratorCollection#iterator()}. The {@link Collection#add(Object)} by default will throw an
* {@link java.lang.UnsupportedOperationException}.
* <p>
* @implNote Any implementor should always use the underlying {@link Cache} instance when performing writes on this
* collection. This is to ensure that the entry is updated using all levels of interceptor stack
*
* @author wburns
* @since 7.0
*/
public abstract class AbstractCloseableIteratorCollection<O, K, V> extends AbstractCollection<O> implements CloseableIteratorCollection<O> {
protected final Cache<K, V> cache;
public AbstractCloseableIteratorCollection(Cache<K, V> cache) {
this.cache = cache;
}
@Override
public abstract CloseableIterator<O> iterator();
@Override
public abstract CloseableSpliterator<O> spliterator();
@Override
public abstract boolean contains(Object o);
@Override
public abstract boolean remove(Object o);
@Override
public int size() {
return cache.size();
}
@Override
public boolean isEmpty() {
return cache.isEmpty();
}
// Copied from AbstractCollection since we need to close iterator
@Override
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
try (CloseableIterator<O> it = iterator()) {
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}
}
// Copied from AbstractCollection since we need to close iterator
@Override
public <T> T[] toArray(T[] a) {
// Estimate size of array; be prepared to see more or fewer elements
int size = size();
T[] r = a.length >= size ? a :
(T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), size);
try (CloseableIterator<O> it = iterator()) {
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) { // fewer elements than expected
if (a == r) {
r[i] = null; // null-terminate
} else if (a.length < i) {
return Arrays.copyOf(r, i);
} else {
System.arraycopy(r, 0, a, 0, i);
if (a.length > i) {
a[i] = null;
}
}
return a;
}
r[i] = (T)it.next();
}
// more elements than expected
return it.hasNext() ? finishToArray(r, it) : r;
}
}
@Override
public boolean removeAll(Collection<?> c) {
boolean modified = false;
for (Object o : c) {
if (remove(o)) {
modified = true;
}
}
return modified;
}
// Copied from AbstractCollection since we need to close iterator
@Override
public boolean retainAll(Collection<?> c) {
boolean modified = false;
try (CloseableIterator<O> it = iterator()) {
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
}
@Override
public void clear() {
cache.clear();
}
// Copied from AbstractCollection to support toArray methods
@SuppressWarnings("unchecked")
private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
int i = r.length;
while (it.hasNext()) {
int cap = r.length;
if (i == cap) {
int newCap = cap + (cap >> 1) + 1;
// overflow-conscious code
if (newCap - MAX_ARRAY_SIZE > 0)
newCap = hugeCapacity(cap + 1);
r = Arrays.copyOf(r, newCap);
}
r[i++] = (T)it.next();
}
// trim if overallocated
return (i == r.length) ? r : Arrays.copyOf(r, i);
}
// Copied from AbstractCollection to support toArray methods
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError
("Required array size too large");
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
}
| 5,209
| 31.160494
| 140
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/GetAllCommand.java
|
package org.infinispan.commands.read;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import org.infinispan.commands.AbstractTopologyAffectedCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
/**
* Retrieves multiple entries at once.
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class GetAllCommand extends AbstractTopologyAffectedCommand {
public static final byte COMMAND_ID = 44;
private Collection<?> keys;
private boolean returnEntries;
public GetAllCommand(Collection<?> keys, long flagsBitSet, boolean returnEntries) {
this.keys = keys;
this.returnEntries = returnEntries;
setFlagsBitSet(flagsBitSet);
}
GetAllCommand() {
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitGetAllCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.PRIMARY;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallCollection(keys, output);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeBoolean(returnEntries);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
keys = MarshallUtil.unmarshallCollection(input, ArrayList::new);
setFlagsBitSet(input.readLong());
returnEntries = input.readBoolean();
}
@Override
public boolean isReturnValueExpected() {
return true;
}
public boolean isReturnEntries() {
return returnEntries;
}
public Collection<?> getKeys() {
return keys;
}
public void setKeys(Collection<?> keys) {
this.keys = keys;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("GetAllCommand{");
sb.append("keys=").append(toStr(keys));
sb.append(", returnEntries=").append(returnEntries);
sb.append(", flags=").append(printFlags());
sb.append('}');
return sb.toString();
}
}
| 2,446
| 25.311828
| 89
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/EntrySetCommand.java
|
package org.infinispan.commands.read;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.context.InvocationContext;
/**
* Command implementation for {@link java.util.Map#entrySet()} functionality.
*
* @author Galder Zamarreño
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @author William Burns
* @since 4.0
*/
public class EntrySetCommand<K, V> extends AbstractLocalCommand implements VisitableCommand {
public EntrySetCommand(long flagsBitSet) {
setFlagsBitSet(flagsBitSet);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitEntrySetCommand(ctx, this);
}
@Override
public String toString() {
return "EntrySetCommand{" +
", flags=" + printFlags() +
'}';
}
}
| 879
| 26.5
| 93
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/AbstractLocalCommand.java
|
package org.infinispan.commands.read;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.AbstractFlagAffectedCommand;
import org.infinispan.commands.LocalCommand;
/**
* Abstract class
*
* @author Manik Surtani
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
public abstract class AbstractLocalCommand extends AbstractFlagAffectedCommand implements LocalCommand {
public byte getCommandId() {
return 0; // no-op
}
public final void writeTo(ObjectOutput output) throws IOException {
//no-op
}
public final void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
//no-op
}
public boolean isReturnValueExpected() {
return false;
}
@Override
public LoadType loadType() {
throw new UnsupportedOperationException();
}
}
| 880
| 21.025
| 104
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/GetKeyValueCommand.java
|
package org.infinispan.commands.read;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
/**
* Implements functionality defined by {@link org.infinispan.Cache#get(Object)} and
* {@link org.infinispan.Cache#containsKey(Object)} operations
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public class GetKeyValueCommand extends AbstractDataCommand {
public static final byte COMMAND_ID = 4;
public GetKeyValueCommand(Object key, int segment, long flagsBitSet) {
super(key, segment, flagsBitSet);
}
public GetKeyValueCommand() {
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitGetKeyValueCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
setFlagsBitSet(input.readLong());
}
public String toString() {
return new StringBuilder()
.append("GetKeyValueCommand {key=")
.append(toStr(key))
.append(", flags=").append(printFlags())
.append("}")
.toString();
}
}
| 1,951
| 26.492958
| 89
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/GetCacheEntryCommand.java
|
package org.infinispan.commands.read;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
/**
* Used to fetch a full CacheEntry rather than just the value.
* This functionality was originally incorporated into GetKeyValueCommand.
*
* @author Sanne Grinovero <sanne@hibernate.org> (C) 2014 Red Hat Inc.
* @since 7.1
*/
public final class GetCacheEntryCommand extends AbstractDataCommand {
public static final byte COMMAND_ID = 45;
public GetCacheEntryCommand(Object key, int segment, long flagsBitSet) {
super(key, segment, flagsBitSet);
}
public GetCacheEntryCommand() {
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitGetCacheEntryCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
setFlagsBitSet(input.readLong());
}
public String toString() {
return new StringBuilder()
.append("GetCacheEntryCommand {key=")
.append(toStr(key))
.append(", flags=").append(printFlags())
.append("}")
.toString();
}
}
| 1,956
| 26.56338
| 89
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/SizeCommand.java
|
package org.infinispan.commands.read;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.commons.util.IntSet;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.util.ByteString;
/**
* Command to calculate the size of the cache
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Mircea.Markus@jboss.com
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @since 4.0
*/
public class SizeCommand extends BaseRpcCommand implements FlagAffectedCommand, TopologyAffectedCommand {
public static final byte COMMAND_ID = 61;
private int topologyId = -1;
private long flags = EnumUtil.EMPTY_BIT_SET;
private IntSet segments;
public SizeCommand(
ByteString cacheName,
IntSet segments,
long flags
) {
super(cacheName);
setFlagsBitSet(flags);
this.segments = segments;
}
public SizeCommand(ByteString name) {
super(name);
}
// Only here for CommandIdUniquenessTest
private SizeCommand() { super(null); }
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitSizeCommand(ctx, this);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
InvocationContextFactory icf = registry.getInvocationContextFactory().running();
InvocationContext ctx = icf.createRemoteInvocationContextForCommand(this, getOrigin());
AsyncInterceptorChain invoker = registry.getInterceptorChain().running();
return invoker.invokeAsync(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
@Override
public long getFlagsBitSet() {
return flags;
}
@Override
public void setFlagsBitSet(long bitSet) {
this.flags = bitSet;
}
public IntSet getSegments() {
return segments;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeLong(flags);
output.writeObject(segments);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
setFlagsBitSet(input.readLong());
segments = (IntSet) input.readObject();
}
@Override
public String toString() {
return "SizeCommand{" +
"topologyId=" + topologyId +
", flags=" + flags +
", segments=" + segments +
'}';
}
}
| 3,344
| 25.76
| 105
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/read/KeySetCommand.java
|
package org.infinispan.commands.read;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.context.InvocationContext;
/**
* Command implementation for {@link java.util.Map#keySet()} functionality.
*
* @author Galder Zamarreño
* @author Mircea.Markus@jboss.com
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @author William Burns
* @since 4.0
*/
public class KeySetCommand<K, V> extends AbstractLocalCommand implements VisitableCommand {
public KeySetCommand(long flagsBitSet) {
setFlagsBitSet(flagsBitSet);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitKeySetCommand(ctx, this);
}
@Override
public String toString() {
return "KeySetCommand{" +
", flags=" + printFlags() +
'}';
}
}
| 904
| 26.424242
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/CacheShutdownCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
/**
* Tell members to shutdown cache.
*
* @author Ryan Emerson
* @since 11.0
*/
public class CacheShutdownCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 94;
private String cacheName;
// For CommandIdUniquenessTest only
public CacheShutdownCommand() {
super(COMMAND_ID);
}
public CacheShutdownCommand(String cacheName) {
super(COMMAND_ID);
this.cacheName = cacheName;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getLocalTopologyManager()
.handleCacheShutdown(cacheName);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
}
@Override
public String toString() {
return "ShutdownCacheCommand{" +
"cacheName='" + cacheName + '\'' +
'}';
}
}
| 1,390
| 23.839286
| 88
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/AbstractCacheControlCommand.java
|
package org.infinispan.commands.topology;
import org.infinispan.commands.GlobalRpcCommand;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.remoting.transport.Address;
/**
* Abstract class that is the basis for the Cache, Rebalance and Topology commands.
*
* @author Ryan Emerson
* @since 11.0
*/
@Scope(Scopes.NONE)
public abstract class AbstractCacheControlCommand implements GlobalRpcCommand {
private final byte commandId;
protected transient Address origin;
AbstractCacheControlCommand(byte commandId) {
this(commandId, null);
}
AbstractCacheControlCommand(byte commandId, Address origin) {
this.commandId = commandId;
this.origin = origin;
}
@Override
public void setOrigin(Address origin) {
this.origin = origin;
}
@Override
public byte getCommandId() {
return commandId;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
}
| 1,010
| 21.466667
| 83
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/TopologyUpdateStableCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.PersistentUUID;
/**
* Update the stable topology.
*
* @author Ryan Emerson
* @since 11.0
*/
public class TopologyUpdateStableCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 97;
private String cacheName;
private ConsistentHash currentCH;
private ConsistentHash pendingCH;
private List<Address> actualMembers;
private List<PersistentUUID> persistentUUIDs;
private int rebalanceId;
private int topologyId;
private int viewId;
private boolean topologyRestored;
// For CommandIdUniquenessTest only
public TopologyUpdateStableCommand() {
super(COMMAND_ID);
}
public TopologyUpdateStableCommand(String cacheName, Address origin, CacheTopology cacheTopology, int viewId) {
super(COMMAND_ID, origin);
this.cacheName = cacheName;
this.topologyId = cacheTopology.getTopologyId();
this.rebalanceId = cacheTopology.getRebalanceId();
this.currentCH = cacheTopology.getCurrentCH();
this.pendingCH = cacheTopology.getPendingCH();
this.actualMembers = cacheTopology.getActualMembers();
this.persistentUUIDs = cacheTopology.getMembersPersistentUUIDs();
this.viewId = viewId;
this.topologyRestored = cacheTopology.wasTopologyRestoredFromState();
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
CacheTopology topology = new CacheTopology(topologyId, rebalanceId, topologyRestored, currentCH, pendingCH,
CacheTopology.Phase.NO_REBALANCE, actualMembers, persistentUUIDs);
return gcr.getLocalTopologyManager()
.handleStableTopologyUpdate(cacheName, topology, origin, viewId);
}
public ConsistentHash getCurrentCH() {
return currentCH;
}
public ConsistentHash getPendingCH() {
return pendingCH;
}
public int getTopologyId() {
return topologyId;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
output.writeObject(currentCH);
output.writeObject(pendingCH);
MarshallUtil.marshallCollection(actualMembers, output);
MarshallUtil.marshallCollection(persistentUUIDs, output);
output.writeInt(topologyId);
output.writeInt(rebalanceId);
output.writeInt(viewId);
output.writeBoolean(topologyRestored);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
currentCH = (ConsistentHash) input.readObject();
pendingCH = (ConsistentHash) input.readObject();
actualMembers = MarshallUtil.unmarshallCollection(input, ArrayList::new);
persistentUUIDs = MarshallUtil.unmarshallCollection(input, ArrayList::new);
topologyId = input.readInt();
rebalanceId = input.readInt();
viewId = input.readInt();
topologyRestored = input.readBoolean();
}
@Override
public String toString() {
return "TopologyUpdateStableCommand{" +
"cacheName='" + cacheName + '\'' +
", origin=" + origin +
", currentCH=" + currentCH +
", pendingCH=" + pendingCH +
", actualMembers=" + actualMembers +
", persistentUUIDs=" + persistentUUIDs +
", rebalanceId=" + rebalanceId +
", topologyId=" + topologyId +
", viewId=" + viewId +
'}';
}
}
| 4,005
| 33.534483
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/TopologyUpdateCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.PersistentUUID;
/**
* Coordinator to member:
* The coordinator is updating the consistent hash.
* Used to signal the end of rebalancing as well.
*
* @author Ryan Emerson
* @since 11.0
*/
public class TopologyUpdateCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 95;
private String cacheName;
private ConsistentHash currentCH;
private ConsistentHash pendingCH;
private CacheTopology.Phase phase;
private List<Address> actualMembers;
private List<PersistentUUID> persistentUUIDs;
private AvailabilityMode availabilityMode;
private int rebalanceId;
private int topologyId;
private int viewId;
// For CommandIdUniquenessTest only
public TopologyUpdateCommand() {
super(COMMAND_ID);
}
public TopologyUpdateCommand(String cacheName, Address origin, CacheTopology cacheTopology,
AvailabilityMode availabilityMode, int viewId) {
super(COMMAND_ID, origin);
this.cacheName = cacheName;
this.topologyId = cacheTopology.getTopologyId();
this.rebalanceId = cacheTopology.getRebalanceId();
this.currentCH = cacheTopology.getCurrentCH();
this.pendingCH = cacheTopology.getPendingCH();
this.phase = cacheTopology.getPhase();
this.availabilityMode = availabilityMode;
this.actualMembers = cacheTopology.getActualMembers();
this.persistentUUIDs = cacheTopology.getMembersPersistentUUIDs();
this.viewId = viewId;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
CacheTopology topology = new CacheTopology(topologyId, rebalanceId, currentCH, pendingCH, phase, actualMembers, persistentUUIDs);
return gcr.getLocalTopologyManager()
.handleTopologyUpdate(cacheName, topology, availabilityMode, viewId, origin);
}
public String getCacheName() {
return cacheName;
}
public ConsistentHash getCurrentCH() {
return currentCH;
}
public ConsistentHash getPendingCH() {
return pendingCH;
}
public CacheTopology.Phase getPhase() {
return phase;
}
public AvailabilityMode getAvailabilityMode() {
return availabilityMode;
}
public int getTopologyId() {
return topologyId;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
output.writeObject(currentCH);
output.writeObject(pendingCH);
MarshallUtil.marshallEnum(phase, output);
MarshallUtil.marshallCollection(actualMembers, output);
MarshallUtil.marshallCollection(persistentUUIDs, output);
MarshallUtil.marshallEnum(availabilityMode, output);
output.writeInt(topologyId);
output.writeInt(rebalanceId);
output.writeInt(viewId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
currentCH = (ConsistentHash) input.readObject();
pendingCH = (ConsistentHash) input.readObject();
phase = MarshallUtil.unmarshallEnum(input, CacheTopology.Phase::valueOf);
actualMembers = MarshallUtil.unmarshallCollection(input, ArrayList::new);
persistentUUIDs = MarshallUtil.unmarshallCollection(input, ArrayList::new);
availabilityMode = MarshallUtil.unmarshallEnum(input, AvailabilityMode::valueOf);
topologyId = input.readInt();
rebalanceId = input.readInt();
viewId = input.readInt();
}
@Override
public String toString() {
return "TopologyUpdateCommand{" +
"cacheName='" + cacheName + '\'' +
", origin=" + origin +
", currentCH=" + currentCH +
", pendingCH=" + pendingCH +
", phase=" + phase +
", actualMembers=" + actualMembers +
", persistentUUIDs=" + persistentUUIDs +
", availabilityMode=" + availabilityMode +
", rebalanceId=" + rebalanceId +
", topologyId=" + topologyId +
", viewId=" + viewId +
'}';
}
}
| 4,715
| 33.423358
| 135
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/RebalancePhaseConfirmCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.remoting.transport.Address;
/**
* A member is confirming that it has finished a topology change during rebalance.
*
* @author Ryan Emerson
* @since 11.0
*/
public class RebalancePhaseConfirmCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 87;
private String cacheName;
private Throwable throwable;
private int topologyId;
private int viewId;
// For CommandIdUniquenessTest only
public RebalancePhaseConfirmCommand() {
super(COMMAND_ID);
}
public RebalancePhaseConfirmCommand(String cacheName, Address origin, Throwable throwable, int topologyId, int viewId) {
super(COMMAND_ID, origin);
this.cacheName = cacheName;
this.throwable = throwable;
this.topologyId = topologyId;
this.viewId = viewId;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getClusterTopologyManager()
.handleRebalancePhaseConfirm(cacheName, origin, topologyId, throwable, viewId);
}
public String getCacheName() {
return cacheName;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
output.writeObject(throwable);
output.writeInt(topologyId);
output.writeInt(viewId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
throwable = (Throwable) input.readObject();
topologyId = input.readInt();
viewId = input.readInt();
}
@Override
public String toString() {
return "RebalancePhaseConfirmCommand{" +
"cacheName='" + cacheName + '\'' +
", origin=" + origin +
", throwable=" + throwable +
", topologyId=" + topologyId +
", viewId=" + viewId +
'}';
}
}
| 2,261
| 28.376623
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/CacheStatusRequestCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.GlobalComponentRegistry;
/**
* The coordinator is requesting information about the running caches.
*
* @author Ryan Emerson
* @since 11.0
*/
public class CacheStatusRequestCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 96;
private int viewId;
// For CommandIdUniquenessTest only
public CacheStatusRequestCommand() {
super(COMMAND_ID);
}
public CacheStatusRequestCommand(int viewId) {
super(COMMAND_ID);
this.viewId = viewId;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getLocalTopologyManager()
.handleStatusRequest(viewId);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeInt(viewId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
viewId = input.readInt();
}
@Override
public String toString() {
return "CacheStatusRequestCommand{" +
"viewId=" + viewId +
'}';
}
}
| 1,311
| 22.854545
| 88
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/CacheLeaveCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.remoting.transport.Address;
/**
* A node is signaling that it wants to leave the cluster.
*
* @author Ryan Emerson
* @since 11.0
*/
public class CacheLeaveCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 86;
private String cacheName;
private int viewId;
// For CommandIdUniquenessTest only
public CacheLeaveCommand() {
super(COMMAND_ID);
}
public CacheLeaveCommand(String cacheName, Address origin, int viewId) {
super(COMMAND_ID, origin);
this.cacheName = cacheName;
this.viewId = viewId;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getClusterTopologyManager()
.handleLeave(cacheName, origin, viewId);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
output.writeInt(viewId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
viewId = input.readInt();
}
@Override
public String toString() {
return "TopologyLeaveCommand{" +
"cacheName='" + cacheName + '\'' +
", origin=" + origin +
", viewId=" + viewId +
'}';
}
}
| 1,685
| 25.761905
| 88
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/CacheAvailabilityUpdateCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.partitionhandling.AvailabilityMode;
/**
* Change the availability of a cache.
*
* @author Ryan Emerson
* @since 11.0
*/
public class CacheAvailabilityUpdateCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 98;
private String cacheName;
private AvailabilityMode availabilityMode;
// For CommandIdUniquenessTest only
public CacheAvailabilityUpdateCommand() {
super(COMMAND_ID);
}
public CacheAvailabilityUpdateCommand(String cacheName, AvailabilityMode availabilityMode) {
super(COMMAND_ID);
this.cacheName = cacheName;
this.availabilityMode = availabilityMode;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getClusterTopologyManager()
.forceAvailabilityMode(cacheName, availabilityMode);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
MarshallUtil.marshallEnum(availabilityMode, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
availabilityMode = MarshallUtil.unmarshallEnum(input, AvailabilityMode::valueOf);
}
@Override
public String toString() {
return "UpdateAvailabilityCommand{" +
"cacheName='" + cacheName + '\'' +
", availabilityMode=" + availabilityMode +
'}';
}
}
| 1,840
| 28.693548
| 95
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/RebalanceStartCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.PersistentUUID;
/**
* The coordinator is starting a rebalance operation.
*
* @author Ryan Emerson
* @since 11.0
*/
public class RebalanceStartCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 92;
private String cacheName;
private ConsistentHash currentCH;
private ConsistentHash pendingCH;
private CacheTopology.Phase phase;
private List<Address> actualMembers;
private List<PersistentUUID> persistentUUIDs;
private int rebalanceId;
private int topologyId;
private int viewId;
// For CommandIdUniquenessTest only
public RebalanceStartCommand() {
super(COMMAND_ID);
}
public RebalanceStartCommand(String cacheName, Address origin, CacheTopology cacheTopology, int viewId) {
super(COMMAND_ID, origin);
this.cacheName = cacheName;
this.topologyId = cacheTopology.getTopologyId();
this.rebalanceId = cacheTopology.getRebalanceId();
this.currentCH = cacheTopology.getCurrentCH();
this.pendingCH = cacheTopology.getPendingCH();
this.phase = cacheTopology.getPhase();
this.actualMembers = cacheTopology.getActualMembers();
this.persistentUUIDs = cacheTopology.getMembersPersistentUUIDs();
this.viewId = viewId;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
CacheTopology topology = new CacheTopology(topologyId, rebalanceId, currentCH, pendingCH, phase, actualMembers, persistentUUIDs);
return gcr.getLocalTopologyManager()
.handleRebalance(cacheName, topology, viewId, origin);
}
public String getCacheName() {
return cacheName;
}
public ConsistentHash getCurrentCH() {
return currentCH;
}
public ConsistentHash getPendingCH() {
return pendingCH;
}
public CacheTopology.Phase getPhase() {
return phase;
}
public int getTopologyId() {
return topologyId;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
output.writeObject(currentCH);
output.writeObject(pendingCH);
MarshallUtil.marshallEnum(phase, output);
MarshallUtil.marshallCollection(actualMembers, output);
MarshallUtil.marshallCollection(persistentUUIDs, output);
output.writeInt(topologyId);
output.writeInt(rebalanceId);
output.writeInt(viewId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
currentCH = (ConsistentHash) input.readObject();
pendingCH = (ConsistentHash) input.readObject();
phase = MarshallUtil.unmarshallEnum(input, CacheTopology.Phase::valueOf);
actualMembers = MarshallUtil.unmarshallCollection(input, ArrayList::new);
persistentUUIDs = MarshallUtil.unmarshallCollection(input, ArrayList::new);
topologyId = input.readInt();
rebalanceId = input.readInt();
viewId = input.readInt();
}
@Override
public String toString() {
return "RebalanceStartCommand{" +
"cacheName='" + cacheName + '\'' +
", origin=" + origin +
", currentCH=" + currentCH +
", pendingCH=" + pendingCH +
", phase=" + phase +
", actualMembers=" + actualMembers +
", persistentUUIDs=" + persistentUUIDs +
", rebalanceId=" + rebalanceId +
", topologyId=" + topologyId +
", viewId=" + viewId +
'}';
}
}
| 4,109
| 32.145161
| 135
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/RebalancePolicyUpdateCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
/**
* Enable or Disable rebalancing.
*
* @author Ryan Emerson
* @since 11.0
*/
public class RebalancePolicyUpdateCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 88;
private String cacheName;
private boolean enabled;
// For CommandIdUniquenessTest only
public RebalancePolicyUpdateCommand() {
super(COMMAND_ID);
}
public RebalancePolicyUpdateCommand(String cacheName, boolean enabled) {
super(COMMAND_ID);
this.cacheName = cacheName;
this.enabled = enabled;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getClusterTopologyManager().setRebalancingEnabled(cacheName, enabled);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
output.writeBoolean(enabled);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
enabled = input.readBoolean();
}
@Override
public String toString() {
return "RebalanceEnableCommand{" +
"cacheName='" + cacheName + '\'' +
'}';
}
}
| 1,563
| 25.508475
| 88
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/CacheJoinCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.topology.CacheJoinInfo;
/**
* A node is requesting to join the cluster.
*
* @author Ryan Emerson
* @since 11.0
*/
public class CacheJoinCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 85;
private String cacheName;
private CacheJoinInfo joinInfo;
private int viewId;
// For CommandIdUniquenessTest only
public CacheJoinCommand() {
super(COMMAND_ID);
}
public CacheJoinCommand(String cacheName, Address origin, CacheJoinInfo joinInfo, int viewId) {
super(COMMAND_ID, origin);
this.cacheName = cacheName;
this.joinInfo = joinInfo;
this.viewId = viewId;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getClusterTopologyManager()
.handleJoin(cacheName, origin, joinInfo, viewId);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
output.writeObject(joinInfo);
output.writeInt(viewId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
joinInfo = (CacheJoinInfo) input.readObject();
viewId = input.readInt();
}
@Override
public String toString() {
return "TopologyJoinCommand{" +
"cacheName='" + cacheName + '\'' +
", origin=" + origin +
", joinInfo=" + joinInfo +
", viewId=" + viewId +
'}';
}
}
| 1,941
| 27.144928
| 98
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/RebalanceStatusRequestCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.topology.RebalancingStatus;
/**
* Query the rebalancing status.
*
* @author Ryan Emerson
* @since 11.0
*/
public class RebalanceStatusRequestCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 90;
private String cacheName;
// For CommandIdUniquenessTest only
public RebalanceStatusRequestCommand() {
super(COMMAND_ID);
}
public RebalanceStatusRequestCommand(String cacheName) {
super(COMMAND_ID);
this.cacheName = cacheName;
}
@Override
public CompletionStage<RebalancingStatus> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
RebalancingStatus status;
if (cacheName == null) {
status = gcr.getClusterTopologyManager().isRebalancingEnabled() ? RebalancingStatus.PENDING : RebalancingStatus.SUSPENDED;
} else {
status = gcr.getClusterTopologyManager().getRebalancingStatus(cacheName);
}
return CompletableFuture.completedFuture(status);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
}
@Override
public String toString() {
return "RebalanceStatusCommand{" +
"cacheName='" + cacheName + '\'' +
'}';
}
}
| 1,799
| 27.571429
| 131
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/topology/CacheShutdownRequestCommand.java
|
package org.infinispan.commands.topology;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.GlobalComponentRegistry;
/**
* A member is requesting a cache shutdown.
*
* @author Ryan Emerson
* @since 11.0
*/
public class CacheShutdownRequestCommand extends AbstractCacheControlCommand {
public static final byte COMMAND_ID = 93;
private String cacheName;
// For CommandIdUniquenessTest only
public CacheShutdownRequestCommand() {
super(COMMAND_ID);
}
public CacheShutdownRequestCommand(String cacheName) {
super(COMMAND_ID);
this.cacheName = cacheName;
}
@Override
public CompletionStage<?> invokeAsync(GlobalComponentRegistry gcr) throws Throwable {
return gcr.getClusterTopologyManager()
.handleShutdownRequest(cacheName);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallString(cacheName, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
cacheName = MarshallUtil.unmarshallString(input);
}
@Override
public String toString() {
return "ShutdownCacheRequestCommand{" +
"cacheName='" + cacheName + '\'' +
'}';
}
}
| 1,431
| 24.571429
| 88
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/ClusteredGetAllCommand.java
|
package org.infinispan.commands.remote;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.read.GetAllCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.entries.InternalCacheValue;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.responses.Response;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Issues a remote getAll call. This is not a {@link org.infinispan.commands.VisitableCommand} and hence not passed up the
* interceptor chain.
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class ClusteredGetAllCommand<K, V> extends BaseClusteredReadCommand {
public static final byte COMMAND_ID = 46;
private static final Log log = LogFactory.getLog(ClusteredGetAllCommand.class);
private List<?> keys;
private GlobalTransaction gtx;
ClusteredGetAllCommand() {
super(null, EnumUtil.EMPTY_BIT_SET);
}
public ClusteredGetAllCommand(ByteString cacheName) {
super(cacheName, EnumUtil.EMPTY_BIT_SET);
}
public ClusteredGetAllCommand(ByteString cacheName, List<?> keys, long flags, GlobalTransaction gtx) {
super(cacheName, flags);
this.keys = keys;
this.gtx = gtx;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
if (!hasAnyFlag(FlagBitSets.FORCE_WRITE_LOCK)) {
return invokeGetAll(componentRegistry);
} else {
return componentRegistry.getCommandsFactory()
.buildLockControlCommand(keys, getFlagsBitSet(), gtx)
.invokeAsync(componentRegistry)
.thenCompose(o -> invokeGetAll(componentRegistry));
}
}
private CompletionStage<Object> invokeGetAll(ComponentRegistry cr) {
// make sure the get command doesn't perform a remote call
// as our caller is already calling the ClusteredGetCommand on all the relevant nodes
GetAllCommand command = cr.getCommandsFactory().buildGetAllCommand(keys, getFlagsBitSet(), true);
command.setTopologyId(topologyId);
InvocationContext invocationContext = cr.getInvocationContextFactory().running().createRemoteInvocationContextForCommand(command, getOrigin());
CompletionStage<Object> future = cr.getInterceptorChain().running().invokeAsync(invocationContext, command);
return future.thenApply(rv -> {
if (log.isTraceEnabled()) log.trace("Found: " + rv);
if (rv == null || rv instanceof Response) {
return rv;
}
Map<K, CacheEntry<K, V>> map = (Map<K, CacheEntry<K, V>>) rv;
InternalCacheValue<V>[] values = new InternalCacheValue[keys.size()];
int i = 0;
for (Object key : keys) {
CacheEntry<K, V> entry = map.get(key);
InternalCacheValue<V> value;
if (entry == null) {
value = null;
} else if (entry instanceof InternalCacheEntry) {
value = ((InternalCacheEntry<K, V>) entry).toInternalCacheValue();
} else {
value = cr.getInternalEntryFactory().running().createValue(entry);
value.setInternalMetadata(entry.getInternalMetadata());
}
values[i++] = value;
}
return values;
});
}
public List<?> getKeys() {
return keys;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallCollection(keys, output);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeObject(gtx);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
keys = MarshallUtil.unmarshallCollection(input, ArrayList::new);
setFlagsBitSet(input.readLong());
gtx = (GlobalTransaction) input.readObject();
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ClusteredGetAllCommand{");
sb.append("keys=").append(keys);
sb.append(", flags=").append(printFlags());
sb.append(", topologyId=").append(topologyId);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClusteredGetAllCommand<?, ?> other = (ClusteredGetAllCommand<?, ?>) obj;
if (gtx == null) {
if (other.gtx != null)
return false;
} else if (!gtx.equals(other.gtx))
return false;
if (keys == null) {
if (other.keys != null)
return false;
} else if (!keys.equals(other.keys))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((gtx == null) ? 0 : gtx.hashCode());
result = prime * result + ((keys == null) ? 0 : keys.hashCode());
return result;
}
}
| 5,801
| 33.535714
| 149
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/package-info.java
|
/**
* Meta-commands that wrap other commands for remote execution. Commands in this package typically expose information
* such as cache name, so that the target invocation environment is able to determine which cache to dispatch the
* wrapped command or commands to.
*
* @author Manik Surtani
* @since 4.0
* @api.private
*/
package org.infinispan.commands.remote;
| 374
| 33.090909
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/CheckTransactionRpcCommand.java
|
package org.infinispan.commands.remote;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.ValidSingleResponseCollector;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
/**
* A {@link CacheRpcCommand} that returns a {@link Collection} of local {@link GlobalTransaction} already completed.
*
* @author Pedro Ruivo
* @since 10.0
*/
public class CheckTransactionRpcCommand implements CacheRpcCommand {
public static final int COMMAND_ID = 83;
private static final ResponseCollectorImpl INSTANCE = new ResponseCollectorImpl();
private final ByteString cacheName;
private Collection<GlobalTransaction> gtxToCheck;
@SuppressWarnings("unused")
public CheckTransactionRpcCommand() {
this(null);
}
public CheckTransactionRpcCommand(ByteString cacheName, Collection<GlobalTransaction> gtxToCheck) {
this.cacheName = cacheName;
this.gtxToCheck = gtxToCheck;
}
public CheckTransactionRpcCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
public static ResponseCollector<Collection<GlobalTransaction>> responseCollector() {
return INSTANCE;
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) {
// Modify the collection destructively and return the list of completed transactions.
TransactionTable txTable = componentRegistry.getTransactionTable();
gtxToCheck.removeIf(txTable::containsLocalTx);
return CompletableFuture.completedFuture(gtxToCheck);
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallCollection(gtxToCheck, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
gtxToCheck = MarshallUtil.unmarshallCollection(input, ArrayList::new);
}
@Override
public Address getOrigin() {
//we don't need to keep track who sent the message
return null;
}
@Override
public void setOrigin(Address origin) {
//we don't need to keep track who sent the message
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public String toString() {
return "CheckTransactionRpcCommand{" +
"cacheName=" + cacheName +
", gtxToCheck=" + gtxToCheck +
'}';
}
/**
* The {@link ResponseCollector} implementation for this command.
* <p>
* It ignores all the exceptions and convert them to {@link Collections#emptyList()}.
*/
private static class ResponseCollectorImpl extends ValidSingleResponseCollector<Collection<GlobalTransaction>> {
@Override
protected Collection<GlobalTransaction> withValidResponse(Address sender, ValidResponse response) {
if (response instanceof SuccessfulResponse) {
//noinspection unchecked
return (Collection<GlobalTransaction>) response.getResponseValue();
} else {
return Collections.emptyList();
}
}
@Override
protected Collection<GlobalTransaction> targetNotFound(Address sender) {
//ignore exceptions
return Collections.emptyList();
}
@Override
protected Collection<GlobalTransaction> withException(Address sender, Exception exception) {
//ignore exceptions
return Collections.emptyList();
}
}
}
| 4,249
| 30.021898
| 116
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/BaseRpcCommand.java
|
package org.infinispan.commands.remote;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
public abstract class BaseRpcCommand implements CacheRpcCommand {
protected final ByteString cacheName;
protected Address origin;
protected BaseRpcCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"cacheName='" + cacheName + '\'' +
'}';
}
@Override
public Address getOrigin() {
return origin;
}
@Override
public void setOrigin(Address origin) {
this.origin = origin;
}
}
| 766
| 19.72973
| 65
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/SingleRpcCommand.java
|
package org.infinispan.commands.remote;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.locks.RemoteLockCommand;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Aggregates a single command for replication.
*
* @author Mircea.Markus@jboss.com
*/
public class SingleRpcCommand extends BaseRpcCommand {
public static final int COMMAND_ID = 1;
private static final Log log = LogFactory.getLog(SingleRpcCommand.class);
private VisitableCommand command;
private SingleRpcCommand() {
super(null); // For command id uniqueness test
}
public SingleRpcCommand(ByteString cacheName, VisitableCommand command) {
super(cacheName);
this.command = command;
}
public SingleRpcCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(command);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
command = (VisitableCommand) input.readObject();
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
command.init(componentRegistry);
InvocationContextFactory icf = componentRegistry.getInvocationContextFactory().running();
InvocationContext ctx = icf.createRemoteInvocationContextForCommand(command, getOrigin());
if (command instanceof RemoteLockCommand) {
ctx.setLockOwner(((RemoteLockCommand) command).getKeyLockOwner());
}
if (log.isTraceEnabled())
log.tracef("Invoking command %s, with originLocal flag set to %b", command, ctx
.isOriginLocal());
return componentRegistry.getInterceptorChain().running().invokeAsync(ctx, command);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SingleRpcCommand)) return false;
SingleRpcCommand that = (SingleRpcCommand) o;
if (Objects.equals(cacheName, that.cacheName))
return false;
return Objects.equals(command, that.command);
}
@Override
public int hashCode() {
int result = cacheName != null ? cacheName.hashCode() : 0;
result = 31 * result + (command != null ? command.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "SingleRpcCommand{" +
"cacheName='" + cacheName + '\'' +
", command=" + command +
'}';
}
public ReplicableCommand getCommand() {
return command;
}
@Override
public boolean isReturnValueExpected() {
return command.isReturnValueExpected();
}
@Override
public boolean isSuccessful() {
return command.isSuccessful();
}
@Override
public boolean canBlock() {
return command.canBlock();
}
@Override
public boolean logThrowable(Throwable t) {
return command.logThrowable(t);
}
}
| 3,522
| 27.642276
| 96
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/ClusteredGetCommand.java
|
package org.infinispan.commands.remote;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.SegmentSpecificCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.configuration.cache.TransactionConfiguration;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.entries.InternalCacheValue;
import org.infinispan.container.entries.MVCCEntry;
import org.infinispan.context.Flag;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Issues a remote get call. This is not a {@link org.infinispan.commands.VisitableCommand} and hence not passed up the
* interceptor chain.
* <p/>
*
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class ClusteredGetCommand extends BaseClusteredReadCommand implements SegmentSpecificCommand {
public static final byte COMMAND_ID = 16;
private static final Log log = LogFactory.getLog(ClusteredGetCommand.class);
private Object key;
private boolean isWrite;
private Integer segment;
private ClusteredGetCommand() {
super(null, EnumUtil.EMPTY_BIT_SET); // For command id uniqueness test
}
public ClusteredGetCommand(ByteString cacheName) {
super(cacheName, EnumUtil.EMPTY_BIT_SET);
}
public ClusteredGetCommand(Object key, ByteString cacheName, Integer segment, long flags) {
super(cacheName, flags);
this.key = key;
this.isWrite = false;
if (segment != null && segment < 0) {
throw new IllegalArgumentException("Segment must 0 or greater!");
}
this.segment = segment;
}
/**
* Invokes a logical "get(key)" on a remote cache and returns results.
* @return
*/
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
// make sure the get command doesn't perform a remote call
// as our caller is already calling the ClusteredGetCommand on all the relevant nodes
// CACHE_MODE_LOCAL is not used as it can be used when we want to ignore the ownership with respect to reads
long flagBitSet = EnumUtil.bitSetOf(Flag.SKIP_REMOTE_LOOKUP);
int segmentToUse;
if (segment != null) {
segmentToUse = segment;
} else {
segmentToUse = componentRegistry.getComponent(KeyPartitioner.class).getSegment(key);
}
// If this get command was due to a write and we are pessimistic that means it already holds the lock for the
// given key - This allows expiration to be performed if needed as it won't have to acquire the lock
// This code and the Flag can be removed when https://issues.redhat.com/browse/ISPN-12332 is complete
if (isWrite) {
TransactionConfiguration transactionConfiguration = componentRegistry.getConfiguration().transaction();
if (transactionConfiguration.transactionMode() == TransactionMode.TRANSACTIONAL) {
if (transactionConfiguration.lockingMode() == LockingMode.PESSIMISTIC) {
flagBitSet = EnumUtil.mergeBitSets(flagBitSet, FlagBitSets.ALREADY_HAS_LOCK);
}
}
}
GetCacheEntryCommand command = componentRegistry.getCommandsFactory().buildGetCacheEntryCommand(key, segmentToUse,
EnumUtil.mergeBitSets(flagBitSet, getFlagsBitSet()));
command.setTopologyId(topologyId);
InvocationContextFactory icf = componentRegistry.getInvocationContextFactory().running();
InvocationContext invocationContext = icf.createRemoteInvocationContextForCommand(command, getOrigin());
AsyncInterceptorChain invoker = componentRegistry.getInterceptorChain().running();
return invoker.invokeAsync(invocationContext, command)
.thenApply(rv -> {
if (log.isTraceEnabled()) log.tracef("Return value for key=%s is %s", key, rv);
//this might happen if the value was fetched from a cache loader
if (rv instanceof MVCCEntry) {
MVCCEntry<?, ?> mvccEntry = (MVCCEntry<?, ?>) rv;
InternalCacheValue<?> icv = componentRegistry.getInternalEntryFactory().wired().createValue(mvccEntry);
icv.setInternalMetadata(mvccEntry.getInternalMetadata());
return icv;
} else if (rv instanceof InternalCacheEntry) {
InternalCacheEntry<?, ?> internalCacheEntry = (InternalCacheEntry<? ,?>) rv;
return internalCacheEntry.toInternalCacheValue();
} else { // null or Response
return rv;
}
});
}
@Deprecated
public GlobalTransaction getGlobalTransaction() {
return null;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
if (segment != null) {
output.writeBoolean(true);
UnsignedNumeric.writeUnsignedInt(output, segment);
} else {
output.writeBoolean(false);
}
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeBoolean(isWrite);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
boolean hasSegment = input.readBoolean();
if (hasSegment) {
segment = UnsignedNumeric.readUnsignedInt(input);
}
setFlagsBitSet(input.readLong());
isWrite = input.readBoolean();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClusteredGetCommand that = (ClusteredGetCommand) o;
return Objects.equals(key, that.key);
}
@Override
public int hashCode() {
return Objects.hashCode(key);
}
@Override
public String toString() {
return new StringBuilder()
.append("ClusteredGetCommand{key=")
.append(key)
.append(", flags=").append(printFlags())
.append(", topologyId=").append(topologyId)
.append(", isWrite=").append(isWrite)
.append("}")
.toString();
}
public boolean isWrite() {
return isWrite;
}
public void setWrite(boolean write) {
isWrite = write;
}
@Override
public int getSegment() {
return segment;
}
public Object getKey() {
return key;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
}
| 7,315
| 35.39801
| 121
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/BaseClusteredReadCommand.java
|
package org.infinispan.commands.remote;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.context.Flag;
import org.infinispan.util.ByteString;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class BaseClusteredReadCommand extends BaseRpcCommand implements TopologyAffectedCommand {
protected int topologyId = -1;
private long flags;
protected BaseClusteredReadCommand(ByteString cacheName, long flagBitSet) {
super(cacheName);
this.flags = flagBitSet;
}
public long getFlagsBitSet() {
return flags;
}
public void setFlagsBitSet(long bitSet) {
flags = bitSet;
}
protected final String printFlags() {
return EnumUtil.prettyPrintBitSet(flags, Flag.class);
}
public boolean hasAnyFlag(long flagBitSet) {
return EnumUtil.containsAny(getFlagsBitSet(), flagBitSet);
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
}
| 1,118
| 23.326087
| 106
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/CacheRpcCommand.java
|
package org.infinispan.commands.remote;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.ByteString;
/**
* The {@link org.infinispan.remoting.rpc.RpcManager} only replicates commands wrapped in a {@link CacheRpcCommand}.
*
* @author Manik Surtani
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public interface CacheRpcCommand extends ReplicableCommand {
/**
* Invoke the command asynchronously.
* <p>
* <p>This method replaces {@link #invoke()} for remote execution.
* The default implementation and {@link #invoke()} will be removed in future versions.
* </p>
*
* @since 11.0
*/
default CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
return invokeAsync();
}
/**
* @return the name of the cache that produced this command. This will also be the name of the cache this command is
* intended for.
*/
ByteString getCacheName();
/**
* Set the origin of the command
*/
void setOrigin(Address origin);
/**
* Get the origin of the command
*/
Address getOrigin();
}
| 1,282
| 25.729167
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/recovery/TxCompletionNotificationCommand.java
|
package org.infinispan.commands.remote.recovery;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Command for removing recovery related information from the cluster.
*
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
public class TxCompletionNotificationCommand extends BaseRpcCommand implements TopologyAffectedCommand {
private static final Log log = LogFactory.getLog(TxCompletionNotificationCommand.class);
public static final int COMMAND_ID = 22;
private XidImpl xid;
private long internalId;
private GlobalTransaction gtx;
private int topologyId = -1;
@SuppressWarnings("unused")
private TxCompletionNotificationCommand() {
super(null); // For command id uniqueness test
}
public TxCompletionNotificationCommand(XidImpl xid, GlobalTransaction gtx, ByteString cacheName) {
super(cacheName);
this.xid = xid;
this.gtx = gtx;
}
public TxCompletionNotificationCommand(long internalId, ByteString cacheName) {
super(cacheName);
this.internalId = internalId;
}
public TxCompletionNotificationCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
if (log.isTraceEnabled())
log.tracef("Processing completed transaction %s", gtx);
RemoteTransaction remoteTx = null;
RecoveryManager recoveryManager = componentRegistry.getRecoveryManager().running();
if (recoveryManager != null) { //recovery in use
if (xid != null) {
remoteTx = (RemoteTransaction) recoveryManager.removeRecoveryInformation(xid);
} else {
remoteTx = (RemoteTransaction) recoveryManager.removeRecoveryInformation(internalId);
}
}
if (remoteTx == null && gtx != null) {
TransactionTable txTable = componentRegistry.getTransactionTableRef().running();
remoteTx = txTable.removeRemoteTransaction(gtx);
}
if (remoteTx == null) return CompletableFutures.completedNull();
forwardCommandRemotely(remoteTx, componentRegistry);
LockManager lockManager = componentRegistry.getLockManager().running();
lockManager.unlockAll(remoteTx.getLockedKeys(), remoteTx.getGlobalTransaction());
return CompletableFutures.completedNull();
}
public GlobalTransaction getGlobalTransaction() {
return gtx;
}
/**
* This only happens during state transfer.
*/
private void forwardCommandRemotely(RemoteTransaction remoteTx, ComponentRegistry registry) {
DistributionManager distributionManager = registry.getDistributionManager();
RpcManager rpcManager = registry.getRpcManager().running();
Set<Object> affectedKeys = remoteTx.getAffectedKeys();
if (log.isTraceEnabled())
log.tracef("Invoking forward of TxCompletionNotification for transaction %s. Affected keys: %s", gtx,
toStr(affectedKeys));
LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology();
if (cacheTopology == null) {
if (log.isTraceEnabled()) {
log.tracef("Not Forwarding command %s because topology is null.", this);
}
return;
}
// forward commands with older topology ids to their new targets
// but we need to make sure we have the latest topology
int localTopologyId = cacheTopology.getTopologyId();
// if it's a tx/lock/write command, forward it to the new owners
if (log.isTraceEnabled()) {
log.tracef("CommandTopologyId=%s, localTopologyId=%s", topologyId, localTopologyId);
}
if (topologyId >= localTopologyId) {
return;
}
Collection<Address> newTargets = new HashSet<>(cacheTopology.getWriteOwners(affectedKeys));
newTargets.remove(rpcManager.getAddress());
// Forwarding to the originator would create a cycle
// TODO This may not be the "real" originator, but one of the original recipients
// or even one of the nodes that one of the original recipients forwarded the command to.
// In non-transactional caches, the "real" originator keeps a lock for the duration
// of the RPC, so this means we could get a deadlock while forwarding to it.
newTargets.remove(origin);
if (!newTargets.isEmpty()) {
// Update the topology id to prevent cycles
topologyId = localTopologyId;
if (log.isTraceEnabled()) {
log.tracef("Forwarding command %s to new targets %s", this, newTargets);
}
// TxCompletionNotificationCommands are the only commands being forwarded now,
// and they must be OOB + asynchronous
rpcManager.sendToMany(newTargets, this, DeliverOrder.NONE);
}
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
if (xid == null) {
output.writeBoolean(true);
output.writeLong(internalId);
} else {
output.writeBoolean(false);
XidImpl.writeTo(output, xid);
}
output.writeObject(gtx);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
if (input.readBoolean()) {
internalId = input.readLong();
} else {
xid = XidImpl.readFrom(input);
}
gtx = (GlobalTransaction) input.readObject();
}
@Override
public String toString() {
return getClass().getSimpleName() +
"{ xid=" + xid +
", internalId=" + internalId +
", topologyId=" + topologyId +
", gtx=" + gtx +
", cacheName=" + cacheName + "} ";
}
}
| 7,200
| 35.368687
| 110
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/recovery/GetInDoubtTransactionsCommand.java
|
package org.infinispan.commands.remote.recovery;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Rpc to obtain all in-doubt prepared transactions stored on remote nodes.
* A transaction is in doubt if it is prepared and the node where it started has crashed.
*
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
public class GetInDoubtTransactionsCommand extends BaseRpcCommand {
private static final Log log = LogFactory.getLog(GetInDoubtTransactionsCommand.class);
public static final int COMMAND_ID = 21;
@SuppressWarnings("unused")
private GetInDoubtTransactionsCommand() {
super(null); // For command id uniqueness test
}
public GetInDoubtTransactionsCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
RecoveryManager recoveryManager = componentRegistry.getRecoveryManager().running();
List<XidImpl> localInDoubtTransactions = recoveryManager.getInDoubtTransactions();
log.tracef("Returning result %s", localInDoubtTransactions);
return CompletableFuture.completedFuture(localInDoubtTransactions);
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public String toString() {
return getClass().getSimpleName() + " { cacheName = " + cacheName + "}";
}
}
| 1,886
| 30.45
| 96
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/recovery/RecoveryCommand.java
|
package org.infinispan.commands.remote.recovery;
import org.infinispan.commands.InitializableCommand;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.ByteString;
/**
* Base class for recovery-related rpc-commands.
*
* @author Mircea.Markus@jboss.com
* @since 5.0
* @deprecated since 11.0, class will be removed with no direct replacement. BaseRpcCommand should be extended instead.
*/
@Deprecated
public abstract class RecoveryCommand extends BaseRpcCommand implements InitializableCommand {
protected RecoveryManager recoveryManager;
private RecoveryCommand() {
super(null); // For command id uniqueness test
}
protected RecoveryCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public void init(ComponentRegistry componentRegistry, boolean isRemote) {
this.recoveryManager = componentRegistry.getRecoveryManager().running();
}
@Override
public boolean isReturnValueExpected() {
return true;
}
}
| 1,126
| 27.897436
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/recovery/GetInDoubtTxInfoCommand.java
|
package org.infinispan.commands.remote.recovery;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.ByteString;
/**
* Command used by the recovery tooling for obtaining the list of in-doubt transactions from a node.
*
* @author Mircea Markus
* @since 5.0
*/
public class GetInDoubtTxInfoCommand extends BaseRpcCommand {
public static final int COMMAND_ID = 23;
private GetInDoubtTxInfoCommand() {
super(null); // For command id uniqueness test
}
public GetInDoubtTxInfoCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
RecoveryManager recoveryManager = componentRegistry.getRecoveryManager().running();
return CompletableFuture.completedFuture(recoveryManager.getInDoubtTransactionInfo());
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public String toString() {
return getClass().getSimpleName() + " { cacheName = " + cacheName + "}";
}
}
| 1,383
| 26.137255
| 100
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/remote/recovery/CompleteTransactionCommand.java
|
package org.infinispan.commands.remote.recovery;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.ByteString;
/**
* Command used by the recovery tooling for forcing transaction completion .
*
* @author Mircea Markus
* @since 5.0
*/
public class CompleteTransactionCommand extends BaseRpcCommand {
public static final byte COMMAND_ID = 24;
/**
* The tx which we want to complete.
*/
private XidImpl xid;
/**
* if true the transaction is committed, otherwise it is rolled back.
*/
private boolean commit;
private CompleteTransactionCommand() {
super(null); // For command id uniqueness test
}
public CompleteTransactionCommand(ByteString cacheName) {
super(cacheName);
}
public CompleteTransactionCommand(ByteString cacheName, XidImpl xid, boolean commit) {
super(cacheName);
this.xid = xid;
this.commit = commit;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable {
RecoveryManager recoveryManager = componentRegistry.getRecoveryManager().running();
return recoveryManager.forceTransactionCompletion(xid, commit);
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
XidImpl.writeTo(output, xid);
output.writeBoolean(commit);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
xid = XidImpl.readFrom(input);
commit = input.readBoolean();
}
@Override
public boolean canBlock() {
//this command performs the 2PC commit.
return true;
}
@Override
public String toString() {
return getClass().getSimpleName() +
"{ xid=" + xid +
", commit=" + commit +
", cacheName=" + cacheName +
"} ";
}
}
| 2,325
| 24.56044
| 96
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/VersionedPrepareCommand.java
|
package org.infinispan.commands.tx;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.container.versioning.IncrementableEntryVersion;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
/**
* Same as {@link PrepareCommand} except that the transaction originator makes evident the versions of entries touched
* and stored in a transaction context so that accurate write skew checks may be performed by the lock owner(s).
*
* @author Manik Surtani
* @since 5.1
*/
public class VersionedPrepareCommand extends PrepareCommand {
public static final byte COMMAND_ID = 26;
private Map<Object, IncrementableEntryVersion> versionsSeen;
public VersionedPrepareCommand() {
super(null);
}
public VersionedPrepareCommand(ByteString cacheName, GlobalTransaction gtx, List<WriteCommand> modifications, boolean onePhase) {
// VersionedPrepareCommands are *always* 2-phase, except when retrying a prepare.
super(cacheName, gtx, modifications, onePhase);
}
public VersionedPrepareCommand(ByteString cacheName) {
super(cacheName);
}
public Map<Object, IncrementableEntryVersion> getVersionsSeen() {
return versionsSeen;
}
public void setVersionsSeen(Map<Object, IncrementableEntryVersion> versionsSeen) {
this.versionsSeen = versionsSeen;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output); //writes global tx, one phase, retried and mods.
MarshallUtil.marshallMap(versionsSeen, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
versionsSeen = MarshallUtil.unmarshallMap(input, HashMap::new);
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public String toString() {
return "VersionedPrepareCommand {" +
"modifications=" + modifications +
", onePhaseCommit=" + onePhaseCommit +
", retried=" + retriedCommand +
", versionsSeen=" + versionsSeen +
", gtx=" + globalTx +
", cacheName='" + cacheName + '\'' +
'}';
}
}
| 2,546
| 30.060976
| 132
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/package-info.java
|
/**
* Commands that represent transactional lifecycle transitions.
*
* @author Manik Surtani
* @since 4.0
*/
package org.infinispan.commands.tx;
| 150
| 17.875
| 63
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/PrepareCommand.java
|
package org.infinispan.commands.tx;
import static org.infinispan.commons.marshall.MarshallUtil.marshallCollection;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.DataWriteCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.RemoveExpiredCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.context.impl.RemoteTxInvocationContext;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.concurrent.locks.TransactionalRemoteLockCommand;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Command corresponding to the 1st phase of 2PC.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class PrepareCommand extends AbstractTransactionBoundaryCommand implements TransactionalRemoteLockCommand {
private static final Log log = LogFactory.getLog(PrepareCommand.class);
public static final byte COMMAND_ID = 12;
protected List<WriteCommand> modifications;
protected boolean onePhaseCommit;
private transient boolean replayEntryWrapping;
protected boolean retriedCommand;
@SuppressWarnings("unused")
private PrepareCommand() {
super(null); // For command id uniqueness test
}
public PrepareCommand(ByteString cacheName, GlobalTransaction gtx, List<WriteCommand> commands, boolean onePhaseCommit) {
super(cacheName);
globalTx = gtx;
modifications = commands == null ? Collections.emptyList() : Collections.unmodifiableList(commands);
this.onePhaseCommit = onePhaseCommit;
}
public PrepareCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
markTransactionAsRemote(true);
RemoteTxInvocationContext ctx = createContext(registry);
if (ctx == null) {
return CompletableFutures.completedNull();
}
if (log.isTraceEnabled())
log.tracef("Invoking remotely originated prepare: %s with invocation context: %s", this, ctx);
CacheNotifier<?, ?> notifier = registry.getCacheNotifier().running();
CompletionStage<Void> stage = notifier.notifyTransactionRegistered(ctx.getGlobalTransaction(), false);
AsyncInterceptorChain invoker = registry.getInterceptorChain().running();
for (VisitableCommand nested : modifications)
nested.init(registry);
if (CompletionStages.isCompletedSuccessfully(stage)) {
return invoker.invokeAsync(ctx, this);
} else {
return stage.thenCompose(v -> invoker.invokeAsync(ctx, this));
}
}
@Override
public RemoteTxInvocationContext createContext(ComponentRegistry componentRegistry) {
RecoveryManager recoveryManager = componentRegistry.getRecoveryManager().running();
if (recoveryManager != null && recoveryManager.isTransactionPrepared(globalTx)) {
log.tracef("The transaction %s is already prepared. Skipping prepare call.", globalTx);
return null;
}
// 1. first create a remote transaction (or get the existing one)
TransactionTable txTable = componentRegistry.getTransactionTableRef().running();
RemoteTransaction remoteTransaction = txTable.getOrCreateRemoteTransaction(globalTx, modifications);
//set the list of modifications anyway, as the transaction might have already been created by a previous
//LockControlCommand with null modifications.
if (hasModifications()) {
remoteTransaction.setModifications(modifications);
}
// 2. then set it on the invocation context
InvocationContextFactory icf = componentRegistry.getInvocationContextFactory().running();
return icf.createRemoteTxInvocationContext(remoteTransaction, getOrigin());
}
@Override
public Collection<?> getKeysToLock() {
if (modifications.isEmpty()) {
return Collections.emptyList();
}
final Set<Object> set = new HashSet<>(modifications.size());
for (WriteCommand writeCommand : modifications) {
if (writeCommand.hasAnyFlag(FlagBitSets.SKIP_LOCKING)) {
continue;
}
switch (writeCommand.getCommandId()) {
case PutKeyValueCommand.COMMAND_ID:
case RemoveCommand.COMMAND_ID:
case ComputeCommand.COMMAND_ID:
case ComputeIfAbsentCommand.COMMAND_ID:
case RemoveExpiredCommand.COMMAND_ID:
case ReplaceCommand.COMMAND_ID:
case ReadWriteKeyCommand.COMMAND_ID:
case ReadWriteKeyValueCommand.COMMAND_ID:
case WriteOnlyKeyCommand.COMMAND_ID:
case WriteOnlyKeyValueCommand.COMMAND_ID:
set.add(((DataWriteCommand) writeCommand).getKey());
break;
case PutMapCommand.COMMAND_ID:
case InvalidateCommand.COMMAND_ID:
case ReadWriteManyCommand.COMMAND_ID:
case ReadWriteManyEntriesCommand.COMMAND_ID:
case WriteOnlyManyCommand.COMMAND_ID:
case WriteOnlyManyEntriesCommand.COMMAND_ID:
set.addAll(writeCommand.getAffectedKeys());
break;
default:
break;
}
}
return set;
}
@Override
public Object getKeyLockOwner() {
return globalTx;
}
@Override
public boolean hasZeroLockAcquisition() {
for (WriteCommand wc : modifications) {
// If even a single command doesn't have the zero lock acquisition timeout flag, we can't use a zero timeout
if (!wc.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) {
return false;
}
}
return true;
}
@Override
public boolean hasSkipLocking() {
return false;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitPrepareCommand((TxInvocationContext<?>) ctx, this);
}
public List<WriteCommand> getModifications() {
return modifications;
}
public boolean isOnePhaseCommit() {
return onePhaseCommit;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output); //global tx
output.writeBoolean(onePhaseCommit);
output.writeBoolean(retriedCommand);
marshallCollection(modifications, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
onePhaseCommit = input.readBoolean();
retriedCommand = input.readBoolean();
modifications = unmarshallCollection(input, ArrayList::new);
}
@Override
public String toString() {
return "PrepareCommand {" +
"modifications=" + modifications +
", onePhaseCommit=" + onePhaseCommit +
", retried=" + retriedCommand +
", " + super.toString();
}
public boolean hasModifications() {
return modifications != null && !modifications.isEmpty();
}
public Collection<?> getAffectedKeys() {
if (modifications == null || modifications.isEmpty())
return Collections.emptySet();
int size = modifications.size();
if (size == 1) return modifications.get(0).getAffectedKeys();
Set<Object> keys = new HashSet<>(size);
for (WriteCommand wc : modifications) keys.addAll(wc.getAffectedKeys());
return keys;
}
/**
* If set to true, then the keys touched by this transaction are to be wrapped again and original ones discarded.
*/
public boolean isReplayEntryWrapping() {
return replayEntryWrapping;
}
/**
* @see #isReplayEntryWrapping()
*/
public void setReplayEntryWrapping(boolean replayEntryWrapping) {
this.replayEntryWrapping = replayEntryWrapping;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
public boolean isRetriedCommand() {
return retriedCommand;
}
public void setRetriedCommand(boolean retriedCommand) {
this.retriedCommand = retriedCommand;
}
}
| 10,329
| 36.02509
| 124
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/VersionedCommitCommand.java
|
package org.infinispan.commands.tx;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.container.versioning.IncrementableEntryVersion;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
/**
* The same as a {@link CommitCommand} except that version information is also carried by this command, used by
* optimistically transactional caches making use of write skew checking when using {@link org.infinispan.util.concurrent.IsolationLevel#REPEATABLE_READ}.
*
* @author Manik Surtani
* @since 5.1
*/
public class VersionedCommitCommand extends CommitCommand {
public static final byte COMMAND_ID = 27;
private Map<Object, IncrementableEntryVersion> updatedVersions;
public VersionedCommitCommand() {
super(null);
}
public VersionedCommitCommand(ByteString cacheName, GlobalTransaction gtx) {
super(cacheName, gtx);
}
public VersionedCommitCommand(ByteString cacheName) {
super(cacheName);
}
public Map<Object, IncrementableEntryVersion> getUpdatedVersions() {
return updatedVersions;
}
public void setUpdatedVersions(Map<Object, IncrementableEntryVersion> updatedVersions) {
this.updatedVersions = updatedVersions;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output); //write global tx
MarshallUtil.marshallMap(updatedVersions, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
updatedVersions = MarshallUtil.unmarshallMap(input, HashMap::new);
}
@Override
public String toString() {
return "VersionedCommitCommand{gtx=" + globalTx +
", cacheName='" + cacheName + '\'' +
", topologyId=" + getTopologyId() +
", updatedVersions=" + updatedVersions +
'}';
}
}
| 2,142
| 29.183099
| 154
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/AbstractTransactionBoundaryCommand.java
|
package org.infinispan.commands.tx;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.RemoteTxInvocationContext;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* An abstract transaction boundary command that holds a reference to a {@link org.infinispan.transaction.xa.GlobalTransaction}
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public abstract class AbstractTransactionBoundaryCommand implements TransactionBoundaryCommand {
private static final Log log = LogFactory.getLog(AbstractTransactionBoundaryCommand.class);
protected GlobalTransaction globalTx;
protected final ByteString cacheName;
private Address origin;
private int topologyId = -1;
public AbstractTransactionBoundaryCommand(ByteString cacheName) {
this.cacheName = cacheName;
}
@Override
public int getTopologyId() {
return topologyId;
}
@Override
public void setTopologyId(int topologyId) {
this.topologyId = topologyId;
}
@Override
public ByteString getCacheName() {
return cacheName;
}
@Override
public GlobalTransaction getGlobalTransaction() {
return globalTx;
}
@Override
public void markTransactionAsRemote(boolean isRemote) {
globalTx.setRemote(isRemote);
}
/**
* This is what is returned to remote callers when an invalid RemoteTransaction is encountered. Can happen if a
* remote node propagates a transactional call to the current node, and the current node has no idea of the transaction
* in question. Can happen during rehashing, when ownerships are reassigned during a transactions.
*
* Returning a null usually means the transactional command succeeded.
* @return return value to respond to a remote caller with if the transaction context is invalid.
*/
protected Object invalidRemoteTxReturnValue(TransactionTable txTable) {
return null;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
globalTx.setRemote(true);
TransactionTable txTable = registry.getTransactionTableRef().running();
RemoteTransaction transaction = txTable.getRemoteTransaction(globalTx);
if (transaction == null) {
if (log.isTraceEnabled()) log.tracef("Did not find a RemoteTransaction for %s", globalTx);
return CompletableFuture.completedFuture(invalidRemoteTxReturnValue(txTable));
}
visitRemoteTransaction(transaction);
InvocationContextFactory icf = registry.getInvocationContextFactory().running();
RemoteTxInvocationContext ctx = icf.createRemoteTxInvocationContext(transaction, getOrigin());
if (log.isTraceEnabled()) log.tracef("About to execute tx command %s", this);
return registry.getInterceptorChain().running().invokeAsync(ctx, this);
}
protected void visitRemoteTransaction(RemoteTransaction tx) {
// to be overridden
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(globalTx);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
globalTx = (GlobalTransaction) input.readObject();
}
@Override
public LoadType loadType() {
throw new UnsupportedOperationException();
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractTransactionBoundaryCommand that = (AbstractTransactionBoundaryCommand) o;
return this.globalTx.equals(that.globalTx);
}
public int hashCode() {
return globalTx.hashCode();
}
@Override
public String toString() {
return "gtx=" + globalTx +
", cacheName='" + cacheName + '\'' +
", topologyId=" + topologyId +
'}';
}
@Override
public Address getOrigin() {
return origin;
}
@Override
public void setOrigin(Address origin) {
this.origin = origin;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
}
| 4,733
| 30.986486
| 127
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/CommitCommand.java
|
package org.infinispan.commands.tx;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.metadata.impl.IracMetadata;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
/**
* Command corresponding to the 2nd phase of 2PC.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public class CommitCommand extends AbstractTransactionBoundaryCommand {
public static final byte COMMAND_ID = 14;
//IRAC versions are segment based and they are generated during prepare phase. We can save some space here.
private Map<Integer, IracMetadata> iracMetadataMap;
private CommitCommand() {
super(null); // For command id uniqueness test
}
public CommitCommand(ByteString cacheName, GlobalTransaction gtx) {
super(cacheName);
this.globalTx = gtx;
}
public CommitCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitCommitCommand((TxInvocationContext) ctx, this);
}
@Override
protected Object invalidRemoteTxReturnValue(TransactionTable txTable) {
TransactionTable.CompletedTransactionStatus txStatus = txTable.getCompletedTransactionStatus(globalTx);
switch (txStatus) {
case COMMITTED:
// The transaction was already committed on this node
return null;
case ABORTED:
throw CONTAINER.remoteTransactionAlreadyRolledBack(globalTx);
case EXPIRED:
throw CONTAINER.remoteTransactionStatusMissing(globalTx);
default: // NOT_COMPLETED
throw new IllegalStateException("Remote transaction not found: " + globalTx);
}
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public String toString() {
return "CommitCommand{" +
"iracMetadataMap=" + iracMetadataMap + ", " +
super.toString();
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output);
MarshallUtil.marshallMap(iracMetadataMap, DataOutput::writeInt, IracMetadata::writeTo, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
iracMetadataMap = MarshallUtil.unmarshallMap(input, DataInput::readInt, IracMetadata::readFrom, HashMap::new);
}
public void addIracMetadata(int segment, IracMetadata metadata) {
if (iracMetadataMap == null) {
iracMetadataMap = new HashMap<>();
}
iracMetadataMap.put(segment, metadata);
}
public IracMetadata getIracMetadata(int segment) {
return iracMetadataMap != null ? iracMetadataMap.get(segment) : null;
}
}
| 3,332
| 31.359223
| 116
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/RollbackCommand.java
|
package org.infinispan.commands.tx;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.Visitor;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.ByteString;
/**
* Command corresponding to a transaction rollback.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public class RollbackCommand extends AbstractTransactionBoundaryCommand {
public static final byte COMMAND_ID = 13;
private RollbackCommand() {
super(null); // For command id uniqueness test
}
public RollbackCommand(ByteString cacheName, GlobalTransaction globalTransaction) {
super(cacheName);
this.globalTx = globalTransaction;
}
public RollbackCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry registry) throws Throwable {
// Need to mark the transaction as completed even if the prepare command was not executed on this node
TransactionTable txTable = registry.getTransactionTableRef().running();
txTable.markTransactionCompleted(globalTx, false);
return super.invokeAsync(registry);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitRollbackCommand((TxInvocationContext) ctx, this);
}
@Override
public void visitRemoteTransaction(RemoteTransaction tx) {
tx.markForRollback(true);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public String toString() {
return "RollbackCommand {" + super.toString();
}
}
| 1,965
| 29.71875
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/tx/TransactionBoundaryCommand.java
|
package org.infinispan.commands.tx;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.transaction.xa.GlobalTransaction;
/**
* An transaction boundary command that allows the retrieval of an attached
* {@link org.infinispan.transaction.xa.GlobalTransaction}
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public interface TransactionBoundaryCommand extends VisitableCommand, CacheRpcCommand, TopologyAffectedCommand {
GlobalTransaction getGlobalTransaction();
void markTransactionAsRemote(boolean remote);
}
| 740
| 32.681818
| 112
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/module/ModuleCommandExtensions.java
|
package org.infinispan.commands.module;
/**
* Module command extensions. To use this hook, you would need to implement this interface and take the necessary steps
* to make it discoverable by the {@link java.util.ServiceLoader} mechanism.
*
* @author Galder Zamarreño
* @since 5.1
*/
public interface ModuleCommandExtensions {
ModuleCommandFactory getModuleCommandFactory();
}
| 388
| 26.785714
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/module/ModuleCommandFactory.java
|
package org.infinispan.commands.module;
import java.util.Map;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.util.ByteString;
/**
* Modules which wish to implement their own commands and visitors must also provide an implementation of this
* interface.
* <p>
* Note that this is a {@link Scopes#GLOBAL} component and as such cannot have {@link Inject} methods referring to
* {@link Scopes#NAMED_CACHE} scoped components. For such components, use a corresponding {@link
* Scopes#NAMED_CACHE}-scoped {@link ModuleCommandInitializer}.
*
* @author Manik Surtani
* @since 5.0
*/
@Scope(Scopes.GLOBAL)
public interface ModuleCommandFactory {
/**
* Provides a map of command IDs to command types of all the commands handled by the command factory instance.
* Unmarshalling requests for these command IDs will be dispatched to this implementation.
*
* @return map of command IDs to command types handled by this implementation.
*/
Map<Byte, Class<? extends ReplicableCommand>> getModuleCommands();
/**
* Construct and initialize a {@link ReplicableCommand} based on the command id.
*
* @param commandId command id to construct
* @return a ReplicableCommand
*/
ReplicableCommand fromStream(byte commandId);
/**
* Construct and initialize a {@link CacheRpcCommand} based on the command id.
*
* @param commandId command id to construct
* @param cacheName cache name at which command to be created is directed
* @return a {@link CacheRpcCommand}
*/
CacheRpcCommand fromStream(byte commandId, ByteString cacheName);
}
| 1,841
| 35.117647
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/PutMapBackupWriteCommand.java
|
package org.infinispan.commands.triangle;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.util.ByteString;
import org.infinispan.util.TriangleFunctionsUtil;
/**
* A {@link BackupWriteCommand} implementation for {@link PutMapCommand}.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class PutMapBackupWriteCommand extends BackupWriteCommand {
public static final byte COMMAND_ID = 78;
private Map<Object, Object> map;
private Metadata metadata;
private Map<Object, PrivateMetadata> internalMetadataMap;
//for testing
@SuppressWarnings("unused")
public PutMapBackupWriteCommand() {
super(null);
}
public PutMapBackupWriteCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
writeBase(output);
MarshallUtil.marshallMap(map, output);
output.writeObject(metadata);
MarshallUtil.marshallMap(internalMetadataMap, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
readBase(input);
map = MarshallUtil.unmarshallMap(input, HashMap::new);
metadata = (Metadata) input.readObject();
internalMetadataMap = MarshallUtil.unmarshallMap(input, HashMap::new);
}
public void setPutMapCommand(PutMapCommand command, Collection<Object> keys) {
setCommonAttributesFromCommand(command);
this.map = TriangleFunctionsUtil.filterEntries(command.getMap(), keys);
this.metadata = command.getMetadata();
this.internalMetadataMap = new HashMap<>();
for (Object key : map.keySet()) {
internalMetadataMap.put(key, command.getInternalMetadata(key));
}
}
@Override
public String toString() {
return "PutMapBackupWriteCommand{" + toStringFields() + '}';
}
@Override
WriteCommand createWriteCommand() {
PutMapCommand cmd = new PutMapCommand(map, metadata, getFlags(), getCommandInvocationId());
cmd.setForwarded(true);
internalMetadataMap.forEach(cmd::setInternalMetadata);
return cmd;
}
@Override
String toStringFields() {
return super.toStringFields() +
", map=" + map +
", metadata=" + metadata +
", internalMetadata=" + internalMetadataMap;
}
}
| 2,776
| 28.542553
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/BackupWriteCommand.java
|
package org.infinispan.commands.triangle;
import static org.infinispan.commands.write.ValueMatcher.MATCH_ALWAYS;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.InvocationContextFactory;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.util.ByteString;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* A write operation sent from the primary owner to the backup owners.
* <p>
* This is a base command with the {@link CommandInvocationId}, topology and flags.
* <p>
* Since the primary → backup operations are ordered by segment, it contains the segment to be updated and its sequence number.
*
* @author Pedro Ruivo
* @since 9.2
*/
public abstract class BackupWriteCommand extends BaseRpcCommand {
//common attributes of all write commands
private CommandInvocationId commandInvocationId;
private int topologyId;
private long flags;
//backup commands are ordered by segment. this is the sequence number of the segment.
private long sequence;
protected int segmentId;
BackupWriteCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public final CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) {
WriteCommand command = createWriteCommand();
if (command == null) {
// No-op command
return CompletableFutures.completedNull();
}
command.init(componentRegistry);
command.setFlagsBitSet(flags);
// Mark the command as a backup write and skip locking
command.addFlags(FlagBitSets.SKIP_LOCKING | FlagBitSets.BACKUP_WRITE);
command.setValueMatcher(MATCH_ALWAYS);
command.setTopologyId(topologyId);
InvocationContextFactory invocationContextFactory = componentRegistry.getInvocationContextFactory().running();
InvocationContext invocationContext = invocationContextFactory.createRemoteInvocationContextForCommand(command, getOrigin());
AsyncInterceptorChain interceptorChain = componentRegistry.getInterceptorChain().running();
return interceptorChain.invokeAsync(invocationContext, command);
}
@Override
public final boolean isReturnValueExpected() {
return false;
}
@Override
public final boolean canBlock() {
return true;
}
public final long getSequence() {
return sequence;
}
public final void setSequence(long sequence) {
this.sequence = sequence;
}
public final CommandInvocationId getCommandInvocationId() {
return commandInvocationId;
}
public final int getTopologyId() {
return topologyId;
}
public final long getFlags() {
return flags;
}
public final int getSegmentId() {
return segmentId;
}
public final void setSegmentId(int segmentId) {
this.segmentId = segmentId;
}
final void writeBase(ObjectOutput output) throws IOException {
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeInt(topologyId);
output.writeLong(flags);
output.writeLong(sequence);
output.writeInt(segmentId);
}
final void readBase(ObjectInput input) throws IOException, ClassNotFoundException {
commandInvocationId = CommandInvocationId.readFrom(input);
topologyId = input.readInt();
flags = input.readLong();
sequence = input.readLong();
segmentId = input.readInt();
}
void setCommonAttributesFromCommand(WriteCommand command) {
this.commandInvocationId = command.getCommandInvocationId();
this.topologyId = command.getTopologyId();
this.flags = command.getFlagsBitSet();
}
abstract WriteCommand createWriteCommand();
String toStringFields() {
return "cacheName=" + cacheName +
", segment=" + segmentId +
", sequence=" + sequence +
", commandInvocationId=" + commandInvocationId +
", topologyId=" + topologyId +
", flags=" + flags;
}
}
| 4,388
| 31.036496
| 132
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/MultiEntriesFunctionalBackupWriteCommand.java
|
package org.infinispan.commands.triangle;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import org.infinispan.commands.functional.AbstractWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyEntriesCommand;
import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.util.ByteString;
import org.infinispan.util.TriangleFunctionsUtil;
/**
* A multi-key {@link BackupWriteCommand} for {@link WriteOnlyManyEntriesCommand} and {@link ReadWriteManyEntriesCommand}.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class MultiEntriesFunctionalBackupWriteCommand extends FunctionalBackupWriteCommand {
public static final byte COMMAND_ID = 79;
private boolean writeOnly;
private Map<?, ?> entries;
//for testing
@SuppressWarnings("unused")
public MultiEntriesFunctionalBackupWriteCommand() {
super(null);
}
public MultiEntriesFunctionalBackupWriteCommand(ByteString cacheName) {
super(cacheName);
}
public <K, V, T> void setWriteOnly(WriteOnlyManyEntriesCommand<K, V, T> command, Collection<Object> keys) {
setCommonAttributesFromCommand(command);
setFunctionalCommand(command);
writeOnly = true;
this.entries = TriangleFunctionsUtil.filterEntries(command.getArguments(), keys);
this.function = command.getBiConsumer();
}
public <K, V, T, R> void setReadWrite(ReadWriteManyEntriesCommand<K, V, T, R> command, Collection<Object> keys) {
setCommonAttributesFromCommand(command);
setFunctionalCommand(command);
writeOnly = false;
this.entries = TriangleFunctionsUtil.filterEntries(command.getArguments(), keys);
this.function = command.getBiFunction();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
writeBase(output);
writeFunctionAndParams(output);
output.writeBoolean(writeOnly);
MarshallUtil.marshallMap(entries, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
readBase(input);
readFunctionAndParams(input);
writeOnly = input.readBoolean();
entries = MarshallUtil.unmarshallMap(input, HashMap::new);
}
@Override
WriteCommand createWriteCommand() {
//noinspection unchecked
AbstractWriteManyCommand cmd = writeOnly ?
new WriteOnlyManyEntriesCommand(entries, (BiConsumer) function, params, getCommandInvocationId(),
keyDataConversion, valueDataConversion) :
new ReadWriteManyEntriesCommand(entries, (BiFunction) function, params, getCommandInvocationId(),
keyDataConversion, valueDataConversion);
cmd.setForwarded(true);
return cmd;
}
}
| 3,125
| 32.612903
| 122
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/SingleKeyBackupWriteCommand.java
|
package org.infinispan.commands.triangle;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.infinispan.commands.write.ComputeCommand;
import org.infinispan.commands.write.ComputeIfAbsentCommand;
import org.infinispan.commands.write.DataWriteCommand;
import org.infinispan.commands.write.IracPutKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.RemoveExpiredCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.util.ByteString;
/**
* A single key {@link BackupWriteCommand} for single key non-functional commands.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class SingleKeyBackupWriteCommand extends BackupWriteCommand {
public static final byte COMMAND_ID = 76;
private static final Operation[] CACHED_OPERATION = Operation.values();
private Operation operation;
private Object key;
private Object valueOrFunction;
private Metadata metadata;
private PrivateMetadata internalMetadata;
//for testing
@SuppressWarnings("unused")
public SingleKeyBackupWriteCommand() {
super(null);
}
public SingleKeyBackupWriteCommand(ByteString cacheName) {
super(cacheName);
}
private static Operation valueOf(int index) {
return CACHED_OPERATION[index];
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
public void setPutKeyValueCommand(PutKeyValueCommand command) {
this.operation = Operation.WRITE;
setCommonAttributesFromCommand(command);
this.key = command.getKey();
this.valueOrFunction = command.getValue();
this.metadata = command.getMetadata();
this.internalMetadata = command.getInternalMetadata();
}
public void setIracPutKeyValueCommand(IracPutKeyValueCommand command) {
this.operation = Operation.WRITE;
setCommonAttributesFromCommand(command);
this.key = command.getKey();
this.valueOrFunction = command.getValue();
this.metadata = command.getMetadata();
this.internalMetadata = command.getInternalMetadata();
}
public void setRemoveCommand(RemoveCommand command, boolean removeExpired) {
this.operation = removeExpired ? Operation.REMOVE_EXPIRED : Operation.REMOVE;
setCommonAttributesFromCommand(command);
this.key = command.getKey();
this.valueOrFunction = command.getValue();
this.internalMetadata = command.getInternalMetadata();
}
public void setReplaceCommand(ReplaceCommand command) {
this.operation = Operation.REPLACE;
setCommonAttributesFromCommand(command);
this.key = command.getKey();
this.valueOrFunction = command.getNewValue();
this.metadata = command.getMetadata();
this.internalMetadata = command.getInternalMetadata();
}
public void setComputeCommand(ComputeCommand command) {
this.operation = command.isComputeIfPresent() ? Operation.COMPUTE_IF_PRESENT : Operation.COMPUTE;
setCommonAttributesFromCommand(command);
this.key = command.getKey();
this.valueOrFunction = command.getRemappingBiFunction();
this.metadata = command.getMetadata();
this.internalMetadata = command.getInternalMetadata();
}
public void setComputeIfAbsentCommand(ComputeIfAbsentCommand command) {
this.operation = Operation.COMPUTE_IF_ABSENT;
setCommonAttributesFromCommand(command);
this.key = command.getKey();
this.valueOrFunction = command.getMappingFunction();
this.metadata = command.getMetadata();
this.internalMetadata = command.getInternalMetadata();
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
writeBase(output);
MarshallUtil.marshallEnum(operation, output);
output.writeObject(key);
output.writeObject(internalMetadata);
switch (operation) {
case COMPUTE_IF_PRESENT:
case COMPUTE_IF_ABSENT:
case COMPUTE:
case REPLACE:
case WRITE:
output.writeObject(metadata);
// falls through
case REMOVE_EXPIRED:
output.writeObject(valueOrFunction);
break;
case REMOVE:
break;
default:
}
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
readBase(input);
operation = MarshallUtil.unmarshallEnum(input, SingleKeyBackupWriteCommand::valueOf);
key = input.readObject();
internalMetadata = (PrivateMetadata) input.readObject();
switch (operation) {
case COMPUTE_IF_PRESENT:
case COMPUTE_IF_ABSENT:
case COMPUTE:
case REPLACE:
case WRITE:
metadata = (Metadata) input.readObject();
// falls through
case REMOVE_EXPIRED:
valueOrFunction = input.readObject();
break;
case REMOVE:
break;
default:
}
}
@Override
public String toString() {
return "SingleKeyBackupWriteCommand{" + toStringFields() + '}';
}
@Override
WriteCommand createWriteCommand() {
DataWriteCommand command;
switch (operation) {
case REMOVE:
command = new RemoveCommand(key, null, false, segmentId, getFlags(), getCommandInvocationId());
break;
case WRITE:
command = EnumUtil.containsAny(getFlags(), FlagBitSets.IRAC_UPDATE) ?
new IracPutKeyValueCommand(key, segmentId, getCommandInvocationId(), valueOrFunction, metadata, internalMetadata) :
new PutKeyValueCommand(key, valueOrFunction, false, false, metadata, segmentId, getFlags(), getCommandInvocationId());
break;
case COMPUTE:
command = new ComputeCommand(key, (BiFunction) valueOrFunction, false, segmentId, getFlags(),
getCommandInvocationId(), metadata);
break;
case REPLACE:
command = new ReplaceCommand(key, null, valueOrFunction, false, metadata, segmentId, getFlags(),
getCommandInvocationId());
break;
case REMOVE_EXPIRED:
// Doesn't matter if it is max idle or not - important thing is that it raises expired event
command = new RemoveExpiredCommand(key, valueOrFunction, null, false, segmentId, getFlags(),
getCommandInvocationId());
break;
case COMPUTE_IF_PRESENT:
command = new ComputeCommand(key, (BiFunction) valueOrFunction, true, segmentId, getFlags(),
getCommandInvocationId(), metadata);
break;
case COMPUTE_IF_ABSENT:
command = new ComputeIfAbsentCommand(key, (Function) valueOrFunction, segmentId, getFlags(),
getCommandInvocationId(), metadata);
break;
default:
throw new IllegalStateException("Unknown operation " + operation);
}
command.setInternalMetadata(internalMetadata);
return command;
}
@Override
String toStringFields() {
return super.toStringFields() +
", operation=" + operation +
", key=" + key +
", valueOrFunction=" + valueOrFunction +
", metadata=" + metadata +
", internalMetadata=" + internalMetadata;
}
private enum Operation {
WRITE,
REMOVE,
REMOVE_EXPIRED,
REPLACE,
COMPUTE,
COMPUTE_IF_PRESENT,
COMPUTE_IF_ABSENT
}
}
| 7,973
| 34.44
| 136
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/SingleKeyFunctionalBackupWriteCommand.java
|
package org.infinispan.commands.triangle;
import static org.infinispan.commands.write.ValueMatcher.MATCH_ALWAYS;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import org.infinispan.commands.functional.AbstractWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyCommand;
import org.infinispan.commands.functional.ReadWriteKeyValueCommand;
import org.infinispan.commands.functional.WriteOnlyKeyCommand;
import org.infinispan.commands.functional.WriteOnlyKeyValueCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.metadata.Metadata;
import org.infinispan.util.ByteString;
/**
* A single key {@link BackupWriteCommand} for single key functional commands.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class SingleKeyFunctionalBackupWriteCommand extends FunctionalBackupWriteCommand {
public static final byte COMMAND_ID = 77;
private static final Operation[] CACHED_OPERATION = Operation.values();
private Operation operation;
private Object key;
private Object value;
private Object prevValue;
private Metadata prevMetadata;
//for testing
@SuppressWarnings("unused")
public SingleKeyFunctionalBackupWriteCommand() {
super(null);
}
public SingleKeyFunctionalBackupWriteCommand(ByteString cacheName) {
super(cacheName);
}
private static Operation valueOf(int index) {
return CACHED_OPERATION[index];
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
public void setReadWriteKeyCommand(ReadWriteKeyCommand command) {
this.operation = Operation.READ_WRITE;
setCommonFields(command);
this.function = command.getFunction();
}
public void setReadWriteKeyValueCommand(ReadWriteKeyValueCommand command) {
this.operation = Operation.READ_WRITE_KEY_VALUE;
setCommonFields(command);
this.function = command.getBiFunction();
this.value = command.getArgument();
this.prevValue = command.getPrevValue();
this.prevMetadata = command.getPrevMetadata();
}
public void setWriteOnlyKeyValueCommand(WriteOnlyKeyValueCommand command) {
this.operation = Operation.WRITE_ONLY_KEY_VALUE;
setCommonFields(command);
this.function = command.getBiConsumer();
this.value = command.getArgument();
}
public void setWriteOnlyKeyCommand(WriteOnlyKeyCommand command) {
this.operation = Operation.WRITE_ONLY;
setCommonFields(command);
this.function = command.getConsumer();
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
writeBase(output);
writeFunctionAndParams(output);
MarshallUtil.marshallEnum(operation, output);
output.writeObject(key);
switch (operation) {
case READ_WRITE_KEY_VALUE:
output.writeObject(prevValue);
output.writeObject(prevMetadata);
case WRITE_ONLY_KEY_VALUE:
output.writeObject(value);
case READ_WRITE:
case WRITE_ONLY:
default:
}
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
readBase(input);
readFunctionAndParams(input);
operation = MarshallUtil.unmarshallEnum(input, SingleKeyFunctionalBackupWriteCommand::valueOf);
key = input.readObject();
switch (operation) {
case READ_WRITE_KEY_VALUE:
prevValue = input.readObject();
prevMetadata = (Metadata) input.readObject();
case WRITE_ONLY_KEY_VALUE:
value = input.readObject();
case READ_WRITE:
case WRITE_ONLY:
default:
}
}
@Override
WriteCommand createWriteCommand() {
switch (operation) {
case READ_WRITE:
//noinspection unchecked
return new ReadWriteKeyCommand(key, (Function) function, segmentId, getCommandInvocationId(), MATCH_ALWAYS,
params, keyDataConversion, valueDataConversion);
case READ_WRITE_KEY_VALUE:
//noinspection unchecked
ReadWriteKeyValueCommand cmd = new ReadWriteKeyValueCommand(key, value, (BiFunction) function, segmentId,
getCommandInvocationId(), MATCH_ALWAYS, params, keyDataConversion, valueDataConversion);
cmd.setPrevValueAndMetadata(prevValue, prevMetadata);
return cmd;
case WRITE_ONLY:
//noinspection unchecked
return new WriteOnlyKeyCommand(key, (Consumer) function, segmentId, getCommandInvocationId(), MATCH_ALWAYS,
params, keyDataConversion, valueDataConversion);
case WRITE_ONLY_KEY_VALUE:
//noinspection unchecked
return new WriteOnlyKeyValueCommand(key, value, (BiConsumer) function, segmentId, getCommandInvocationId(),
MATCH_ALWAYS, params, keyDataConversion, valueDataConversion);
default:
throw new IllegalStateException("Unknown operation " + operation);
}
}
private <C extends AbstractWriteKeyCommand> void setCommonFields(C command) {
setCommonAttributesFromCommand(command);
setFunctionalCommand(command);
this.key = command.getKey();
}
private enum Operation {
READ_WRITE_KEY_VALUE,
READ_WRITE,
WRITE_ONLY_KEY_VALUE,
WRITE_ONLY
}
}
| 5,596
| 33.549383
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/FunctionalBackupWriteCommand.java
|
package org.infinispan.commands.triangle;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.functional.FunctionalCommand;
import org.infinispan.encoding.DataConversion;
import org.infinispan.functional.impl.Params;
import org.infinispan.util.ByteString;
/**
* A base {@link BackupWriteCommand} used by {@link FunctionalCommand}.
*
* @author Pedro Ruivo
* @since 9.2
*/
abstract class FunctionalBackupWriteCommand extends BackupWriteCommand {
Object function;
Params params;
DataConversion keyDataConversion;
DataConversion valueDataConversion;
FunctionalBackupWriteCommand(ByteString cacheName) {
super(cacheName);
}
final void writeFunctionAndParams(ObjectOutput output) throws IOException {
output.writeObject(function);
Params.writeObject(output, params);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
}
final void readFunctionAndParams(ObjectInput input) throws IOException, ClassNotFoundException {
function = input.readObject();
params = Params.readObject(input);
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
}
final void setFunctionalCommand(FunctionalCommand command) {
this.params = command.getParams();
this.keyDataConversion = command.getKeyDataConversion();
this.valueDataConversion = command.getValueDataConversion();
}
}
| 1,542
| 29.86
| 99
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/MultiKeyFunctionalBackupWriteCommand.java
|
package org.infinispan.commands.triangle;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.Function;
import org.infinispan.commands.functional.AbstractWriteManyCommand;
import org.infinispan.commands.functional.ReadWriteManyCommand;
import org.infinispan.commands.functional.WriteOnlyManyCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.util.ByteString;
/**
* A multi-key {@link BackupWriteCommand} for {@link WriteOnlyManyCommand} and {@link ReadWriteManyCommand}.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class MultiKeyFunctionalBackupWriteCommand extends FunctionalBackupWriteCommand {
public static final byte COMMAND_ID = 80;
private boolean writeOnly;
private Collection<?> keys;
//for testing
@SuppressWarnings("unused")
public MultiKeyFunctionalBackupWriteCommand() {
super(null);
}
public MultiKeyFunctionalBackupWriteCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
public <K, V> void setWriteOnly(WriteOnlyManyCommand<K, V> command, Collection<Object> keys) {
setCommonAttributesFromCommand(command);
setFunctionalCommand(command);
this.writeOnly = true;
this.keys = keys;
this.function = command.getConsumer();
}
public <K, V, R> void setReadWrite(ReadWriteManyCommand<K, V, R> command, Collection<Object> keys) {
setCommonAttributesFromCommand(command);
setFunctionalCommand(command);
this.writeOnly = false;
this.keys = keys;
this.function = command.getFunction();
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
writeBase(output);
writeFunctionAndParams(output);
output.writeBoolean(writeOnly);
MarshallUtil.marshallCollection(keys, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
readBase(input);
readFunctionAndParams(input);
writeOnly = input.readBoolean();
keys = MarshallUtil.unmarshallCollection(input, ArrayList::new);
}
@Override
WriteCommand createWriteCommand() {
//noinspection unchecked
AbstractWriteManyCommand cmd = writeOnly ?
new WriteOnlyManyCommand(keys, (Consumer) function, params, getCommandInvocationId(),
keyDataConversion, valueDataConversion) :
new ReadWriteManyCommand(keys, (Function) function, params, getCommandInvocationId(),
keyDataConversion, valueDataConversion);
cmd.setForwarded(true);
return cmd;
}
}
| 2,850
| 30.32967
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/triangle/BackupNoopCommand.java
|
package org.infinispan.commands.triangle;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.util.ByteString;
/**
* A command that tell a backup owner to ignore a sequence id after the primary failed to send a regular write command.
*
* @author Dan Berindei
* @since 12.1
*/
public class BackupNoopCommand extends BackupWriteCommand {
public static final byte COMMAND_ID = 81;
//for testing
@SuppressWarnings("unused")
public BackupNoopCommand() {
super(null);
}
public BackupNoopCommand(ByteString cacheName) {
super(cacheName);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
public void setWriteCommand(WriteCommand command) {
super.setCommonAttributesFromCommand(command);
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
writeBase(output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
readBase(input);
}
@Override
public String toString() {
return "BackupNoopCommand{" + toStringFields() + '}';
}
@Override
WriteCommand createWriteCommand() {
return null;
}
@Override
String toStringFields() {
return super.toStringFields();
}
}
| 1,385
| 20.65625
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/ExceptionAckCommand.java
|
package org.infinispan.commands.write;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commons.CacheException;
import org.infinispan.remoting.transport.ResponseCollectors;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.CommandAckCollector;
/**
* A command that represents an exception acknowledge sent by any owner.
* <p>
* The acknowledge represents an unsuccessful execution of the operation.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class ExceptionAckCommand extends BackupAckCommand {
public static final byte COMMAND_ID = 42;
private Throwable throwable;
public ExceptionAckCommand() {
super();
}
public ExceptionAckCommand(ByteString cacheName) {
super(cacheName);
}
public ExceptionAckCommand(ByteString cacheName, long id, Throwable throwable, int topologyId) {
super(cacheName, id, topologyId);
this.throwable = throwable;
}
@Override
public void ack(CommandAckCollector ackCollector) {
CacheException remoteException = ResponseCollectors.wrapRemoteException(getOrigin(), this.throwable);
ackCollector.completeExceptionally(id, remoteException, topologyId);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeLong(id);
output.writeObject(throwable);
output.writeInt(topologyId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
id = input.readLong();
throwable = (Throwable) input.readObject();
topologyId = input.readInt();
}
@Override
public String toString() {
return "ExceptionAckCommand{" +
"id=" + id +
", throwable=" + throwable +
", topologyId=" + topologyId +
'}';
}
}
| 1,944
| 26.394366
| 107
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/InvalidateCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.infinispan.commands.AbstractTopologyAffectedCommand;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.util.concurrent.locks.RemoteLockCommand;
/**
* Removes an entry from memory.
*
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class InvalidateCommand extends AbstractTopologyAffectedCommand implements WriteCommand, RemoteLockCommand {
public static final int COMMAND_ID = 6;
protected Object[] keys;
protected CommandInvocationId commandInvocationId;
public InvalidateCommand() {
}
public InvalidateCommand(long flagsBitSet, CommandInvocationId commandInvocationId, Object... keys) {
this.keys = keys;
this.commandInvocationId = commandInvocationId;
setFlagsBitSet(flagsBitSet);
}
public InvalidateCommand(long flagsBitSet, Collection<Object> keys, CommandInvocationId commandInvocationId) {
this(flagsBitSet, commandInvocationId, keys == null || keys.isEmpty() ? Util.EMPTY_OBJECT_ARRAY : keys.toArray());
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public String toString() {
return "InvalidateCommand{keys=" +
toStr(Arrays.asList(keys)) +
'}';
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
CommandInvocationId.writeTo(output, commandInvocationId);
MarshallUtil.marshallArray(keys, output);
output.writeLong(getFlagsBitSet());
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
commandInvocationId = CommandInvocationId.readFrom(input);
keys = MarshallUtil.unmarshallArray(input, Util::objectArray);
setFlagsBitSet(input.readLong());
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitInvalidateCommand(ctx, this);
}
public Object[] getKeys() {
return keys;
}
@Override
public boolean isSuccessful() {
return true;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public ValueMatcher getValueMatcher() {
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
}
@Override
public Collection<?> getAffectedKeys() {
return new HashSet<>(Arrays.asList(keys));
}
@Override
public void fail() {
throw new UnsupportedOperationException();
}
@Override
public CommandInvocationId getCommandInvocationId() {
return commandInvocationId;
}
@Override
public PrivateMetadata getInternalMetadata(Object key) {
//TODO? support invalidation?
return null;
}
@Override
public void setInternalMetadata(Object key, PrivateMetadata internalMetadata) {
//no-op
}
@Override
public Collection<?> getKeysToLock() {
return Arrays.asList(keys);
}
@Override
public Object getKeyLockOwner() {
return commandInvocationId;
}
@Override
public boolean hasZeroLockAcquisition() {
return hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
@Override
public boolean hasSkipLocking() {
return hasAnyFlag(FlagBitSets.SKIP_LOCKING);
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InvalidateCommand that = (InvalidateCommand) obj;
if (!hasSameFlags(that))
return false;
return Arrays.equals(keys, that.keys);
}
@Override
public int hashCode() {
return keys != null ? Arrays.hashCode(keys) : 0;
}
}
| 4,481
| 24.465909
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/package-info.java
|
/**
* Commands that alter the state of the cache.
*
* @author Manik Surtani
* @since 4.0
*/
package org.infinispan.commands.write;
| 136
| 16.125
| 46
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/ValueMatcher.java
|
package org.infinispan.commands.write;
import org.infinispan.Cache;
/**
* A policy for determining if a write command should be executed based on the current value in the cache.
*
* When retrying conditional write commands in non-transactional caches, it is also used to determine the appropriate
* return value. E.g. if a {@code putIfAbsent(k, v)} already succeeded on a backup owner which became the primary owner,
* when retrying the command will find {@code v} in the cache but should return {@code null}. For non-conditional
* commands it's impossible to know what the previous value was, so the command is allowed to return {@code v}.
*
* @author Dan Berindei
* @since 6.0
*/
public enum ValueMatcher {
/**
* Always match. Used when the command is not conditional or when the value was already checked
* (on the primary owner, in non-tx caches, or on the originator, in tx caches).
* Also used when retrying {@link Cache#remove(Object)} operations.
*/
MATCH_ALWAYS() {
@Override
public boolean matches(Object existingValue, Object expectedValue, Object newValue) {
return true;
}
@Override
public boolean nonExistentEntryCanMatch() {
return true;
}
@Override
public ValueMatcher matcherForRetry() {
return MATCH_ALWAYS;
}
},
/**
* Match when the existing value is equal to the expected value.
* Used for {@link Cache#putIfAbsent(Object, Object)}, {@link Cache#replace(Object, Object, Object)},
* and {@link Cache#remove(Object, Object)}.
*/
MATCH_EXPECTED() {
@Override
public boolean matches(Object existingValue, Object expectedValue, Object newValue) {
return existingValue == null ? expectedValue == null : existingValue.equals(expectedValue);
}
@Override
public boolean nonExistentEntryCanMatch() {
return true;
}
@Override
public ValueMatcher matcherForRetry() {
return MATCH_EXPECTED_OR_NEW;
}
},
/**
* Match when the existing value is equal to the expected value or to the new value.
* Used only in non-tx caches, when retrying a conditional command on the primary owner.
*/
MATCH_EXPECTED_OR_NEW() {
@Override
public boolean matches(Object existingValue, Object expectedValue, Object newValue) {
if (existingValue == null)
return expectedValue == null || newValue == null;
else
return existingValue.equals(expectedValue) || existingValue.equals(newValue);
}
@Override
public boolean nonExistentEntryCanMatch() {
return true;
}
@Override
public ValueMatcher matcherForRetry() {
return MATCH_EXPECTED_OR_NEW;
}
},
MATCH_EXPECTED_OR_NULL() {
@Override
public boolean matches(Object existingValue, Object expectedValue, Object newValue) {
return existingValue == null || existingValue.equals(expectedValue);
}
@Override
public boolean nonExistentEntryCanMatch() {
return true;
}
@Override
public ValueMatcher matcherForRetry() {
return MATCH_EXPECTED_OR_NULL;
}
},
/**
* Match any non-null value. Used for {@link Cache#replace(Object, Object)} and {@link Cache#remove(Object)}.
*/
MATCH_NON_NULL() {
@Override
public boolean matches(Object existingValue, Object expectedValue, Object newValue) {
return existingValue != null;
}
@Override
public boolean nonExistentEntryCanMatch() {
return false;
}
@Override
public ValueMatcher matcherForRetry() {
return MATCH_ALWAYS;
}
},
/**
* Never match. Only used in transactional mode, as unsuccessful commands are still sent remotely,
* even though they should not be performed.
*/
MATCH_NEVER() {
@Override
public boolean matches(Object existingValue, Object expectedValue, Object newValue) {
return false;
}
@Override
public boolean nonExistentEntryCanMatch() {
return false;
}
@Override
public ValueMatcher matcherForRetry() {
return MATCH_NEVER;
}
},;
public abstract boolean matches(Object existingValue, Object expectedValue, Object newValue);
/**
* @deprecated Since 9.0, no longer used.
*/
@Deprecated
public abstract boolean nonExistentEntryCanMatch();
public abstract ValueMatcher matcherForRetry();
private static final ValueMatcher[] CACHED_VALUES = values();
public static ValueMatcher valueOf(int ordinal) {
return CACHED_VALUES[ordinal];
}
}
| 4,712
| 29.211538
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/BackupAckCommand.java
|
package org.infinispan.commands.write;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.CommandAckCollector;
/**
* A command that represents an acknowledge sent by a backup owner to the originator.
* <p>
* The acknowledge signals a successful execution of the operation.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class BackupAckCommand extends BaseRpcCommand {
public static final byte COMMAND_ID = 2;
protected long id;
protected int topologyId;
public BackupAckCommand() {
super(null);
}
public BackupAckCommand(ByteString cacheName) {
super(cacheName);
}
public BackupAckCommand(ByteString cacheName, long id, int topologyId) {
super(cacheName);
this.id = id;
this.topologyId = topologyId;
}
public void ack(CommandAckCollector ackCollector) {
ackCollector.backupAck(id, getOrigin(), topologyId);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeLong(id);
output.writeInt(topologyId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
id = input.readLong();
topologyId = input.readInt();
}
@Override
public String toString() {
return "BackupAckCommand{" +
"id=" + id +
", topologyId=" + topologyId +
'}';
}
}
| 1,707
| 22.39726
| 87
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/AbstractDataWriteCommand.java
|
package org.infinispan.commands.write;
import java.util.Collection;
import java.util.Collections;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.read.AbstractDataCommand;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.util.concurrent.locks.RemoteLockCommand;
/**
* Stuff common to WriteCommands
*
* @author Manik Surtani
* @since 4.0
*/
public abstract class AbstractDataWriteCommand extends AbstractDataCommand implements DataWriteCommand, RemoteLockCommand {
protected CommandInvocationId commandInvocationId;
protected AbstractDataWriteCommand() {
}
protected AbstractDataWriteCommand(Object key, int segment, long flagsBitSet, CommandInvocationId commandInvocationId) {
super(key, segment, flagsBitSet);
this.commandInvocationId = commandInvocationId;
}
@Override
public Collection<?> getAffectedKeys() {
return Collections.singleton(key);
}
@Override
public boolean isReturnValueExpected() {
return !hasAnyFlag(FlagBitSets.SKIP_REMOTE_LOOKUP | FlagBitSets.IGNORE_RETURN_VALUES);
}
@Override
public Collection<?> getKeysToLock() {
return getAffectedKeys();
}
@Override
public final Object getKeyLockOwner() {
return commandInvocationId;
}
@Override
public final boolean hasZeroLockAcquisition() {
return hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
@Override
public final boolean hasSkipLocking() {
return hasAnyFlag(FlagBitSets.SKIP_LOCKING);
}
@Override
public CommandInvocationId getCommandInvocationId() {
return commandInvocationId;
}
}
| 1,667
| 25.0625
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/RemoveExpiredCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.util.concurrent.TimeoutException;
/**
* Removes an entry that is expired from memory
*
* @author William Burns
* @since 8.0
*/
public class RemoveExpiredCommand extends RemoveCommand {
public static final int COMMAND_ID = 58;
private boolean maxIdle;
private Long lifespan;
public RemoveExpiredCommand() {
// The value matcher will always be the same, so we don't need to serialize it like we do for the other commands
this.valueMatcher = ValueMatcher.MATCH_EXPECTED_OR_NULL;
}
public RemoveExpiredCommand(Object key, Object value, Long lifespan, boolean maxIdle, int segment,
long flagBitSet, CommandInvocationId commandInvocationId) {
//valueEquivalence can be null because this command never compares values.
super(key, value, false, segment, flagBitSet, commandInvocationId);
this.lifespan = lifespan;
this.maxIdle = maxIdle;
this.valueMatcher = ValueMatcher.MATCH_EXPECTED_OR_NULL;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitRemoveExpiredCommand(ctx, this);
}
@Override
public boolean isConditional() {
return true;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public String toString() {
return "RemoveExpiredCommand{" +
"key=" + toStr(key) +
", value=" + toStr(value) +
", lifespan=" + lifespan +
", maxIdle=" + maxIdle +
", internalMetadata=" + getInternalMetadata() +
'}';
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeObject(key);
output.writeObject(value);
UnsignedNumeric.writeUnsignedInt(output, segment);
if (lifespan != null) {
output.writeBoolean(true);
output.writeLong(lifespan);
} else {
output.writeBoolean(false);
}
output.writeBoolean(maxIdle);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeObject(getInternalMetadata());
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
commandInvocationId = CommandInvocationId.readFrom(input);
key = input.readObject();
value = input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
boolean lifespanProvided = input.readBoolean();
if (lifespanProvided) {
lifespan = input.readLong();
} else {
lifespan = null;
}
maxIdle = input.readBoolean();
setFlagsBitSet(input.readLong());
setInternalMetadata((PrivateMetadata) input.readObject());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
RemoveExpiredCommand that = (RemoveExpiredCommand) o;
return maxIdle == that.maxIdle && Objects.equals(lifespan, that.lifespan);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), lifespan, maxIdle);
}
/**
* Whether this remove expired was fired because of max idle
* @return if this command is max idle based expiration
*/
public boolean isMaxIdle() {
return maxIdle;
}
public Long getLifespan() {
return lifespan;
}
@Override
public boolean logThrowable(Throwable t) {
Throwable cause = t;
do {
if (cause instanceof TimeoutException) {
return !hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
} while ((cause = cause.getCause()) != null);
return true;
}
}
| 4,382
| 29.65035
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/PutKeyValueCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.MetadataAwareCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
/**
* Implements functionality defined by {@link org.infinispan.Cache#put(Object, Object)}
*
* <p>Note: Since 9.4, when the flag {@link org.infinispan.context.Flag#PUT_FOR_STATE_TRANSFER} is set,
* the metadata is actually an {@code InternalMetadata} that includes the timestamps of the entry
* from the source node.</p>
*
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class PutKeyValueCommand extends AbstractDataWriteCommand implements MetadataAwareCommand {
public static final byte COMMAND_ID = 8;
private Object value;
private boolean putIfAbsent;
private boolean successful = true;
private boolean returnEntry = false;
private Metadata metadata;
private ValueMatcher valueMatcher;
private PrivateMetadata internalMetadata;
public PutKeyValueCommand() {
}
public PutKeyValueCommand(Object key, Object value, boolean putIfAbsent, boolean returnEntry, Metadata metadata,
int segment, long flagsBitSet, CommandInvocationId commandInvocationId) {
super(key, segment, flagsBitSet, commandInvocationId);
this.value = value;
this.putIfAbsent = putIfAbsent;
this.returnEntry = returnEntry;
this.valueMatcher = putIfAbsent ? ValueMatcher.MATCH_EXPECTED : ValueMatcher.MATCH_ALWAYS;
this.metadata = metadata;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitPutKeyValueCommand(ctx, this);
}
@Override
public LoadType loadType() {
if (isConditional() || !hasAnyFlag(FlagBitSets.IGNORE_RETURN_VALUES)) {
return LoadType.PRIMARY;
} else {
return LoadType.DONT_LOAD;
}
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(value);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeObject(metadata);
MarshallUtil.marshallEnum(valueMatcher, output);
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeBoolean(putIfAbsent);
output.writeObject(internalMetadata);
output.writeBoolean(returnEntry);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
value = input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
metadata = (Metadata) input.readObject();
valueMatcher = MarshallUtil.unmarshallEnum(input, ValueMatcher::valueOf);
commandInvocationId = CommandInvocationId.readFrom(input);
setFlagsBitSet(input.readLong());
putIfAbsent = input.readBoolean();
internalMetadata = (PrivateMetadata) input.readObject();
returnEntry = input.readBoolean();
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public boolean isPutIfAbsent() {
return putIfAbsent;
}
public void setPutIfAbsent(boolean putIfAbsent) {
this.putIfAbsent = putIfAbsent;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
PutKeyValueCommand that = (PutKeyValueCommand) o;
return putIfAbsent == that.putIfAbsent &&
Objects.equals(value, that.value) &&
Objects.equals(metadata, that.metadata);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (putIfAbsent ? 1 : 0);
result = 31 * result + (metadata != null ? metadata.hashCode() : 0);
return result;
}
@Override
public String toString() {
return new StringBuilder()
.append("PutKeyValueCommand{key=")
.append(toStr(key))
.append(", value=").append(toStr(value))
.append(", flags=").append(printFlags())
.append(", commandInvocationId=").append(CommandInvocationId.show(commandInvocationId))
.append(", putIfAbsent=").append(putIfAbsent)
.append(", returnEntry=").append(returnEntry)
.append(", valueMatcher=").append(valueMatcher)
.append(", metadata=").append(metadata)
.append(", internalMetadata=").append(internalMetadata)
.append(", successful=").append(successful)
.append(", topologyId=").append(getTopologyId())
.append(", segment=").append(segment)
.append("}")
.toString();
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public boolean isConditional() {
return putIfAbsent;
}
@Override
public ValueMatcher getValueMatcher() {
return valueMatcher;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
this.valueMatcher = valueMatcher;
}
@Override
public void fail() {
successful = false;
}
@Override
public boolean isReturnValueExpected() {
return isConditional() || super.isReturnValueExpected();
}
public PrivateMetadata getInternalMetadata() {
return internalMetadata;
}
public void setInternalMetadata(PrivateMetadata internalMetadata) {
this.internalMetadata = internalMetadata;
}
public boolean isReturnEntryNecessary() {
return returnEntry;
}
}
| 6,523
| 29.629108
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/EvictCommand.java
|
package org.infinispan.commands.write;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.LocalCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.context.InvocationContext;
/**
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class EvictCommand extends RemoveCommand implements LocalCommand {
public EvictCommand(Object key, int segment, long flagsBitSet, CommandInvocationId commandInvocationId) {
super(key, null, false, segment, flagsBitSet, commandInvocationId);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitEvictCommand(ctx, this);
}
@Override
public byte getCommandId() {
return -1; // these are not meant for replication!
}
@Override
public String toString() {
return new StringBuilder()
.append("EvictCommand{key=")
.append(key)
.append(", value=").append(value)
.append(", flags=").append(printFlags())
.append("}")
.toString();
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
}
| 1,179
| 26.44186
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/BackupMultiKeyAckCommand.java
|
package org.infinispan.commands.write;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.CommandAckCollector;
/**
* A command that represents an acknowledge sent by a backup owner to the originator.
* <p>
* The acknowledge signals a successful execution of a multi-key command, like {@link PutMapCommand}. It contains the
* segments ids of the updated keys.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class BackupMultiKeyAckCommand extends BackupAckCommand {
public static final byte COMMAND_ID = 41;
private int segment;
public BackupMultiKeyAckCommand() {
super(null);
}
public BackupMultiKeyAckCommand(ByteString cacheName) {
super(cacheName);
}
public BackupMultiKeyAckCommand(ByteString cacheName, long id, int segment,
int topologyId) {
super(cacheName, id, topologyId);
this.segment = segment;
}
@Override
public void ack(CommandAckCollector ackCollector) {
ackCollector.multiKeyBackupAck(id, getOrigin(), segment, topologyId);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeLong(id);
output.writeInt(segment);
output.writeInt(topologyId);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
id = input.readLong();
segment = input.readInt();
topologyId = input.readInt();
}
@Override
public String toString() {
return "BackupMultiKeyAckCommand{" +
"id=" + id +
", segment=" + segment +
", topologyId=" + topologyId +
'}';
}
}
| 1,817
| 24.605634
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/IracPutKeyValueCommand.java
|
package org.infinispan.commands.write;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.MetadataAwareCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.impl.CallInterceptor;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.xsite.spi.SiteEntry;
import org.infinispan.xsite.spi.XSiteEntryMergePolicy;
/**
* A {@link WriteCommand} used to handle updates from the remote site (for asynchronous cross-site replication).
* <p>
* Asynchronous cross-site replication may originate conflicts and this command allows to change its value based on the
* user's {@link XSiteEntryMergePolicy} installed. The value (and metadata) can change until the command reaches the end
* of the {@link AsyncInterceptorChain}, where the {@link CallInterceptor} checks its state and updates or removes the
* key.
* <p>
* Note, this command is non-transactional, even for transactional caches. This simplifies the conflict resolution.
*
* @author Pedro Ruivo
* @since 12.0
*/
public class IracPutKeyValueCommand extends AbstractDataWriteCommand implements MetadataAwareCommand {
public static final byte COMMAND_ID = 28;
private Object value;
private Metadata metadata;
private PrivateMetadata privateMetadata;
private boolean successful = true;
private boolean expiration;
public IracPutKeyValueCommand() {}
public IracPutKeyValueCommand(Object key, int segment, CommandInvocationId commandInvocationId, Object value,
Metadata metadata, PrivateMetadata privateMetadata) {
super(key, segment, FlagBitSets.IRAC_UPDATE, commandInvocationId);
assert privateMetadata != null;
this.value = value;
this.metadata = metadata;
this.privateMetadata = privateMetadata;
}
@Override
public PrivateMetadata getInternalMetadata() {
return privateMetadata;
}
@Override
public void setInternalMetadata(PrivateMetadata internalMetadata) {
this.privateMetadata = internalMetadata;
}
@Override
public PrivateMetadata getInternalMetadata(Object key) {
assert Objects.equals(this.key, key);
return getInternalMetadata();
}
@Override
public void setInternalMetadata(Object key, PrivateMetadata internalMetadata) {
assert Objects.equals(this.key, key);
setInternalMetadata(internalMetadata);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public ValueMatcher getValueMatcher() {
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
//no-op
}
@Override
public void fail() {
this.successful = false;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitIracPutKeyValueCommand(ctx, this);
}
@Override
public LoadType loadType() {
//primary owner always need the previous value to check the versions.
return LoadType.PRIMARY;
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public Object getValue() {
return value;
}
/**
* @return {@code true} if this command state is a removal operation, {@code false} otherwise.
*/
public boolean isRemove() {
return value == null;
}
/**
* Creates the {@link SiteEntry} to be used in {@link XSiteEntryMergePolicy}.
*
* @param site The remote site name.
* @return The {@link SiteEntry}.
*/
public SiteEntry<Object> createSiteEntry(String site) {
return new SiteEntry<>(site, value, metadata);
}
/**
* Updates this command state with the result of {@link XSiteEntryMergePolicy#merge(Object, SiteEntry,
* SiteEntry)}.
*
* @param siteEntry The resolved {@link SiteEntry}.
*/
public void updateCommand(SiteEntry<Object> siteEntry) {
this.value = siteEntry.getValue();
setMetadata(siteEntry.getMetadata());
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(value);
output.writeObject(metadata);
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeObject(privateMetadata);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeBoolean(expiration);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
value = input.readObject();
metadata = (Metadata) input.readObject();
commandInvocationId = CommandInvocationId.readFrom(input);
privateMetadata = (PrivateMetadata) input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
expiration = input.readBoolean();
setFlagsBitSet(FlagBitSets.IRAC_UPDATE);
}
public boolean isExpiration() {
return expiration;
}
public void setExpiration(boolean expiration) {
this.expiration = expiration;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
IracPutKeyValueCommand that = (IracPutKeyValueCommand) o;
return Objects.equals(value, that.value) &&
Objects.equals(metadata, that.metadata) &&
Objects.equals(privateMetadata, that.privateMetadata);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), value, metadata, privateMetadata);
}
@Override
public String toString() {
return "IracPutKeyValueCommand{" +
"key=" + key +
", value=" + value +
", metadata=" + metadata +
", privateMetadata=" + privateMetadata +
", successful=" + successful +
", commandInvocationId=" + commandInvocationId +
'}';
}
}
| 6,652
| 28.568889
| 120
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/ComputeCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import java.util.function.BiFunction;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.MetadataAwareCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
public class ComputeCommand extends AbstractDataWriteCommand implements MetadataAwareCommand {
public static final int COMMAND_ID = 68;
private BiFunction remappingBiFunction;
private Metadata metadata;
private boolean computeIfPresent;
private boolean successful = true;
private PrivateMetadata internalMetadata;
public ComputeCommand() {
}
public ComputeCommand(Object key,
BiFunction remappingBiFunction,
boolean computeIfPresent,
int segment, long flagsBitSet,
CommandInvocationId commandInvocationId,
Metadata metadata) {
super(key, segment, flagsBitSet, commandInvocationId);
this.remappingBiFunction = remappingBiFunction;
this.computeIfPresent = computeIfPresent;
this.metadata = metadata;
}
public boolean isComputeIfPresent() {
return computeIfPresent;
}
public void setComputeIfPresent(boolean computeIfPresent) {
this.computeIfPresent = computeIfPresent;
}
@Override
public void init(ComponentRegistry componentRegistry) {
componentRegistry.wireDependencies(remappingBiFunction);
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public boolean isConditional() {
return isComputeIfPresent();
}
@Override
public ValueMatcher getValueMatcher() {
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
//implementation not needed
}
@Override
public void fail() {
successful = false;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
public BiFunction getRemappingBiFunction() {
return remappingBiFunction;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeBoolean(computeIfPresent);
output.writeObject(remappingBiFunction);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeObject(metadata);
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
computeIfPresent = input.readBoolean();
remappingBiFunction = (BiFunction) input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
metadata = (Metadata) input.readObject();
commandInvocationId = CommandInvocationId.readFrom(input);
setFlagsBitSet(input.readLong());
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitComputeCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
ComputeCommand that = (ComputeCommand) o;
if (!Objects.equals(metadata, that.metadata)) return false;
if (!Objects.equals(computeIfPresent, that.computeIfPresent)) return false;
return Objects.equals(remappingBiFunction, that.remappingBiFunction);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), computeIfPresent, remappingBiFunction, metadata);
}
@Override
public String toString() {
return "ComputeCommand{" +
"key=" + toStr(key) +
", isComputeIfPresent=" + toStr(computeIfPresent) +
", remappingBiFunction=" + toStr(remappingBiFunction) +
", metadata=" + metadata +
", flags=" + printFlags() +
", successful=" + isSuccessful() +
", valueMatcher=" + getValueMatcher() +
", topologyId=" + getTopologyId() +
'}';
}
@Override
public final boolean isReturnValueExpected() {
return true;
}
@Override
public PrivateMetadata getInternalMetadata() {
return internalMetadata;
}
@Override
public void setInternalMetadata(PrivateMetadata internalMetadata) {
this.internalMetadata = internalMetadata;
}
}
| 5,375
| 28.059459
| 94
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/InvalidateL1Command.java
|
package org.infinispan.commands.write;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.Collections;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.context.InvocationContext;
import org.infinispan.remoting.transport.Address;
/**
* Invalidates an entry in a L1 cache (used with DIST mode)
*
* @author Manik Surtani
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class InvalidateL1Command extends InvalidateCommand {
public static final int COMMAND_ID = 7;
private Address writeOrigin;
public InvalidateL1Command() {
writeOrigin = null;
}
public InvalidateL1Command(long flagsBitSet,
CommandInvocationId commandInvocationId, Object... keys) {
super(flagsBitSet, commandInvocationId, keys);
writeOrigin = null;
}
public InvalidateL1Command(long flagsBitSet, Collection<Object> keys, CommandInvocationId commandInvocationId) {
this(null, flagsBitSet, keys, commandInvocationId);
}
public InvalidateL1Command(Address writeOrigin, long flagsBitSet, Collection<Object> keys,
CommandInvocationId commandInvocationId) {
super(flagsBitSet, keys, commandInvocationId);
this.writeOrigin = writeOrigin;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
public void setKeys(Object[] keys) {
this.keys = keys;
}
@Override
public Collection<?> getKeysToLock() {
//no keys to lock
return Collections.emptyList();
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output); //command invocation id + keys
output.writeObject(writeOrigin);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
writeOrigin = (Address) input.readObject();
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitInvalidateL1Command(ctx, this);
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"num keys=" + (keys == null ? 0 : keys.length) +
", origin=" + writeOrigin +
'}';
}
/**
* Returns true if the write that caused the invalidation was performed on this node.
* More formal, if a put(k) happens on node A and ch(A)={B}, then an invalidation message
* might be multicasted by B to all cluster members including A. This method returns true
* if and only if the node where it is invoked is A.
*/
public boolean isCausedByALocalWrite(Address address) {
return writeOrigin != null && writeOrigin.equals(address);
}
}
| 2,866
| 29.178947
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/ReplaceCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.MetadataAwareCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
/**
* @author Mircea.Markus@jboss.com
* @author Galder Zamarreño
* @since 4.0
*/
public class ReplaceCommand extends AbstractDataWriteCommand implements MetadataAwareCommand {
public static final byte COMMAND_ID = 11;
private Object oldValue;
private Object newValue;
private Metadata metadata;
private boolean successful = true;
private boolean returnEntry = false;
private PrivateMetadata internalMetadata;
private ValueMatcher valueMatcher;
public ReplaceCommand() {
}
public ReplaceCommand(Object key, Object oldValue, Object newValue, boolean returnEntry,
Metadata metadata, int segment, long flagsBitSet,
CommandInvocationId commandInvocationId) {
super(key, segment, flagsBitSet, commandInvocationId);
this.oldValue = oldValue;
this.newValue = newValue;
this.returnEntry = returnEntry;
this.metadata = metadata;
this.valueMatcher = oldValue != null ? ValueMatcher.MATCH_EXPECTED : ValueMatcher.MATCH_NON_NULL;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReplaceCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.PRIMARY;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(oldValue);
output.writeObject(newValue);
output.writeBoolean(returnEntry);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeObject(metadata);
MarshallUtil.marshallEnum(valueMatcher, output);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
oldValue = input.readObject();
newValue = input.readObject();
returnEntry = input.readBoolean();
segment = UnsignedNumeric.readUnsignedInt(input);
metadata = (Metadata) input.readObject();
valueMatcher = MarshallUtil.unmarshallEnum(input, ValueMatcher::valueOf);
setFlagsBitSet(input.readLong());
commandInvocationId = CommandInvocationId.readFrom(input);
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
ReplaceCommand that = (ReplaceCommand) o;
return Objects.equals(metadata, that.metadata) &&
Objects.equals(newValue, that.newValue) &&
Objects.equals(oldValue, that.oldValue);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (oldValue != null ? oldValue.hashCode() : 0);
result = 31 * result + (newValue != null ? newValue.hashCode() : 0);
result = 31 * result + (metadata != null ? metadata.hashCode() : 0);
return result;
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public boolean isConditional() {
return true;
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public Object getOldValue() {
return oldValue;
}
public void setOldValue(Object oldValue) {
this.oldValue = oldValue;
}
public Object getNewValue() {
return newValue;
}
public void setNewValue(Object newValue) {
this.newValue = newValue;
}
@Override
public ValueMatcher getValueMatcher() {
return valueMatcher;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
this.valueMatcher = valueMatcher;
}
@Override
public void fail() {
successful = false;
}
@Override
public final boolean isReturnValueExpected() {
return true;
}
public final boolean isReturnEntry() {
return returnEntry;
}
@Override
public String toString() {
return "ReplaceCommand{" +
"key=" + toStr(key) +
", oldValue=" + toStr(oldValue) +
", newValue=" + toStr(newValue) +
", metadata=" + metadata +
", flags=" + printFlags() +
", commandInvocationId=" + CommandInvocationId.show(commandInvocationId) +
", successful=" + successful +
", valueMatcher=" + valueMatcher +
", topologyId=" + getTopologyId() +
'}';
}
@Override
public PrivateMetadata getInternalMetadata() {
return internalMetadata;
}
@Override
public void setInternalMetadata(PrivateMetadata internalMetadata) {
this.internalMetadata = internalMetadata;
}
}
| 5,755
| 27.49505
| 103
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/RemoveCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.MetadataAwareCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
/**
* @author Mircea.Markus@jboss.com
* @author <a href="mailto:galder.zamarreno@jboss.com">Galder Zamarreno</a>
* @since 4.0
*/
public class RemoveCommand extends AbstractDataWriteCommand implements MetadataAwareCommand {
public static final byte COMMAND_ID = 10;
protected boolean successful = true;
private boolean nonExistent = false;
private boolean returnEntry = false;
protected Metadata metadata;
protected ValueMatcher valueMatcher;
private PrivateMetadata internalMetadata;
/**
* When not null, value indicates that the entry should only be removed if the key is mapped to this value.
* When null, the entry should be removed regardless of what value it is mapped to.
*/
protected Object value;
public RemoveCommand(Object key, Object value, boolean returnEntry, int segment, long flagsBitSet,
CommandInvocationId commandInvocationId) {
super(key, segment, flagsBitSet, commandInvocationId);
this.value = value;
this.valueMatcher = value != null ? ValueMatcher.MATCH_EXPECTED : ValueMatcher.MATCH_ALWAYS;
this.returnEntry = returnEntry;
}
public RemoveCommand() {
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitRemoveCommand(ctx, this);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
RemoveCommand that = (RemoveCommand) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return new StringBuilder()
.append("RemoveCommand{key=")
.append(toStr(key))
.append(", value=").append(toStr(value))
.append(", returnEntry=").append(returnEntry)
.append(", metadata=").append(metadata)
.append(", internalMetadata=").append(internalMetadata)
.append(", flags=").append(printFlags())
.append(", commandInvocationId=").append(CommandInvocationId.show(commandInvocationId))
.append(", valueMatcher=").append(valueMatcher)
.append(", topologyId=").append(getTopologyId())
.append("}")
.toString();
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public boolean isConditional() {
return value != null;
}
public void nonExistant() {
nonExistent = false;
}
public boolean isNonExistent() {
return nonExistent;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(value);
output.writeBoolean(returnEntry);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeObject(metadata);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
MarshallUtil.marshallEnum(valueMatcher, output);
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
value = input.readObject();
returnEntry = input.readBoolean();
segment = UnsignedNumeric.readUnsignedInt(input);
metadata = (Metadata) input.readObject();
setFlagsBitSet(input.readLong());
valueMatcher = MarshallUtil.unmarshallEnum(input, ValueMatcher::valueOf);
commandInvocationId = CommandInvocationId.readFrom(input);
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public ValueMatcher getValueMatcher() {
return valueMatcher;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
this.valueMatcher = valueMatcher;
}
@Override
public void fail() {
successful = false;
}
@Override
public LoadType loadType() {
return isConditional() || !hasAnyFlag(FlagBitSets.IGNORE_RETURN_VALUES) ? LoadType.PRIMARY : LoadType.DONT_LOAD;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public boolean isReturnEntryNecessary() {
return returnEntry;
}
@Override
public final boolean isReturnValueExpected() {
// IGNORE_RETURN_VALUES ignored for conditional remove
return isConditional() || super.isReturnValueExpected();
}
public PrivateMetadata getInternalMetadata() {
return internalMetadata;
}
public void setInternalMetadata(PrivateMetadata internalMetadata) {
this.internalMetadata = internalMetadata;
}
}
| 5,750
| 27.899497
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/ComputeIfAbsentCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Objects;
import java.util.function.Function;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.MetadataAwareCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
public class ComputeIfAbsentCommand extends AbstractDataWriteCommand implements MetadataAwareCommand {
public static final int COMMAND_ID = 69;
private Function mappingFunction;
private Metadata metadata;
private boolean successful = true;
private PrivateMetadata internalMetadata;
public ComputeIfAbsentCommand() {
}
public ComputeIfAbsentCommand(Object key,
Function mappingFunction,
int segment, long flagsBitSet,
CommandInvocationId commandInvocationId,
Metadata metadata) {
super(key, segment, flagsBitSet, commandInvocationId);
this.mappingFunction = mappingFunction;
this.metadata = metadata;
}
@Override
public void init(ComponentRegistry componentRegistry) {
componentRegistry.wireDependencies(mappingFunction);
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public ValueMatcher getValueMatcher() {
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
//implementation not needed
}
@Override
public void fail() {
successful = false;
}
public Function getMappingFunction() {
return mappingFunction;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(mappingFunction);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeObject(metadata);
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
mappingFunction = (Function) input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
metadata = (Metadata) input.readObject();
commandInvocationId = CommandInvocationId.readFrom(input);
setFlagsBitSet(input.readLong());
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitComputeIfAbsentCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.PRIMARY;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
ComputeIfAbsentCommand that = (ComputeIfAbsentCommand) o;
if (!Objects.equals(metadata, that.metadata)) return false;
return Objects.equals(mappingFunction, that.mappingFunction);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), mappingFunction, metadata);
}
@Override
public String toString() {
return "ComputeIfAbsentCommand{" +
"key=" + toStr(key) +
", mappingFunction=" + toStr(mappingFunction) +
", metadata=" + metadata +
", flags=" + printFlags() +
", successful=" + isSuccessful() +
", valueMatcher=" + getValueMatcher() +
", topologyId=" + getTopologyId() +
'}';
}
@Override
public final boolean isReturnValueExpected() {
return true;
}
@Override
public PrivateMetadata getInternalMetadata() {
return internalMetadata;
}
@Override
public void setInternalMetadata(PrivateMetadata internalMetadata) {
this.internalMetadata = internalMetadata;
}
}
| 4,798
| 27.229412
| 102
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/WriteCommand.java
|
package org.infinispan.commands.write;
import java.util.Collection;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.TopologyAffectedCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.metadata.impl.PrivateMetadata;
/**
* A command that modifies the cache in some way
*
* @author Manik Surtani
* @since 4.0
*/
public interface WriteCommand extends VisitableCommand, FlagAffectedCommand, TopologyAffectedCommand {
/**
* Some commands may want to provide information on whether the command was successful or not. This is different
* from a failure, which usually would result in an exception being thrown. An example is a putIfAbsent() not doing
* anything because the key in question was present. This would result in a isSuccessful() call returning false.
*
* @return true if the command completed successfully, false otherwise.
*/
boolean isSuccessful();
/**
* Certain commands only work based on a certain condition or state of the cache. For example, {@link
* org.infinispan.Cache#putIfAbsent(Object, Object)} only does anything if a condition is met, i.e., the entry in
* question is not already present. This method tests whether the command in question is conditional or not.
*
* @return true if the command is conditional, false otherwise
*/
boolean isConditional();
/**
* @return The current value matching policy.
*/
ValueMatcher getValueMatcher();
/**
* @param valueMatcher The new value matching policy.
*/
void setValueMatcher(ValueMatcher valueMatcher);
/**
*
* @return a collection of keys affected by this write command. Some commands - such as ClearCommand - may return
* an empty collection for this method.
*/
Collection<?> getAffectedKeys();
/**
* Used for conditional commands, to update the status of the command on the originator
* based on the result of its execution on the primary owner.
*
* @deprecated since 9.1
*/
@Deprecated
default void updateStatusFromRemoteResponse(Object remoteResponse) {}
/**
* Make subsequent invocations of {@link #isSuccessful()} return <code>false</code>.
*/
void fail();
/**
* Indicates whether the command is write-only, meaning that it makes no
* attempt to read the previously associated value with key for which the
* command is directed.
*
* @return true is the command is write only, false otherwise.
*/
default boolean isWriteOnly() {
return false;
}
/**
* @return the {@link CommandInvocationId} associated to the command.
*/
CommandInvocationId getCommandInvocationId();
PrivateMetadata getInternalMetadata(Object key);
void setInternalMetadata(Object key, PrivateMetadata internalMetadata);
}
| 2,911
| 32.090909
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/PutMapCommand.java
|
package org.infinispan.commands.write;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import org.infinispan.commands.AbstractTopologyAffectedCommand;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.MetadataAwareCommand;
import org.infinispan.commands.Visitor;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.util.concurrent.locks.RemoteLockCommand;
/**
* A command writing multiple key/value pairs with the same metadata.
*
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class PutMapCommand extends AbstractTopologyAffectedCommand implements WriteCommand, MetadataAwareCommand, RemoteLockCommand {
public static final byte COMMAND_ID = 9;
private Map<Object, Object> map;
private Metadata metadata;
private boolean isForwarded = false;
private Map<Object, PrivateMetadata> internalMetadataMap;
public CommandInvocationId getCommandInvocationId() {
return commandInvocationId;
}
private CommandInvocationId commandInvocationId;
public PutMapCommand() {
}
@SuppressWarnings("unchecked")
public PutMapCommand(Map<?, ?> map, Metadata metadata, long flagsBitSet, CommandInvocationId commandInvocationId) {
this.map = (Map<Object, Object>) map;
this.metadata = metadata;
this.commandInvocationId = commandInvocationId;
setFlagsBitSet(flagsBitSet);
this.internalMetadataMap = new HashMap<>();
}
public PutMapCommand(PutMapCommand command) {
this.map = command.map;
this.metadata = command.metadata;
this.isForwarded = command.isForwarded;
this.commandInvocationId = command.commandInvocationId;
setFlagsBitSet(command.getFlagsBitSet());
this.internalMetadataMap = new HashMap<>(command.internalMetadataMap);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitPutMapCommand(ctx, this);
}
@Override
public Collection<?> getKeysToLock() {
return isForwarded ? Collections.emptyList() : Collections.unmodifiableCollection(map.keySet());
}
@Override
public Object getKeyLockOwner() {
return commandInvocationId;
}
@Override
public boolean hasZeroLockAcquisition() {
return hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
@Override
public boolean hasSkipLocking() {
return hasAnyFlag(FlagBitSets.SKIP_LOCKING);
}
public Map<Object, Object> getMap() {
return map;
}
public void setMap(Map<Object, Object> map) {
this.map = map;
this.internalMetadataMap.keySet().retainAll(map.keySet());
}
public final PutMapCommand withMap(Map<Object, Object> map) {
setMap(map);
return this;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
MarshallUtil.marshallMap(map, output);
output.writeObject(metadata);
output.writeBoolean(isForwarded);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
CommandInvocationId.writeTo(output, commandInvocationId);
MarshallUtil.marshallMap(internalMetadataMap, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
map = MarshallUtil.unmarshallMap(input, LinkedHashMap::new);
metadata = (Metadata) input.readObject();
isForwarded = input.readBoolean();
setFlagsBitSet(input.readLong());
commandInvocationId = CommandInvocationId.readFrom(input);
internalMetadataMap = MarshallUtil.unmarshallMap(input, HashMap::new);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PutMapCommand that = (PutMapCommand) o;
return Objects.equals(metadata, that.metadata) &&
Objects.equals(map, that.map);
}
@Override
public int hashCode() {
int result = map != null ? map.hashCode() : 0;
result = 31 * result + (metadata != null ? metadata.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("PutMapCommand{map={");
if (!map.isEmpty()) {
Iterator<Entry<Object, Object>> it = map.entrySet().iterator();
int i = 0;
for (;;) {
Entry<Object, Object> e = it.next();
sb.append(toStr(e.getKey())).append('=').append(toStr(e.getValue()));
if (!it.hasNext()) {
break;
}
if (i > 100) {
sb.append(" ...");
break;
}
sb.append(", ");
i++;
}
}
sb.append("}, flags=").append(printFlags())
.append(", metadata=").append(metadata)
.append(", internalMetadata=").append(internalMetadataMap)
.append(", isForwarded=").append(isForwarded)
.append("}");
return sb.toString();
}
@Override
public boolean isSuccessful() {
return true;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public ValueMatcher getValueMatcher() {
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
// Do nothing
}
@Override
public Collection<?> getAffectedKeys() {
return map.keySet();
}
@Override
public void fail() {
throw new UnsupportedOperationException();
}
@Override
public boolean isReturnValueExpected() {
return !hasAnyFlag(FlagBitSets.IGNORE_RETURN_VALUES);
}
@Override
public LoadType loadType() {
return hasAnyFlag(FlagBitSets.IGNORE_RETURN_VALUES) ? LoadType.DONT_LOAD : LoadType.PRIMARY;
}
@Override
public Metadata getMetadata() {
return metadata;
}
@Override
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
/**
* For non transactional caches that support concurrent writes (default), the commands are forwarded between nodes,
* e.g.:
* - commands is executed on node A, but some of the keys should be locked on node B
* - the command is send to the main owner (B)
* - B tries to acquire lock on the keys it owns, then forwards the commands to the other owners as well
* - at this last stage, the command has the "isForwarded" flag set to true.
*/
public boolean isForwarded() {
return isForwarded;
}
/**
* @see #isForwarded()
*/
public void setForwarded(boolean forwarded) {
isForwarded = forwarded;
}
@Override
public PrivateMetadata getInternalMetadata(Object key) {
return internalMetadataMap.get(key);
}
@Override
public void setInternalMetadata(Object key, PrivateMetadata internalMetadata) {
this.internalMetadataMap.put(key, internalMetadata);
}
}
| 7,550
| 27.931034
| 133
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/DataWriteCommand.java
|
package org.infinispan.commands.write;
import org.infinispan.commands.DataCommand;
import org.infinispan.metadata.impl.PrivateMetadata;
/**
* Mixes features from DataCommand and WriteCommand
*
* @author Manik Surtani
* @since 4.0
*/
public interface DataWriteCommand extends WriteCommand, DataCommand {
PrivateMetadata getInternalMetadata();
void setInternalMetadata(PrivateMetadata internalMetadata);
@Override
default PrivateMetadata getInternalMetadata(Object key) {
return key.equals(getKey()) ? getInternalMetadata() : null;
}
@Override
default void setInternalMetadata(Object key, PrivateMetadata internalMetadata) {
if (key.equals(getKey())) {
setInternalMetadata(internalMetadata);
}
}
}
| 758
| 24.3
| 83
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/write/ClearCommand.java
|
package org.infinispan.commands.write;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.Collections;
import org.infinispan.commands.AbstractTopologyAffectedCommand;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.metadata.impl.PrivateMetadata;
/**
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class ClearCommand extends AbstractTopologyAffectedCommand implements WriteCommand {
public static final byte COMMAND_ID = 5;
public ClearCommand() {
}
public ClearCommand(long flagsBitSet) {
setFlagsBitSet(flagsBitSet);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitClearCommand(ctx, this);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
setFlagsBitSet(input.readLong());
}
@Override
public String toString() {
return new StringBuilder()
.append("ClearCommand{flags=")
.append(printFlags())
.append("}")
.toString();
}
@Override
public boolean isSuccessful() {
return true;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public ValueMatcher getValueMatcher() {
return ValueMatcher.MATCH_ALWAYS;
}
@Override
public void setValueMatcher(ValueMatcher valueMatcher) {
// Do nothing
}
@Override
public Collection<?> getAffectedKeys() {
return Collections.emptySet();
}
@Override
public void fail() {
throw new UnsupportedOperationException();
}
@Override
public CommandInvocationId getCommandInvocationId() {
return null;
}
@Override
public PrivateMetadata getInternalMetadata(Object key) {
return null;
}
@Override
public void setInternalMetadata(Object key, PrivateMetadata internalMetadata) {
//no-op
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClearCommand that = (ClearCommand) o;
if (getTopologyId() != that.getTopologyId()) return false;
return getFlagsBitSet() == that.getFlagsBitSet();
}
@Override
public int hashCode() {
int result = getTopologyId();
long flags = getFlagsBitSet();
result = 31 * result + (int) (flags ^ (flags >>> 32));
return result;
}
}
| 3,091
| 21.903704
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/TxReadOnlyManyCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.impl.Params;
public class TxReadOnlyManyCommand<K, V, R> extends ReadOnlyManyCommand<K, V, R> {
public static final byte COMMAND_ID = 65;
// These mutations must have the same order of iteration as keys. We can guarantee that because the mutations
// are set only when replicating the command to other nodes where we have already narrowed the key set
private List<List<Mutation<K, V, ?>>> mutations;
public TxReadOnlyManyCommand() {
}
public TxReadOnlyManyCommand(Collection<?> keys, List<List<Mutation<K, V, ?>>> mutations,
Params params, DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(keys, null, params, keyDataConversion, valueDataConversion);
this.mutations = mutations;
}
public TxReadOnlyManyCommand(ReadOnlyManyCommand c, List<List<Mutation<K, V, ?>>> mutations) {
super(c);
this.mutations = mutations;
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (mutations != null) {
for (List<Mutation<K, V, ?>> list : mutations) {
for (Mutation<K, V, ?> m : list) {
m.inject(componentRegistry);
}
}
}
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
super.writeTo(output);
// TODO: if the marshaller does not support object counting we could marshall the same functions many times
// This encoding is optimized for mostly-empty inner lists but is as efficient as regular collection
// encoding from MarshallUtil if all the inner lists are non-empty
int emptyLists = 0;
for (List<Mutation<K, V, ?>> list : mutations) {
if (list.isEmpty()) {
emptyLists++;
} else {
if (emptyLists > 0) output.writeInt(-emptyLists);
output.writeInt(list.size());
for (Mutation<K, V, ?> mut : list) {
Mutations.writeTo(output, mut);
}
emptyLists = 0;
}
}
if (emptyLists > 0) output.writeInt(-emptyLists);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
super.readFrom(input);
int numMutations = keys.size();
mutations = new ArrayList<>(numMutations);
for (int i = 0; i < numMutations; ++i) {
int length = input.readInt();
if (length < 0) {
i -= length;
while (length < 0) {
mutations.add(Collections.emptyList());
++length;
}
if (i >= numMutations) {
break;
}
length = input.readInt();
}
List<Mutation<K, V, ?>> list = new ArrayList<>(length);
for (int j = 0; j < length; ++j) {
list.add(Mutations.readFrom(input));
}
mutations.add(list);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("TxReadOnlyManyCommand{");
sb.append("keys=").append(keys);
sb.append(", f=").append(f);
sb.append(", mutations=").append(mutations);
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
public List<List<Mutation<K, V, ?>>> getMutations() {
return mutations;
}
}
| 3,966
| 32.905983
| 113
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/WriteOnlyManyEntriesCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.impl.Params;
public final class WriteOnlyManyEntriesCommand<K, V, T> extends AbstractWriteManyCommand<K, V> {
public static final byte COMMAND_ID = 57;
private Map<?, ?> arguments;
private BiConsumer<T, WriteEntryView<K, V>> f;
public WriteOnlyManyEntriesCommand(Map<?, ?> arguments,
BiConsumer<T, WriteEntryView<K, V>> f,
Params params,
CommandInvocationId commandInvocationId,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(commandInvocationId, params, keyDataConversion, valueDataConversion);
this.arguments = arguments;
this.f = f;
}
public WriteOnlyManyEntriesCommand(WriteOnlyManyEntriesCommand<K, V, T> command) {
super(command);
this.arguments = command.arguments;
this.f = command.f;
}
public WriteOnlyManyEntriesCommand() {
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
public BiConsumer<T, WriteEntryView<K, V>> getBiConsumer() {
return f;
}
public Map<?, ?> getArguments() {
return arguments;
}
public void setArguments(Map<?, ?> arguments) {
this.arguments = arguments;
this.internalMetadataMap.keySet().retainAll(arguments.keySet());
}
public final WriteOnlyManyEntriesCommand<K, V, T> withArguments(Map<?, ?> entries) {
setArguments(entries);
return this;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
CommandInvocationId.writeTo(output, commandInvocationId);
MarshallUtil.marshallMap(arguments, output);
output.writeObject(f);
output.writeBoolean(isForwarded);
Params.writeObject(output, params);
output.writeInt(topologyId);
output.writeLong(flags);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
MarshallUtil.marshallMap(internalMetadataMap, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
commandInvocationId = CommandInvocationId.readFrom(input);
// We use LinkedHashMap in order to guarantee the same order of iteration
arguments = MarshallUtil.unmarshallMap(input, LinkedHashMap::new);
f = (BiConsumer<T, WriteEntryView<K, V>>) input.readObject();
isForwarded = input.readBoolean();
params = Params.readObject(input);
topologyId = input.readInt();
flags = input.readLong();
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
this.internalMetadataMap = MarshallUtil.unmarshallMap(input, ConcurrentHashMap::new);
}
@Override
public boolean isReturnValueExpected() {
// Scattered cache always needs some response.
return true;
}
@Override
public Collection<?> getAffectedKeys() {
return arguments.keySet();
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitWriteOnlyManyEntriesCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
@Override
public boolean isWriteOnly() {
return true;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("WriteOnlyManyEntriesCommand{");
sb.append("arguments=").append(arguments);
sb.append(", f=").append(f.getClass().getName());
sb.append(", isForwarded=").append(isForwarded);
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
@Override
public Collection<?> getKeysToLock() {
return arguments.keySet();
}
@Override
public Mutation<K, V, ?> toMutation(Object key) {
return new Mutations.WriteWithValue<>(keyDataConversion, valueDataConversion, arguments.get(key), f);
}
}
| 5,159
| 32.076923
| 107
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/WriteOnlyKeyCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.Consumer;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commands.write.ValueMatcher;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.impl.Params;
import org.infinispan.metadata.impl.PrivateMetadata;
public final class WriteOnlyKeyCommand<K, V> extends AbstractWriteKeyCommand<K, V> {
public static final byte COMMAND_ID = 54;
private Consumer<WriteEntryView<K, V>> f;
public WriteOnlyKeyCommand(Object key,
Consumer<WriteEntryView<K, V>> f,
int segment, CommandInvocationId id,
ValueMatcher valueMatcher,
Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(key, valueMatcher, segment, id, params, keyDataConversion, valueDataConversion);
this.f = f;
}
public WriteOnlyKeyCommand() {
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(f);
MarshallUtil.marshallEnum(valueMatcher, output);
UnsignedNumeric.writeUnsignedInt(output, segment);
Params.writeObject(output, params);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
CommandInvocationId.writeTo(output, commandInvocationId);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
f = (Consumer<WriteEntryView<K, V>>) input.readObject();
valueMatcher = MarshallUtil.unmarshallEnum(input, ValueMatcher::valueOf);
segment = UnsignedNumeric.readUnsignedInt(input);
params = Params.readObject(input);
setFlagsBitSet(input.readLong());
commandInvocationId = CommandInvocationId.readFrom(input);
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public boolean isConditional() {
return false;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitWriteOnlyKeyCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
@Override
public boolean isWriteOnly() {
return true;
}
@Override
public Mutation<K, V, ?> toMutation(Object key) {
return new Mutations.Write(keyDataConversion, valueDataConversion, f);
}
public Consumer<WriteEntryView<K, V>> getConsumer() {
return f;
}
}
| 3,774
| 33.009009
| 92
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/WriteOnlyKeyValueCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.BiConsumer;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commands.write.ValueMatcher;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.impl.Params;
import org.infinispan.metadata.impl.PrivateMetadata;
public final class WriteOnlyKeyValueCommand<K, V, T> extends AbstractWriteKeyCommand<K, V> {
public static final byte COMMAND_ID = 55;
private BiConsumer<T, WriteEntryView<K, V>> f;
private Object argument;
public WriteOnlyKeyValueCommand(Object key, Object argument,
BiConsumer<T, WriteEntryView<K, V>> f,
int segment, CommandInvocationId id,
ValueMatcher valueMatcher,
Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(key, valueMatcher, segment, id, params, keyDataConversion, valueDataConversion);
this.f = f;
this.argument = argument;
}
public WriteOnlyKeyValueCommand() {
// No-op, for marshalling
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(argument);
output.writeObject(f);
MarshallUtil.marshallEnum(valueMatcher, output);
UnsignedNumeric.writeUnsignedInt(output, segment);
Params.writeObject(output, params);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
CommandInvocationId.writeTo(output, commandInvocationId);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
argument = input.readObject();
f = (BiConsumer<T, WriteEntryView<K, V>>) input.readObject();
valueMatcher = MarshallUtil.unmarshallEnum(input, ValueMatcher::valueOf);
segment = UnsignedNumeric.readUnsignedInt(input);
params = Params.readObject(input);
setFlagsBitSet(input.readLong());
commandInvocationId = CommandInvocationId.readFrom(input);
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public boolean isConditional() {
return false;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitWriteOnlyKeyValueCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
@Override
public boolean isWriteOnly() {
return true;
}
@Override
public Mutation<K, V, ?> toMutation(Object key) {
return new Mutations.WriteWithValue<>(keyDataConversion, valueDataConversion, argument, f);
}
public BiConsumer<T, WriteEntryView<K, V>> getBiConsumer() {
return f;
}
public Object getArgument() {
return argument;
}
}
| 4,116
| 33.308333
| 97
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/Mutation.java
|
package org.infinispan.commands.functional;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.encoding.DataConversion;
import org.infinispan.functional.EntryView;
/**
* Simplified version of functional command used for read-only operations after transactional modifications.
*/
public interface Mutation<K, V, R> extends InjectableComponent {
/**
* @return Internal identifier used for purposes of marshalling
*/
byte type();
/**
* Mutate the view
* @param view
* */
R apply(EntryView.ReadWriteEntryView<K, V> view);
DataConversion keyDataConversion();
DataConversion valueDataConversion();
}
| 685
| 24.407407
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/WriteOnlyManyCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.WriteEntryView;
import org.infinispan.functional.impl.Params;
public final class WriteOnlyManyCommand<K, V> extends AbstractWriteManyCommand<K, V> {
public static final byte COMMAND_ID = 56;
private Collection<?> keys;
private Consumer<WriteEntryView<K, V>> f;
public WriteOnlyManyCommand(Collection<?> keys,
Consumer<WriteEntryView<K, V>> f,
Params params,
CommandInvocationId commandInvocationId,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(commandInvocationId, params, keyDataConversion, valueDataConversion);
this.keys = keys;
this.f = f;
}
public WriteOnlyManyCommand(WriteOnlyManyCommand<K, V> command) {
super(command);
this.keys = command.keys;
this.f = command.f;
}
public WriteOnlyManyCommand() {
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
public Consumer<WriteEntryView<K, V>> getConsumer() {
return f;
}
public void setKeys(Collection<?> keys) {
this.keys = keys;
this.internalMetadataMap.keySet().retainAll(keys);
}
public final WriteOnlyManyCommand<K, V> withKeys(Collection<?> keys) {
setKeys(keys);
return this;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
CommandInvocationId.writeTo(output, commandInvocationId);
MarshallUtil.marshallCollection(keys, output);
output.writeObject(f);
output.writeBoolean(isForwarded);
Params.writeObject(output, params);
output.writeInt(topologyId);
output.writeLong(flags);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
MarshallUtil.marshallMap(internalMetadataMap, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
commandInvocationId = CommandInvocationId.readFrom(input);
keys = MarshallUtil.unmarshallCollectionUnbounded(input, ArrayList::new);
f = (Consumer<WriteEntryView<K, V>>) input.readObject();
isForwarded = input.readBoolean();
params = Params.readObject(input);
topologyId = input.readInt();
flags = input.readLong();
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
this.internalMetadataMap = MarshallUtil.unmarshallMap(input, ConcurrentHashMap::new);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitWriteOnlyManyCommand(ctx, this);
}
@Override
public boolean isReturnValueExpected() {
// Scattered cache always needs some response.
return true;
}
@Override
public Collection<?> getAffectedKeys() {
return keys;
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
@Override
public boolean isWriteOnly() {
return true;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("WriteOnlyManyCommand{");
sb.append("keys=").append(keys);
sb.append(", f=").append(f.getClass().getName());
sb.append(", isForwarded=").append(isForwarded);
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
@Override
public Collection<?> getKeysToLock() {
return keys;
}
@Override
public Mutation<K, V, ?> toMutation(Object key) {
return new Mutations.Write<>(keyDataConversion, valueDataConversion, f);
}
}
| 4,740
| 30.606667
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/ReadWriteManyCommand.java
|
package org.infinispan.commands.functional;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.impl.Params;
// TODO: the command does not carry previous values to backup, so it can cause
// the values on primary and backup owners to diverge in case of topology change
public final class ReadWriteManyCommand<K, V, R> extends AbstractWriteManyCommand<K, V> {
public static final byte COMMAND_ID = 52;
private Collection<?> keys;
private Function<ReadWriteEntryView<K, V>, R> f;
boolean isForwarded = false;
public ReadWriteManyCommand(Collection<?> keys,
Function<ReadWriteEntryView<K, V>, R> f, Params params,
CommandInvocationId commandInvocationId,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(commandInvocationId, params, keyDataConversion, valueDataConversion);
this.keys = keys;
this.f = f;
}
public ReadWriteManyCommand(ReadWriteManyCommand command) {
super(command);
this.keys = command.keys;
this.f = command.f;
}
public ReadWriteManyCommand() {
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
public Function<ReadWriteEntryView<K, V>, R> getFunction() {
return f;
}
public void setKeys(Collection<?> keys) {
this.keys = keys;
this.internalMetadataMap.keySet().retainAll(keys);
}
public final ReadWriteManyCommand<K, V, R> withKeys(Collection<?> keys) {
setKeys(keys);
return this;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
CommandInvocationId.writeTo(output, commandInvocationId);
MarshallUtil.marshallCollection(keys, output);
output.writeObject(f);
output.writeBoolean(isForwarded);
Params.writeObject(output, params);
output.writeInt(topologyId);
output.writeLong(flags);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
MarshallUtil.marshallMap(internalMetadataMap, output);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
commandInvocationId = CommandInvocationId.readFrom(input);
keys = MarshallUtil.unmarshallCollection(input, ArrayList::new);
f = (Function<ReadWriteEntryView<K, V>, R>) input.readObject();
isForwarded = input.readBoolean();
params = Params.readObject(input);
topologyId = input.readInt();
flags = input.readLong();
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
this.internalMetadataMap = MarshallUtil.unmarshallMap(input, ConcurrentHashMap::new);
}
public boolean isForwarded() {
return isForwarded;
}
public void setForwarded(boolean forwarded) {
isForwarded = forwarded;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReadWriteManyCommand(ctx, this);
}
@Override
public Collection<?> getAffectedKeys() {
return keys;
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ReadWriteManyCommand{");
sb.append("keys=").append(keys);
sb.append(", f=").append(f);
sb.append(", isForwarded=").append(isForwarded);
sb.append(", keyDataConversion=").append(keyDataConversion);
sb.append(", valueDataConversion=").append(valueDataConversion);
sb.append('}');
return sb.toString();
}
@Override
public Collection<?> getKeysToLock() {
return keys;
}
public Mutation toMutation(Object key) {
return new Mutations.ReadWrite<>(keyDataConversion, valueDataConversion, f);
}
}
| 4,909
| 30.883117
| 91
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/FunctionalCommand.java
|
package org.infinispan.commands.functional;
import org.infinispan.encoding.DataConversion;
import org.infinispan.functional.impl.Params;
/**
* A command that carries operation rather than final value.
*/
public interface FunctionalCommand<K, V> {
Params getParams();
Mutation<K, V, ?> toMutation(Object key);
DataConversion getKeyDataConversion();
DataConversion getValueDataConversion();
}
| 410
| 21.833333
| 60
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/commands/functional/ReadWriteKeyValueCommand.java
|
package org.infinispan.commands.functional;
import static org.infinispan.commons.util.Util.toStr;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.BiFunction;
import org.infinispan.commands.CommandInvocationId;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.functional.functions.InjectableComponent;
import org.infinispan.commands.write.ValueMatcher;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.encoding.DataConversion;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
import org.infinispan.functional.impl.Params;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
public final class ReadWriteKeyValueCommand<K, V, T, R> extends AbstractWriteKeyCommand<K, V> {
public static final byte COMMAND_ID = 51;
private Object argument;
private BiFunction<T, ReadWriteEntryView<K, V>, R> f;
private Object prevValue;
private Metadata prevMetadata;
public ReadWriteKeyValueCommand(Object key, Object argument, BiFunction<T, ReadWriteEntryView<K, V>, R> f,
int segment, CommandInvocationId id,
ValueMatcher valueMatcher,
Params params,
DataConversion keyDataConversion,
DataConversion valueDataConversion) {
super(key, valueMatcher, segment, id, params, keyDataConversion, valueDataConversion);
this.argument = argument;
this.f = f;
}
public ReadWriteKeyValueCommand() {
// No-op, for marshalling
}
@Override
public void init(ComponentRegistry componentRegistry) {
super.init(componentRegistry);
if (f instanceof InjectableComponent)
((InjectableComponent) f).inject(componentRegistry);
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
output.writeObject(argument);
output.writeObject(f);
MarshallUtil.marshallEnum(valueMatcher, output);
UnsignedNumeric.writeUnsignedInt(output, segment);
Params.writeObject(output, params);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
CommandInvocationId.writeTo(output, commandInvocationId);
output.writeObject(prevValue);
output.writeObject(prevMetadata);
DataConversion.writeTo(output, keyDataConversion);
DataConversion.writeTo(output, valueDataConversion);
output.writeObject(internalMetadata);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
argument = input.readObject();
f = (BiFunction<T, ReadWriteEntryView<K, V>, R>) input.readObject();
valueMatcher = MarshallUtil.unmarshallEnum(input, ValueMatcher::valueOf);
segment = UnsignedNumeric.readUnsignedInt(input);
params = Params.readObject(input);
setFlagsBitSet(input.readLong());
commandInvocationId = CommandInvocationId.readFrom(input);
prevValue = input.readObject();
prevMetadata = (Metadata) input.readObject();
keyDataConversion = DataConversion.readFrom(input);
valueDataConversion = DataConversion.readFrom(input);
internalMetadata = (PrivateMetadata) input.readObject();
}
@Override
public boolean isConditional() {
return true;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReadWriteKeyValueCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.OWNER;
}
@Override
public String toString() {
return new StringBuilder("ReadWriteKeyValueCommand{")
.append("key=").append(toStr(key))
.append(", argument=").append(toStr(argument))
.append(", f=").append(f.getClass().getName())
.append(", prevValue=").append(toStr(prevValue))
.append(", prevMetadata=").append(toStr(prevMetadata))
.append(", flags=").append(printFlags())
.append(", commandInvocationId=").append(commandInvocationId)
.append(", topologyId=").append(getTopologyId())
.append(", valueMatcher=").append(valueMatcher)
.append(", successful=").append(successful)
.append(", keyDataConversion=").append(keyDataConversion)
.append(", valueDataConversion=").append(valueDataConversion)
.append("}")
.toString();
}
@Override
public Mutation toMutation(Object key) {
return new Mutations.ReadWriteWithValue<>(keyDataConversion, valueDataConversion, argument, f);
}
public void setPrevValueAndMetadata(Object prevValue, Metadata prevMetadata) {
this.prevMetadata = prevMetadata;
this.prevValue = prevValue;
}
public Object getArgument() {
return argument;
}
public BiFunction<T, ReadWriteEntryView<K, V>, R> getBiFunction() {
return f;
}
public Object getPrevValue() {
return prevValue;
}
public Metadata getPrevMetadata() {
return prevMetadata;
}
}
| 5,558
| 34.864516
| 109
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.