proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/serialization/DataOutputSerializationAdapter.java
|
DataOutputSerializationAdapter
|
readLongArray
|
class DataOutputSerializationAdapter implements SerializationAdapter<DataOutput>, DeserializationAdapter<DataInput> {
public static DataOutputSerializationAdapter INSTANCE = new DataOutputSerializationAdapter();
private DataOutputSerializationAdapter() {}
@Override
public boolean readBoolean(DataInput source) throws IOException {
return source.readBoolean();
}
@Override
public byte readByte(DataInput source) throws IOException {
return source.readByte();
}
@Override
public int readInt(DataInput source) throws IOException {
return source.readInt();
}
@Override
public long readLong(DataInput source) throws IOException {
return source.readLong();
}
@Override
public long[] readLongArray(DataInput source) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public double[] readDoubleArray(DataInput source) throws IOException {
int size = source.readInt();
double array[] = new double[size];
for (int i = 0; i < size; i++) {
array[i] = source.readDouble();
}
return array;
}
@Override
public String readString(DataInput source) throws IOException {
return source.readUTF();
}
@Override
public void writeBoolean(DataOutput target, boolean value) throws IOException {
target.writeBoolean(value);
}
@Override
public void writeByte(DataOutput target, byte value) throws IOException {
target.writeByte(value);
}
@Override
public void writeInt(DataOutput target, int value) throws IOException {
target.writeInt(value);
}
@Override
public void writeLong(DataOutput target, long value) throws IOException {
target.writeLong(value);
}
@Override
public void writeLongArray(DataOutput target, long[] value) throws IOException {
target.writeInt(value.length);
for (int i = 0; i < value.length; i++) {
target.writeLong(value[i]);
}
}
@Override
public void writeDoubleArray(DataOutput target, double[] value) throws IOException {
target.writeInt(value.length);
for (int i = 0; i < value.length; i++) {
target.writeDouble(value[i]);
}
}
@Override
public void writeString(DataOutput target, String value) throws IOException {
target.writeUTF(value);
}
}
|
int size = source.readInt();
long array[] = new long[size];
for (int i = 0; i < size; i++) {
array[i] = source.readLong();
}
return array;
| 637
| 61
| 698
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/serialization/InternalSerializationHelper.java
|
InternalSerializationHelper
|
deserializeRequest
|
class InternalSerializationHelper {
public static byte[] serializeState(RemoteBucketState state, Version backwardCompatibilityVersion) {
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(byteStream);
RemoteBucketState.SERIALIZATION_HANDLE.serialize(DataOutputSerializationAdapter.INSTANCE, output, state, backwardCompatibilityVersion, Scope.PERSISTED_STATE);
output.close();
byteStream.close();
return byteStream.toByteArray();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static RemoteBucketState deserializeState(byte[] bytes) {
try {
try (DataInputStream inputSteam = new DataInputStream(new ByteArrayInputStream(bytes))) {
return RemoteBucketState.SERIALIZATION_HANDLE.deserialize(DataOutputSerializationAdapter.INSTANCE, inputSteam);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static byte[] serializeRequest(Request<?> request) {
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(byteStream);
Request.SERIALIZATION_HANDLE.serialize(DataOutputSerializationAdapter.INSTANCE, output, request, request.getBackwardCompatibilityVersion(), Scope.REQUEST);
output.close();
byteStream.close();
return byteStream.toByteArray();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static <T> Request<T> deserializeRequest(byte[] bytes) {<FILL_FUNCTION_BODY>}
public static byte[] serializeResult(CommandResult<?> result, Version backwardCompatibilityVersion) {
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(byteStream);
CommandResult.SERIALIZATION_HANDLE.serialize(DataOutputSerializationAdapter.INSTANCE, output, result, backwardCompatibilityVersion, Scope.RESPONSE);
output.close();
byteStream.close();
return byteStream.toByteArray();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static <T> CommandResult<T> deserializeResult(byte[] bytes, Version backwardCompatibilityVersion) {
try {
try (DataInputStream inputSteam = new DataInputStream(new ByteArrayInputStream(bytes))) {
return (CommandResult<T>) CommandResult.SERIALIZATION_HANDLE.deserialize(DataOutputSerializationAdapter.INSTANCE, inputSteam);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
|
try {
try (DataInputStream inputSteam = new DataInputStream(new ByteArrayInputStream(bytes))) {
return (Request<T>) Request.SERIALIZATION_HANDLE.deserialize(DataOutputSerializationAdapter.INSTANCE, inputSteam);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
| 717
| 91
| 808
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/serialization/PrimitiveSerializationHandles.java
|
PrimitiveSerializationHandles
|
toJsonCompatibleSnapshot
|
class PrimitiveSerializationHandles {
public static SerializationHandle<Nothing> NULL_HANDLE = new SerializationHandle<Nothing>() {
@Override
public <I> Nothing deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
return null;
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, Nothing serializableObject, Version backwardCompatibilityVersion, Scope scope) throws IOException {
}
@Override
public int getTypeId() {
return 0;
}
@Override
public Class<Nothing> getSerializedType() {
return Nothing.class;
}
@Override
public Nothing fromJsonCompatibleSnapshot(Map<String, Object> snapshot) {
return Nothing.INSTANCE;
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(Nothing serializableObject, Version backwardCompatibilityVersion, Scope scope) {
return new HashMap<>();
}
@Override
public String getTypeName() {
return "Nothing";
}
};
public static SerializationHandle<Long> LONG_HANDLE = new SerializationHandle<Long>() {
@Override
public <I> Long deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
return adapter.readLong(input);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, Long value, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeLong(output, value);
}
@Override
public int getTypeId() {
return -1;
}
@Override
public Class<Long> getSerializedType() {
return Long.TYPE;
}
@Override
public Long fromJsonCompatibleSnapshot(Map<String, Object> snapshot) {
return readLongValue(snapshot, "value");
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(Long serializableObject, Version backwardCompatibilityVersion, Scope scope) {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "Long";
}
};
public static SerializationHandle<Boolean> BOOLEAN_HANDLE = new SerializationHandle<Boolean>() {
@Override
public <I> Boolean deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
return adapter.readBoolean(input);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, Boolean value, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeBoolean(output, value);
}
@Override
public int getTypeId() {
return -2;
}
@Override
public Class<Boolean> getSerializedType() {
return Boolean.TYPE;
}
@Override
public Boolean fromJsonCompatibleSnapshot(Map<String, Object> snapshot) {
return (Boolean) snapshot.get("value");
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(Boolean serializableObject, Version backwardCompatibilityVersion, Scope scope) {
Map<String, Object> result = new HashMap<>();
result.put("value", serializableObject);
return result;
}
@Override
public String getTypeName() {
return "Boolean";
}
};
public static final SerializationHandle[] primitiveHandlesById = new SerializationHandle[] {
NULL_HANDLE,
LONG_HANDLE,
BOOLEAN_HANDLE
};
}
|
Map<String, Object> result = new HashMap<>();
result.put("value", serializableObject);
return result;
| 941
| 35
| 976
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/serialization/SerializationHandles.java
|
SerializationHandles
|
getHandleByTypeId
|
class SerializationHandles {
public static final SerializationHandles CORE_HANDLES = new SerializationHandles(Arrays.asList(
Bandwidth.SERIALIZATION_HANDLE, // 1
BucketConfiguration.SERIALIZATION_HANDLE, // 2
BucketState64BitsInteger.SERIALIZATION_HANDLE, // 3
// BucketStateIEEE754.SERIALIZATION_HANDLE, // 4
RemoteBucketState.SERIALIZATION_HANDLE, // 5
RemoteStat.SERIALIZATION_HANDLE, // 6
CommandResult.SERIALIZATION_HANDLE, // 10
ConsumptionProbe.SERIALIZATION_HANDLE, // 11
EstimationProbe.SERIALIZATION_HANDLE, // 12
MultiResult.SERIALIZATION_HANDLE, // 13
RemoteVerboseResult.SERIALIZATION_HANDLE, // 14
BucketNotFoundError.SERIALIZATION_HANDLE, // 15
UnsupportedTypeError.SERIALIZATION_HANDLE, // 16
UsageOfObsoleteApiError.SERIALIZATION_HANDLE, // 17
UsageOfUnsupportedApiError.SERIALIZATION_HANDLE, // 18
UnsupportedNamedTypeError.SERIALIZATION_HANDLE, // 19
CreateInitialStateAndExecuteCommand.SERIALIZATION_HANDLE, // 21
MultiCommand.SERIALIZATION_HANDLE, // 22
ReserveAndCalculateTimeToSleepCommand.SERIALIZATION_HANDLE, // 23
AddTokensCommand.SERIALIZATION_HANDLE, // 24
ConsumeAsMuchAsPossibleCommand.SERIALIZATION_HANDLE, // 25
CreateSnapshotCommand.SERIALIZATION_HANDLE, // 26
GetAvailableTokensCommand.SERIALIZATION_HANDLE, // 27
EstimateAbilityToConsumeCommand.SERIALIZATION_HANDLE, // 28
TryConsumeCommand.SERIALIZATION_HANDLE, // 29
TryConsumeAndReturnRemainingTokensCommand.SERIALIZATION_HANDLE, // 30
ReplaceConfigurationCommand.SERIALIZATION_HANDLE, // 32
GetConfigurationCommand.SERIALIZATION_HANDLE, // 33
ConsumeIgnoringRateLimitsCommand.SERIALIZATION_HANDLE, // 34
VerboseCommand.SERIALIZATION_HANDLE, // 35
SyncCommand.SERIALIZATION_HANDLE, // 36
Request.SERIALIZATION_HANDLE, // 37
ForceAddTokensCommand.SERIALIZATION_HANDLE, // 38
ResetCommand.SERIALIZATION_HANDLE, // 39
ConfigurationNeedToBeReplacedError.SERIALIZATION_HANDLE, // 40
CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand.SERIALIZATION_HANDLE, // 41
CheckConfigurationVersionAndExecuteCommand.SERIALIZATION_HANDLE, // 42
LockFreeBucket.SERIALIZATION_HANDLE, // 60
SynchronizedBucket.SERIALIZATION_HANDLE, // 61
ThreadUnsafeBucket.SERIALIZATION_HANDLE, // 62
BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy.SERIALIZATION_HANDLE, // 70
FixedTtlExpirationAfterWriteStrategy.SERIALIZATION_HANDLE, // 71
NoneExpirationAfterWriteStrategy.SERIALIZATION_HANDLE // 72
));
private final Collection<SerializationHandle<?>> allHandles;
private final SerializationHandle[] handlesById;
private final Map<String, SerializationHandle<?>> handlesByName;
public SerializationHandles(Collection<SerializationHandle<?>> allHandles) {
this.handlesByName = new HashMap<>();
Map<Integer, SerializationHandle<?>> serializersById = new HashMap<>();
int maxTypeId = 0;
for (SerializationHandle<?> handle : allHandles) {
int typeId = handle.getTypeId();
if (typeId <= 0) {
throw new IllegalArgumentException("non positive typeId=" + typeId + " detected for " + handle);
}
maxTypeId = Math.max(maxTypeId, typeId);
SerializationHandle<?> conflictingHandle = serializersById.get(typeId);
if (conflictingHandle != null) {
String msg = "Serialization ID " + typeId + " duplicated for " + handle + " and " + conflictingHandle;
throw new IllegalArgumentException(msg);
}
serializersById.put(typeId, handle);
String typeName = handle.getTypeName();
if (typeName == null || typeName.isEmpty()) {
throw new IllegalArgumentException("null typeName detected for " + handle);
}
conflictingHandle = handlesByName.get(typeName);
if (conflictingHandle != null) {
String msg = "Serialization typeName " + typeName + " duplicated for " + handle + " and " + conflictingHandle;
throw new IllegalArgumentException(msg);
}
handlesByName.put(typeName, handle);
}
for (SerializationHandle<?> handle : PrimitiveSerializationHandles.primitiveHandlesById) {
String typeName = handle.getTypeName();
if (typeName == null || typeName.isEmpty()) {
throw new IllegalArgumentException("null typeName detected for " + handle);
}
SerializationHandle<?> conflictingHandle = handlesByName.get(typeName);
if (conflictingHandle != null) {
String msg = "Serialization typeName " + typeName + " duplicated for " + handle + " and " + conflictingHandle;
throw new IllegalArgumentException(msg);
}
handlesByName.put(typeName, handle);
}
this.allHandles = Collections.unmodifiableCollection(allHandles);
this.handlesById = new SerializationHandle[maxTypeId + 1];
for (SerializationHandle<?> handle : allHandles) {
handlesById[handle.getTypeId()] = handle;
}
}
public SerializationHandles merge(SerializationHandle<?>... handles) {
List<SerializationHandle<?>> resultHandles = new ArrayList<>(this.allHandles);
for (SerializationHandle<?> handle : handles) {
resultHandles.add(handle);
}
return new SerializationHandles(resultHandles);
}
public <T> SerializationHandle<T> getHandleByTypeId(int typeId) {<FILL_FUNCTION_BODY>}
public Collection<SerializationHandle<?>> getAllHandles() {
return allHandles;
}
public SerializationHandle<?> getHandleByTypeName(String typeName) {
SerializationHandle<?> handle = handlesByName.get(typeName);
if (handle == null) {
throw new UnsupportedNamedTypeException(typeName);
}
return handle;
}
}
|
if (typeId > 0) {
if (typeId >= handlesById.length) {
throw new UnsupportedTypeException(typeId);
}
SerializationHandle<T> serializationHandle = handlesById[typeId];
if (serializationHandle == null) {
throw new UnsupportedTypeException(typeId);
}
return serializationHandle;
} else {
typeId = -typeId;
if (typeId >= PrimitiveSerializationHandles.primitiveHandlesById.length) {
throw new UnsupportedTypeException(typeId);
}
return PrimitiveSerializationHandles.primitiveHandlesById[typeId];
}
| 1,851
| 166
| 2,017
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/versioning/UsageOfObsoleteApiException.java
|
UsageOfObsoleteApiException
|
formatMessage
|
class UsageOfObsoleteApiException extends BackwardCompatibilityException {
private final int requestedFormatNumber;
private final int minSupportedFormatNumber;
public UsageOfObsoleteApiException(int requestedFormatNumber, int minSupportedFormatNumber) {
super(formatMessage(requestedFormatNumber, minSupportedFormatNumber));
this.requestedFormatNumber = requestedFormatNumber;
this.minSupportedFormatNumber = minSupportedFormatNumber;
}
public int getRequestedFormatNumber() {
return requestedFormatNumber;
}
public int getMinSupportedFormatNumber() {
return minSupportedFormatNumber;
}
private static String formatMessage(int formatNumber, int minFormatNumber) {<FILL_FUNCTION_BODY>}
}
|
String fmt = "Command cannot be executed, because it encoded in {0} format number, when minimum supported by backend is {1}";
return MessageFormat.format(fmt, formatNumber, minFormatNumber);
| 195
| 52
| 247
|
<methods>public void <init>(java.lang.String) <variables>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/versioning/UsageOfUnsupportedApiException.java
|
UsageOfUnsupportedApiException
|
formatMessage
|
class UsageOfUnsupportedApiException extends BackwardCompatibilityException {
private final int requestedFormatNumber;
private final int maxSupportedFormatNumber;
public UsageOfUnsupportedApiException(int requestedFormatNumber, int maxSupportedFormatNumber) {
super(formatMessage(requestedFormatNumber, maxSupportedFormatNumber));
this.requestedFormatNumber = requestedFormatNumber;
this.maxSupportedFormatNumber = maxSupportedFormatNumber;
}
public int getRequestedFormatNumber() {
return requestedFormatNumber;
}
public int getMaxSupportedFormatNumber() {
return maxSupportedFormatNumber;
}
private static String formatMessage(int formatNumber, int maxFormatNumber) {<FILL_FUNCTION_BODY>}
}
|
String fmt = "Command cannot be executed, because it encoded in {0} format number, when maximum supported by backend is {1}";
return MessageFormat.format(fmt, formatNumber, maxFormatNumber);
| 193
| 52
| 245
|
<methods>public void <init>(java.lang.String) <variables>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/local/LocalBucketBuilder.java
|
LocalBucketBuilder
|
withCustomTimePrecision
|
class LocalBucketBuilder {
private final ConfigurationBuilder configurationBuilder;
public LocalBucketBuilder() {
configurationBuilder = new ConfigurationBuilder();
}
/**
* Adds limited bandwidth for all buckets which will be constructed by this builder.
*
* @param bandwidth limitation
* @return this builder instance
*/
public LocalBucketBuilder addLimit(Bandwidth bandwidth) {
configurationBuilder.addLimit(bandwidth);
return this;
}
public LocalBucketBuilder addLimit(Function<BandwidthBuilderCapacityStage, BandwidthBuilderBuildStage> bandwidthConfigurator) {
if (bandwidthConfigurator == null) {
throw BucketExceptions.nullBuilder();
}
BandwidthBuilderBuildStage builder = bandwidthConfigurator.apply(Bandwidth.builder());
Bandwidth bandwidth = builder.build();
return addLimit(bandwidth);
}
private TimeMeter timeMeter = TimeMeter.SYSTEM_MILLISECONDS;
private SynchronizationStrategy synchronizationStrategy = SynchronizationStrategy.LOCK_FREE;
private MathType mathType = MathType.INTEGER_64_BITS;
/**
* Specifies {@link TimeMeter#SYSTEM_NANOTIME} as time meter for buckets that will be created by this builder.
*
* @return this builder instance
*/
public LocalBucketBuilder withNanosecondPrecision() {
this.timeMeter = TimeMeter.SYSTEM_NANOTIME;
return this;
}
/**
* Specifies {@link TimeMeter#SYSTEM_MILLISECONDS} as time meter for buckets that will be created by this builder.
*
* @return this builder instance
*/
public LocalBucketBuilder withMillisecondPrecision() {
this.timeMeter = TimeMeter.SYSTEM_MILLISECONDS;
return this;
}
/**
* Specifies {@code customTimeMeter} time meter for buckets that will be created by this builder.
*
* @param customTimeMeter object which will measure time.
*
* @return this builder instance
*/
public LocalBucketBuilder withCustomTimePrecision(TimeMeter customTimeMeter) {<FILL_FUNCTION_BODY>}
/**
* Specifies {@code synchronizationStrategy} for buckets that will be created by this builder.
*
* @param synchronizationStrategy the strategy of synchronization which need to be applied to prevent data-races in multi-threading usage scenario.
*
* @return this builder instance
*/
public LocalBucketBuilder withSynchronizationStrategy(SynchronizationStrategy synchronizationStrategy) {
if (synchronizationStrategy == null) {
throw BucketExceptions.nullSynchronizationStrategy();
}
this.synchronizationStrategy = synchronizationStrategy;
return this;
}
/**
* <b>Warnings:</b> this is not a part of Public API.
*
* This method is intended to be used strongly by internal code and can be removed at any time without prior notice.
*
* @param mathType
* @return
*/
@Experimental
public LocalBucketBuilder withMath(MathType mathType) {
this.mathType = Objects.requireNonNull(mathType);
return this;
}
/**
* Constructs the bucket.
*
* @return the new bucket
*/
public LocalBucket build() {
BucketConfiguration configuration = buildConfiguration();
switch (synchronizationStrategy) {
case LOCK_FREE: return new LockFreeBucket(configuration, mathType, timeMeter);
case SYNCHRONIZED: return new SynchronizedBucket(configuration, mathType, timeMeter);
case NONE: return new ThreadUnsafeBucket(configuration, mathType, timeMeter);
default: throw new IllegalStateException();
}
}
private BucketConfiguration buildConfiguration() {
BucketConfiguration configuration = configurationBuilder.build();
for (Bandwidth bandwidth : configuration.getBandwidths()) {
if (bandwidth.isIntervallyAligned() && !timeMeter.isWallClockBased()) {
throw BucketExceptions.intervallyAlignedRefillCompatibleOnlyWithWallClock();
}
}
return configuration;
}
}
|
if (customTimeMeter == null) {
throw BucketExceptions.nullTimeMeter();
}
this.timeMeter = customTimeMeter;
return this;
| 1,099
| 49
| 1,148
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/local/LocalBucketSerializationHelper.java
|
LocalBucketSerializationHelper
|
fromBinarySnapshot
|
class LocalBucketSerializationHelper {
private static final DataOutputSerializationAdapter adapter = DataOutputSerializationAdapter.INSTANCE;
static byte[] toBinarySnapshot(LocalBucket localBucket) throws IOException {
SerializationHandle<LocalBucket> serializationHandle = getSerializationHandle(localBucket);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(baos);
adapter.writeInt(output, serializationHandle.getTypeId());
serializationHandle.serialize(adapter, output, localBucket, Versions.getLatest(), Scope.PERSISTED_STATE);
return baos.toByteArray();
}
static LocalBucket fromBinarySnapshot(byte[] snapshot) throws IOException {<FILL_FUNCTION_BODY>}
static Map<String, Object> toJsonCompatibleSnapshot(LocalBucket bucket) throws IOException {
SerializationHandle<LocalBucket> serializationHandle = getSerializationHandle(bucket);
Map<String, Object> jsonMap = serializationHandle.toJsonCompatibleSnapshot(bucket, Versions.getLatest(), Scope.PERSISTED_STATE);
jsonMap.put("type", serializationHandle.getTypeName());
return jsonMap;
}
static LocalBucket fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
String typeName = (String) snapshot.get("type");
SerializationHandle<LocalBucket> serializationHandle = getSerializationHandle(typeName);
return serializationHandle.fromJsonCompatibleSnapshot(snapshot);
}
private static SerializationHandle<LocalBucket> getSerializationHandle(LocalBucket localBucket) throws IOException {
switch (localBucket.getSynchronizationStrategy()) {
case LOCK_FREE: return (SerializationHandle) LockFreeBucket.SERIALIZATION_HANDLE;
case SYNCHRONIZED: return (SerializationHandle) SynchronizedBucket.SERIALIZATION_HANDLE;
case NONE: return (SerializationHandle) ThreadUnsafeBucket.SERIALIZATION_HANDLE;
default: throw new IOException("Unknown SynchronizationStrategy:" + localBucket.getSynchronizationStrategy());
}
}
private static SerializationHandle<LocalBucket> getSerializationHandle(int typeId) throws IOException {
if (typeId == LockFreeBucket.SERIALIZATION_HANDLE.getTypeId()) {
return (SerializationHandle) LockFreeBucket.SERIALIZATION_HANDLE;
} else if (typeId == SynchronizedBucket.SERIALIZATION_HANDLE.getTypeId()) {
return (SerializationHandle) SynchronizedBucket.SERIALIZATION_HANDLE;
} else if (typeId == ThreadUnsafeBucket.SERIALIZATION_HANDLE.getTypeId()) {
return (SerializationHandle) ThreadUnsafeBucket.SERIALIZATION_HANDLE;
} else {
throw new IOException("Unknown typeId=" + typeId);
}
}
private static SerializationHandle<LocalBucket> getSerializationHandle(String typeName) throws IOException {
if (LockFreeBucket.SERIALIZATION_HANDLE.getTypeName().equals(typeName)) {
return (SerializationHandle) LockFreeBucket.SERIALIZATION_HANDLE;
} else if (SynchronizedBucket.SERIALIZATION_HANDLE.getTypeName().equals(typeName)) {
return (SerializationHandle) SynchronizedBucket.SERIALIZATION_HANDLE;
} else if (ThreadUnsafeBucket.SERIALIZATION_HANDLE.getTypeName().equals(typeName)) {
return (SerializationHandle) ThreadUnsafeBucket.SERIALIZATION_HANDLE;
} else {
throw new IOException("Unknown typeName=" + typeName);
}
}
}
|
ByteArrayInputStream bais = new ByteArrayInputStream(snapshot);
DataInputStream input = new DataInputStream(bais);
int typeId = adapter.readInt(input);
SerializationHandle<LocalBucket> serializationHandle = getSerializationHandle(typeId);
return serializationHandle.deserialize(adapter, input);
| 965
| 83
| 1,048
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/util/concurrent/batch/AsyncBatchHelper.java
|
AsyncBatchHelper
|
lockExclusivelyOrEnqueue
|
class AsyncBatchHelper<T, R, CT, CR> {
private static final WaitingTask<?, ?> QUEUE_EMPTY_BUT_EXECUTION_IN_PROGRESS = new WaitingTask<>(null);
private static final WaitingTask<?, ?> QUEUE_EMPTY = new WaitingTask<>(null);
private final Function<List<T>, CT> taskCombiner;
private final Function<CT, CompletableFuture<CR>> asyncCombinedTaskExecutor;
private final Function<T, CompletableFuture<R>> asyncTaskExecutor;
private final BiFunction<CT, CR, List<R>> combinedResultSplitter;
private final AtomicReference<WaitingTask> headReference = new AtomicReference<>(QUEUE_EMPTY);
public static <T, R, CT, CR> AsyncBatchHelper<T, R, CT, CR> create(
Function<List<T>, CT> taskCombiner,
Function<CT, CompletableFuture<CR>> asyncCombinedTaskExecutor,
Function<T, CompletableFuture<R>> asyncTaskExecutor,
BiFunction<CT, CR, List<R>> combinedResultSplitter) {
return new AsyncBatchHelper<>(taskCombiner, asyncCombinedTaskExecutor, asyncTaskExecutor, combinedResultSplitter);
}
public static <T, R, CT, CR> AsyncBatchHelper<T, R, CT, CR> create(
Function<List<T>, CT> taskCombiner,
Function<CT, CompletableFuture<CR>> asyncCombinedTaskExecutor,
BiFunction<CT, CR, List<R>> combinedResultSplitter
) {
Function<T, CompletableFuture<R>> asyncTaskExecutor = new Function<T, CompletableFuture<R>>() {
@Override
public CompletableFuture<R> apply(T task) {
CT combinedTask = taskCombiner.apply(Collections.singletonList(task));
CompletableFuture<CR> resultFuture = asyncCombinedTaskExecutor.apply(combinedTask);
return resultFuture.thenApply((CR combinedResult) -> {
List<R> results = combinedResultSplitter.apply(combinedTask, combinedResult);
return results.get(0);
});
}
};
return new AsyncBatchHelper<T, R, CT, CR>(taskCombiner, asyncCombinedTaskExecutor, asyncTaskExecutor, combinedResultSplitter);
}
private AsyncBatchHelper(Function<List<T>, CT> taskCombiner,
Function<CT, CompletableFuture<CR>> asyncCombinedTaskExecutor,
Function<T, CompletableFuture<R>> asyncTaskExecutor,
BiFunction<CT, CR, List<R>> combinedResultSplitter) {
this.taskCombiner = requireNonNull(taskCombiner);
this.asyncCombinedTaskExecutor = requireNonNull(asyncCombinedTaskExecutor);
this.asyncTaskExecutor = requireNonNull(asyncTaskExecutor);
this.combinedResultSplitter = requireNonNull(combinedResultSplitter);
}
public CompletableFuture<R> executeAsync(T task) {
WaitingTask<T, R> waitingTask = lockExclusivelyOrEnqueue(task);
if (waitingTask != null) {
// there is another request is in progress, our request will be scheduled later
return waitingTask.future;
}
try {
return asyncTaskExecutor.apply(task)
.whenComplete((result, error) -> scheduleNextBatchAsync());
} catch (Throwable error) {
CompletableFuture<R> failedFuture = new CompletableFuture<>();
failedFuture.completeExceptionally(error);
return failedFuture;
}
}
private void scheduleNextBatchAsync() {
List<WaitingTask<T, R>> waitingNodes = takeAllWaitingTasksOrFreeLock();
if (waitingNodes.isEmpty()) {
return;
}
try {
List<T> commandsInBatch = new ArrayList<>(waitingNodes.size());
for (WaitingTask<T, R> waitingNode : waitingNodes) {
commandsInBatch.add(waitingNode.wrappedTask);
}
CT multiCommand = taskCombiner.apply(commandsInBatch);
CompletableFuture<CR> combinedFuture = asyncCombinedTaskExecutor.apply(multiCommand);
combinedFuture
.whenComplete((multiResult, error) -> completeWaitingFutures(multiCommand, waitingNodes, multiResult, error))
.whenComplete((multiResult, error) -> scheduleNextBatchAsync());
} catch (Throwable e) {
try {
for (WaitingTask waitingNode : waitingNodes) {
waitingNode.future.completeExceptionally(e);
}
} finally {
scheduleNextBatchAsync();
}
}
}
private void completeWaitingFutures(CT combinedTask, List<WaitingTask<T, R>> waitingNodes, CR multiResult, Throwable error) {
if (error != null) {
for (WaitingTask<T, R> waitingNode : waitingNodes) {
try {
waitingNode.future.completeExceptionally(error);
} catch (Throwable t) {
waitingNode.future.completeExceptionally(t);
}
}
} else {
List<R> singleResults = combinedResultSplitter.apply(combinedTask, multiResult);
for (int i = 0; i < waitingNodes.size(); i++) {
try {
waitingNodes.get(i).future.complete(singleResults.get(i));
} catch (Throwable t) {
waitingNodes.get(i).future.completeExceptionally(t);
}
}
}
}
private WaitingTask<T, R> lockExclusivelyOrEnqueue(T command) {<FILL_FUNCTION_BODY>}
private List<WaitingTask<T, R>> takeAllWaitingTasksOrFreeLock() {
WaitingTask<T, R> head;
while (true) {
head = headReference.get();
if (head == QUEUE_EMPTY_BUT_EXECUTION_IN_PROGRESS) {
if (headReference.compareAndSet(QUEUE_EMPTY_BUT_EXECUTION_IN_PROGRESS, QUEUE_EMPTY)) {
return Collections.emptyList();
} else {
continue;
}
}
if (headReference.compareAndSet(head, QUEUE_EMPTY_BUT_EXECUTION_IN_PROGRESS)) {
break;
}
}
WaitingTask<T, R> current = head;
List<WaitingTask<T, R>> waitingNodes = new ArrayList<>();
while (current != QUEUE_EMPTY_BUT_EXECUTION_IN_PROGRESS) {
waitingNodes.add(current);
WaitingTask<T, R> tmp = current.previous;
current.previous = null; // nullify the reference to previous node in order to avoid GC nepotism
current = tmp;
}
Collections.reverse(waitingNodes);
return waitingNodes;
}
private static class WaitingTask<T, R> {
public final T wrappedTask;
public final CompletableFuture<R> future = new CompletableFuture<>();
public WaitingTask<T, R> previous;
WaitingTask(T task) {
this.wrappedTask = task;
}
}
}
|
WaitingTask<T, R> waitingTask = new WaitingTask<>(command);
while (true) {
WaitingTask<T, R> previous = headReference.get();
if (previous == QUEUE_EMPTY) {
if (headReference.compareAndSet(previous, QUEUE_EMPTY_BUT_EXECUTION_IN_PROGRESS)) {
return null;
} else {
continue;
}
}
waitingTask.previous = previous;
if (headReference.compareAndSet(previous, waitingTask)) {
return waitingTask;
} else {
waitingTask.previous = null;
}
}
| 1,870
| 173
| 2,043
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastCompareAndSwapBasedProxyManager.java
|
HazelcastCompareAndSwapBasedProxyManager
|
beginCompareAndSwapOperation
|
class HazelcastCompareAndSwapBasedProxyManager<K> extends AbstractCompareAndSwapBasedProxyManager<K> {
private final IMap<K, byte[]> map;
public HazelcastCompareAndSwapBasedProxyManager(IMap<K, byte[]> map) {
this(map, ClientSideConfig.getDefault());
}
public HazelcastCompareAndSwapBasedProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
throw new UnsupportedOperationException();
}
@Override
public boolean isAsyncModeSupported() {
// Because Hazelcast IMap does not provide "replaceAsync" API.
return false;
}
@Override
public void removeProxy(K key) {
map.remove(key);
}
@Override
protected CompareAndSwapOperation beginCompareAndSwapOperation(K key) {<FILL_FUNCTION_BODY>}
@Override
protected AsyncCompareAndSwapOperation beginAsyncCompareAndSwapOperation(K key) {
throw new UnsupportedOperationException();
}
}
|
return new CompareAndSwapOperation() {
@Override
public Optional<byte[]> getStateData(Optional<Long> timeoutNanos) {
byte[] data = map.get(key);
return Optional.ofNullable(data);
}
@Override
public boolean compareAndSwap(byte[] originalData, byte[] newData, RemoteBucketState newState, Optional<Long> timeoutNanos) {
if (originalData == null) {
return map.putIfAbsent(key, newData) == null;
} else {
return map.replace(key, originalData, newData);
}
}
};
| 325
| 163
| 488
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) <variables>private static final CommandResult<?> UNSUCCESSFUL_CAS_RESULT
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastEntryProcessor.java
|
HazelcastEntryProcessor
|
process
|
class HazelcastEntryProcessor<K, T> implements EntryProcessor<K, byte[], byte[]>, ComparableByContent<HazelcastEntryProcessor> {
private static final long serialVersionUID = 1L;
private final byte[] requestBytes;
private EntryProcessor<K, byte[], byte[]> backupProcessor;
public HazelcastEntryProcessor(Request<T> request) {
this.requestBytes = serializeRequest(request);
}
public HazelcastEntryProcessor(byte[] requestBytes) {
this.requestBytes = requestBytes;
}
@Override
public byte[] process(Map.Entry<K, byte[]> entry) {<FILL_FUNCTION_BODY>}
@Override
public EntryProcessor<K, byte[], byte[]> getBackupProcessor() {
return backupProcessor;
}
public byte[] getRequestBytes() {
return requestBytes;
}
@Override
public boolean equalsByContent(HazelcastEntryProcessor other) {
return Arrays.equals(requestBytes, other.requestBytes);
}
}
|
return new AbstractBinaryTransaction(requestBytes) {
@Override
public boolean exists() {
return entry.getValue() != null;
}
@Override
protected byte[] getRawState() {
return entry.getValue();
}
@Override
protected void setRawState(byte[] newStateBytes, RemoteBucketState newState) {
ExpirationAfterWriteStrategy expirationStrategy = getExpirationStrategy();
long ttlMillis = expirationStrategy == null ? -1 : expirationStrategy.calculateTimeToLiveMillis(newState, getCurrentTimeNanos());
if (ttlMillis > 0) {
ExtendedMapEntry<K, byte[]> extendedEntry = (ExtendedMapEntry<K, byte[]>) entry;
extendedEntry.setValue(newStateBytes, ttlMillis, TimeUnit.MILLISECONDS);
backupProcessor = new VersionedBackupProcessor<>(newStateBytes, ttlMillis);
} else {
entry.setValue(newStateBytes);
backupProcessor = new SimpleBackupProcessor<>(newStateBytes);
}
}
}.execute();
| 275
| 278
| 553
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastLockBasedProxyManager.java
|
HazelcastLockBasedProxyManager
|
allocateTransaction
|
class HazelcastLockBasedProxyManager<K> extends AbstractLockBasedProxyManager<K> {
private final IMap<K, byte[]> map;
public HazelcastLockBasedProxyManager(IMap<K, byte[]> map) {
this(map, ClientSideConfig.getDefault());
}
public HazelcastLockBasedProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
}
@Override
public void removeProxy(K key) {
map.remove(key);
}
@Override
public boolean isAsyncModeSupported() {
// Because Hazelcast IMap does not provide "lockAsync" API.
return false;
}
@Override
public boolean isExpireAfterWriteSupported() {
return true;
}
@Override
protected LockBasedTransaction allocateTransaction(K key, Optional<Long> requestTimeout) {<FILL_FUNCTION_BODY>}
}
|
return new LockBasedTransaction() {
@Override
public void begin(Optional<Long> requestTimeout) {
// do nothing
}
@Override
public void rollback() {
// do nothing
}
@Override
public void commit(Optional<Long> requestTimeout) {
// do nothing
}
@Override
public byte[] lockAndGet(Optional<Long> requestTimeout) {
map.lock(key);
return map.get(key);
}
@Override
public void unlock() {
map.unlock(key);
}
@Override
public void create(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeout) {
save(data, newState);
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeout) {
save(data, newState);
}
private void save(byte[] data, RemoteBucketState newState) {
ExpirationAfterWriteStrategy expiration = getClientSideConfig().getExpirationAfterWriteStrategy().orElse(null);
if (expiration == null) {
map.put(key, data);
} else {
long currentTimeNanos = getClientSideConfig().getClientSideClock().orElse(TimeMeter.SYSTEM_MILLISECONDS).currentTimeNanos();
long ttlMillis = expiration.calculateTimeToLiveMillis(newState, currentTimeNanos);
if (ttlMillis > 0) {
map.put(key, data, ttlMillis, TimeUnit.MILLISECONDS);
} else {
map.put(key, data);
}
}
}
@Override
public void release() {
// do nothing
}
};
| 268
| 462
| 730
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastProxyManager.java
|
HazelcastProxyManager
|
addCustomSerializers
|
class HazelcastProxyManager<K> extends AbstractProxyManager<K> {
private final IMap<K, byte[]> map;
private final String offloadableExecutorName;
public HazelcastProxyManager(IMap<K, byte[]> map) {
this(map, ClientSideConfig.getDefault());
}
public HazelcastProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
this.offloadableExecutorName = null;
}
public HazelcastProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig, String offlodableExecutorName) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
this.offloadableExecutorName = Objects.requireNonNull(offlodableExecutorName);
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
HazelcastEntryProcessor<K, T> entryProcessor = offloadableExecutorName == null?
new HazelcastEntryProcessor<>(request) :
new HazelcastOffloadableEntryProcessor<>(request, offloadableExecutorName);
byte[] response = map.executeOnKey(key, entryProcessor);
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
return deserializeResult(response, backwardCompatibilityVersion);
}
@Override
public boolean isAsyncModeSupported() {
return true;
}
@Override
public boolean isExpireAfterWriteSupported() {
return true;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
HazelcastEntryProcessor<K, T> entryProcessor = offloadableExecutorName == null?
new HazelcastEntryProcessor<>(request) :
new HazelcastOffloadableEntryProcessor<>(request, offloadableExecutorName);
CompletionStage<byte[]> future = map.submitToKey(key, entryProcessor);
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
return (CompletableFuture) future.thenApply((byte[] bytes) -> InternalSerializationHelper.deserializeResult(bytes, backwardCompatibilityVersion));
}
@Override
public void removeProxy(K key) {
map.remove(key);
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
CompletionStage<byte[]> hazelcastFuture = map.removeAsync(key);
CompletableFuture<Void> resultFuture = new CompletableFuture<>();
hazelcastFuture.whenComplete((oldState, error) -> {
if (error == null) {
resultFuture.complete(null);
} else {
resultFuture.completeExceptionally(error);
}
});
return resultFuture;
}
/**
* Registers custom Hazelcast serializers for all classes from Bucket4j library which can be transferred over network.
* Each serializer will have different typeId, and this id will not be changed in the feature releases.
*
* <p>
* <strong>Note:</strong> it would be better to leave an empty space in the Ids in order to handle the extension of Bucket4j library when new classes can be added to library.
* For example if you called {@code getAllSerializers(10000)} then it would be reasonable to avoid registering your custom types in the interval 10000-10100.
* </p>
*
* @param typeIdBase a starting number from for typeId sequence
*/
public static void addCustomSerializers(SerializationConfig serializationConfig, final int typeIdBase) {<FILL_FUNCTION_BODY>}
}
|
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new HazelcastEntryProcessorSerializer(SerializationUtilities.getSerializerTypeId(HazelcastEntryProcessorSerializer.class, typeIdBase)))
.setTypeClass(HazelcastEntryProcessor.class)
);
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new SimpleBackupProcessorSerializer(SerializationUtilities.getSerializerTypeId(SimpleBackupProcessorSerializer.class, typeIdBase)))
.setTypeClass(SimpleBackupProcessor.class)
);
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new HazelcastOffloadableEntryProcessorSerializer(SerializationUtilities.getSerializerTypeId(HazelcastOffloadableEntryProcessorSerializer.class, typeIdBase)))
.setTypeClass(HazelcastOffloadableEntryProcessor.class)
);
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new VersionedBackupProcessorSerializer(SerializationUtilities.getSerializerTypeId(VersionedBackupProcessorSerializer.class, typeIdBase)))
.setTypeClass(VersionedBackupProcessor.class)
);
| 973
| 303
| 1,276
|
<methods>public AsyncProxyManager<K> asAsync() ,public RemoteBucketBuilder<K> builder() ,public Optional<io.github.bucket4j.BucketConfiguration> getProxyConfiguration(K) <variables>private static final io.github.bucket4j.distributed.proxy.RecoveryStrategy DEFAULT_RECOVERY_STRATEGY,private static final io.github.bucket4j.distributed.proxy.optimization.Optimization DEFAULT_REQUEST_OPTIMIZER,private AsyncProxyManager<K> asyncView,private final non-sealed io.github.bucket4j.distributed.proxy.ClientSideConfig clientSideConfig
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/SimpleBackupProcessor.java
|
SimpleBackupProcessor
|
process
|
class SimpleBackupProcessor<K> implements EntryProcessor<K, byte[], byte[]>, ComparableByContent<SimpleBackupProcessor> {
private static final long serialVersionUID = 1L;
private final byte[] state;
public SimpleBackupProcessor(byte[] state) {
this.state = state;
}
public byte[] getState() {
return state;
}
@Override
public boolean equalsByContent(SimpleBackupProcessor other) {
return Arrays.equals(state, other.state);
}
@Override
public byte[] process(Map.Entry<K, byte[]> entry) {<FILL_FUNCTION_BODY>}
}
|
entry.setValue(state);
return null; // return value from backup processor is ignored, see https://github.com/hazelcast/hazelcast/pull/14995
| 172
| 50
| 222
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/VersionedBackupProcessor.java
|
VersionedBackupProcessor
|
process
|
class VersionedBackupProcessor<K> implements EntryProcessor<K, byte[], byte[]>, ComparableByContent<VersionedBackupProcessor> {
private static final long serialVersionUID = 1L;
private final byte[] state;
private final Long ttlMillis;
public VersionedBackupProcessor(byte[] state, Long ttlMillis) {
this.state = state;
this.ttlMillis = ttlMillis;
}
public byte[] getState() {
return state;
}
public Long getTtlMillis() {
return ttlMillis;
}
@Override
public boolean equalsByContent(VersionedBackupProcessor other) {
return Arrays.equals(state, other.state) && Objects.equals(ttlMillis, other.ttlMillis);
}
@Override
public byte[] process(Map.Entry<K, byte[]> entry) {<FILL_FUNCTION_BODY>}
}
|
if (ttlMillis == null) {
entry.setValue(state);
} else {
ExtendedMapEntry extendedMapEntry = (ExtendedMapEntry) entry;
extendedMapEntry.setValue(state, ttlMillis, TimeUnit.MILLISECONDS);
}
return null; // return value from backup processor is ignored, see https://github.com/hazelcast/hazelcast/pull/14995
| 248
| 113
| 361
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/serialization/HazelcastOffloadableEntryProcessorSerializer.java
|
HazelcastOffloadableEntryProcessorSerializer
|
read0
|
class HazelcastOffloadableEntryProcessorSerializer implements StreamSerializer<HazelcastOffloadableEntryProcessor>, TypedStreamDeserializer<HazelcastOffloadableEntryProcessor> {
private final int typeId;
public HazelcastOffloadableEntryProcessorSerializer(int typeId) {
this.typeId = typeId;
}
public HazelcastOffloadableEntryProcessorSerializer() {
this.typeId = SerializationUtilities.getSerializerTypeId(this.getClass());
}
public Class<HazelcastOffloadableEntryProcessor> getSerializableType() {
return HazelcastOffloadableEntryProcessor.class;
}
@Override
public int getTypeId() {
return typeId;
}
@Override
public void destroy() {
}
@Override
public void write(ObjectDataOutput out, HazelcastOffloadableEntryProcessor serializable) throws IOException {
out.writeByteArray(serializable.getRequestBytes());
out.writeUTF(serializable.getExecutorName());
}
@Override
public HazelcastOffloadableEntryProcessor read(ObjectDataInput in) throws IOException {
return read0(in);
}
@Override
public HazelcastOffloadableEntryProcessor read(ObjectDataInput in, Class aClass) throws IOException {
return read0(in);
}
private HazelcastOffloadableEntryProcessor read0(ObjectDataInput in) throws IOException {<FILL_FUNCTION_BODY>}
}
|
byte[] commandBytes = in.readByteArray();
String executorName = in.readUTF();
return new HazelcastOffloadableEntryProcessor(commandBytes, executorName);
| 380
| 48
| 428
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/serialization/SerializationUtilities.java
|
SerializationUtilities
|
getSerializerTypeId
|
class SerializationUtilities {
public static final String TYPE_ID_BASE_PROP_NAME = "bucket4j.hazelcast.serializer.type_id_base";
private static final Map<Class<? extends Serializer>, Integer> serializerTypeIdOffsets = Map.ofEntries(
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(HazelcastEntryProcessorSerializer.class, 0),
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(SimpleBackupProcessorSerializer.class, 1),
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(HazelcastOffloadableEntryProcessorSerializer.class, 2),
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(VersionedBackupProcessorSerializer.class, 3)
);
public static int getSerializerTypeId(Class<? extends Serializer> serializerType) {<FILL_FUNCTION_BODY>}
public static int getSerializerTypeId(Class<? extends Serializer> serializerType, int typeIdBase) {
return typeIdBase + SerializationUtilities.getSerializerTypeIdOffset(serializerType);
}
private static Optional<Integer> getSerializersTypeIdBase() {
return Optional.ofNullable(
getSerializerTypeIdBaseFromSystemProperty()
.orElseGet(() -> getSerializerTypeIdBaseFromEnvironmentVariable()
.orElseGet(() -> null)));
}
private static int getSerializerTypeIdOffset(Class<? extends Serializer> serializerType) {
if (serializerTypeIdOffsets.containsKey(serializerType)) {
return serializerTypeIdOffsets.get(serializerType);
} else {
String msg = MessageFormat.format("The internal configuration does not include any offset for the serializerType [{0}]", serializerType);
throw new IllegalStateException(msg);
}
}
private static Optional<Integer> getSerializerTypeIdBaseFromEnvironmentVariable() {
return getPropertyValueFromExternal(() -> System.getenv(SerializationUtilities.TYPE_ID_BASE_PROP_NAME), "Environment Variable");
}
private static Optional<Integer> getSerializerTypeIdBaseFromSystemProperty() {
return getPropertyValueFromExternal(() -> System.getProperty(SerializationUtilities.TYPE_ID_BASE_PROP_NAME), "System Property");
}
private static Optional<Integer> getPropertyValueFromExternal(Supplier<String> typeIdSupplier, String source) {
Optional<Integer> retVal = Optional.empty();
String typeIdBaseStr = typeIdSupplier.get();
if (!StringUtil.isNullOrEmptyAfterTrim(typeIdBaseStr)) {
retVal = parseInteger(typeIdBaseStr);
if (retVal.isEmpty()) {
String msg = MessageFormat.format("The {0} [{1}] has an invalid format. It must be a positive Integer.", source, TYPE_ID_BASE_PROP_NAME);
throw new InvalidConfigurationParameterException(msg);
}
}
return retVal;
}
private static Optional<Integer> parseInteger(String strNum) {
Optional<Integer> retVal = Optional.empty();
if (null != strNum) {
try {
Integer d = Integer.parseInt(strNum.trim());
retVal = Optional.of(d);
} catch (NumberFormatException nfe) {
retVal = Optional.empty();
}
}
return retVal;
}
}
|
var typeIdBase = getSerializersTypeIdBase();
if (typeIdBase.isEmpty()) {
String msg = MessageFormat.format("Missing TypeIdBase number, impossible to load Bucket4j custom serializers. It must be provided in form of Environment Variable or System Property, both using the following key: [{0}]", TYPE_ID_BASE_PROP_NAME);
throw new MissingConfigurationParameterException(msg);
}
return getSerializerTypeId(serializerType, typeIdBase.get());
| 871
| 125
| 996
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast-4/src/main/java/io/github/bucket4j/grid/hazelcast/serialization/VersionedBackupProcessorSerializer.java
|
VersionedBackupProcessorSerializer
|
read0
|
class VersionedBackupProcessorSerializer implements StreamSerializer<VersionedBackupProcessor>, TypedStreamDeserializer<VersionedBackupProcessor> {
private final int typeId;
public VersionedBackupProcessorSerializer(int typeId) {
this.typeId = typeId;
}
public VersionedBackupProcessorSerializer() {
this.typeId = SerializationUtilities.getSerializerTypeId(this.getClass());
}
public Class<VersionedBackupProcessor> getSerializableType() {
return VersionedBackupProcessor.class;
}
@Override
public int getTypeId() {
return typeId;
}
@Override
public void destroy() {
}
@Override
public void write(ObjectDataOutput out, VersionedBackupProcessor serializable) throws IOException {
out.writeInt(v_8_10_0.getNumber());
out.writeByteArray(serializable.getState());
if (serializable.getTtlMillis() != null) {
out.writeBoolean(true);
out.writeLong(serializable.getTtlMillis());
} else {
out.writeBoolean(false);
}
}
@Override
public VersionedBackupProcessor read(ObjectDataInput in) throws IOException {
return read0(in);
}
@Override
public VersionedBackupProcessor read(ObjectDataInput in, Class aClass) throws IOException {
return read0(in);
}
private VersionedBackupProcessor read0(ObjectDataInput in) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int version = in.readInt();
Versions.check(version, v_8_10_0, v_8_10_0);
byte[] state = in.readByteArray();
Long ttlMillis = in.readBoolean() ? in.readLong() : null;
return new VersionedBackupProcessor(state, ttlMillis);
| 397
| 90
| 487
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastCompareAndSwapBasedProxyManager.java
|
HazelcastCompareAndSwapBasedProxyManager
|
beginCompareAndSwapOperation
|
class HazelcastCompareAndSwapBasedProxyManager<K> extends AbstractCompareAndSwapBasedProxyManager<K> {
private final IMap<K, byte[]> map;
public HazelcastCompareAndSwapBasedProxyManager(IMap<K, byte[]> map) {
this(map, ClientSideConfig.getDefault());
}
public HazelcastCompareAndSwapBasedProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
throw new UnsupportedOperationException();
}
@Override
public boolean isAsyncModeSupported() {
// Because Hazelcast IMap does not provide "replaceAsync" API.
return false;
}
@Override
public void removeProxy(K key) {
map.remove(key);
}
@Override
protected CompareAndSwapOperation beginCompareAndSwapOperation(K key) {<FILL_FUNCTION_BODY>}
@Override
protected AsyncCompareAndSwapOperation beginAsyncCompareAndSwapOperation(K key) {
throw new UnsupportedOperationException();
}
}
|
return new CompareAndSwapOperation() {
@Override
public Optional<byte[]> getStateData(Optional<Long> timeoutNanos) {
byte[] data = map.get(key);
return Optional.ofNullable(data);
}
@Override
public boolean compareAndSwap(byte[] originalData, byte[] newData, RemoteBucketState newState, Optional<Long> timeoutNanos) {
if (originalData == null) {
return map.putIfAbsent(key, newData) == null;
} else {
return map.replace(key, originalData, newData);
}
}
};
| 325
| 163
| 488
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) <variables>private static final CommandResult<?> UNSUCCESSFUL_CAS_RESULT
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastEntryProcessor.java
|
HazelcastEntryProcessor
|
setRawState
|
class HazelcastEntryProcessor<K, T> implements EntryProcessor<K, byte[], byte[]>, ComparableByContent<HazelcastEntryProcessor> {
private static final long serialVersionUID = 1L;
private final byte[] requestBytes;
private EntryProcessor<K, byte[], byte[]> backupProcessor;
public HazelcastEntryProcessor(Request<T> request) {
this.requestBytes = serializeRequest(request);
}
public HazelcastEntryProcessor(byte[] requestBytes) {
this.requestBytes = requestBytes;
}
@Override
public byte[] process(Map.Entry<K, byte[]> entry) {
return new AbstractBinaryTransaction(requestBytes) {
@Override
public boolean exists() {
return entry.getValue() != null;
}
@Override
protected byte[] getRawState() {
return entry.getValue();
}
@Override
protected void setRawState(byte[] newStateBytes, RemoteBucketState newState) {<FILL_FUNCTION_BODY>}
}.execute();
}
@Override
public EntryProcessor<K, byte[], byte[]> getBackupProcessor() {
return backupProcessor;
}
public byte[] getRequestBytes() {
return requestBytes;
}
@Override
public boolean equalsByContent(HazelcastEntryProcessor other) {
return Arrays.equals(requestBytes, other.requestBytes);
}
}
|
ExpirationAfterWriteStrategy expirationStrategy = getExpirationStrategy();
long ttlMillis = expirationStrategy == null ? -1 : expirationStrategy.calculateTimeToLiveMillis(newState, getCurrentTimeNanos());
if (ttlMillis > 0) {
ExtendedMapEntry<K, byte[]> extendedEntry = (ExtendedMapEntry<K, byte[]>) entry;
extendedEntry.setValue(newStateBytes, ttlMillis, TimeUnit.MILLISECONDS);
backupProcessor = new VersionedBackupProcessor<>(newStateBytes, ttlMillis);
} else {
entry.setValue(newStateBytes);
backupProcessor = new SimpleBackupProcessor<>(newStateBytes);
}
| 373
| 180
| 553
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastLockBasedProxyManager.java
|
HazelcastLockBasedProxyManager
|
allocateTransaction
|
class HazelcastLockBasedProxyManager<K> extends AbstractLockBasedProxyManager<K> {
private final IMap<K, byte[]> map;
public HazelcastLockBasedProxyManager(IMap<K, byte[]> map) {
this(map, ClientSideConfig.getDefault());
}
public HazelcastLockBasedProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
}
@Override
public void removeProxy(K key) {
map.remove(key);
}
@Override
public boolean isAsyncModeSupported() {
// Because Hazelcast IMap does not provide "lockAsync" API.
return false;
}
@Override
public boolean isExpireAfterWriteSupported() {
return true;
}
@Override
protected LockBasedTransaction allocateTransaction(K key, Optional<Long> requestTimeout) {<FILL_FUNCTION_BODY>}
}
|
return new LockBasedTransaction() {
@Override
public void begin(Optional<Long> requestTimeout) {
// do nothing
}
@Override
public void rollback() {
// do nothing
}
@Override
public void commit(Optional<Long> requestTimeout) {
// do nothing
}
@Override
public byte[] lockAndGet(Optional<Long> requestTimeout) {
map.lock(key);
return map.get(key);
}
@Override
public void unlock() {
map.unlock(key);
}
@Override
public void create(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeout) {
save(data, newState);
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeout) {
save(data, newState);
}
private void save(byte[] data, RemoteBucketState newState) {
ExpirationAfterWriteStrategy expiration = getClientSideConfig().getExpirationAfterWriteStrategy().orElse(null);
if (expiration == null) {
map.put(key, data);
} else {
long currentTimeNanos = getClientSideConfig().getClientSideClock().orElse(TimeMeter.SYSTEM_MILLISECONDS).currentTimeNanos();
long ttlMillis = expiration.calculateTimeToLiveMillis(newState, currentTimeNanos);
if (ttlMillis > 0) {
map.put(key, data, ttlMillis, TimeUnit.MILLISECONDS);
} else {
map.put(key, data);
}
}
}
@Override
public void release() {
// do nothing
}
};
| 268
| 462
| 730
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/HazelcastProxyManager.java
|
HazelcastProxyManager
|
removeAsync
|
class HazelcastProxyManager<K> extends AbstractProxyManager<K> {
private final IMap<K, byte[]> map;
private final String offloadableExecutorName;
public HazelcastProxyManager(IMap<K, byte[]> map) {
this(map, ClientSideConfig.getDefault());
}
public HazelcastProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
this.offloadableExecutorName = null;
}
public HazelcastProxyManager(IMap<K, byte[]> map, ClientSideConfig clientSideConfig, String offlodableExecutorName) {
super(clientSideConfig);
this.map = Objects.requireNonNull(map);
this.offloadableExecutorName = Objects.requireNonNull(offlodableExecutorName);
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
HazelcastEntryProcessor<K, T> entryProcessor = offloadableExecutorName == null?
new HazelcastEntryProcessor<>(request) :
new HazelcastOffloadableEntryProcessor<>(request, offloadableExecutorName);
byte[] response = map.executeOnKey(key, entryProcessor);
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
return deserializeResult(response, backwardCompatibilityVersion);
}
@Override
public boolean isAsyncModeSupported() {
return true;
}
@Override
public boolean isExpireAfterWriteSupported() {
return true;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
HazelcastEntryProcessor<K, T> entryProcessor = offloadableExecutorName == null?
new HazelcastEntryProcessor<>(request) :
new HazelcastOffloadableEntryProcessor<>(request, offloadableExecutorName);
CompletionStage<byte[]> future = map.submitToKey(key, entryProcessor);
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
return (CompletableFuture) future.thenApply((byte[] bytes) -> InternalSerializationHelper.deserializeResult(bytes, backwardCompatibilityVersion));
}
@Override
public void removeProxy(K key) {
map.remove(key);
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {<FILL_FUNCTION_BODY>}
/**
* Registers custom Hazelcast serializers for all classes from Bucket4j library which can be transferred over network.
* Each serializer will have different typeId, and this id will not be changed in the feature releases.
*
* <p>
* <strong>Note:</strong> it would be better to leave an empty space in the Ids in order to handle the extension of Bucket4j library when new classes can be added to library.
* For example if you called {@code getAllSerializers(10000)} then it would be reasonable to avoid registering your custom types in the interval 10000-10100.
* </p>
*
* @param typeIdBase a starting number from for typeId sequence
*/
public static void addCustomSerializers(SerializationConfig serializationConfig, final int typeIdBase) {
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new HazelcastEntryProcessorSerializer(SerializationUtilities.getSerializerTypeId(HazelcastEntryProcessorSerializer.class, typeIdBase)))
.setTypeClass(HazelcastEntryProcessor.class)
);
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new SimpleBackupProcessorSerializer(SerializationUtilities.getSerializerTypeId(SimpleBackupProcessorSerializer.class, typeIdBase)))
.setTypeClass(SimpleBackupProcessor.class)
);
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new HazelcastOffloadableEntryProcessorSerializer(SerializationUtilities.getSerializerTypeId(HazelcastOffloadableEntryProcessorSerializer.class, typeIdBase)))
.setTypeClass(HazelcastOffloadableEntryProcessor.class)
);
serializationConfig.addSerializerConfig(
new SerializerConfig()
.setImplementation(new VersionedBackupProcessorSerializer(SerializationUtilities.getSerializerTypeId(VersionedBackupProcessorSerializer.class, typeIdBase)))
.setTypeClass(VersionedBackupProcessor.class)
);
}
}
|
CompletionStage<byte[]> hazelcastFuture = map.removeAsync(key);
CompletableFuture<Void> resultFuture = new CompletableFuture<>();
hazelcastFuture.whenComplete((oldState, error) -> {
if (error == null) {
resultFuture.complete(null);
} else {
resultFuture.completeExceptionally(error);
}
});
return resultFuture;
| 1,169
| 107
| 1,276
|
<methods>public AsyncProxyManager<K> asAsync() ,public RemoteBucketBuilder<K> builder() ,public Optional<io.github.bucket4j.BucketConfiguration> getProxyConfiguration(K) <variables>private static final io.github.bucket4j.distributed.proxy.RecoveryStrategy DEFAULT_RECOVERY_STRATEGY,private static final io.github.bucket4j.distributed.proxy.optimization.Optimization DEFAULT_REQUEST_OPTIMIZER,private AsyncProxyManager<K> asyncView,private final non-sealed io.github.bucket4j.distributed.proxy.ClientSideConfig clientSideConfig
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/SimpleBackupProcessor.java
|
SimpleBackupProcessor
|
process
|
class SimpleBackupProcessor<K> implements EntryProcessor<K, byte[], byte[]>, ComparableByContent<SimpleBackupProcessor> {
private static final long serialVersionUID = 1L;
private final byte[] state;
public SimpleBackupProcessor(byte[] state) {
this.state = state;
}
public byte[] getState() {
return state;
}
@Override
public boolean equalsByContent(SimpleBackupProcessor other) {
return Arrays.equals(state, other.state);
}
@Override
public byte[] process(Map.Entry<K, byte[]> entry) {<FILL_FUNCTION_BODY>}
}
|
entry.setValue(state);
return null; // return value from backup processor is ignored, see https://github.com/hazelcast/hazelcast/pull/14995
| 172
| 50
| 222
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/VersionedBackupProcessor.java
|
VersionedBackupProcessor
|
process
|
class VersionedBackupProcessor<K> implements EntryProcessor<K, byte[], byte[]>, ComparableByContent<VersionedBackupProcessor> {
private static final long serialVersionUID = 1L;
private final byte[] state;
private final Long ttlMillis;
public VersionedBackupProcessor(byte[] state, Long ttlMillis) {
this.state = state;
this.ttlMillis = ttlMillis;
}
public byte[] getState() {
return state;
}
public Long getTtlMillis() {
return ttlMillis;
}
@Override
public boolean equalsByContent(VersionedBackupProcessor other) {
return Arrays.equals(state, other.state) && Objects.equals(ttlMillis, other.ttlMillis);
}
@Override
public byte[] process(Map.Entry<K, byte[]> entry) {<FILL_FUNCTION_BODY>}
}
|
if (ttlMillis == null) {
entry.setValue(state);
} else {
ExtendedMapEntry extendedMapEntry = (ExtendedMapEntry) entry;
extendedMapEntry.setValue(state, ttlMillis, TimeUnit.MILLISECONDS);
}
return null; // return value from backup processor is ignored, see https://github.com/hazelcast/hazelcast/pull/14995
| 248
| 113
| 361
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/serialization/HazelcastOffloadableEntryProcessorSerializer.java
|
HazelcastOffloadableEntryProcessorSerializer
|
read0
|
class HazelcastOffloadableEntryProcessorSerializer implements StreamSerializer<HazelcastOffloadableEntryProcessor>, TypedStreamDeserializer<HazelcastOffloadableEntryProcessor> {
private final int typeId;
public HazelcastOffloadableEntryProcessorSerializer(int typeId) {
this.typeId = typeId;
}
public HazelcastOffloadableEntryProcessorSerializer() {
this.typeId = SerializationUtilities.getSerializerTypeId(this.getClass());
}
public Class<HazelcastOffloadableEntryProcessor> getSerializableType() {
return HazelcastOffloadableEntryProcessor.class;
}
@Override
public int getTypeId() {
return typeId;
}
@Override
public void destroy() {
}
@Override
public void write(ObjectDataOutput out, HazelcastOffloadableEntryProcessor serializable) throws IOException {
out.writeByteArray(serializable.getRequestBytes());
out.writeString(serializable.getExecutorName());
}
@Override
public HazelcastOffloadableEntryProcessor read(ObjectDataInput in) throws IOException {
return read0(in);
}
@Override
public HazelcastOffloadableEntryProcessor read(ObjectDataInput in, Class aClass) throws IOException {
return read0(in);
}
private HazelcastOffloadableEntryProcessor read0(ObjectDataInput in) throws IOException {<FILL_FUNCTION_BODY>}
}
|
byte[] commandBytes = in.readByteArray();
String executorName = in.readString();
return new HazelcastOffloadableEntryProcessor(commandBytes, executorName);
| 380
| 48
| 428
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/serialization/SerializationUtilities.java
|
SerializationUtilities
|
getPropertyValueFromExternal
|
class SerializationUtilities {
public static final String TYPE_ID_BASE_PROP_NAME = "bucket4j.hazelcast.serializer.type_id_base";
private static final Map<Class<? extends Serializer>, Integer> serializerTypeIdOffsets = Map.ofEntries(
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(HazelcastEntryProcessorSerializer.class, 0),
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(SimpleBackupProcessorSerializer.class, 1),
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(HazelcastOffloadableEntryProcessorSerializer.class, 2),
new AbstractMap.SimpleEntry<Class<? extends Serializer>, Integer>(VersionedBackupProcessorSerializer.class, 3)
);
public static int getSerializerTypeId(Class<? extends Serializer> serializerType) {
var typeIdBase = getSerializersTypeIdBase();
if (typeIdBase.isEmpty()) {
String msg = MessageFormat.format("Missing TypeIdBase number, impossible to load Bucket4j custom serializers. It must be provided in form of Environment Variable or System Property, both using the following key: [{0}]", TYPE_ID_BASE_PROP_NAME);
throw new MissingConfigurationParameterException(msg);
}
return getSerializerTypeId(serializerType, typeIdBase.get());
}
public static int getSerializerTypeId(Class<? extends Serializer> serializerType, int typeIdBase) {
return typeIdBase + SerializationUtilities.getSerializerTypeIdOffset(serializerType);
}
private static Optional<Integer> getSerializersTypeIdBase() {
return Optional.ofNullable(
getSerializerTypeIdBaseFromSystemProperty()
.orElseGet(() -> getSerializerTypeIdBaseFromEnvironmentVariable()
.orElseGet(() -> null)));
}
private static int getSerializerTypeIdOffset(Class<? extends Serializer> serializerType) {
if (serializerTypeIdOffsets.containsKey(serializerType)) {
return serializerTypeIdOffsets.get(serializerType);
} else {
String msg = MessageFormat.format("The internal configuration does not include any offset for the serializerType [{0}]", serializerType);
throw new IllegalStateException(msg);
}
}
private static Optional<Integer> getSerializerTypeIdBaseFromEnvironmentVariable() {
return getPropertyValueFromExternal(() -> System.getenv(SerializationUtilities.TYPE_ID_BASE_PROP_NAME), "Environment Variable");
}
private static Optional<Integer> getSerializerTypeIdBaseFromSystemProperty() {
return getPropertyValueFromExternal(() -> System.getProperty(SerializationUtilities.TYPE_ID_BASE_PROP_NAME), "System Property");
}
private static Optional<Integer> getPropertyValueFromExternal(Supplier<String> typeIdSupplier, String source) {<FILL_FUNCTION_BODY>}
private static Optional<Integer> parseInteger(String strNum) {
Optional<Integer> retVal = Optional.empty();
if (null != strNum) {
try {
Integer d = Integer.parseInt(strNum.trim());
retVal = Optional.of(d);
} catch (NumberFormatException nfe) {
retVal = Optional.empty();
}
}
return retVal;
}
}
|
Optional<Integer> retVal = Optional.empty();
String typeIdBaseStr = typeIdSupplier.get();
if (!StringUtil.isNullOrEmptyAfterTrim(typeIdBaseStr)) {
retVal = parseInteger(typeIdBaseStr);
if (retVal.isEmpty()) {
String msg = MessageFormat.format("The {0} [{1}] has an invalid format. It must be a positive Integer.", source, TYPE_ID_BASE_PROP_NAME);
throw new InvalidConfigurationParameterException(msg);
}
}
return retVal;
| 854
| 142
| 996
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-hazelcast-all/bucket4j-hazelcast/src/main/java/io/github/bucket4j/grid/hazelcast/serialization/VersionedBackupProcessorSerializer.java
|
VersionedBackupProcessorSerializer
|
read0
|
class VersionedBackupProcessorSerializer implements StreamSerializer<VersionedBackupProcessor>, TypedStreamDeserializer<VersionedBackupProcessor> {
private final int typeId;
public VersionedBackupProcessorSerializer(int typeId) {
this.typeId = typeId;
}
public VersionedBackupProcessorSerializer() {
this.typeId = SerializationUtilities.getSerializerTypeId(this.getClass());
}
public Class<VersionedBackupProcessor> getSerializableType() {
return VersionedBackupProcessor.class;
}
@Override
public int getTypeId() {
return typeId;
}
@Override
public void destroy() {
}
@Override
public void write(ObjectDataOutput out, VersionedBackupProcessor serializable) throws IOException {
out.writeInt(v_8_10_0.getNumber());
out.writeByteArray(serializable.getState());
if (serializable.getTtlMillis() != null) {
out.writeBoolean(true);
out.writeLong(serializable.getTtlMillis());
} else {
out.writeBoolean(false);
}
}
@Override
public VersionedBackupProcessor read(ObjectDataInput in) throws IOException {
return read0(in);
}
@Override
public VersionedBackupProcessor read(ObjectDataInput in, Class aClass) throws IOException {
return read0(in);
}
private VersionedBackupProcessor read0(ObjectDataInput in) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int version = in.readInt();
Versions.check(version, v_8_10_0, v_8_10_0);
byte[] state = in.readByteArray();
Long ttlMillis = in.readBoolean() ? in.readLong() : null;
return new VersionedBackupProcessor(state, ttlMillis);
| 397
| 90
| 487
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thick/IgniteProxyManager.java
|
IgniteProxyManager
|
removeAsync
|
class IgniteProxyManager<K> extends AbstractProxyManager<K> {
private final IgniteCache<K, byte[]> cache;
public IgniteProxyManager(IgniteCache<K, byte[]> cache) {
this(cache, ClientSideConfig.getDefault());
}
public IgniteProxyManager(IgniteCache<K, byte[]> cache, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.cache = Objects.requireNonNull(cache);
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
IgniteProcessor<K> entryProcessor = new IgniteProcessor<>(request);
byte[] resultBytes = cache.invoke(key, entryProcessor);
return deserializeResult(resultBytes, request.getBackwardCompatibilityVersion());
}
@Override
public void removeProxy(K key) {
cache.remove(key);
}
@Override
public boolean isAsyncModeSupported() {
return true;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
IgniteProcessor<K> entryProcessor = new IgniteProcessor<>(request);
IgniteFuture<byte[]> igniteFuture = cache.invokeAsync(key, entryProcessor);
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
CompletableFuture<CommandResult<T>> completableFuture = new CompletableFuture<>();
igniteFuture.listen((IgniteInClosure<IgniteFuture<byte[]>>) completedIgniteFuture -> {
try {
byte[] resultBytes = completedIgniteFuture.get();
CommandResult<T> result = deserializeResult(resultBytes, backwardCompatibilityVersion);
completableFuture.complete(result);
} catch (Throwable t) {
completableFuture.completeExceptionally(t);
}
});
return completableFuture;
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {<FILL_FUNCTION_BODY>}
private static class IgniteProcessor<K> implements Serializable, CacheEntryProcessor<K, byte[], byte[]> {
private static final long serialVersionUID = 1;
private final byte[] requestBytes;
private IgniteProcessor(Request<?> request) {
this.requestBytes = serializeRequest(request);
}
@Override
public byte[] process(MutableEntry<K, byte[]> entry, Object... arguments) throws EntryProcessorException {
return new AbstractBinaryTransaction(requestBytes) {
@Override
public boolean exists() {
return entry.exists();
}
@Override
protected byte[] getRawState() {
return entry.getValue();
}
@Override
protected void setRawState(byte[] newStateBytes, RemoteBucketState newState) {
entry.setValue(newStateBytes);
}
}.execute();
}
}
}
|
IgniteFuture<Boolean> igniteFuture = cache.removeAsync(key);
CompletableFuture<Void> completableFuture = new CompletableFuture<>();
igniteFuture.listen((IgniteInClosure<IgniteFuture<Boolean>>) completedIgniteFuture -> {
try {
completedIgniteFuture.get();
completableFuture.complete(null);
} catch (Throwable t) {
completableFuture.completeExceptionally(t);
}
});
return completableFuture;
| 756
| 128
| 884
|
<methods>public AsyncProxyManager<K> asAsync() ,public RemoteBucketBuilder<K> builder() ,public Optional<io.github.bucket4j.BucketConfiguration> getProxyConfiguration(K) <variables>private static final io.github.bucket4j.distributed.proxy.RecoveryStrategy DEFAULT_RECOVERY_STRATEGY,private static final io.github.bucket4j.distributed.proxy.optimization.Optimization DEFAULT_REQUEST_OPTIMIZER,private AsyncProxyManager<K> asyncView,private final non-sealed io.github.bucket4j.distributed.proxy.ClientSideConfig clientSideConfig
|
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thin/ThinClientUtils.java
|
ThinClientUtils
|
convertFuture
|
class ThinClientUtils {
public static <T> CompletableFuture<T> convertFuture(IgniteClientFuture<T> igniteFuture) {<FILL_FUNCTION_BODY>}
}
|
CompletableFuture<T> completableFuture = new CompletableFuture<>();
igniteFuture.whenComplete((T result, Throwable error) -> {
if (error != null) {
completableFuture.completeExceptionally(error);
} else {
completableFuture.complete(result);
}
});
return completableFuture;
| 51
| 91
| 142
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thin/cas/IgniteThinClientCasBasedProxyManager.java
|
IgniteThinClientCasBasedProxyManager
|
beginAsyncCompareAndSwapOperation
|
class IgniteThinClientCasBasedProxyManager<K> extends AbstractCompareAndSwapBasedProxyManager<K> {
private final ClientCache<K, ByteBuffer> cache;
public IgniteThinClientCasBasedProxyManager(ClientCache<K, ByteBuffer> cache) {
this(cache, ClientSideConfig.getDefault());
}
public IgniteThinClientCasBasedProxyManager(ClientCache<K, ByteBuffer> cache, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.cache = Objects.requireNonNull(cache);
}
@Override
protected CompareAndSwapOperation beginCompareAndSwapOperation(K key) {
return new CompareAndSwapOperation() {
@Override
public Optional<byte[]> getStateData(Optional<Long> timeoutNanos) {
ByteBuffer persistedState = cache.get(key);
if (persistedState == null) {
return Optional.empty();
}
byte[] persistedStateBytes = persistedState.array();
return Optional.of(persistedStateBytes);
}
@Override
public boolean compareAndSwap(byte[] originalDataBytes, byte[] newDataBytes, RemoteBucketState newState, Optional<Long> timeoutNanos) {
ByteBuffer newData = ByteBuffer.wrap(newDataBytes);
if (originalDataBytes == null) {
return cache.putIfAbsent(key, newData);
}
ByteBuffer originalData = ByteBuffer.wrap(originalDataBytes);
return cache.replace(key, originalData, newData);
}
};
}
@Override
protected AsyncCompareAndSwapOperation beginAsyncCompareAndSwapOperation(K key) {<FILL_FUNCTION_BODY>}
@Override
public boolean isAsyncModeSupported() {
return true;
}
@Override
public void removeProxy(K key) {
cache.remove(key);
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
IgniteClientFuture<Boolean> igniteFuture = cache.removeAsync(key);
return ThinClientUtils.convertFuture(igniteFuture).thenApply(result -> null);
}
}
|
return new AsyncCompareAndSwapOperation() {
@Override
public CompletableFuture<Optional<byte[]>> getStateData(Optional<Long> timeoutNanos) {
IgniteClientFuture<ByteBuffer> igniteFuture = cache.getAsync(key);
CompletableFuture<ByteBuffer> resultFuture = ThinClientUtils.convertFuture(igniteFuture);
return resultFuture.thenApply((ByteBuffer persistedState) -> {
if (persistedState == null) {
return Optional.empty();
}
byte[] persistedStateBytes = persistedState.array();
return Optional.of(persistedStateBytes);
});
}
@Override
public CompletableFuture<Boolean> compareAndSwap(byte[] originalDataBytes, byte[] newDataBytes, RemoteBucketState newState, Optional<Long> timeoutNanos) {
ByteBuffer newData = ByteBuffer.wrap(newDataBytes);
if (originalDataBytes == null) {
IgniteClientFuture<Boolean> igniteFuture = cache.putIfAbsentAsync(key, newData);
return ThinClientUtils.convertFuture(igniteFuture);
}
ByteBuffer originalData = ByteBuffer.wrap(originalDataBytes);
IgniteClientFuture<Boolean> igniteFuture = cache.replaceAsync(key, originalData, newData);
return ThinClientUtils.convertFuture(igniteFuture);
}
};
| 558
| 344
| 902
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) <variables>private static final CommandResult<?> UNSUCCESSFUL_CAS_RESULT
|
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thin/compute/Bucket4jComputeTask.java
|
Bucket4jComputeTask
|
map
|
class Bucket4jComputeTask <K> extends ComputeTaskAdapter<Bucket4jComputeTaskParams<K>, byte[]> {
public static final String JOB_NAME = Bucket4jComputeTask.class.getName();
@IgniteInstanceResource
private Ignite ignite;
@Override
public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, Bucket4jComputeTaskParams<K> params) throws IgniteException {<FILL_FUNCTION_BODY>}
@Override
public byte[] reduce(List<ComputeJobResult> results) throws IgniteException {
return results.get(0).getData();
}
}
|
Bucket4jComputeJob<K> job = new Bucket4jComputeJob<>(params);
ClusterNode primaryNodeForKey = ignite.affinity(params.getCacheName()).mapKeyToNode(params.getKey());
for (ClusterNode clusterNode : subgrid) {
if (clusterNode == primaryNodeForKey) {
return Collections.singletonMap(job, clusterNode);
}
}
// should never come here, but if it happen let's execute Job on random node
int randomNode = ThreadLocalRandom.current().nextInt(subgrid.size());
return Collections.singletonMap(job, subgrid.get(randomNode));
| 178
| 170
| 348
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thin/compute/Bucket4jComputeTaskParams.java
|
Bucket4jComputeTaskParams
|
toString
|
class Bucket4jComputeTaskParams<K> implements Serializable {
private final String cacheName;
private final K key;
private final IgniteEntryProcessor<K> processor;
public Bucket4jComputeTaskParams(String cacheName, K key, IgniteEntryProcessor<K> processor) {
this.cacheName = cacheName;
this.key = key;
this.processor = processor;
}
public IgniteEntryProcessor<K> getProcessor() {
return processor;
}
public K getKey() {
return key;
}
public String getCacheName() {
return cacheName;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Bucket4jComputeTaskParams{" +
"cacheName='" + cacheName + '\'' +
", key=" + key +
", processor=" + processor +
'}';
| 192
| 54
| 246
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thin/compute/IgniteEntryProcessor.java
|
IgniteEntryProcessor
|
process
|
class IgniteEntryProcessor<K> implements Serializable, CacheEntryProcessor<K, byte[], byte[]> {
private static final long serialVersionUID = 1;
private final byte[] requestBytes;
IgniteEntryProcessor(Request<?> request) {
this.requestBytes = serializeRequest(request);
}
@Override
public byte[] process(MutableEntry<K, byte[]> entry, Object... arguments) throws EntryProcessorException {<FILL_FUNCTION_BODY>}
}
|
return new AbstractBinaryTransaction(requestBytes) {
@Override
public boolean exists() {
return entry.exists();
}
@Override
protected byte[] getRawState() {
return entry.getValue();
}
@Override
protected void setRawState(byte[] newStateBytes, RemoteBucketState newState) {
entry.setValue(newStateBytes);
}
}.execute();
| 127
| 108
| 235
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-ignite/src/main/java/io/github/bucket4j/grid/ignite/thin/compute/IgniteThinClientProxyManager.java
|
IgniteThinClientProxyManager
|
executeAsync
|
class IgniteThinClientProxyManager<K> extends AbstractProxyManager<K> {
private final ClientCache<K, byte[]> cache;
private final ClientCompute clientCompute;
public IgniteThinClientProxyManager(ClientCache<K, byte[]> cache, ClientCompute clientCompute) {
this(cache, clientCompute, ClientSideConfig.getDefault());
}
public IgniteThinClientProxyManager(ClientCache<K, byte[]> cache, ClientCompute clientCompute, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.cache = Objects.requireNonNull(cache);
this.clientCompute = Objects.requireNonNull(clientCompute);
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
IgniteEntryProcessor<K> entryProcessor = new IgniteEntryProcessor<>(request);
Bucket4jComputeTaskParams<K> taskParams = new Bucket4jComputeTaskParams<>(cache.getName(), key, entryProcessor);
try {
byte[] resultBytes = clientCompute.execute(Bucket4jComputeTask.JOB_NAME, taskParams);
return deserializeResult(resultBytes, request.getBackwardCompatibilityVersion());
} catch (InterruptedException e) {
throw BucketExceptions.executionException(e);
}
}
@Override
public boolean isAsyncModeSupported() {
return true;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {<FILL_FUNCTION_BODY>}
@Override
public void removeProxy(K key) {
cache.remove(key);
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
IgniteClientFuture<Boolean> igniteFuture = cache.removeAsync(key);
return ThinClientUtils.convertFuture(igniteFuture).thenApply(result -> null);
}
}
|
IgniteEntryProcessor<K> entryProcessor = new IgniteEntryProcessor<>(request);
Bucket4jComputeTaskParams<K> taskParams = new Bucket4jComputeTaskParams<>(cache.getName(), key, entryProcessor);
IgniteClientFuture<byte[]> igniteFuture = clientCompute.executeAsync2(Bucket4jComputeTask.JOB_NAME, taskParams);
CompletableFuture<byte[]> completableFuture = ThinClientUtils.convertFuture(igniteFuture);
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
return completableFuture.thenApply((byte[] resultBytes) -> deserializeResult(resultBytes, backwardCompatibilityVersion));
| 513
| 171
| 684
|
<methods>public AsyncProxyManager<K> asAsync() ,public RemoteBucketBuilder<K> builder() ,public Optional<io.github.bucket4j.BucketConfiguration> getProxyConfiguration(K) <variables>private static final io.github.bucket4j.distributed.proxy.RecoveryStrategy DEFAULT_RECOVERY_STRATEGY,private static final io.github.bucket4j.distributed.proxy.optimization.Optimization DEFAULT_REQUEST_OPTIMIZER,private AsyncProxyManager<K> asyncView,private final non-sealed io.github.bucket4j.distributed.proxy.ClientSideConfig clientSideConfig
|
bucket4j_bucket4j
|
bucket4j/bucket4j-infinispan-all/bucket4j-infinispan/src/main/java/io/github/bucket4j/grid/infinispan/InfinispanProcessor.java
|
InfinispanProcessor
|
apply
|
class InfinispanProcessor<K, R> implements
SerializableFunction<EntryView.ReadWriteEntryView<K, byte[]>, byte[]>,
ComparableByContent<InfinispanProcessor> {
private static final long serialVersionUID = 911L;
private final byte[] requestBytes;
public InfinispanProcessor(Request<R> request) {
this.requestBytes = InternalSerializationHelper.serializeRequest(request);
}
public InfinispanProcessor(byte[] requestBytes) {
this.requestBytes = requestBytes;
}
@Override
public byte[] apply(EntryView.ReadWriteEntryView<K, byte[]> entry) {<FILL_FUNCTION_BODY>}
@Override
public boolean equalsByContent(InfinispanProcessor other) {
return ComparableByContent.equals(requestBytes, other.requestBytes);
}
public byte[] getRequestBytes() {
return requestBytes;
}
}
|
if (requestBytes.length == 0) {
// it is the marker to remove bucket state
if (entry.find().isPresent()) {
entry.remove();
return new byte[0];
}
}
return new AbstractBinaryTransaction(requestBytes) {
@Override
public boolean exists() {
return entry.find().isPresent();
}
@Override
protected byte[] getRawState() {
return entry.get();
}
@Override
protected void setRawState(byte[] newStateBytes, RemoteBucketState newState) {
entry.set(newStateBytes);
}
}.execute();
| 251
| 166
| 417
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-infinispan-all/bucket4j-infinispan/src/main/java/io/github/bucket4j/grid/infinispan/InfinispanProxyManager.java
|
InfinispanProxyManager
|
execute
|
class InfinispanProxyManager<K> extends AbstractProxyManager<K> {
private final InfinispanProcessor<K, Void> REMOVE_BUCKET_ENTRY_PROCESSOR = new InfinispanProcessor<>(new byte[0]);
private final ReadWriteMap<K, byte[]> readWriteMap;
public InfinispanProxyManager(ReadWriteMap<K, byte[]> readWriteMap) {
this(readWriteMap, ClientSideConfig.getDefault());
}
public InfinispanProxyManager(ReadWriteMap<K, byte[]> readWriteMap, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.readWriteMap = Objects.requireNonNull(readWriteMap);
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {<FILL_FUNCTION_BODY>}
@Override
public boolean isAsyncModeSupported() {
return true;
}
@Override
public void removeProxy(K key) {
try {
removeAsync(key).get();
} catch (InterruptedException | ExecutionException e) {
throw new CacheException(e);
}
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
try {
CompletableFuture<byte[]> resultFuture = readWriteMap.eval(key, REMOVE_BUCKET_ENTRY_PROCESSOR);
return resultFuture.thenApply(resultBytes -> null);
} catch (Throwable t) {
CompletableFuture<Void> fail = new CompletableFuture<>();
fail.completeExceptionally(t);
return fail;
}
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
try {
InfinispanProcessor<K, T> entryProcessor = new InfinispanProcessor<>(request);
CompletableFuture<byte[]> resultFuture = readWriteMap.eval(key, entryProcessor);
return resultFuture.thenApply(resultBytes -> deserializeResult(resultBytes, request.getBackwardCompatibilityVersion()));
} catch (Throwable t) {
CompletableFuture<CommandResult<T>> fail = new CompletableFuture<>();
fail.completeExceptionally(t);
return fail;
}
}
}
|
InfinispanProcessor<K, T> entryProcessor = new InfinispanProcessor<>(request);
try {
CompletableFuture<byte[]> resultFuture = readWriteMap.eval(key, entryProcessor);
return (CommandResult<T>) resultFuture.thenApply(resultBytes -> deserializeResult(resultBytes, request.getBackwardCompatibilityVersion())).get();
} catch (InterruptedException | ExecutionException e) {
throw new CacheException(e);
}
| 601
| 122
| 723
|
<methods>public AsyncProxyManager<K> asAsync() ,public RemoteBucketBuilder<K> builder() ,public Optional<io.github.bucket4j.BucketConfiguration> getProxyConfiguration(K) <variables>private static final io.github.bucket4j.distributed.proxy.RecoveryStrategy DEFAULT_RECOVERY_STRATEGY,private static final io.github.bucket4j.distributed.proxy.optimization.Optimization DEFAULT_REQUEST_OPTIMIZER,private AsyncProxyManager<K> asyncView,private final non-sealed io.github.bucket4j.distributed.proxy.ClientSideConfig clientSideConfig
|
bucket4j_bucket4j
|
bucket4j/bucket4j-infinispan-all/bucket4j-infinispan/src/main/java/io/github/bucket4j/grid/infinispan/serialization/Bucket4jProtobufContextInitializer.java
|
Bucket4jProtobufContextInitializer
|
registerSchema
|
class Bucket4jProtobufContextInitializer implements SerializationContextInitializer {
private static final String FOOTER = "package bucket4j;\n";
private static final String TYPE_TEMPLATE = "message [type_name] {\n" +
"\n" +
" required bytes data = 1;\n" +
"\n" +
"}\n\n";
@Override
public String getProtoFileName() {
return "bucket4j.proto";
}
@Override
public String getProtoFile() throws UncheckedIOException {
return "/" + getProtoFileName();
}
@Override
public void registerSchema(SerializationContext serCtx) {<FILL_FUNCTION_BODY>}
@Override
public void registerMarshallers(SerializationContext serCtx) {
serCtx.registerMarshaller(new InfinispanProcessorMarshaller("bucket4j.InfinispanProcessor"));
}
}
|
StringBuilder protoBuilder = new StringBuilder(FOOTER);
protoBuilder.append(TYPE_TEMPLATE.replace("[type_name]", "InfinispanProcessor"));
String generatedProtoFile = protoBuilder.toString();
FileDescriptorSource protoSource = FileDescriptorSource.fromString(getProtoFileName(), generatedProtoFile);
serCtx.registerProtoFiles(protoSource);
| 247
| 97
| 344
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-jcache/src/main/java/io/github/bucket4j/grid/jcache/CompatibilityTest.java
|
CompatibilityTest
|
test
|
class CompatibilityTest {
final Cache<String, Integer> cache;
public CompatibilityTest(Cache<String, Integer> cache) {
this.cache = cache;
}
public void test() throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
String key = "42";
int threads = 4;
int iterations = 1000;
cache.put(key, 0);
CountDownLatch latch = new CountDownLatch(threads);
for (int i = 0; i < threads; i++) {
new Thread(() -> {
try {
for (int j = 0; j < iterations; j++) {
EntryProcessor<String, Integer, Void> processor = (EntryProcessor<String, Integer, Void> & Serializable) (mutableEntry, objects) -> {
try {
Thread.sleep(1);
} catch (InterruptedException e1) {
throw new IllegalStateException(e1);
}
int value = mutableEntry.getValue();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
mutableEntry.setValue(value + 1);
return null;
};
cache.invoke(key, processor);
}
} finally {
latch.countDown();
}
}).start();
}
latch.await();
int value = cache.get(key);
if (value == threads * iterations) {
System.out.println("Implementation which you use is compatible with Bucket4j");
} else {
String msg = "Implementation which you use is not compatible with Bucket4j";
msg += ", " + (threads * iterations - value) + " writes are missed";
throw new IllegalStateException(msg);
}
| 76
| 396
| 472
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-jcache/src/main/java/io/github/bucket4j/grid/jcache/JCacheProxyManager.java
|
JCacheProxyManager
|
executeAsync
|
class JCacheProxyManager<K> extends AbstractProxyManager<K> {
private static final Map<String, String> incompatibleProviders = Collections.emptyMap();
static {
// incompatibleProviders.put("org.infinispan", " use module bucket4j-infinispan directly");
}
private static final Set<String> preferLambdaStyleProviders = Collections.singleton("org.infinispan");
private final Cache<K, byte[]> cache;
private final boolean preferLambdaStyle;
public JCacheProxyManager(Cache<K, byte[]> cache) {
this(cache, ClientSideConfig.getDefault());
}
public JCacheProxyManager(Cache<K, byte[]> cache, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
checkCompatibilityWithProvider(cache);
this.cache = Objects.requireNonNull(cache);
this.preferLambdaStyle = preferLambdaStyle(cache);
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
EntryProcessor<K, byte[], byte[]> entryProcessor = preferLambdaStyle? createLambdaProcessor(request) : new BucketProcessor<>(request);
byte[] resultBytes = cache.invoke(key, entryProcessor);
return InternalSerializationHelper.deserializeResult(resultBytes, request.getBackwardCompatibilityVersion());
}
@Override
public void removeProxy(K key) {
cache.remove(key);
}
@Override
public boolean isAsyncModeSupported() {
return false;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {<FILL_FUNCTION_BODY>}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
// because JCache does not specify async API
throw new UnsupportedOperationException();
}
private void checkCompatibilityWithProvider(Cache<K, byte[]> cache) {
CacheManager cacheManager = cache.getCacheManager();
if (cacheManager == null) {
return;
}
CachingProvider cachingProvider = cacheManager.getCachingProvider();
if (cachingProvider == null) {
return;
}
String providerClassName = cachingProvider.getClass().getName();
incompatibleProviders.forEach((providerPrefix, recommendation) -> {
if (providerClassName.startsWith(providerPrefix)) {
String message = "The Cache provider " + providerClassName + " is incompatible with Bucket4j, " + recommendation;
throw new UnsupportedOperationException(message);
}
});
}
private boolean preferLambdaStyle(Cache<K, byte[]> cache) {
CacheManager cacheManager = cache.getCacheManager();
if (cacheManager == null) {
return false;
}
CachingProvider cachingProvider = cacheManager.getCachingProvider();
if (cachingProvider == null) {
return false;
}
String providerClassName = cachingProvider.getClass().getName();
for (String providerPrefix : preferLambdaStyleProviders) {
if (providerClassName.startsWith(providerPrefix)) {
return true;
}
}
return false;
}
public <T> EntryProcessor<K, byte[], byte[]> createLambdaProcessor(Request<T> request) {
byte[] serializedRequest = InternalSerializationHelper.serializeRequest(request);
return (Serializable & EntryProcessor<K, byte[], byte[]>) (mutableEntry, objects)
-> new JCacheTransaction(mutableEntry, serializedRequest).execute();
}
private static class BucketProcessor<K, T> implements Serializable, EntryProcessor<K, byte[], byte[]> {
private static final long serialVersionUID = 911;
private final byte[] serializedRequest;
public BucketProcessor(Request<T> request) {
this.serializedRequest = InternalSerializationHelper.serializeRequest(request);
}
@Override
public byte[] process(MutableEntry<K, byte[]> mutableEntry, Object... arguments) {
return new JCacheTransaction(mutableEntry, serializedRequest).execute();
}
}
private static class JCacheTransaction extends AbstractBinaryTransaction {
private final MutableEntry<?, byte[]> targetEntry;
private JCacheTransaction(MutableEntry<?, byte[]> targetEntry, byte[] requestBytes) {
super(requestBytes);
this.targetEntry = targetEntry;
}
@Override
public boolean exists() {
return targetEntry.exists();
}
@Override
protected byte[] getRawState() {
return targetEntry.getValue();
}
@Override
protected void setRawState(byte[] newStateBytes, RemoteBucketState newState) {
targetEntry.setValue(newStateBytes);
}
}
}
|
// because JCache does not specify async API
throw new UnsupportedOperationException();
| 1,245
| 23
| 1,268
|
<methods>public AsyncProxyManager<K> asAsync() ,public RemoteBucketBuilder<K> builder() ,public Optional<io.github.bucket4j.BucketConfiguration> getProxyConfiguration(K) <variables>private static final io.github.bucket4j.distributed.proxy.RecoveryStrategy DEFAULT_RECOVERY_STRATEGY,private static final io.github.bucket4j.distributed.proxy.optimization.Optimization DEFAULT_REQUEST_OPTIMIZER,private AsyncProxyManager<K> asyncView,private final non-sealed io.github.bucket4j.distributed.proxy.ClientSideConfig clientSideConfig
|
bucket4j_bucket4j
|
bucket4j/bucket4j-mariadb/src/main/java/io/github/bucket4j/mariadb/MariaDBSelectForUpdateBasedProxyManager.java
|
MariaDBSelectForUpdateBasedProxyManager
|
update
|
class MariaDBSelectForUpdateBasedProxyManager<K> extends AbstractSelectForUpdateBasedProxyManager<K> {
private final DataSource dataSource;
private final SQLProxyConfiguration<K> configuration;
private final String removeSqlQuery;
private final String updateSqlQuery;
private final String insertSqlQuery;
private final String selectSqlQuery;
/**
*
* @param configuration {@link SQLProxyConfiguration} configuration.
*/
public MariaDBSelectForUpdateBasedProxyManager(SQLProxyConfiguration<K> configuration) {
super(configuration.getClientSideConfig());
this.dataSource = Objects.requireNonNull(configuration.getDataSource());
this.configuration = configuration;
this.removeSqlQuery = MessageFormat.format("DELETE FROM {0} WHERE {1} = ?", configuration.getTableName(), configuration.getIdName());
updateSqlQuery = MessageFormat.format("UPDATE {0} SET {1}=? WHERE {2}=?", configuration.getTableName(), configuration.getStateName(), configuration.getIdName());
insertSqlQuery = MessageFormat.format("INSERT IGNORE INTO {0}({1}, {2}) VALUES(?, null)",
configuration.getTableName(), configuration.getIdName(), configuration.getStateName(), configuration.getIdName());
selectSqlQuery = MessageFormat.format("SELECT {0} FROM {1} WHERE {2} = ? FOR UPDATE", configuration.getStateName(), configuration.getTableName(), configuration.getIdName());
}
@Override
protected SelectForUpdateBasedTransaction allocateTransaction(K key, Optional<Long> timeoutNanos) {
Connection connection;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
return new SelectForUpdateBasedTransaction() {
@Override
public void begin(Optional<Long> timeoutNanos) {
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> timeoutNanos) {<FILL_FUNCTION_BODY>}
@Override
public void release() {
try {
connection.close();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void commit(Optional<Long> timeoutNanos) {
try {
connection.commit();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public LockAndGetResult tryLockAndGet(Optional<Long> timeoutNanos) {
try (PreparedStatement selectStatement = connection.prepareStatement(selectSqlQuery)) {
applyTimeout(selectStatement, timeoutNanos);
configuration.getPrimaryKeyMapper().set(selectStatement, 1, key);
try (ResultSet rs = selectStatement.executeQuery()) {
if (!rs.next()) {
return LockAndGetResult.notLocked();
}
byte[] bucketStateBeforeTransaction = rs.getBytes(configuration.getStateName());
return LockAndGetResult.locked(bucketStateBeforeTransaction);
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public boolean tryInsertEmptyData(Optional<Long> timeoutNanos) {
try (PreparedStatement insertStatement = connection.prepareStatement(insertSqlQuery)) {
applyTimeout(insertStatement, timeoutNanos);
configuration.getPrimaryKeyMapper().set(insertStatement, 1, key);
insertStatement.executeUpdate();
return true;
} catch (SQLTransactionRollbackException conflict) {
// do nothing, because parallel transaction has been already inserted the row
return false;
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
};
}
@Override
public void removeProxy(K key) {
try (Connection connection = dataSource.getConnection()) {
try(PreparedStatement removeStatement = connection.prepareStatement(removeSqlQuery)) {
configuration.getPrimaryKeyMapper().set(removeStatement, 1, key);
removeStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
}
|
try {
try (PreparedStatement updateStatement = connection.prepareStatement(updateSqlQuery)) {
applyTimeout(updateStatement, timeoutNanos);
updateStatement.setBytes(1, data);
configuration.getPrimaryKeyMapper().set(updateStatement, 2, key);
updateStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
| 1,198
| 112
| 1,310
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>private static final CommandResult#RAW RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION
|
bucket4j_bucket4j
|
bucket4j/bucket4j-mssql/src/main/java/io/github/bucket4j/mssql/MSSQLSelectForUpdateBasedProxyManager.java
|
MSSQLSelectForUpdateBasedProxyManager
|
allocateTransaction
|
class MSSQLSelectForUpdateBasedProxyManager<K> extends AbstractSelectForUpdateBasedProxyManager<K> {
private final DataSource dataSource;
private final SQLProxyConfiguration<K> configuration;
private final String removeSqlQuery;
private final String updateSqlQuery;
private final String insertSqlQuery;
private final String selectSqlQuery;
/**
*
* @param configuration {@link SQLProxyConfiguration} configuration.
*/
public MSSQLSelectForUpdateBasedProxyManager(SQLProxyConfiguration<K> configuration) {
super(configuration.getClientSideConfig());
this.dataSource = Objects.requireNonNull(configuration.getDataSource());
this.configuration = configuration;
this.removeSqlQuery = MessageFormat.format("DELETE FROM {0} WHERE {1} = ?", configuration.getTableName(), configuration.getIdName());
this.updateSqlQuery = MessageFormat.format("UPDATE {0} SET {1}=? WHERE {2}=?", configuration.getTableName(), configuration.getStateName(), configuration.getIdName());
this.insertSqlQuery = MessageFormat.format(
"INSERT INTO {0}({1},{2}) VALUES(?, null)",
configuration.getTableName(), configuration.getIdName(), configuration.getStateName());
this.selectSqlQuery = MessageFormat.format("SELECT {0} FROM {1} WITH(ROWLOCK, UPDLOCK) WHERE {2} = ?", configuration.getStateName(), configuration.getTableName(), configuration.getIdName());
}
@Override
protected SelectForUpdateBasedTransaction allocateTransaction(K key, Optional<Long> requestTimeoutNanos) {<FILL_FUNCTION_BODY>}
@Override
public void removeProxy(K key) {
try (Connection connection = dataSource.getConnection()) {
try(PreparedStatement removeStatement = connection.prepareStatement(removeSqlQuery)) {
configuration.getPrimaryKeyMapper().set(removeStatement, 1, key);
removeStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
}
|
Connection connection;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
return new SelectForUpdateBasedTransaction() {
@Override
public void begin(Optional<Long> requestTimeoutNanos) {
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void commit(Optional<Long> requestTimeoutNanos) {
try {
connection.commit();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public LockAndGetResult tryLockAndGet(Optional<Long> requestTimeoutNanos) {
try (PreparedStatement selectStatement = connection.prepareStatement(selectSqlQuery)) {
applyTimeout(selectStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(selectStatement, 1, key);
try (ResultSet rs = selectStatement.executeQuery()) {
if (rs.next()) {
byte[] data = rs.getBytes(configuration.getStateName());
return LockAndGetResult.locked(data);
} else {
return LockAndGetResult.notLocked();
}
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public boolean tryInsertEmptyData(Optional<Long> requestTimeoutNanos) {
try (PreparedStatement insertStatement = connection.prepareStatement(insertSqlQuery)) {
applyTimeout(insertStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(insertStatement, 1, key);
return insertStatement.executeUpdate() > 0;
} catch (SQLException e) {
if (e.getErrorCode() == 1205) {
// https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/mssqlserver-1205-database-engine-error?view=sql-server-ver16
// another transaction won the lock, initial bucket dada will be inserted by other actor
return false;
} else if (e.getErrorCode() == 2627) {
// duplicate key, another parallel transaction has inserted the data
return false;
} else {
throw new BucketExceptions.BucketExecutionException(e);
}
}
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeoutNanos) {
try {
try (PreparedStatement updateStatement = connection.prepareStatement(updateSqlQuery)) {
applyTimeout(updateStatement, requestTimeoutNanos);
updateStatement.setBytes(1, data);
configuration.getPrimaryKeyMapper().set(updateStatement, 2, key);
updateStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void release() {
try {
connection.close();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
};
| 520
| 910
| 1,430
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>private static final CommandResult#RAW RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION
|
bucket4j_bucket4j
|
bucket4j/bucket4j-mysql/src/main/java/io/github/bucket4j/mysql/MySQLSelectForUpdateBasedProxyManager.java
|
MySQLSelectForUpdateBasedProxyManager
|
allocateTransaction
|
class MySQLSelectForUpdateBasedProxyManager<K> extends AbstractSelectForUpdateBasedProxyManager<K> {
private final DataSource dataSource;
private final SQLProxyConfiguration<K> configuration;
private final String removeSqlQuery;
private final String updateSqlQuery;
private final String insertSqlQuery;
private final String selectSqlQuery;
/**
*
* @param configuration {@link SQLProxyConfiguration} configuration.
*/
public MySQLSelectForUpdateBasedProxyManager(SQLProxyConfiguration<K> configuration) {
super(configuration.getClientSideConfig());
this.dataSource = Objects.requireNonNull(configuration.getDataSource());
this.configuration = configuration;
this.removeSqlQuery = MessageFormat.format("DELETE FROM {0} WHERE {1} = ?", configuration.getTableName(), configuration.getIdName());
updateSqlQuery = MessageFormat.format("UPDATE {0} SET {1}=? WHERE {2}=?", configuration.getTableName(), configuration.getStateName(), configuration.getIdName());
insertSqlQuery = MessageFormat.format("INSERT IGNORE INTO {0}({1}, {2}) VALUES(?, null)",
configuration.getTableName(), configuration.getIdName(), configuration.getStateName(), configuration.getIdName());
selectSqlQuery = MessageFormat.format("SELECT {0} FROM {1} WHERE {2} = ? FOR UPDATE", configuration.getStateName(), configuration.getTableName(), configuration.getIdName());
}
@Override
protected SelectForUpdateBasedTransaction allocateTransaction(K key, Optional<Long> requestTimeoutNanos) {<FILL_FUNCTION_BODY>}
@Override
public void removeProxy(K key) {
try (Connection connection = dataSource.getConnection()) {
try(PreparedStatement removeStatement = connection.prepareStatement(removeSqlQuery)) {
configuration.getPrimaryKeyMapper().set(removeStatement, 1, key);
removeStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
}
|
Connection connection;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
return new SelectForUpdateBasedTransaction() {
@Override
public void begin(Optional<Long> requestTimeoutNanos) {
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeoutNanos) {
try {
try (PreparedStatement updateStatement = connection.prepareStatement(updateSqlQuery)) {
applyTimeout(updateStatement, requestTimeoutNanos);
updateStatement.setBytes(1, data);
configuration.getPrimaryKeyMapper().set(updateStatement, 2, key);
updateStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void release() {
try {
connection.close();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void commit(Optional<Long> requestTimeoutNanos) {
try {
connection.commit();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public LockAndGetResult tryLockAndGet(Optional<Long> requestTimeoutNanos) {
try (PreparedStatement selectStatement = connection.prepareStatement(selectSqlQuery)) {
applyTimeout(selectStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(selectStatement, 1, key);
try (ResultSet rs = selectStatement.executeQuery()) {
if (!rs.next()) {
return LockAndGetResult.notLocked();
}
byte[] bucketStateBeforeTransaction = rs.getBytes(configuration.getStateName());
return LockAndGetResult.locked(bucketStateBeforeTransaction);
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public boolean tryInsertEmptyData(Optional<Long> requestTimeoutNanos) {
try (PreparedStatement insertStatement = connection.prepareStatement(insertSqlQuery)) {
applyTimeout(insertStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(insertStatement, 1, key);
insertStatement.executeUpdate();
return true;
} catch (MySQLTransactionRollbackException conflict) {
// do nothing, because parallel transaction has been already inserted the row
return false;
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
};
| 509
| 809
| 1,318
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>private static final CommandResult#RAW RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION
|
bucket4j_bucket4j
|
bucket4j/bucket4j-oracle/src/main/java/io/github/bucket4j/oracle/OracleSelectForUpdateBasedProxyManager.java
|
OracleSelectForUpdateBasedProxyManager
|
allocateTransaction
|
class OracleSelectForUpdateBasedProxyManager<K> extends AbstractSelectForUpdateBasedProxyManager<K> {
private final DataSource dataSource;
private final SQLProxyConfiguration<K> configuration;
private final String removeSqlQuery;
private final String updateSqlQuery;
private final String insertSqlQuery;
private final String selectSqlQuery;
/**
*
* @param configuration {@link SQLProxyConfiguration} configuration.
*/
public OracleSelectForUpdateBasedProxyManager(SQLProxyConfiguration<K> configuration) {
super(configuration.getClientSideConfig());
this.dataSource = Objects.requireNonNull(configuration.getDataSource());
this.configuration = configuration;
this.removeSqlQuery = MessageFormat.format("DELETE FROM {0} WHERE {1} = ?", configuration.getTableName(), configuration.getIdName());
this.updateSqlQuery = MessageFormat.format("UPDATE {0} SET {1}=? WHERE {2}=?", configuration.getTableName(), configuration.getStateName(), configuration.getIdName());
//this.insertSqlQuery = MessageFormat.format("INSERT INTO {0}({1}, {2}) VALUES(?, null) ON CONFLICT({3}) DO NOTHING",
this.insertSqlQuery = MessageFormat.format(
"MERGE INTO {0} b1\n" +
"USING (SELECT ? {1} FROM dual) b2\n" +
"ON (b1.{1} = b2.{1})\n" +
"WHEN NOT matched THEN\n" +
"INSERT ({1}, {2}) VALUES (?, null)",
configuration.getTableName(), configuration.getIdName(), configuration.getStateName(), configuration.getIdName());
this.selectSqlQuery = MessageFormat.format("SELECT {0} FROM {1} WHERE {2} = ? FOR UPDATE", configuration.getStateName(), configuration.getTableName(), configuration.getIdName());
}
@Override
protected SelectForUpdateBasedTransaction allocateTransaction(K key, Optional<Long> requestTimeoutNanos) {<FILL_FUNCTION_BODY>}
@Override
public void removeProxy(K key) {
try (Connection connection = dataSource.getConnection()) {
try(PreparedStatement removeStatement = connection.prepareStatement(removeSqlQuery)) {
configuration.getPrimaryKeyMapper().set(removeStatement, 1, key);
removeStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
}
|
Connection connection;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
return new SelectForUpdateBasedTransaction() {
@Override
public void begin(Optional<Long> requestTimeoutNanos) {
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void commit(Optional<Long> requestTimeoutNanos) {
try {
connection.commit();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public LockAndGetResult tryLockAndGet(Optional<Long> requestTimeoutNanos) {
try (PreparedStatement selectStatement = connection.prepareStatement(selectSqlQuery)) {
applyTimeout(selectStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(selectStatement, 1, key);
try (ResultSet rs = selectStatement.executeQuery()) {
if (rs.next()) {
byte[] data = rs.getBytes(configuration.getStateName());
return LockAndGetResult.locked(data);
} else {
return LockAndGetResult.notLocked();
}
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public boolean tryInsertEmptyData(Optional<Long> requestTimeoutNanos) {
try (PreparedStatement insertStatement = connection.prepareStatement(insertSqlQuery)) {
applyTimeout(insertStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(insertStatement, 1, key);
configuration.getPrimaryKeyMapper().set(insertStatement, 2, key);
return insertStatement.executeUpdate() > 0;
} catch (SQLIntegrityConstraintViolationException integrityException) {
return false;
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeoutNanos) {
try {
try (PreparedStatement updateStatement = connection.prepareStatement(updateSqlQuery)) {
applyTimeout(updateStatement, requestTimeoutNanos);
updateStatement.setBytes(1, data);
configuration.getPrimaryKeyMapper().set(updateStatement, 2, key);
updateStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void release() {
try {
connection.close();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
};
| 623
| 814
| 1,437
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>private static final CommandResult#RAW RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION
|
bucket4j_bucket4j
|
bucket4j/bucket4j-postgresql/src/main/java/io/github/bucket4j/postgresql/PostgreSQLSelectForUpdateBasedProxyManager.java
|
PostgreSQLSelectForUpdateBasedProxyManager
|
tryLockAndGet
|
class PostgreSQLSelectForUpdateBasedProxyManager<K> extends AbstractSelectForUpdateBasedProxyManager<K> {
private final DataSource dataSource;
private final SQLProxyConfiguration<K> configuration;
private final String removeSqlQuery;
private final String updateSqlQuery;
private final String insertSqlQuery;
private final String selectSqlQuery;
/**
*
* @param configuration {@link SQLProxyConfiguration} configuration.
*/
public PostgreSQLSelectForUpdateBasedProxyManager(SQLProxyConfiguration<K> configuration) {
super(configuration.getClientSideConfig());
this.dataSource = Objects.requireNonNull(configuration.getDataSource());
this.configuration = configuration;
this.removeSqlQuery = MessageFormat.format("DELETE FROM {0} WHERE {1} = ?", configuration.getTableName(), configuration.getIdName());
this.updateSqlQuery = MessageFormat.format("UPDATE {0} SET {1}=? WHERE {2}=?", configuration.getTableName(), configuration.getStateName(), configuration.getIdName());
this.insertSqlQuery = MessageFormat.format("INSERT INTO {0}({1}, {2}) VALUES(?, null) ON CONFLICT({3}) DO NOTHING",
configuration.getTableName(), configuration.getIdName(), configuration.getStateName(), configuration.getIdName());
this.selectSqlQuery = MessageFormat.format("SELECT {0} FROM {1} WHERE {2} = ? FOR UPDATE", configuration.getStateName(), configuration.getTableName(), configuration.getIdName());
}
@Override
protected SelectForUpdateBasedTransaction allocateTransaction(K key, Optional<Long> requestTimeoutNanos) {
Connection connection;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
return new SelectForUpdateBasedTransaction() {
@Override
public void begin(Optional<Long> requestTimeoutNanos) {
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void commit(Optional<Long> requestTimeoutNanos) {
try {
connection.commit();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public LockAndGetResult tryLockAndGet(Optional<Long> requestTimeoutNanos) {<FILL_FUNCTION_BODY>}
@Override
public boolean tryInsertEmptyData(Optional<Long> requestTimeoutNanos) {
try (PreparedStatement insertStatement = connection.prepareStatement(insertSqlQuery)) {
applyTimeout(insertStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(insertStatement, 1, key);
return insertStatement.executeUpdate() > 0;
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeoutNanos) {
try {
try (PreparedStatement updateStatement = connection.prepareStatement(updateSqlQuery)) {
applyTimeout(updateStatement, requestTimeoutNanos);
updateStatement.setBytes(1, data);
configuration.getPrimaryKeyMapper().set(updateStatement, 2, key);
updateStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void release() {
try {
connection.close();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
};
}
@Override
public void removeProxy(K key) {
try (Connection connection = dataSource.getConnection()) {
try(PreparedStatement removeStatement = connection.prepareStatement(removeSqlQuery)) {
configuration.getPrimaryKeyMapper().set(removeStatement, 1, key);
removeStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
}
|
try (PreparedStatement selectStatement = connection.prepareStatement(selectSqlQuery)) {
applyTimeout(selectStatement, requestTimeoutNanos);
configuration.getPrimaryKeyMapper().set(selectStatement, 1, key);
try (ResultSet rs = selectStatement.executeQuery()) {
if (rs.next()) {
byte[] data = rs.getBytes(configuration.getStateName());
return LockAndGetResult.locked(data);
} else {
return LockAndGetResult.notLocked();
}
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
| 1,131
| 165
| 1,296
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>private static final CommandResult#RAW RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION
|
bucket4j_bucket4j
|
bucket4j/bucket4j-postgresql/src/main/java/io/github/bucket4j/postgresql/PostgreSQLadvisoryLockBasedProxyManager.java
|
PostgreSQLadvisoryLockBasedProxyManager
|
update
|
class PostgreSQLadvisoryLockBasedProxyManager<K> extends AbstractLockBasedProxyManager<K> {
private final DataSource dataSource;
private final SQLProxyConfiguration<K> configuration;
private final String removeSqlQuery;
private final String updateSqlQuery;
private final String insertSqlQuery;
private final String selectSqlQuery;
/**
*
* @param configuration {@link SQLProxyConfiguration} configuration.
*/
public <T extends Object> PostgreSQLadvisoryLockBasedProxyManager(SQLProxyConfiguration<K> configuration) {
super(configuration.getClientSideConfig());
this.dataSource = Objects.requireNonNull(configuration.getDataSource());
this.configuration = configuration;
this.removeSqlQuery = MessageFormat.format("DELETE FROM {0} WHERE {1} = ?", configuration.getTableName(), configuration.getIdName());
this.updateSqlQuery = MessageFormat.format("UPDATE {0} SET {1}=? WHERE {2}=?", configuration.getTableName(), configuration.getStateName(), configuration.getIdName());
this.insertSqlQuery = MessageFormat.format("INSERT INTO {0}({1}, {2}) VALUES(?, ?)", configuration.getTableName(), configuration.getIdName(), configuration.getStateName());
this.selectSqlQuery = MessageFormat.format("SELECT {0} FROM {1} WHERE {2} = ?", configuration.getStateName(), configuration.getTableName(), configuration.getIdName());
}
@Override
protected LockBasedTransaction allocateTransaction(K key, Optional<Long> requestTimeout) {
Connection connection;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
return new LockBasedTransaction() {
@Override
public void begin(Optional<Long> requestTimeout) {
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public byte[] lockAndGet(Optional<Long> requestTimeout) {
try {
String lockSQL = "SELECT pg_advisory_xact_lock(?)";
try (PreparedStatement lockStatement = connection.prepareStatement(lockSQL)) {
applyTimeout(lockStatement, requestTimeout);
long advisoryLockValue = (key instanceof Number) ? ((Number) key).longValue(): key.hashCode();
lockStatement.setLong(1, advisoryLockValue);
lockStatement.executeQuery();
}
try (PreparedStatement selectStatement = connection.prepareStatement(selectSqlQuery)) {
configuration.getPrimaryKeyMapper().set(selectStatement, 1, key);
try (ResultSet rs = selectStatement.executeQuery()) {
if (rs.next()) {
return rs.getBytes(configuration.getStateName());
} else {
return null;
}
}
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void update(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeout) {<FILL_FUNCTION_BODY>}
@Override
public void release() {
try {
connection.close();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void create(byte[] data, RemoteBucketState newState, Optional<Long> requestTimeout) {
try {
try (PreparedStatement insertStatement = connection.prepareStatement(insertSqlQuery)) {
applyTimeout(insertStatement, requestTimeout);
configuration.getPrimaryKeyMapper().set(insertStatement, 1, key);
insertStatement.setBytes(2, data);
insertStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void commit(Optional<Long> requestTimeout) {
try {
connection.commit();
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
@Override
public void unlock() {
// advisory lock implicitly unlocked on commit/rollback
}
};
}
@Override
public void removeProxy(K key) {
try (Connection connection = dataSource.getConnection()) {
try(PreparedStatement removeStatement = connection.prepareStatement(removeSqlQuery)) {
configuration.getPrimaryKeyMapper().set(removeStatement, 1, key);
removeStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
}
}
|
try {
try (PreparedStatement updateStatement = connection.prepareStatement(updateSqlQuery)) {
applyTimeout(updateStatement, requestTimeout);
updateStatement.setBytes(1, data);
configuration.getPrimaryKeyMapper().set(updateStatement, 2, key);
updateStatement.executeUpdate();
}
} catch (SQLException e) {
throw new BucketExceptions.BucketExecutionException(e);
}
| 1,265
| 110
| 1,375
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) ,public boolean isAsyncModeSupported() <variables>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-redis/src/main/java/io/github/bucket4j/redis/AbstractRedisProxyManagerBuilder.java
|
AbstractRedisProxyManagerBuilder
|
getNotNullExpirationStrategy
|
class AbstractRedisProxyManagerBuilder<T extends AbstractRedisProxyManagerBuilder> {
private ExpirationAfterWriteStrategy expirationStrategy;
private ClientSideConfig clientSideConfig = ClientSideConfig.getDefault();
/**
* @deprecated use {@link ClientSideConfig#withExpirationAfterWriteStrategy(ExpirationAfterWriteStrategy)} and {@link #withClientSideConfig(ClientSideConfig)}
*
* @param expirationStrategy
* @return
*/
@Deprecated
public T withExpirationStrategy(ExpirationAfterWriteStrategy expirationStrategy) {
this.expirationStrategy = Objects.requireNonNull(expirationStrategy);
return (T) this;
}
public T withClientSideConfig(ClientSideConfig clientSideConfig) {
this.clientSideConfig = Objects.requireNonNull(clientSideConfig);
return (T) this;
}
public ExpirationAfterWriteStrategy getNotNullExpirationStrategy() {<FILL_FUNCTION_BODY>}
public ClientSideConfig getClientSideConfig() {
return clientSideConfig;
}
}
|
Optional<ExpirationAfterWriteStrategy> optionalStrategy = clientSideConfig.getExpirationAfterWriteStrategy();
if (optionalStrategy.isPresent()) {
return optionalStrategy.get();
}
if (expirationStrategy == null) {
return ExpirationAfterWriteStrategy.none();
}
return expirationStrategy;
| 266
| 81
| 347
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-redis/src/main/java/io/github/bucket4j/redis/jedis/cas/JedisBasedProxyManager.java
|
JedisBasedProxyManagerBuilder
|
compareAndSwap
|
class JedisBasedProxyManagerBuilder<K> extends AbstractRedisProxyManagerBuilder<JedisBasedProxyManagerBuilder<K>> {
private final RedisApi redisApi;
private Mapper<K> keyMapper;
public <Key> JedisBasedProxyManagerBuilder<Key> withKeyMapper(Mapper<Key> keyMapper) {
this.keyMapper = (Mapper) Objects.requireNonNull(keyMapper);
return (JedisBasedProxyManagerBuilder) this;
}
private JedisBasedProxyManagerBuilder(Mapper<K> keyMapper, RedisApi redisApi) {
this.keyMapper = Objects.requireNonNull(keyMapper);
this.redisApi = Objects.requireNonNull(redisApi);
}
public JedisBasedProxyManager<K> build() {
return new JedisBasedProxyManager<K>(this);
}
}
private JedisBasedProxyManager(JedisBasedProxyManagerBuilder<K> builder) {
super(builder.getClientSideConfig());
this.redisApi = builder.redisApi;
this.expirationStrategy = builder.getNotNullExpirationStrategy();
this.keyMapper = builder.keyMapper;
}
@Override
protected CompareAndSwapOperation beginCompareAndSwapOperation(K key) {
byte[] keyBytes = keyMapper.toBytes(key);
return new CompareAndSwapOperation() {
@Override
public Optional<byte[]> getStateData(Optional<Long> timeoutNanos) {
return Optional.ofNullable(redisApi.get(keyBytes));
}
@Override
public boolean compareAndSwap(byte[] originalData, byte[] newData, RemoteBucketState newState, Optional<Long> timeoutNanos) {
return JedisBasedProxyManager.this.compareAndSwap(keyBytes, originalData, newData, newState);
}
};
}
@Override
protected AsyncCompareAndSwapOperation beginAsyncCompareAndSwapOperation(K key) {
throw new UnsupportedOperationException();
}
@Override
public void removeProxy(K key) {
redisApi.delete(keyMapper.toBytes(key));
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
throw new UnsupportedOperationException();
}
@Override
public boolean isAsyncModeSupported() {
return false;
}
private Boolean compareAndSwap(byte[] key, byte[] originalData, byte[] newData, RemoteBucketState newState) {<FILL_FUNCTION_BODY>
|
long ttlMillis = calculateTtlMillis(newState);
if (ttlMillis > 0) {
if (originalData == null) {
// nulls are prohibited as values, so "replace" must not be used in such cases
byte[][] keysAndArgs = {key, newData, encodeLong(ttlMillis)};
Object res = redisApi.eval(LuaScripts.SCRIPT_SET_NX_PX.getBytes(StandardCharsets.UTF_8), 1, keysAndArgs);
return res != null && !res.equals(0L);
} else {
byte[][] keysAndArgs = {key, originalData, newData, encodeLong(ttlMillis)};
Object res = redisApi.eval(LuaScripts.SCRIPT_COMPARE_AND_SWAP_PX.getBytes(StandardCharsets.UTF_8), 1, keysAndArgs);
return res != null && !res.equals(0L);
}
} else {
if (originalData == null) {
// nulls are prohibited as values, so "replace" must not be used in such cases
byte[][] keysAndArgs = {key, newData};
Object res = redisApi.eval(LuaScripts.SCRIPT_SET_NX.getBytes(StandardCharsets.UTF_8), 1, keysAndArgs);
return res != null && !res.equals(0L);
} else {
byte[][] keysAndArgs = {key, originalData, newData};
Object res = redisApi.eval(LuaScripts.SCRIPT_COMPARE_AND_SWAP.getBytes(StandardCharsets.UTF_8), 1, keysAndArgs);
return res != null && !res.equals(0L);
}
}
| 655
| 444
| 1,099
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) <variables>private static final CommandResult<?> UNSUCCESSFUL_CAS_RESULT
|
bucket4j_bucket4j
|
bucket4j/bucket4j-redis/src/main/java/io/github/bucket4j/redis/lettuce/cas/LettuceBasedProxyManager.java
|
LettuceBasedProxyManagerBuilder
|
compareAndSwapFuture
|
class LettuceBasedProxyManagerBuilder<K> extends AbstractRedisProxyManagerBuilder<LettuceBasedProxyManagerBuilder<K>> {
private final RedisApi<K> redisApi;
private LettuceBasedProxyManagerBuilder(RedisApi<K> redisApi) {
this.redisApi = Objects.requireNonNull(redisApi);
}
public LettuceBasedProxyManager<K> build() {
return new LettuceBasedProxyManager<>(this);
}
}
private LettuceBasedProxyManager(LettuceBasedProxyManagerBuilder<K> builder) {
super(builder.getClientSideConfig());
this.expirationStrategy = builder.getNotNullExpirationStrategy();
this.redisApi = builder.redisApi;
}
@Override
protected CompareAndSwapOperation beginCompareAndSwapOperation(K key) {
@SuppressWarnings("unchecked")
K[] keys = (K[]) new Object[]{key};
return new CompareAndSwapOperation() {
@Override
public Optional<byte[]> getStateData(Optional<Long> timeoutNanos) {
RedisFuture<byte[]> stateFuture = redisApi.get(key);
return Optional.ofNullable(getFutureValue(stateFuture, timeoutNanos));
}
@Override
public boolean compareAndSwap(byte[] originalData, byte[] newData, RemoteBucketState newState, Optional<Long> timeoutNanos) {
return getFutureValue(compareAndSwapFuture(keys, originalData, newData, newState), timeoutNanos);
}
};
}
@Override
protected AsyncCompareAndSwapOperation beginAsyncCompareAndSwapOperation(K key) {
@SuppressWarnings("unchecked")
K[] keys = (K[]) new Object[]{key};
return new AsyncCompareAndSwapOperation() {
@Override
public CompletableFuture<Optional<byte[]>> getStateData(Optional<Long> timeoutNanos) {
RedisFuture<byte[]> stateFuture = redisApi.get(key);
return convertToCompletableFuture(stateFuture, timeoutNanos)
.thenApply(Optional::ofNullable);
}
@Override
public CompletableFuture<Boolean> compareAndSwap(byte[] originalData, byte[] newData, RemoteBucketState newState, Optional<Long> timeoutNanos) {
return convertToCompletableFuture(compareAndSwapFuture(keys, originalData, newData, newState), timeoutNanos);
}
};
}
@Override
public void removeProxy(K key) {
RedisFuture<?> future = redisApi.delete(key);
getFutureValue(future, Optional.empty());
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
RedisFuture<?> future = redisApi.delete(key);
return convertToCompletableFuture(future, Optional.empty()).thenApply(bytes -> null);
}
@Override
public boolean isAsyncModeSupported() {
return true;
}
private RedisFuture<Boolean> compareAndSwapFuture(K[] keys, byte[] originalData, byte[] newData, RemoteBucketState newState) {<FILL_FUNCTION_BODY>
|
long ttlMillis = calculateTtlMillis(newState);
if (ttlMillis > 0) {
if (originalData == null) {
// nulls are prohibited as values, so "replace" must not be used in such cases
byte[][] params = {newData, encodeLong(ttlMillis)};
return redisApi.eval(LuaScripts.SCRIPT_SET_NX_PX, ScriptOutputType.BOOLEAN, keys, params);
} else {
byte[][] params = {originalData, newData, encodeLong(ttlMillis)};
return redisApi.eval(LuaScripts.SCRIPT_COMPARE_AND_SWAP_PX, ScriptOutputType.BOOLEAN, keys, params);
}
} else {
if (originalData == null) {
// nulls are prohibited as values, so "replace" must not be used in such cases
byte[][] params = {newData};
return redisApi.eval(LuaScripts.SCRIPT_SET_NX, ScriptOutputType.BOOLEAN, keys, params);
} else {
byte[][] params = {originalData, newData};
return redisApi.eval(LuaScripts.SCRIPT_COMPARE_AND_SWAP, ScriptOutputType.BOOLEAN, keys, params);
}
}
| 828
| 336
| 1,164
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) <variables>private static final CommandResult<?> UNSUCCESSFUL_CAS_RESULT
|
bucket4j_bucket4j
|
bucket4j/bucket4j-redis/src/main/java/io/github/bucket4j/redis/redisson/cas/RedissonBasedProxyManager.java
|
RedissonBasedProxyManagerBuilder
|
compareAndSwap
|
class RedissonBasedProxyManagerBuilder<K> extends AbstractRedisProxyManagerBuilder<RedissonBasedProxyManagerBuilder<K>> {
private final CommandAsyncExecutor commandExecutor;
private Mapper<K> keyMapper;
private RedissonBasedProxyManagerBuilder(Mapper<K> keyMapper, CommandAsyncExecutor commandExecutor) {
this.keyMapper = Objects.requireNonNull(keyMapper);
this.commandExecutor = Objects.requireNonNull(commandExecutor);
}
public <Key> RedissonBasedProxyManagerBuilder<Key> withKeyMapper(Mapper<Key> keyMapper) {
this.keyMapper = (Mapper) Objects.requireNonNull(keyMapper);
return (RedissonBasedProxyManagerBuilder) this;
}
public RedissonBasedProxyManager<K> build() {
return new RedissonBasedProxyManager<>(this);
}
}
private RedissonBasedProxyManager(RedissonBasedProxyManagerBuilder<K> builder) {
super(builder.getClientSideConfig());
this.commandExecutor = builder.commandExecutor;
this.expirationStrategy = builder.getNotNullExpirationStrategy();
this.keyMapper = builder.keyMapper;
}
@Override
public boolean isExpireAfterWriteSupported() {
return true;
}
@Override
protected CompareAndSwapOperation beginCompareAndSwapOperation(K key) {
String stringKey = keyMapper.toString(key);
List<Object> keys = Collections.singletonList(stringKey);
return new CompareAndSwapOperation() {
@Override
public Optional<byte[]> getStateData(Optional<Long> timeoutNanos) {
RFuture<byte[]> persistedState = commandExecutor.readAsync(stringKey, ByteArrayCodec.INSTANCE, RedisCommands.GET, stringKey);
return Optional.ofNullable(getWithTimeout(persistedState, timeoutNanos));
}
@Override
public boolean compareAndSwap(byte[] originalData, byte[] newData, RemoteBucketState newState, Optional<Long> timeoutNanos) {<FILL_FUNCTION_BODY>
|
long ttlMillis = calculateTtlMillis(newState);
if (ttlMillis > 0) {
if (originalData == null) {
// Redisson prohibits the usage null as values, so "replace" must not be used in such cases
RFuture<Boolean> redissonFuture = commandExecutor.writeAsync(stringKey, ByteArrayCodec.INSTANCE, SET, stringKey, encodeByteArray(newData), "PX", ttlMillis, "NX");
return getWithTimeout(redissonFuture, timeoutNanos);
} else {
Object[] params = new Object[] {originalData, newData, ttlMillis};
RFuture<Boolean> redissonFuture = commandExecutor.evalWriteAsync(stringKey, ByteArrayCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, LuaScripts.SCRIPT_COMPARE_AND_SWAP_PX, keys, params);
return getWithTimeout(redissonFuture, timeoutNanos);
}
} else {
if (originalData == null) {
// Redisson prohibits the usage null as values, so "replace" must not be used in such cases
RFuture<Boolean> redissonFuture = commandExecutor.writeAsync(stringKey, ByteArrayCodec.INSTANCE, SET, stringKey, encodeByteArray(newData), "NX");
return getWithTimeout(redissonFuture, timeoutNanos);
} else {
Object[] params = new Object[] {originalData, newData};
RFuture<Boolean> redissonFuture = commandExecutor.evalWriteAsync(stringKey, ByteArrayCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, LuaScripts.SCRIPT_COMPARE_AND_SWAP, keys, params);
return getWithTimeout(redissonFuture, timeoutNanos);
}
}
| 521
| 447
| 968
|
<methods>public CommandResult<T> execute(K, Request<T>) ,public CompletableFuture<CommandResult<T>> executeAsync(K, Request<T>) <variables>private static final CommandResult<?> UNSUCCESSFUL_CAS_RESULT
|
sohutv_cachecloud
|
cachecloud/cachecloud-custom/src/main/java/com/sohu/cache/configuration/DefaultRestTemplateConfig.java
|
DefaultRestTemplateConfig
|
restTemplate
|
class DefaultRestTemplateConfig {
private static int connectTimeout = 4000;
private static int readTimeout = 5000;
@ConditionalOnMissingBean(name = "restTemplate")
@Bean
RestTemplate restTemplate() {<FILL_FUNCTION_BODY>}
}
|
HttpComponentsClientHttpRequestFactory f = new HttpComponentsClientHttpRequestFactory();
f.setConnectTimeout(connectTimeout);
f.setReadTimeout(readTimeout);
f.setConnectionRequestTimeout(connectTimeout);
RestTemplate restTemplate = new RestTemplate(f);
return restTemplate;
| 75
| 76
| 151
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-custom/src/main/java/com/sohu/cache/login/impl/DefaultLoginComponent.java
|
DefaultLoginComponent
|
getUrl
|
class DefaultLoginComponent implements LoginComponent {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestTemplate restTemplate;
@Value(value = "${server.port:8080}")
private String serverPort;
private static final String RELATIVE_URL = "/manage/loginCheck";
/**
* it is open for change
* @param userName
* @param password
* @return
*/
@Override
public boolean passportCheck(String userName, String password) {
//default password login check
if(EnvCustomUtil.pwdswitch){
String url = getUrl() + RELATIVE_URL;
Map<String, Object> requestMap = new HashMap<>();
requestMap.put("name", userName);
requestMap.put("password", password);
Map<String, Object> map = restTemplate.postForObject(url, requestMap, Map.class);
if(map != null && map.get("status") != null && Integer.parseInt(map.get("status").toString()) == 200){
return true;
}
return false;
}
//todo need to implement by your own business
return true;
}
private String getUrl() {<FILL_FUNCTION_BODY>}
@Override
public String getEmail(String ticket) {
return null;
}
@Override
public String getRedirectUrl(HttpServletRequest request) {
StringBuffer redirectUrl = new StringBuffer();
redirectUrl.append(request.getSession(true).getServletContext().getContextPath());
redirectUrl.append("/manage/login?");
// 跳转地址
redirectUrl.append("redirectUrl");
redirectUrl.append("=");
redirectUrl.append(request.getRequestURI());
// 跳转参数
String query = request.getQueryString();
if (StringUtils.isNotBlank(query)) {
redirectUrl.append("?");
try {
redirectUrl.append(URLEncoder.encode(request.getQueryString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
}
return redirectUrl.toString();
}
@Override
public String getLogoutUrl() {
return null;
}
}
|
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
logger.error(e.getMessage(), e);
}
if(address != null){
return "http://" + address.getHostAddress() + ":" + this.serverPort;
}
return "http://127.0.0.1:" + this.serverPort;
| 607
| 111
| 718
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/AlertConfigStrategy.java
|
AlertConfigStrategy
|
isCompareStringRight
|
class AlertConfigStrategy {
protected final static String MB_STRING = "MB";
protected final static String EMPTY = "";
/**
* 检查配置
*
* @param instanceAlertConfig
* @param alertConfigBaseData
*/
public abstract List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig,
AlertConfigBaseData alertConfigBaseData);
/**
* 比较long类型
*
* @param instanceAlertConfig 报警配置
* @param currentValue 当前值
* @return
*/
protected boolean isCompareLongRight(InstanceAlertConfig instanceAlertConfig, long currentValue) {
long alertValue = NumberUtils.toLong(instanceAlertConfig.getAlertValue());
int compareType = instanceAlertConfig.getCompareType();
if (compareType == InstanceAlertCompareTypeEnum.LESS_THAN.getValue() && currentValue < alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.MORE_THAN.getValue() && currentValue > alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.EQUAL.getValue() && currentValue == alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.NOT_EQUAL.getValue() && currentValue != alertValue) {
return false;
}
return true;
}
/**
* 比较int类型
*
* @param instanceAlertConfig 报警配置
* @param currentValue 当前值
* @return
*/
protected boolean isCompareIntRight(InstanceAlertConfig instanceAlertConfig, int currentValue) {
int alertValue = NumberUtils.toInt(instanceAlertConfig.getAlertValue());
int compareType = instanceAlertConfig.getCompareType();
if (compareType == InstanceAlertCompareTypeEnum.LESS_THAN.getValue() && currentValue < alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.MORE_THAN.getValue() && currentValue > alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.EQUAL.getValue() && currentValue == alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.NOT_EQUAL.getValue() && currentValue != alertValue) {
return false;
}
return true;
}
/**
* 比较double类型
*
* @param instanceAlertConfig 报警配置
* @param currentValue 当前值
* @return
*/
protected boolean isCompareDoubleRight(InstanceAlertConfig instanceAlertConfig, double currentValue) {
double alertValue = NumberUtils.toDouble(instanceAlertConfig.getAlertValue());
int compareType = instanceAlertConfig.getCompareType();
if (compareType == InstanceAlertCompareTypeEnum.LESS_THAN.getValue() && currentValue < alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.MORE_THAN.getValue() && currentValue > alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.EQUAL.getValue() && currentValue == alertValue) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.NOT_EQUAL.getValue() && currentValue != alertValue) {
return false;
}
return true;
}
/**
* 比较字符串类型
*
* @param instanceAlertConfig 报警配置
* @param currentValue 当期值
* @return
*/
protected boolean isCompareStringRight(InstanceAlertConfig instanceAlertConfig, String currentValue) {<FILL_FUNCTION_BODY>}
/**
* 获取全量统计项中的内容
*/
protected static Object getValueFromRedisInfo(StandardStats standardStats, String attribute) {
if (standardStats == null) {
return null;
}
// 转换成Map
Map<String, Object> infoMap = JsonUtil.fromJson(standardStats.getInfoJson(), Map.class);
if (MapUtils.isEmpty(infoMap)) {
return null;
}
for (Entry<String, Object> entry : infoMap.entrySet()) {
Object object = entry.getValue();
// 转换成Map<String, Map<String,Object>>
if (!(object instanceof Map)) {
continue;
}
Map<String, Object> sectionInfoMap = (Map<String, Object>) object;
if (sectionInfoMap.containsKey(attribute)) {
return MapUtils.getObject(sectionInfoMap, attribute);
}
}
return null;
}
/**
* 获取差值统计项中的内容
* @param redisInfo
* @param attribute
* @return
*/
protected static Object getValueFromDiffInfo(StandardStats standardStats, String attribute) {
if (standardStats == null) {
return null;
}
Map<String, Object> diffInfoMap = JsonUtil.fromJson(standardStats.getDiffJson(), Map.class);
if (MapUtils.isEmpty(diffInfoMap)) {
return null;
}
return MapUtils.getObject(diffInfoMap, attribute);
}
/**
* 获取cluster info统计项中的内容
* @param redisInfo
* @param attribute
* @return
*/
protected static Object getValueFromClusterInfo(StandardStats standardStats, String attribute) {
if (standardStats == null) {
return null;
}
Map<String, Object> clusterInfoMap = JsonUtil.fromJson(standardStats.getClusterInfoJson(), Map.class);
if (MapUtils.isEmpty(clusterInfoMap)) {
return null;
}
return MapUtils.getObject(clusterInfoMap, attribute);
}
/**
* 把字节变为兆
* @param value
* @return
*/
protected long changeByteToMB(long value) {
return value / 1024 / 1024;
}
}
|
String alertValue = instanceAlertConfig.getAlertValue();
int compareType = instanceAlertConfig.getCompareType();
if (compareType == InstanceAlertCompareTypeEnum.EQUAL.getValue() && currentValue.equals(alertValue)) {
return false;
} else if (compareType == InstanceAlertCompareTypeEnum.NOT_EQUAL.getValue()
&& !currentValue.equals(alertValue)) {
return false;
}
return true;
| 1,585
| 121
| 1,706
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/AofCurrentSizeAlertStrategy.java
|
AofCurrentSizeAlertStrategy
|
checkConfig
|
class AofCurrentSizeAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.aof_current_size.getValue());
// 没有配置Aof
if (object == null) {
return null;
}
long aofCurrentSize = NumberUtils.toLong(object.toString());
aofCurrentSize = changeByteToMB(aofCurrentSize);
boolean compareRight = isCompareLongRight(instanceAlertConfig, aofCurrentSize);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(aofCurrentSize),
instanceInfo.getAppId(), MB_STRING));
| 69
| 199
| 268
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/ClientBiggestInputBufAlertStrategy.java
|
ClientBiggestInputBufAlertStrategy
|
checkConfig
|
class ClientBiggestInputBufAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.client_biggest_input_buf.getValue());
if (object == null) {
return null;
}
// 关系比对
long clientBiggestInputBuf = NumberUtils.toLong(object.toString()) ;
clientBiggestInputBuf = changeByteToMB(clientBiggestInputBuf);
boolean compareRight = isCompareLongRight(instanceAlertConfig, clientBiggestInputBuf);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(clientBiggestInputBuf),
instanceInfo.getAppId(), MB_STRING));
| 69
| 206
| 275
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/ClientLongestOutputListAlertStrategy.java
|
ClientLongestOutputListAlertStrategy
|
checkConfig
|
class ClientLongestOutputListAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.client_longest_output_list.getValue());
if (object == null) {
return null;
}
// 关系比对
long clientLongestOutputList = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, clientLongestOutputList);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(clientLongestOutputList),
instanceInfo.getAppId(), EMPTY));
| 69
| 186
| 255
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/ClusterSlotsOkAlertStrategy.java
|
ClusterSlotsOkAlertStrategy
|
checkConfig
|
class ClusterSlotsOkAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromClusterInfo(alertConfigBaseData.getStandardStats(), RedisClusterInfoEnum.cluster_slots_ok.getValue());
if (object == null) {
return null;
}
// 关系比对
int clusterSlotsOk = NumberUtils.toInt(object.toString());
boolean compareRight = isCompareIntRight(instanceAlertConfig, clusterSlotsOk);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(clusterSlotsOk),
instanceInfo.getAppId(), EMPTY));
| 70
| 181
| 251
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/ClusterStateAlertStrategy.java
|
ClusterStateAlertStrategy
|
checkConfig
|
class ClusterStateAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromClusterInfo(alertConfigBaseData.getStandardStats(), RedisClusterInfoEnum.cluster_state.getValue());
if (object == null) {
return null;
}
// 关系比对
String clusterState = object.toString();
boolean compareRight = isCompareStringRight(instanceAlertConfig, clusterState);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(clusterState),
instanceInfo.getAppId(), EMPTY));
| 68
| 166
| 234
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/DefaultCommonAlertStrategy.java
|
DefaultCommonAlertStrategy
|
checkConfig
|
class DefaultCommonAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
private boolean judgeNumber(Object object){
Pattern numberPattern = Pattern.compile("^-?(([0-9]|([1-9][0-9]*))(\\.[0-9]+)?)$");
Matcher matcher = numberPattern.matcher(object.toString());
return matcher.matches();
}
private boolean judegNumberIsDouble(Object object){
return object.toString().contains(".");
}
}
|
Object object = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), instanceAlertConfig.getAlertConfig());
if (object == null) {
return null;
}
if(judgeNumber(object)){
if(judegNumberIsDouble(object)){
double currentValue= NumberUtils.toDouble(object.toString());
boolean compareRight = isCompareDoubleRight(instanceAlertConfig, currentValue);
if (compareRight) {
return null;
}
}else{
long currentValue = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, currentValue);
if (compareRight) {
return null;
}
}
}else{
String currentValue = object.toString();
boolean compareRight = isCompareStringRight(instanceAlertConfig, currentValue);
if (compareRight) {
return null;
}
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, object.toString(),
instanceInfo.getAppId(), EMPTY));
| 179
| 294
| 473
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/InstantaneousOpsPerSecAlertStrategy.java
|
InstantaneousOpsPerSecAlertStrategy
|
checkConfig
|
class InstantaneousOpsPerSecAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.instantaneous_ops_per_sec.getValue());
if (object == null) {
return null;
}
// 关系比对
long instantaneousOpsPerSec = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, instantaneousOpsPerSec);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(instantaneousOpsPerSec),
instanceInfo.getAppId(), EMPTY));
| 71
| 191
| 262
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MasterSlaveOffsetAlertStrategy.java
|
MasterSlaveOffsetAlertStrategy
|
checkConfig
|
class MasterSlaveOffsetAlertStrategy extends AlertConfigStrategy {
/**
* 格式:
* connected_slaves:2
* slave0:ip=x.x.x.x,port=6380,state=online,offset=33119690469561,lag=1
* slave1:ip=x.x.x.x,port=6380,state=online,offset=33119690513578,lag=0
* master_repl_offset:33119653194425
*/
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object connectedSlavesObject = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.connected_slaves.getValue());
if (connectedSlavesObject == null) {
return null;
}
int connectedSlaves = NumberUtils.toInt(connectedSlavesObject.toString());
if (connectedSlaves == 0) {
return null;
}
Object masterReplOffsetObject = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.master_repl_offset.getValue());
if (masterReplOffsetObject == null) {
return null;
}
List<InstanceAlertValueResult> instanceAlertValueResultList = new ArrayList<InstanceAlertValueResult>();
for (int i = 0; i < connectedSlaves; i++) {
Object slaveInfo = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), "slave" + i);
if (slaveInfo == null) {
continue;
}
String[] arr = slaveInfo.toString().split(",");
if (arr.length < 5) {
continue;
}
String state = arr[2];
if (!"state=online".equals(state)) {
continue;
}
String slaveHostPort = arr[0] + "," + arr[1];
String slaveOffsetStr = arr[3];
String[] slaveOffsetArr = slaveOffsetStr.split("=");
if (slaveOffsetArr.length != 2) {
continue;
}
String slaveOffset = slaveOffsetArr[1];
long diffOffset = Math.abs(NumberUtils.toLong(masterReplOffsetObject.toString()) - NumberUtils.toLong(slaveOffset));
boolean compareRight = isCompareDoubleRight(instanceAlertConfig, diffOffset);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
InstanceAlertValueResult instanceAlertValueResult = new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(diffOffset),
instanceInfo.getAppId(), EMPTY);
String otherInfo = String.format("masterOffset is %s<br/>slaveOffset is %s<br/>%s", masterReplOffsetObject.toString(), slaveOffset, slaveHostPort);
instanceAlertValueResult.setOtherInfo(otherInfo);
instanceAlertValueResultList.add(instanceAlertValueResult);
}
return instanceAlertValueResultList;
| 214
| 622
| 836
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MemFragmentationRatioAlertStrategy.java
|
MemFragmentationRatioAlertStrategy
|
checkConfig
|
class MemFragmentationRatioAlertStrategy extends AlertConfigStrategy {
/**
* 实例最小500MB才进行内存碎片率检查,否则价值不是很大
*/
private final static long MIN_CHECK_MEMORY = 500L * 1024 * 1024;
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
// 检查内存
Object usedMemoryObject = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.used_memory.getValue());
long usedMemory = NumberUtils.toLong(usedMemoryObject.toString());
if (usedMemory < MIN_CHECK_MEMORY) {
return null;
}
// 内存碎片率
Object memFragmentationRatioObject = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.mem_fragmentation_ratio.getValue());
if (memFragmentationRatioObject == null) {
return null;
}
// 关系比对
double memFragmentationRatio = NumberUtils.toDouble(memFragmentationRatioObject.toString());
boolean compareRight = isCompareDoubleRight(instanceAlertConfig, memFragmentationRatio);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
InstanceAlertValueResult instanceAlertValueResult = new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(memFragmentationRatio),
instanceInfo.getAppId(), EMPTY);
instanceAlertValueResult.setOtherInfo(String.format("内存使用为%s MB", String.valueOf(changeByteToMB(usedMemory))));
return Arrays.asList(instanceAlertValueResult);
| 134
| 352
| 486
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteAofDelayedFsyncAlertStrategy.java
|
MinuteAofDelayedFsyncAlertStrategy
|
checkConfig
|
class MinuteAofDelayedFsyncAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.aof_delayed_fsync.getValue());
if (object == null) {
return null;
}
long aofDelayedFsync = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, aofDelayedFsync);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(aofDelayedFsync),
instanceInfo.getAppId(), EMPTY));
| 73
| 181
| 254
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteRejectedConnectionsAlertStrategy.java
|
MinuteRejectedConnectionsAlertStrategy
|
checkConfig
|
class MinuteRejectedConnectionsAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.rejected_connections.getValue());
if (object == null) {
return null;
}
long minuteRejectedConnections = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, minuteRejectedConnections);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(minuteRejectedConnections),
instanceInfo.getAppId(), EMPTY));
| 71
| 175
| 246
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteSyncFullAlertStrategy.java
|
MinuteSyncFullAlertStrategy
|
checkConfig
|
class MinuteSyncFullAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.sync_full.getValue());
if (object == null) {
return null;
}
long minuteSyncFull = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, minuteSyncFull);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(minuteSyncFull),
instanceInfo.getAppId(), EMPTY));
| 69
| 167
| 236
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteSyncPartialErrAlertStrategy.java
|
MinuteSyncPartialErrAlertStrategy
|
checkConfig
|
class MinuteSyncPartialErrAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.sync_partial_err.getValue());
if (object == null) {
return null;
}
long minuteSyncPartialErr = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, minuteSyncPartialErr);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(minuteSyncPartialErr),
instanceInfo.getAppId(), EMPTY));
| 71
| 175
| 246
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteSyncPartialOkAlertStrategy.java
|
MinuteSyncPartialOkAlertStrategy
|
checkConfig
|
class MinuteSyncPartialOkAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.sync_partial_ok.getValue());
if (object == null) {
return null;
}
long minuteSyncPartialOk = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, minuteSyncPartialOk);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(minuteSyncPartialOk),
instanceInfo.getAppId(), EMPTY));
| 71
| 175
| 246
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteTotalNetInputMBytesAlertStrategy.java
|
MinuteTotalNetInputMBytesAlertStrategy
|
checkConfig
|
class MinuteTotalNetInputMBytesAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object totalNetInputBytesObject = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.total_net_input_bytes.getValue());
if (totalNetInputBytesObject == null) {
return null;
}
// 关系比对
long totalNetInputBytes = NumberUtils.toLong(totalNetInputBytesObject.toString()) ;
totalNetInputBytes = changeByteToMB(totalNetInputBytes);
boolean compareRight = isCompareLongRight(instanceAlertConfig, totalNetInputBytes);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(totalNetInputBytes),
instanceInfo.getAppId(), MB_STRING));
| 71
| 211
| 282
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteTotalNetOutputMBytesAlertStrategy.java
|
MinuteTotalNetOutputMBytesAlertStrategy
|
checkConfig
|
class MinuteTotalNetOutputMBytesAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object totalNetOutputBytesObject = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.total_net_output_bytes.getValue());
if (totalNetOutputBytesObject == null) {
return null;
}
// 关系比对
long totalNetOutputBytes = NumberUtils.toLong(totalNetOutputBytesObject.toString());
totalNetOutputBytes = changeByteToMB(totalNetOutputBytes);
boolean compareRight = isCompareLongRight(instanceAlertConfig, totalNetOutputBytes);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(totalNetOutputBytes),
instanceInfo.getAppId(), MB_STRING));
| 71
| 210
| 281
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteUsedCpuSysChStrategy.java
|
MinuteUsedCpuSysChStrategy
|
checkConfig
|
class MinuteUsedCpuSysChStrategy extends AlertConfigStrategy{
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.used_cpu_sys_children.getValue());
if (object == null) {
return null;
}
double min_used_cpu_sys_children_err= NumberUtils.toDouble(object.toString());
boolean compareRight = isCompareDoubleRight(instanceAlertConfig, min_used_cpu_sys_children_err);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(min_used_cpu_sys_children_err),
instanceInfo.getAppId(), EMPTY));
| 70
| 195
| 265
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteUsedCpuSysStrategy.java
|
MinuteUsedCpuSysStrategy
|
checkConfig
|
class MinuteUsedCpuSysStrategy extends AlertConfigStrategy{
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.used_cpu_sys.getValue());
if (object == null) {
return null;
}
double min_used_cpu_sys_err= NumberUtils.toDouble(object.toString());
boolean compareRight = isCompareDoubleRight(instanceAlertConfig, min_used_cpu_sys_err);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(min_used_cpu_sys_err),
instanceInfo.getAppId(), EMPTY));
| 69
| 187
| 256
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteUsedCpuUserChStrategy.java
|
MinuteUsedCpuUserChStrategy
|
checkConfig
|
class MinuteUsedCpuUserChStrategy extends AlertConfigStrategy{
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.used_cpu_user_children.getValue());
if (object == null) {
return null;
}
double min_used_cpu_user_children_err= NumberUtils.toDouble(object.toString());
boolean compareRight = isCompareDoubleRight(instanceAlertConfig, min_used_cpu_user_children_err);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(min_used_cpu_user_children_err),
instanceInfo.getAppId(), EMPTY));
| 69
| 195
| 264
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/MinuteUsedCpuUserStrategy.java
|
MinuteUsedCpuUserStrategy
|
checkConfig
|
class MinuteUsedCpuUserStrategy extends AlertConfigStrategy{
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.used_cpu_user.getValue());
if (object == null) {
return null;
}
double min_used_cpu_user_err= NumberUtils.toDouble(object.toString());
boolean compareRight = isCompareDoubleRight(instanceAlertConfig, min_used_cpu_user_err);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(min_used_cpu_user_err),
instanceInfo.getAppId(), EMPTY));
| 68
| 187
| 255
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/alert/strategy/RdbLastBgsaveStatusAlertStrategy.java
|
RdbLastBgsaveStatusAlertStrategy
|
checkConfig
|
class RdbLastBgsaveStatusAlertStrategy extends AlertConfigStrategy {
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {<FILL_FUNCTION_BODY>}
}
|
Object object = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.rdb_last_bgsave_status.getValue());
if (object == null) {
return null;
}
// 关系比对
String rdbLastBgsaveStatus = object.toString();
boolean compareRight = isCompareStringRight(instanceAlertConfig, rdbLastBgsaveStatus);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(rdbLastBgsaveStatus),
instanceInfo.getAppId(), EMPTY));
| 71
| 188
| 259
|
<methods>public non-sealed void <init>() ,public abstract List<com.sohu.cache.entity.InstanceAlertValueResult> checkConfig(com.sohu.cache.entity.InstanceAlertConfig, com.sohu.cache.alert.bean.AlertConfigBaseData) <variables>protected static final java.lang.String EMPTY,protected static final java.lang.String MB_STRING
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/async/CounterRejectedExecutionHandler.java
|
CounterRejectedExecutionHandler
|
rejectedExecution
|
class CounterRejectedExecutionHandler implements RejectedExecutionHandler {
private Logger logger = LoggerFactory.getLogger(CounterRejectedExecutionHandler.class);
public static final AtomicLongMap<String> THREAD_POOL_REJECT_MAP = AtomicLongMap.create();
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {<FILL_FUNCTION_BODY>}
}
|
NamedThreadFactory namedThreadFactory = (NamedThreadFactory) executor.getThreadFactory();
String threadPoolName = namedThreadFactory.getThreadPoolName();
if (StringUtils.isBlank(threadPoolName)) {
logger.warn("threadPoolName is null");
return;
}
THREAD_POOL_REJECT_MAP.getAndIncrement(threadPoolName);
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
executor.toString());
| 108
| 133
| 241
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/async/KeyCallable.java
|
KeyCallable
|
call
|
class KeyCallable<V> implements Callable<V> {
private final String key;
private volatile boolean cancelled = false;
public KeyCallable(String key) {
this.key = key;
}
public abstract V execute();
@Override
public V call() throws Exception {<FILL_FUNCTION_BODY>}
public void cancel() {
this.cancelled = true;
}
public String getKey() {
return key;
}
public boolean isCancelled() {
return cancelled;
}
}
|
if (!cancelled) {
V v = execute();
return v;
}
return null;
| 175
| 38
| 213
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/async/NamedThreadFactory.java
|
NamedThreadFactory
|
newThread
|
class NamedThreadFactory implements ThreadFactory {
private static final AtomicInteger POOL_SEQ = new AtomicInteger(1);
private final AtomicInteger mThreadNum = new AtomicInteger(1);
private final String mPrefix;
private final boolean mDaemo;
private final ThreadGroup mGroup;
public NamedThreadFactory() {
this("pool-" + POOL_SEQ.getAndIncrement(), false);
}
public NamedThreadFactory(String prefix) {
this(prefix, false);
}
public NamedThreadFactory(String prefix, boolean daemo) {
mPrefix = prefix + "-thread-";
mDaemo = daemo;
SecurityManager s = System.getSecurityManager();
mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
}
public Thread newThread(Runnable runnable) {<FILL_FUNCTION_BODY>}
public ThreadGroup getThreadGroup() {
return mGroup;
}
public String getThreadPoolName() {
return mPrefix;
}
}
|
String name = mPrefix + mThreadNum.getAndIncrement();
Thread ret = new Thread(mGroup, runnable, name, 0);
ret.setDaemon(mDaemo);
return ret;
| 327
| 64
| 391
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/async/impl/AsyncServiceImpl.java
|
AsyncServiceImpl
|
assemblePool
|
class AsyncServiceImpl implements AsyncService {
private final static String DEFAULT_THREAD_POOL = "default_thread_pool";
public final ConcurrentMap<String, ExecutorService> threadPoolMap = new ConcurrentSkipListMap<String, ExecutorService>();
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ExecutorService defaultThreadPool = AsyncThreadPoolFactory.DEFAULT_ASYNC_THREAD_POOL;
public AsyncServiceImpl() {
threadPoolMap.put(DEFAULT_THREAD_POOL, defaultThreadPool);
}
@Override
public boolean submitFuture(KeyCallable<?> callable) {
return submitFuture(DEFAULT_THREAD_POOL, callable);
}
@Override
public boolean submitFuture(String threadPoolKey, KeyCallable<?> callable) {
try {
ExecutorService executorService = threadPoolMap.get(threadPoolKey);
if (executorService == null) {
logger.warn("threadPoolKey={} not found , used defaultThreadPool", threadPoolKey);
executorService = defaultThreadPool;
}
Future future = executorService.submit(callable);
return true;
} catch (Exception e) {
logger.error(callable.getKey(), e);
return false;
}
}
@Override
public Future<?> submitFuture(Callable<?> callable) {
try {
Future<?> future = defaultThreadPool.submit(callable);
return future;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return null;
}
}
@Override
public void assemblePool(String threadPoolKey, ThreadPoolExecutor threadPool) {<FILL_FUNCTION_BODY>}
@PreDestroy
public void destory() {
for (ExecutorService executorService : threadPoolMap.values()) {
if (!executorService.isShutdown()) {
executorService.shutdown();
}
}
threadPoolMap.clear();
}
}
|
ExecutorService executorService = threadPoolMap.putIfAbsent(threadPoolKey, threadPool);
if (executorService != null) {
logger.warn("{} is assembled", threadPoolKey);
}
| 531
| 57
| 588
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/heartbeat/RedisClientController.java
|
RedisClientController
|
wrapClientParams
|
class RedisClientController {
@Autowired
private AppClientService appClientService;
/**
* 通过appId返回RedisCluster实例信息
*
* @param appId
*/
@RequestMapping(value = "/redis/cluster/{appId}.json", method = RequestMethod.GET)
public Map<String, Object> getClusterByAppIdAndKey(HttpServletRequest request, @PathVariable long appId) {
AppClientParams clientParams = wrapClientParams(request, appId, ConstUtils.CACHE_TYPE_REDIS_CLUSTER);
return appClientService.getAppClientInfo(clientParams);
}
/**
* 通过appId返回RedisSentinel实例信息
*
* @param appId
*/
@RequestMapping(value = "/redis/sentinel/{appId}.json")
public Map<String, Object> getSentinelAppById(HttpServletRequest request, @PathVariable long appId, Model model) {
AppClientParams clientParams = wrapClientParams(request, appId, ConstUtils.CACHE_REDIS_SENTINEL);
return appClientService.getAppClientInfo(clientParams);
}
/**
* 通过appId返回RedisStandalone实例信息
*
* @param appId
*/
@RequestMapping(value = "/redis/standalone/{appId}.json")
public Map<String, Object> getStandaloneAppById(HttpServletRequest request, @PathVariable long appId, Model model) {
AppClientParams clientParams = wrapClientParams(request, appId, ConstUtils.CACHE_REDIS_STANDALONE);
return appClientService.getAppClientInfo(clientParams);
}
private AppClientParams wrapClientParams(HttpServletRequest request, long appId, int type) {<FILL_FUNCTION_BODY>}
}
|
String appClientIp = IpUtil.getIpAddr(request);
String clientVersion = request.getParameter("clientVersion");
return new AppClientParams(appId, type, appClientIp, clientVersion);
| 473
| 57
| 530
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/heartbeat/RedisClientReportDataController.java
|
RedisClientReportDataController
|
dealAppClientReportData
|
class RedisClientReportDataController {
private final Logger logger = LoggerFactory.getLogger(RedisClientReportDataController.class);
@Autowired
private DealClientReportService dealClientReportService;
/**
* 上报客户端上传数据
*
* @param
* @param model
*/
@RequestMapping(value = "/reportData.json", method = RequestMethod.POST)
public void reportData(HttpServletRequest request, HttpServletResponse response, Model model) {
return;
}
@RequestMapping(value = "/v1/reportData/exception", method = RequestMethod.POST)
public ResponseEntity<String> reportExceptionData(@RequestParam("clientVersion") String clientVersion,
@RequestParam("stats") String json) {
return dealAppClientReportData(clientVersion, json);
}
@RequestMapping(value = "/v1/reportData/command", method = RequestMethod.POST)
public ResponseEntity<String> reportCommandData(@RequestParam("clientVersion") String clientVersion,
@RequestParam("stats") String json) {
return dealAppClientReportData(clientVersion, json);
}
/**
* 统一统一上报数据
*
* @param clientVersion
* @param json
* @return
*/
private ResponseEntity<String> dealAppClientReportData(String clientVersion, String json) {<FILL_FUNCTION_BODY>}
private boolean clientIpFilter(String clientIp) {
if (StringUtil.isBlank(clientIp)) {
return true;
}
//todo 可自行实现客户端ip过滤逻辑
return false;
}
/**
* 检验json正确性,返回AppClientReportModel
*
* @param json
* @return
*/
private AppClientReportModel checkAppClientReportJson(String json) {
if (StringUtils.isNotBlank(json)) {
try {
return JsonUtil.fromJson(json, AppClientReportModel.class);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
return null;
}
}
|
HttpStatus status = HttpStatus.CREATED;
// 验证json的正确性
AppClientReportModel appClientReportModel = checkAppClientReportJson(json);
if (appClientReportModel == null) {
logger.error("reportWrong message: {}", json);
status = HttpStatus.BAD_REQUEST;
return ResponseEntity.status(status).body("reportWrong message");
} else if (clientIpFilter(appClientReportModel.getClientIp())) {
logger.debug("discard report data, clientIp:{}", appClientReportModel.getClientIp());
return ResponseEntity.status(status).body("success");
}
// 处理数据
boolean result = dealClientReportService.deal(appClientReportModel);
if (!result) {
logger.error("appClientReportCommandService deal fail, appClientReportModel is {}", appClientReportModel);
status = HttpStatus.INTERNAL_SERVER_ERROR;
return ResponseEntity.status(status).body("message deal fail");
}
return ResponseEntity.status(status).body("success");
| 551
| 270
| 821
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/AppClientReportCommandServiceImpl.java
|
AppClientReportCommandServiceImpl
|
getAppCommandClientStatistics
|
class AppClientReportCommandServiceImpl implements AppClientReportCommandService {
@Autowired
private AppClientCommandStatisticsDao appClientCommandStatisticsDao;
@Autowired
private ReportDataComponent reportDataComponent;
@Override
public void batchSave(long appId, String clientIp, long currentMin, List<Map<String, Object>> commandStatsModels) {
try {
// 1.client上报
if (CollectionUtils.isEmpty(commandStatsModels)) {
log.warn("commandStatsModels is empty:{},{}", clientIp, currentMin);
return;
}
// 2.解析
List<AppClientCommandStatistics> appClientCommandStatisticsList = commandStatsModels.stream()
.filter(appClientCommandStatistics -> generate(appId, clientIp, currentMin, appClientCommandStatistics) != null)
.map(appClientCommandStatistics -> generate(appId, clientIp, currentMin, appClientCommandStatistics))
.collect(Collectors.toList());
// 4.批量保存
if (CollectionUtils.isNotEmpty(appClientCommandStatisticsList)) {
appClientCommandStatisticsDao.batchSave(appClientCommandStatisticsList);
//上报数据
reportDataComponent.reportCommandData(appClientCommandStatisticsList);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@Override
public List<String> getAppDistinctCommand(Long appId, long startTime, long endTime) {
try {
return appClientCommandStatisticsDao.getAppDistinctCommand(appId, startTime, endTime);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Collections.emptyList();
}
}
@Override
public Map<String, List<Map<String, Object>>> getAppCommandClientStatistics(Long appId, String command, long startTime, long endTime, String clientIp) {<FILL_FUNCTION_BODY>}
@Override
public List<Map<String, Object>> getAppClientStatisticsByCommand(Long appId, String command, long startTime, long endTime) {
try {
List<Map<String, Object>> getAppClientStatisticsByCommand = appClientCommandStatisticsDao.getAppCommandStatistics(appId, startTime, endTime, command, null);
return getAppClientStatisticsByCommand;
} catch (Exception e) {
log.error(e.getMessage(), e);
return Collections.emptyList();
}
}
@Override
public List<String> getAppDistinctClients(Long appId, long startTime, long endTime) {
try {
return appClientCommandStatisticsDao.getAppDistinctClients(appId, startTime, endTime);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Collections.emptyList();
}
}
@Override
public List<Map<String, Object>> getSumCmdStatByCmd(Long appId, long startTime, long endTime, String command) {
try {
return appClientCommandStatisticsDao.getSumCmdStatByCmd(appId, startTime, endTime, command);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Collections.emptyList();
}
}
@Override
public List<Map<String, Object>> getSumCmdStatByClient(Long appId, long startTime, long endTime, String clientIp) {
try {
return appClientCommandStatisticsDao.getSumCmdStatByClient(appId, startTime, endTime, clientIp);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Collections.emptyList();
}
}
private AppClientCommandStatistics generate(long appId, String clientIp, long currentMin, Map<String, Object> commandStatsModel) {
try {
AppClientCommandStatistics appClientCommandStatistics = (AppClientCommandStatistics) MapUtil.mapToObject(commandStatsModel, AppClientCommandStatistics.class);
if (appClientCommandStatistics != null) {
appClientCommandStatistics.setAppId(appId);
appClientCommandStatistics.setClientIp(clientIp);
appClientCommandStatistics.setCurrentMin(currentMin);
}
return appClientCommandStatistics;
} catch (Exception e) {
log.error("generate appClientCommandStatistics error {}, {}", e.getMessage(), e);
return null;
}
}
}
|
try {
List<Map<String, Object>> appClientCommandStatisticsList = appClientCommandStatisticsDao.getAppCommandStatistics(appId, startTime, endTime, command, clientIp);
Map<String, List<Map<String, Object>>> commandStatisticsMap = Maps.newHashMap();
appClientCommandStatisticsList.stream().forEach(commandStatistic -> {
String client_ip = MapUtils.getString(commandStatistic, "client_ip");
ArrayList commandStatisticList = (ArrayList) MapUtils.getObject(commandStatisticsMap, client_ip);
if (CollectionUtils.isEmpty(commandStatisticList)) {
commandStatisticList = Lists.newArrayList();
commandStatisticsMap.put(client_ip, commandStatisticList);
}
commandStatisticList.add(commandStatistic);
});
return commandStatisticsMap;
} catch (Exception e) {
log.error(e.getMessage(), e);
return Collections.emptyMap();
}
| 1,168
| 251
| 1,419
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/AppClientServiceImpl.java
|
AppClientServiceImpl
|
initApps
|
class AppClientServiceImpl implements AppClientService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private InstanceDao instanceDao;
@Autowired
private AppDao appDao;
@Autowired
private ClientVersionService clientVersionService;
private ConcurrentMap<Long, Map<String, Object>> appClientMap = Maps.newConcurrentMap();
@PostConstruct
public void initApps() {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> getAppClientInfo(AppClientParams appClientParams) {
AppClientCommand command = new AppClientCommand(appClientParams, appDao, instanceDao, clientVersionService,
appClientMap);
return command.execute();
}
}
|
long start = System.currentTimeMillis();
List<AppDesc> onlineApps = appDao.getOnlineApps();
if (onlineApps == null) {
return;
}
Map<Long, List<InstanceInfo>> cacheInstances = Maps.newHashMap();
List<InstanceInfo> allInstances = instanceDao.getAllInsts();
for (InstanceInfo instanceInfo : allInstances) {
long appId = instanceInfo.getAppId();
if (instanceInfo.isOnline()) {
List<InstanceInfo> instances = cacheInstances.get(appId);
if (instances == null) {
instances = Lists.newArrayList();
cacheInstances.put(appId, instances);
}
instances.add(instanceInfo);
}
}
Map<Long, String> cacheMaxVersions = Maps.newHashMap();
List<Map<String, Object>> appMaxVersions = clientVersionService.getAllMaxClientVersion();
for (Map<String, Object> map : appMaxVersions) {
long appId = MapUtils.getLongValue(map, "appId");
String clientVersion = MapUtils.getString(map, "clientVersion");
cacheMaxVersions.put(appId, clientVersion);
}
for (AppDesc appDesc : onlineApps) {
int type = appDesc.getType();
long appId = appDesc.getAppId();
AppClientParams appClientParams = new AppClientParams(appId, type, null, null);
appClientParams.setCacheAppDesc(appDesc);
appClientParams.setCacheInstanceInfos(cacheInstances.get(appId));
appClientParams.setCacheMaxVersion(cacheMaxVersions.get(appId));
AppClientCommand command = new AppClientCommand(appClientParams, appDao, instanceDao, clientVersionService,
appClientMap);
Map<String, Object> model;
if (type == ConstUtils.CACHE_TYPE_REDIS_CLUSTER) {
model = command.getRedisClusterInfo(false);
command.addAppClient(appId, model);
} else if (type == ConstUtils.CACHE_REDIS_SENTINEL) {
model = command.getRedisSentinelInfo(false);
command.addAppClient(appId, model);
} else if (type == ConstUtils.CACHE_REDIS_STANDALONE) {
model = command.getRedisStandaloneInfo(false);
command.addAppClient(appId, model);
}
}
long end = System.currentTimeMillis();
logger.warn("AppClientService: app-client-size={} cost={} ms", appClientMap.size(), (end - start));
| 212
| 688
| 900
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/AppInstanceClientRelationServiceImpl.java
|
AppInstanceClientRelationServiceImpl
|
batchSave
|
class AppInstanceClientRelationServiceImpl implements AppInstanceClientRelationService {
private Logger logger = LoggerFactory.getLogger(AppInstanceClientRelationServiceImpl.class);
private AppInstanceClientRelationDao appInstanceClientRelationDao;
@Override
public void batchSave(List<AppClientCostTimeStat> appClientCostTimeStatList) {<FILL_FUNCTION_BODY>}
@Override
public List<AppInstanceClientRelation> getAppInstanceClientRelationList(Long appId, Date date) {
try {
return appInstanceClientRelationDao.getAppInstanceClientRelationList(appId, date);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyList();
}
}
public void setAppInstanceClientRelationDao(AppInstanceClientRelationDao appInstanceClientRelationDao) {
this.appInstanceClientRelationDao = appInstanceClientRelationDao;
}
}
|
if (CollectionUtils.isEmpty(appClientCostTimeStatList)) {
return;
}
try {
List<AppInstanceClientRelation> appInstanceClientRelationList = new ArrayList<AppInstanceClientRelation>();
for (AppClientCostTimeStat appClientCostTimeStat : appClientCostTimeStatList) {
AppInstanceClientRelation appInstanceClientRelation = AppInstanceClientRelation.generateFromAppClientCostTimeStat(appClientCostTimeStat);
if (appInstanceClientRelation != null) {
appInstanceClientRelationList.add(appInstanceClientRelation);
}
}
if (CollectionUtils.isNotEmpty(appInstanceClientRelationList)) {
appInstanceClientRelationDao.batchSave(appInstanceClientRelationList);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
| 278
| 235
| 513
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/ClientReportExceptionServiceImpl.java
|
ClientReportExceptionServiceImpl
|
getInstanceExceptionStat
|
class ClientReportExceptionServiceImpl implements ClientReportExceptionService {
private final Logger logger = LoggerFactory.getLogger(ClientReportExceptionServiceImpl.class);
/**
* 客户端异常操作
*/
private AppClientExceptionStatDao appClientExceptionStatDao;
/**
* host:port与instanceInfo简单缓存
*/
private ClientReportInstanceService clientReportInstanceService;
/**
* 客户端ip,版本查询
*/
private AppClientVersionDao appClientVersionDao;
@Override
public List<AppClientExceptionStat> getAppExceptionList(Long appId, long startTime, long endTime, int type,
String clientIp, Page page) {
try {
return appClientExceptionStatDao.getAppExceptionList(appId, startTime, endTime, type, clientIp, page);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyList();
}
}
@Override
public int getAppExceptionCount(Long appId, long startTime, long endTime, int type, String clientIp) {
try {
return appClientExceptionStatDao.getAppExceptionCount(appId, startTime, endTime, type, clientIp);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return 0;
}
}
@Override
public List<ClientInstanceException> getInstanceExceptionStat(String ip, long collectTime) {<FILL_FUNCTION_BODY>}
public void setAppClientExceptionStatDao(AppClientExceptionStatDao appClientExceptionStatDao) {
this.appClientExceptionStatDao = appClientExceptionStatDao;
}
public void setAppClientVersionDao(AppClientVersionDao appClientVersionDao) {
this.appClientVersionDao = appClientVersionDao;
}
public void setClientReportInstanceService(ClientReportInstanceService clientReportInstanceService) {
this.clientReportInstanceService = clientReportInstanceService;
}
}
|
try {
return appClientExceptionStatDao.getInstanceExceptionStat(ip, collectTime);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyList();
}
| 585
| 66
| 651
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/ClientReportInstanceServiceImpl.java
|
ClientReportInstanceServiceImpl
|
getInstanceInfoByHostPort
|
class ClientReportInstanceServiceImpl implements ClientReportInstanceService {
private Logger logger = LoggerFactory.getLogger(ClientReportInstanceServiceImpl.class);
/**
* 不要求一致性的本地缓存(hostport<=>instanceInfo)
*/
private final static ConcurrentHashMap<String, InstanceInfo> hostPortInstanceMap = new ConcurrentHashMap<String, InstanceInfo>();
private InstanceDao instanceDao;
@Override
public InstanceInfo getInstanceInfoByHostPort(String host, int port) {<FILL_FUNCTION_BODY>}
public void setInstanceDao(InstanceDao instanceDao) {
this.instanceDao = instanceDao;
}
}
|
String hostPort = host + ":" + port;
try {
InstanceInfo instanceInfo = hostPortInstanceMap.get(hostPort);
if (instanceInfo == null) {
instanceInfo = instanceDao.getInstByIpAndPort(host, port);
if (instanceInfo != null) {
hostPortInstanceMap.putIfAbsent(hostPort, instanceInfo);
}
}
return instanceInfo;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return null;
}
| 200
| 154
| 354
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/ClientReportValueDistriServiceImplV2.java
|
ClientReportValueDistriServiceImplV2
|
getAppValueDistriList
|
class ClientReportValueDistriServiceImplV2 implements ClientReportValueDistriService {
private final Logger logger = LoggerFactory.getLogger(ClientReportValueDistriServiceImplV2.class);
public static Set<String> excludeCommands = new HashSet<String>();
static {
excludeCommands.add("ping");
excludeCommands.add("quit");
}
/**
* 客户端统计值分布数据操作
*/
private AppClientValueStatDao appClientValueStatDao;
/**
* host:port与instanceInfo简单缓存
*/
private ClientReportInstanceService clientReportInstanceService;
@Override
public List<AppClientValueDistriSimple> getAppValueDistriList(long appId, long startTime, long endTime) {<FILL_FUNCTION_BODY>}
@Override
public int deleteBeforeCollectTime(long collectTime) {
try {
return appClientValueStatDao.deleteBeforeCollectTime(collectTime);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return -1;
}
}
public void setClientReportInstanceService(ClientReportInstanceService clientReportInstanceService) {
this.clientReportInstanceService = clientReportInstanceService;
}
public void setAppClientValueStatDao(AppClientValueStatDao appClientValueStatDao) {
this.appClientValueStatDao = appClientValueStatDao;
}
}
|
try {
return appClientValueStatDao.getAppValueDistriList(appId, startTime, endTime);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyList();
}
| 373
| 66
| 439
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/ClientVersionServiceImpl.java
|
ClientVersionServiceImpl
|
getAppAllClientVersion
|
class ClientVersionServiceImpl implements ClientVersionService {
private final Logger logger = LoggerFactory.getLogger(ClientVersionServiceImpl.class);
private AppClientVersionDao appClientVersionDao;
@Override
public void saveOrUpdateClientVersion(long appId, String appClientIp, String clientVersion) {
try {
AppClientVersion appClientVersion = new AppClientVersion();
appClientVersion.setAppId(appId);
appClientVersion.setClientIp(appClientIp);
appClientVersion.setClientVersion(clientVersion);
appClientVersion.setReportTime(new Date());
appClientVersionDao.saveOrUpdateClientVersion(appClientVersion);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Override
public List<AppClientVersion> getAppAllClientVersion(long appId) {<FILL_FUNCTION_BODY>}
public String getAppMaxClientVersion(long appId) {
try {
return appClientVersionDao.getAppMaxClientVersion(appId);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return null;
}
}
@Override
public List<Map<String, Object>> getAllMaxClientVersion() {
try {
return appClientVersionDao.getAllMaxClientVersion();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyList();
}
}
@Override
public List<AppClientVersion> getAll(long appId) {
try {
return appClientVersionDao.getAll(appId);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyList();
}
}
public void setAppClientVersionDao(AppClientVersionDao appClientVersionDao) {
this.appClientVersionDao = appClientVersionDao;
}
}
|
try {
return appClientVersionDao.getAppAllClientVersion(appId);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyList();
}
| 561
| 65
| 626
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/client/service/impl/DealClientReportServiceImpl.java
|
DealClientReportServiceImpl
|
deal
|
class DealClientReportServiceImpl implements DealClientReportService {
@Autowired
private AsyncService asyncService;
@Autowired
private AppClientReportCommandService appClientReportCommandService;
@Autowired
private AppClientReportExceptionService appClientReportExceptionService;
@Override
public void init() {
asyncService.assemblePool(getThreadPoolKey(), AsyncThreadPoolFactory.CLIENT_REPORT_THREAD_POOL);
}
@Override
public boolean deal(final AppClientReportModel appClientReportModel) {<FILL_FUNCTION_BODY>}
private String getThreadPoolKey() {
return AsyncThreadPoolFactory.CLIENT_REPORT_POOL;
}
}
|
try {
// 上报的数据
final long appId = appClientReportModel.getAppId();
final String clientIp = appClientReportModel.getClientIp();
final String redisPoolConfig = JSON.toJSONString(appClientReportModel.getConfig());
final long currentMin = appClientReportModel.getCurrentMin();
final List<Map<String, Object>> commandStatsModels = appClientReportModel.getCommandStatsModels();
final List<Map<String, Object>> exceptionModels = appClientReportModel.getExceptionModels();
String key = getThreadPoolKey() + "_" + clientIp;
asyncService.submitFuture(getThreadPoolKey(), new KeyCallable<Boolean>(key) {
@Override
public Boolean execute() {
try {
if (CollectionUtils.isNotEmpty(commandStatsModels)) {
appClientReportCommandService.batchSave(appId, clientIp, currentMin, commandStatsModels);
}
if (CollectionUtils.isNotEmpty(exceptionModels)) {
appClientReportExceptionService.batchSave(appId, clientIp, redisPoolConfig, currentMin, exceptionModels);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
});
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
| 183
| 358
| 541
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/configuration/AsyncConfiguration.java
|
AsyncConfiguration
|
forkJoinPool
|
class AsyncConfiguration {
private int parallelism=256;
@Bean
public ForkJoinPool forkJoinPool() {<FILL_FUNCTION_BODY>}
}
|
log.info("availableProcessors:{}, parallelism:{}", Runtime.getRuntime().availableProcessors(), parallelism);
ForkJoinPool forkJoinPool = new ForkJoinPool(parallelism);
return forkJoinPool;
| 49
| 58
| 107
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/configuration/SSHPoolConfig.java
|
SSHPoolConfig
|
clientSessionPool
|
class SSHPoolConfig {
/**
* ssh连接池配置
* @return
*/
@Bean
public GenericKeyedObjectPool<SSHMachineInfo, ClientSession> clientSessionPool() throws GeneralSecurityException, IOException {<FILL_FUNCTION_BODY>}
}
|
GenericKeyedObjectPoolConfig genericKeyedObjectPoolConfig = new GenericKeyedObjectPoolConfig();
genericKeyedObjectPoolConfig.setTestWhileIdle(true);
genericKeyedObjectPoolConfig.setTestOnReturn(true);
genericKeyedObjectPoolConfig.setMaxTotalPerKey(5);
genericKeyedObjectPoolConfig.setMaxIdlePerKey(1);
genericKeyedObjectPoolConfig.setMinIdlePerKey(1);
genericKeyedObjectPoolConfig.setMaxWaitMillis(30000);
genericKeyedObjectPoolConfig.setTimeBetweenEvictionRunsMillis(20000);
genericKeyedObjectPoolConfig.setJmxEnabled(false);
SSHSessionPooledObjectFactory factory = new SSHSessionPooledObjectFactory();
GenericKeyedObjectPool<SSHMachineInfo, ClientSession> genericKeyedObjectPool = new GenericKeyedObjectPool<>(
factory,
genericKeyedObjectPoolConfig);
return genericKeyedObjectPool;
| 72
| 249
| 321
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/AppDataMigrateResult.java
|
AppDataMigrateResult
|
isSuccess
|
class AppDataMigrateResult {
private int status;
private String message;
public AppDataMigrateResult(int status, String message) {
this.status = status;
this.message = message;
}
public boolean isSuccess() {<FILL_FUNCTION_BODY>}
public static AppDataMigrateResult success() {
return new AppDataMigrateResult(1, "所有检查都成功,可以迁移啦!");
}
public static AppDataMigrateResult success(String message) {
return new AppDataMigrateResult(1, message);
}
public static AppDataMigrateResult fail(String message) {
return new AppDataMigrateResult(0, message);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "RedisMigrateResult [status=" + status + ", message=" + message + "]";
}
}
|
if (status == 1) {
return true;
}
return false;
| 366
| 30
| 396
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/AppDescEnum.java
|
AppDescEnum
|
getByType
|
class AppDescEnum {
/**
* 应用类型:0 正式,1:测试 2:试用
*/
public static enum AppTest {
IS_TEST(1),
NOT_TEST(0),
IS_TRAIL(2);
private int value;
private AppTest(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 应用重要度
*/
public static enum AppImportantLevel {
SUPER_IMPORTANT(1, "S"),
VERY_IMPORTANT(2, "A"),
IMPORTANT(3, "B"),
COMMON(4, "C");
private int value;
private String info;
private AppImportantLevel(int value, String info) {
this.value = value;
this.info = info;
}
public int getValue() {
return value;
}
public String getInfo() {
return info;
}
}
/**
* 应用内存淘汰策略
*/
public static enum MaxmemoryPolicyType {
NOEVICTION(0, "noeviction","不淘汰,占满写入失败"),
ALLKEYSLRU(1, "allkeys-lru","所有键-最近最少使用"),
ALLKEYSLFU(2, "allkeys-lfu","所有键-最少频率使用"),
VOLATILELRU(3, "volatile-lru","有过期时间的键-最近最少使用"),
VOLATILELFU(4, "volatile-lfu","有过期时间的键-最少频率使用"),
ALLKEYSRANDOM(5, "allkeys-random","所有键-随机"),
VOLATILERANDOM(6, "volatile-random","有过期时间的键-随机"),
VOLATILETTL(7, "volatile-ttl","有过期时间的键-剩余时间最短");
private int type;
private String name;
private String desc;
private MaxmemoryPolicyType(int type, String name, String desc) {
this.type = type;
this.name = name;
this.desc = desc;
}
public int getType(){
return type;
}
public String getName(){
return name;
}
public String getDesc(){
return desc;
}
public static MaxmemoryPolicyType getByType(int type){<FILL_FUNCTION_BODY>}
public static List<MaxmemoryPolicyType> getAll(){
MaxmemoryPolicyType[] values = MaxmemoryPolicyType.values();
return Arrays.asList(values);
}
}
}
|
Optional<MaxmemoryPolicyType> policyTypeOptional = Arrays.asList(MaxmemoryPolicyType.values()).stream().filter(maxmemoryPolicyType -> maxmemoryPolicyType.type == type).findFirst();
if(policyTypeOptional.isPresent()){
return policyTypeOptional.get();
}
return null;
| 730
| 80
| 810
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/ClusterOperateResult.java
|
ClusterOperateResult
|
toString
|
class ClusterOperateResult {
private int status;
private String message;
public ClusterOperateResult(int status, String message) {
this.status = status;
this.message = message;
}
public static ClusterOperateResult success() {
return new ClusterOperateResult(1, "");
}
public static ClusterOperateResult fail(String message) {
return new ClusterOperateResult(0, message);
}
public boolean isSuccess() {
return status == 1;
}
public int getStatus() {
return status;
}
public String getMessage() {
return message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "ClusterOperateResult [status=" + status + ", message=" + message + "]";
| 203
| 28
| 231
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/CommandResult.java
|
CommandResult
|
toString
|
class CommandResult {
private String command;
private String result;
private List<String> resultLines;
public CommandResult(String command, String result) {
super();
this.command = command;
this.result = result;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public List<String> getResultLines() {
return resultLines;
}
public void setResultLines(List<String> resultLines) {
this.resultLines = resultLines;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "CommandResult [command=" + command + ", result=" + result + ", resultLines=" + resultLines + "]";
| 277
| 39
| 316
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/DataFormatCheckResult.java
|
DataFormatCheckResult
|
toString
|
class DataFormatCheckResult {
private int status;
private String message;
private final static int SUCCESS = 1;
private final static int FAIL = 0;
public DataFormatCheckResult(int status, String message) {
this.status = status;
this.message = message;
}
public boolean isSuccess() {
if (status == SUCCESS) {
return true;
}
return false;
}
public static DataFormatCheckResult success(String message) {
return new DataFormatCheckResult(SUCCESS, message);
}
public static DataFormatCheckResult fail(String message) {
return new DataFormatCheckResult(FAIL, message);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "DataFormatCheckResult [status=" + status + ", message=" + message + "]";
| 340
| 30
| 370
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/HorizontalResult.java
|
HorizontalResult
|
toString
|
class HorizontalResult {
private int status;
private String message;
public HorizontalResult(int status, String message) {
this.status = status;
this.message = message;
}
public static HorizontalResult checkSuccess() {
return new HorizontalResult(1, "所有检查都成功,可以开始水平扩容了!");
}
public static HorizontalResult scaleSuccess() {
return new HorizontalResult(1, "水平扩容已经成功开始!");
}
public static HorizontalResult fail(String message) {
return new HorizontalResult(0, message);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "HorizontalResult [status=" + status + ", message=" + message + "]";
| 305
| 29
| 334
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/ImportAppResult.java
|
ImportAppResult
|
toString
|
class ImportAppResult {
private int status;
private String message;
public ImportAppResult(int status, String message) {
this.status = status;
this.message = message;
}
public static ImportAppResult success() {
return new ImportAppResult(1, "所有检查都成功,可以添加啦!");
}
public static ImportAppResult fail(String message) {
return new ImportAppResult(0, message);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "ImportAppResult [status=" + status + ", message=" + message + "]";
| 264
| 29
| 293
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/constant/OperateResult.java
|
OperateResult
|
toString
|
class OperateResult {
private boolean isSuccess;
private String message;
private OperateResult(boolean isSuccess, String message) {
this.isSuccess = isSuccess;
this.message = message;
}
public static OperateResult success() {
return new OperateResult(true, "");
}
public static OperateResult fail(String message) {
return new OperateResult(false, message);
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OperateResult [isSuccess=" + isSuccess + ", message=" + message + "]";
| 224
| 29
| 253
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppAudit.java
|
AppAudit
|
getStatusDesc
|
class AppAudit {
private long id;
private long appId;
private long userId;
private long operateId;
private String userName;
/**
* 申请类型:AppAuditType
*/
private int type;
/**
* 预留参数1
*/
private String param1;
/**
* 预留参数2
*/
private String param2;
/**
* 预留参数3
*/
private String param3;
/**
* 申请描述
*/
private String info;
/**
* 0:等待审批; 1:审批通过; -1:驳回
*/
private int status;
private Date createTime;
private Date modifyTime;
/**
* 驳回原因
*/
private String refuseReason;
/**
* 任务ID
*/
private long taskId;
private AppDesc appDesc;
private AppAuditLog appAuditLog;
public Date getCreateTime() {
if (createTime != null) {
return (Date) createTime.clone();
}
return null;
}
public void setCreateTime(Date createTime) {
this.createTime = (Date) createTime.clone();
}
public Date getModifyTime() {
if (modifyTime == null) {
return null;
}
return (Date) modifyTime.clone();
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = (Date) modifyTime.clone();
}
public String getTypeDesc() {
if (AppAuditType.getAppAuditType(type) != null) {
return AppAuditType.getAppAuditType(type).getInfo();
}
return "";
}
public String getStatusDesc() {<FILL_FUNCTION_BODY>}
public String getCreateTimeFormat() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (createTime != null) {
return sdf.format(createTime);
}
return "";
}
}
|
// 0:等待审批; 1:审批通过; -1:驳回
if (status == 0) {
return "等待审批";
} else if (status == 1) {
return "审批通过";
} else if (status == -1) {
return "驳回";
} else {
return status + "";
}
| 682
| 107
| 789
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppAuditLog.java
|
AppAuditLog
|
generate
|
class AppAuditLog implements Serializable {
/**
* 日志id
*/
private Long id;
/**
* 应用id
*/
private Long appId;
/**
* 审批id
*/
private Long appAuditId;
/**
* 用户id
*/
private Long userId;
/**
* 用户
*/
private AppUser appUser;
/**
* 日志详情 是个json
*/
private String info;
/**
* 创建时间
*/
private Date createTime;
/**
* 日志类型
*/
private Integer type;
public Date getCreateTime() {
return (Date) createTime.clone();
}
public void setCreateTime(Date createTime) {
this.createTime = (Date) createTime.clone();
}
/**
* 生成日志
* @param appDesc
* @param appUser
* @param appAuditId
* @param type
* @return
*/
public static AppAuditLog generate(AppDesc appDesc, AppUser appUser, Long appAuditId, AppAuditLogTypeEnum type){<FILL_FUNCTION_BODY>}
}
|
if(appDesc == null || appUser == null || appAuditId == null){
return null;
}
AppAuditLog log = new AppAuditLog();
log.setAppId(appDesc.getAppId());
log.setUserId(appUser.getId());
log.setAppAuditId(appAuditId);
log.setType(type.value());
log.setCreateTime(new Date());
log.setInfo(JSONObject.fromObject(appDesc).toString());
return log;
| 403
| 151
| 554
|
<no_super_class>
|
sohutv_cachecloud
|
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppClientCostTimeStat.java
|
AppClientCostTimeStat
|
hashCode
|
class AppClientCostTimeStat {
private long id;
/**
* 应用id
*/
private long appId;
/**
* 格式yyyyMMddHHmm00
*/
private long collectTime;
/**
* 客户端ip
*/
private String clientIp;
/**
* 上报时间
*/
private Date reportTime;
/**
* 创建时间
*/
private Date createTime;
/**
* 命令
*/
private String command;
/**
* 调用次数
*/
private int count;
/**
* 实例ip
*/
private String instanceHost;
/**
* 实例port
*/
private int instancePort;
/**
* 实例id
*/
private long instanceId;
/**
* 中位值
*/
private int median;
/**
* 平均值
*/
private double mean;
/**
* 90%最大值
*/
private int ninetyPercentMax;
/**
* 99%最大值
*/
private int ninetyNinePercentMax;
/**
* 100%最大值
*/
private int hundredMax;
public Date getReportTime() {
return (Date) reportTime.clone();
}
public void setReportTime(Date reportTime) {
this.reportTime = (Date) reportTime.clone();
}
public Date getCreateTime() {
return (Date) createTime.clone();
}
public void setCreateTime(Date createTime) {
this.createTime = (Date) createTime.clone();
}
public Long getCollectTimeStamp() throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date;
try {
date = sdf.parse(String.valueOf(this.collectTime));
return date.getTime();
} catch (Exception e) {
return 0L;
}
}
public Long getTimeStamp() throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = sdf.parse(String.valueOf(this.collectTime));
return date.getTime();
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AppClientCostTimeStat other = (AppClientCostTimeStat) obj;
if (clientIp == null) {
if (other.clientIp != null)
return false;
} else if (!clientIp.equals(other.clientIp))
return false;
if (instanceId != other.instanceId)
return false;
return true;
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((clientIp == null) ? 0 : clientIp.hashCode());
result = prime * result + (int) (instanceId ^ (instanceId >>> 32));
return result;
| 943
| 80
| 1,023
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.