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
|
|---|---|---|---|---|---|---|---|---|---|
lets-blade_blade
|
blade/blade-core/src/main/java/com/hellokaton/blade/server/decode/FullHttpRequestDecode.java
|
FullHttpRequestDecode
|
channelRead0
|
class FullHttpRequestDecode extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {<FILL_FUNCTION_BODY>}
}
|
String address = ctx.channel().remoteAddress().toString();
HttpRequest httpRequest = new HttpRequest(address, fullHttpRequest);
ctx.fireChannelRead(httpRequest);
| 60
| 45
| 105
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-core/src/main/java/com/hellokaton/blade/server/decode/HttpObjectAggregatorDecode.java
|
HttpObjectAggregatorDecode
|
operationComplete
|
class HttpObjectAggregatorDecode extends HttpObjectAggregator {
private static final FullHttpResponse EXPECTATION_FAILED = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.EXPECTATION_FAILED, Unpooled.EMPTY_BUFFER);
private static final FullHttpResponse TOO_LARGE_CLOSE = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);
private static final FullHttpResponse TOO_LARGE = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);
static {
EXPECTATION_FAILED.headers().set(CONTENT_LENGTH, 0);
TOO_LARGE.headers().set(CONTENT_LENGTH, 0);
TOO_LARGE_CLOSE.headers().set(CONTENT_LENGTH, 0);
TOO_LARGE_CLOSE.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
}
public HttpObjectAggregatorDecode(int maxContentLength) {
super(maxContentLength);
}
@Override
protected void handleOversizedMessage(final ChannelHandlerContext ctx, HttpMessage oversized) throws Exception {
if (oversized instanceof HttpRequest) {
// send back a 413 and close the connection
HttpRequest httpRequest = (HttpRequest) oversized;
log.info("Request [{}] Failed to send a 413 Request Entity Too Large.", httpRequest.uri());
// If the client started to send data already, close because it's impossible to recover.
// If keep-alive is off and 'Expect: 100-continue' is missing, no need to leave the connection open.
if (oversized instanceof FullHttpMessage ||
!HttpUtil.is100ContinueExpected(oversized) && !HttpUtil.isKeepAlive(oversized)) {
ChannelFuture future = ctx.writeAndFlush(TOO_LARGE_CLOSE.retainedDuplicate());
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {<FILL_FUNCTION_BODY>}
});
} else {
ctx.writeAndFlush(TOO_LARGE.retainedDuplicate()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
log.warn("Failed to send a 413 Request Entity Too Large.", future.cause());
ctx.close();
}
}
});
}
} else if (oversized instanceof HttpResponse) {
ctx.close();
throw new TooLongHttpContentException("Response entity too large: " + oversized);
} else {
throw new IllegalStateException();
}
}
}
|
if (!future.isSuccess()) {
log.warn("Failed to send a 413 Request Entity Too Large.", future.cause());
}
ctx.close();
| 762
| 46
| 808
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-core/src/main/java/com/hellokaton/blade/task/Task.java
|
Task
|
stop
|
class Task {
private String name;
private Runnable task;
private ScheduledFuture<?> future;
private CronExpression cronExpression;
private volatile boolean isRunning = true;
private long delay;
public Task(String name, CronExpression cronExpression, long delay) {
this.name = name;
this.cronExpression = cronExpression;
this.delay = delay;
}
public boolean stop() {<FILL_FUNCTION_BODY>}
}
|
if (!isRunning) {
return true;
}
isRunning = false;
var flag = future.cancel(true);
log.info("{}Task [{}] stoped", getStartedSymbol(), name);
return flag;
| 138
| 63
| 201
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-core/src/main/java/com/hellokaton/blade/task/TaskManager.java
|
TaskManager
|
init
|
class TaskManager {
private final static Map<String, Task> TASK_MAP = new HashMap<>(8);
private final static ReentrantReadWriteLock rrw = new ReentrantReadWriteLock();
private final static Lock readLock = rrw.readLock();
private final static Lock writeLock = rrw.writeLock();
private static CronExecutorService cronExecutorService;
public static void init(CronExecutorService cronExecutorService) {<FILL_FUNCTION_BODY>}
public static CronExecutorService getExecutorService() {
return cronExecutorService;
}
public static void addTask(Task task) {
writeLock.lock();
try {
TASK_MAP.put(task.getName(), task);
} finally {
writeLock.unlock();
}
log.info("{}Add task [{}]", getStartedSymbol(), task.getName());
}
public static List<Task> getTasks() {
Collection<Task> values;
readLock.lock();
try {
values = Optional.ofNullable(TASK_MAP.values()).orElse(Collections.EMPTY_LIST);
} finally {
readLock.unlock();
}
return new ArrayList<>(values);
}
public static Task getTask(String name) {
readLock.lock();
try {
return TASK_MAP.get(name);
} finally {
readLock.unlock();
}
}
public static boolean stopTask(String name) {
Task task;
readLock.lock();
try {
task = TASK_MAP.get(name);
} finally {
readLock.unlock();
}
return task == null ? Boolean.FALSE : task.stop();
}
}
|
if (null != TaskManager.cronExecutorService) {
throw new RuntimeException("Don't re-initialize the task thread pool.");
}
TaskManager.cronExecutorService = cronExecutorService;
Runtime.getRuntime().addShutdownHook(new Thread(cronExecutorService::shutdown));
| 446
| 78
| 524
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-core/src/main/java/com/hellokaton/blade/task/cron/CronThreadPoolExecutor.java
|
CronThreadPoolExecutor
|
submit
|
class CronThreadPoolExecutor extends ScheduledThreadPoolExecutor implements CronExecutorService {
public CronThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize, threadFactory);
}
@Override
public ScheduledFuture<?> submit(Task task) {<FILL_FUNCTION_BODY>}
}
|
if (task == null) throw new NullPointerException();
CronExpression expression = task.getCronExpression();
Runnable scheduleTask = () -> {
Date now = new Date();
Date time = expression.getNextValidTimeAfter(now);
try {
while (time != null) {
if (!task.isRunning()) {
break;
}
CronThreadPoolExecutor.this.schedule(task.getTask(), time.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
while (now.before(time)) {
Thread.sleep(time.getTime() - now.getTime());
now = new Date();
}
time = expression.getNextValidTimeAfter(now);
}
} catch (RejectedExecutionException | CancellationException e) {
// Occurs if executor was already shutdown when schedule() is called
} catch (InterruptedException e) {
// Occurs when executing tasks are interrupted during shutdownNow()
Thread.currentThread().interrupt();
}
};
return this.schedule(scheduleTask, task.getDelay(), TimeUnit.MILLISECONDS);
| 91
| 290
| 381
|
<methods>public void <init>(int) ,public void <init>(int, java.util.concurrent.ThreadFactory) ,public void <init>(int, java.util.concurrent.RejectedExecutionHandler) ,public void <init>(int, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler) ,public void execute(java.lang.Runnable) ,public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() ,public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() ,public BlockingQueue<java.lang.Runnable> getQueue() ,public boolean getRemoveOnCancelPolicy() ,public ScheduledFuture<?> schedule(java.lang.Runnable, long, java.util.concurrent.TimeUnit) ,public ScheduledFuture<V> schedule(Callable<V>, long, java.util.concurrent.TimeUnit) ,public ScheduledFuture<?> scheduleAtFixedRate(java.lang.Runnable, long, long, java.util.concurrent.TimeUnit) ,public ScheduledFuture<?> scheduleWithFixedDelay(java.lang.Runnable, long, long, java.util.concurrent.TimeUnit) ,public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean) ,public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean) ,public void setRemoveOnCancelPolicy(boolean) ,public void shutdown() ,public List<java.lang.Runnable> shutdownNow() ,public Future<?> submit(java.lang.Runnable) ,public Future<T> submit(Callable<T>) ,public Future<T> submit(java.lang.Runnable, T) <variables>private static final long DEFAULT_KEEPALIVE_MILLIS,private volatile boolean continueExistingPeriodicTasksAfterShutdown,private volatile boolean executeExistingDelayedTasksAfterShutdown,volatile boolean removeOnCancel,private static final java.util.concurrent.atomic.AtomicLong sequencer
|
lets-blade_blade
|
blade/blade-core/src/main/java/com/hellokaton/blade/validator/ValidationResult.java
|
ValidationResult
|
throwIfInvalid
|
class ValidationResult {
private boolean valid;
private String message;
private String code;
public static ValidationResult ok() {
return new ValidationResult(true, null, null);
}
public static ValidationResult ok(String code) {
return new ValidationResult(true, null, code);
}
public static ValidationResult fail(String message) {
return new ValidationResult(false, message, null);
}
public static ValidationResult fail(String code, String message) {
return new ValidationResult(false, message, code);
}
public void throwIfInvalid() {
this.throwMessage(getMessage());
}
public void throwIfInvalid(String fieldName) {<FILL_FUNCTION_BODY>}
public <T, R> void throwIfInvalid(TypeFunction<T, R> function) {
var fieldName = BladeKit.getLambdaFieldName(function);
throwIfInvalid(fieldName);
}
public void throwMessage(String msg) {
if (!isValid()) throw new ValidatorException(msg);
}
}
|
if (!isValid()) throw new ValidatorException(fieldName + " " + getMessage());
| 283
| 25
| 308
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-core/src/main/java/com/hellokaton/blade/watcher/EnvironmentWatcher.java
|
EnvironmentWatcher
|
run
|
class EnvironmentWatcher implements Runnable {
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
if (BladeConst.CLASSPATH.endsWith(".jar")) {
return;
}
final Path path = Paths.get(BladeConst.CLASSPATH);
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
// start an infinite loop
while (true) {
final WatchKey key = watchService.take();
for (WatchEvent<?> watchEvent : key.pollEvents()) {
final WatchEvent.Kind<?> kind = watchEvent.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
// get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final String filename = watchEventPath.context().toString();
// print it out
if (log.isDebugEnabled()) {
log.debug("⬢ {} -> {}", kind, filename);
}
if (kind == StandardWatchEventKinds.ENTRY_DELETE &&
filename.startsWith(".app") && filename.endsWith(".properties.swp")) {
// reload env
log.info("⬢ Reload environment");
Environment environment = Environment.of("classpath:" + filename.substring(1, filename.length() - 4));
WebContext.blade().environment(environment);
// notify
WebContext.blade().eventManager().fireEvent(EventType.ENVIRONMENT_CHANGED, new Event().attribute("environment", environment));
}
}
// reset the keyf
boolean valid = key.reset();
// exit loop if the key is not valid (if the directory was
// deleted, for
if (!valid) {
break;
}
}
} catch (IOException | InterruptedException ex) {
log.error("Environment watch error", ex);
}
| 38
| 503
| 541
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-examples/src/main/java/com/example/Application.java
|
Application
|
index
|
class Application {
@GET("/hello")
public Map<String, Object> hello(Request req) {
Map<String, Object> result = new HashMap<>();
result.put("name", "hellokaton");
result.putAll(req.queryParams());
return result;
}
@POST("/read_body")
public String readBody(@Body String body) {
log.info("读取到 body = {}", body);
return body;
}
@POST("/form_data")
public String formData(Request req, @Form Integer age) {
log.info("读取到 form = {}", req.formParams());
log.info("读取到 age = {}", age);
return "hello";
}
@DELETE("/users/:uid")
public RestResponse<?> deleteUser(@PathParam String uid) {
log.info("删除 uid = {}", uid);
return RestResponse.success(uid);
}
@POST(value = "/upload", responseType = ResponseType.TEXT)
public String upload(@Multipart FileItem fileItem) throws IOException {
log.info("读取到 fileItem = {}", fileItem);
fileItem.moveTo(new File(fileItem.getFileName()));
return fileItem.getFileName();
}
@GET
public String index(Request req) {<FILL_FUNCTION_BODY>}
@GET(value = "home", responseType = ResponseType.VIEW)
public String home() {
return "home.html";
}
@POST
public String verifyToken(Request req) {
System.out.println("token = " + req.header("X-CSRF-TOKEN"));
return "nice.. :)";
}
@GET(value = "/preview/:id", responseType = ResponseType.PREVIEW)
public void preview(@PathParam String id, Response response) throws IOException {
response.write(new File("/Users/biezhi/Downloads/146373013842336153820220427172437.pdf"));
}
@GET(value = "/file/:id", responseType = ResponseType.STREAM)
public void download(@PathParam String id, Response response) throws Exception {
response.write("abcd.pdf", new File("/Users/biezhi/Downloads/146373013842336153820220427172437.pdf"));
}
@ANY(value = "/hello/:id", responseType = ResponseType.JSON)
public RestResponse<String> helloAny(@PathParam String id) {
return RestResponse.success(id);
}
@GET(value = "/ss", responseType = ResponseType.PREVIEW)
public StaticFileBody staticFile() {
return StaticFileBody.of("/static/main.css");
}
@GET(value = "/img")
public void img(Response response) throws IOException {
ByteBufOutputStream out = new ByteBufOutputStream(Unpooled.buffer());
BufferedImage image = drawImage();
ImageIO.write(image, "PNG", out);
response.contentType("image/png");
response.body(new ByteBody(out.buffer()));
}
private BufferedImage drawImage() {
BufferedImage image = new BufferedImage(200, 250, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.BLACK);
Ellipse2D.Double ellipse = new Ellipse2D.Double(20, 20, 100, 100);
graphics.draw(ellipse);
graphics.dispose();
return image;
}
@GET(value = "/public/**", responseType = ResponseType.PREVIEW)
public StaticFileBody publicDir() {
return StaticFileBody.of("/static/");
}
public static void main(String[] args) {
CorsOptions corsOptions = CorsOptions.forAnyOrigin().allowNullOrigin().allowCredentials();
LimitOptions limitOptions = LimitOptions.create();
limitOptions.setExpression("1/s");
Blade.create()
.cors(corsOptions)
.http(HttpOptions::enableSession)
.get("/base/:uid", ctx -> {
ctx.text(ctx.pathString("uid"));
})
.get("/base/:uid/hello", ctx -> {
ctx.text(ctx.pathString("uid") + ": hello");
})
.before("/**", ctx -> {
System.out.println("bebebebebe");
})
// .use(new CsrfMiddleware())
// .use(new LimitMiddleware(limitOptions))
.start(Application.class, args);
}
}
|
String token = req.attribute("_csrf_token");
System.out.println("token = " + token);
token = null == token ? "token is null" : token;
return token;
| 1,268
| 53
| 1,321
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/Ansi.java
|
Ansi
|
format
|
class Ansi {
// Color code strings from:
// http://www.topmudsites.com/forums/mud-coding/413-java-ansi.html
public static final String SANE = "\u001B[0m";
public static final String HIGH_INTENSITY = "\u001B[1m";
public static final String LOW_INTENSITY = "\u001B[2m";
public static final String ITALIC = "\u001B[3m";
public static final String UNDERLINE = "\u001B[4m";
public static final String BLINK = "\u001B[5m";
public static final String RAPID_BLINK = "\u001B[6m";
public static final String REVERSE_VIDEO = "\u001B[7m";
public static final String INVISIBLE_TEXT = "\u001B[8m";
public static final String BLACK = "\u001B[30m";
public static final String RED = "\u001B[31m";
public static final String GREEN = "\u001B[32m";
public static final String YELLOW = "\u001B[33m";
public static final String BLUE = "\u001B[34m";
public static final String MAGENTA = "\u001B[35m";
public static final String CYAN = "\u001B[36m";
public static final String WHITE = "\u001B[37m";
public static final String BACKGROUND_BLACK = "\u001B[40m";
public static final String BACKGROUND_RED = "\u001B[41m";
public static final String BACKGROUND_GREEN = "\u001B[42m";
public static final String BACKGROUND_YELLOW = "\u001B[43m";
public static final String BACKGROUND_BLUE = "\u001B[44m";
public static final String BACKGROUND_MAGENTA = "\u001B[45m";
public static final String BACKGROUND_CYAN = "\u001B[46m";
public static final String BACKGROUND_WHITE = "\u001B[47m";
public static final Ansi HighIntensity = new Ansi(HIGH_INTENSITY);
public static final Ansi Bold = HighIntensity;
public static final Ansi LowIntensity = new Ansi(LOW_INTENSITY);
public static final Ansi Normal = LowIntensity;
public static final Ansi Italic = new Ansi(ITALIC);
public static final Ansi Underline = new Ansi(UNDERLINE);
public static final Ansi Blink = new Ansi(BLINK);
public static final Ansi RapidBlink = new Ansi(RAPID_BLINK);
public static final Ansi Black = new Ansi(BLACK);
public static final Ansi Red = new Ansi(RED);
public static final Ansi Green = new Ansi(GREEN);
public static final Ansi Yellow = new Ansi(YELLOW);
public static final Ansi Blue = new Ansi(BLUE);
public static final Ansi Magenta = new Ansi(MAGENTA);
public static final Ansi Cyan = new Ansi(CYAN);
public static final Ansi White = new Ansi(WHITE);
public static final Ansi BgBlack = new Ansi(BACKGROUND_BLACK);
public static final Ansi BgRed = new Ansi(BACKGROUND_RED);
public static final Ansi BgGreen = new Ansi(BACKGROUND_GREEN);
public static final Ansi BgYellow = new Ansi(BACKGROUND_YELLOW);
public static final Ansi BgBlue = new Ansi(BACKGROUND_BLUE);
public static final Ansi BgMagenta = new Ansi(BACKGROUND_MAGENTA);
public static final Ansi BgCyan = new Ansi(BACKGROUND_CYAN);
public static final Ansi BgWhite = new Ansi(BACKGROUND_WHITE);
final private String[] codes;
final private String codes_str;
public Ansi(String... codes) {
this.codes = codes;
String _codes_str = "";
for (String code : codes) {
_codes_str += code;
}
codes_str = _codes_str;
}
public Ansi and(Ansi other) {
List<String> both = new ArrayList<String>();
Collections.addAll(both, codes);
Collections.addAll(both, other.codes);
return new Ansi(both.toArray(new String[]{}));
}
public String colorize(String original) {
return codes_str + original + SANE;
}
public String format(String template, Object... args) {<FILL_FUNCTION_BODY>}
}
|
if (isWindows()) {
if (null == args || args.length == 0) {
return template;
}
return String.format(template, args);
}
String text = (null == args || args.length == 0) ? template : String.format(template, args);
return colorize(text);
| 1,340
| 83
| 1,423
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/Assert.java
|
Assert
|
notEmpty
|
class Assert {
public static void greaterThan(double num, double exp, String msg) {
if (num < exp) {
throw new IllegalArgumentException(msg);
}
}
public static void notNull(Object object, String msg) {
if (null == object) {
throw new IllegalArgumentException(msg);
}
}
public static void notEmpty(String str, String msg) {<FILL_FUNCTION_BODY>}
public static <T> void notEmpty(T[] arr, String msg) {
if (null == arr || arr.length == 0) {
throw new IllegalArgumentException(msg);
}
}
public static <T> T wrap(Callable<T> callable) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void packageNotEmpty(Class<?> clazz,String msg){
if (clazz.getPackage() == null) {
throw new IllegalArgumentException("[" + clazz.getName() + ".java] " + msg);
}
}
}
|
if (null == str || "".equals(str)) {
throw new IllegalArgumentException(msg);
}
| 287
| 30
| 317
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/BeanKit.java
|
BeanKit
|
copy
|
class BeanKit {
public static <T> T copy(Object origin, Class<T> destCls) {
T dest = ReflectKit.newInstance(destCls);
copy(origin, dest);
return dest;
}
public static void copy(Object origin, Object dest) {<FILL_FUNCTION_BODY>}
}
|
String fileName, str, getName, setName;
List<Field> fields = new ArrayList<>();
Method getMethod;
Method setMethod;
try {
Class<?> c1 = origin.getClass();
Class<?> c2 = dest.getClass();
Class<?> c1Superclass = c1.getSuperclass();
Class<?> c2Superclass = c2.getSuperclass();
List<Field> fs1 = new ArrayList<>(Arrays.asList(c1.getDeclaredFields()));
while (!c1Superclass.equals(Object.class)) {
List<Field> parentFields = Arrays.asList(c1Superclass.getDeclaredFields());
fs1.addAll(parentFields);
c1Superclass = c1Superclass.getSuperclass();
}
List<Field> fs2 = new ArrayList<>(Arrays.asList(c2.getDeclaredFields()));
while (!c2Superclass.equals(Object.class)) {
List<Field> parentFields = Arrays.asList(c2Superclass.getDeclaredFields());
fs2.addAll(parentFields);
c2Superclass = c2Superclass.getSuperclass();
}
// two class attributes exclude different attributes, leaving only the same attributes.
for (Field aFs2 : fs2) {
for (Field aFs1 : fs1) {
if (aFs1.getName().equals(aFs2.getName())) {
fields.add(aFs1);
break;
}
}
}
if (fields.size() > 0) {
for (Field f : fields) {
fileName = f.getName();
// capitalize the first letter of the property name.
str = fileName.substring(0, 1).toUpperCase();
// getXXX and setXXX
getName = "get" + str + fileName.substring(1);
setName = "set" + str + fileName.substring(1);
try {
getMethod = c1.getMethod(getName);
setMethod = c2.getMethod(setName, f.getType());
if (null != getMethod && null != setMethod) {
Object o = getMethod.invoke(origin);
if (null != o) {
setMethod.invoke(dest, o);
}
}
} catch (NoSuchMethodException e) {
}
}
}
} catch (Exception e) {
throw new BeanCopyException(e);
}
| 91
| 651
| 742
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/CaseInsensitiveHashMap.java
|
CaseInsensitiveHashMap
|
put
|
class CaseInsensitiveHashMap<V> extends LinkedHashMap<String, V> {
private final Map<String, String> KEY_MAPPING;
public CaseInsensitiveHashMap() {
super();
KEY_MAPPING = new HashMap<>();
}
public CaseInsensitiveHashMap(int initialCapacity) {
super(initialCapacity);
KEY_MAPPING = new HashMap<>(initialCapacity);
}
public CaseInsensitiveHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
this.KEY_MAPPING = new HashMap<>(initialCapacity);
}
@Override
public boolean containsKey(Object key) {
return super.containsKey(realKey(key));
}
@Override
public V get(Object key) {
return super.get(realKey(key));
}
@Override
public V put(String key, V value) {<FILL_FUNCTION_BODY>}
@Override
public void putAll(Map<? extends String, ? extends V> m) {
m.forEach(this::put);
}
@Override
public V remove(Object key) {
Object realKey;
if (key != null) {
realKey = KEY_MAPPING.remove(key.toString().toLowerCase(Locale.ENGLISH));
} else {
realKey = null;
}
return super.remove(realKey);
}
@Override
public V getOrDefault(Object key, V defaultValue) {
//当 lowerCaseMap 中不包含当前key时直接返回默认值
if (key != null && !KEY_MAPPING.containsKey(key.toString().toLowerCase(Locale.ENGLISH))) {
return defaultValue;
}
//转换key之后从super中获取值
return super.getOrDefault(realKey(key), defaultValue);
}
@Override
public void clear() {
KEY_MAPPING.clear();
super.clear();
}
private Object realKey(Object key) {
if (key != null) {
return KEY_MAPPING.get(key.toString().toLowerCase(Locale.ENGLISH));
} else {
return null;
}
}
}
|
if (key == null) {
return super.put(null, value);
} else {
String oldKey = KEY_MAPPING.put(key.toLowerCase(Locale.ENGLISH), key);
V oldValue = super.remove(oldKey);
super.put(key, value);
return oldValue;
}
| 598
| 90
| 688
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends V>) ,public void <init>(int, float) ,public void <init>(int, float, boolean) ,public void clear() ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,V>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super V>) ,public V get(java.lang.Object) ,public V getOrDefault(java.lang.Object, V) ,public Set<java.lang.String> keySet() ,public void replaceAll(BiFunction<? super java.lang.String,? super V,? extends V>) ,public Collection<V> values() <variables>final boolean accessOrder,transient Entry<java.lang.String,V> head,private static final long serialVersionUID,transient Entry<java.lang.String,V> tail
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/CollectionKit.java
|
CollectionKit
|
newSets
|
class CollectionKit {
/**
* Determines whether an array is empty
*
* @param array array object
* @param <T> array type
* @return return array is empty
*/
public static <T> boolean isEmpty(T[] array) {
return null == array || array.length == 0;
}
/**
* Determines whether an array is not empty
*
* @param array array object
* @param <T> array type
* @return return array is not empty
*/
public static <T> boolean isNotEmpty(T[] array) {
return null != array && array.length > 0;
}
/**
* Determines whether an collection is empty
*
* @param collection collection object
* @param <T> collection type
* @return return collection is empty
*/
public static <T> boolean isEmpty(Collection<T> collection) {
return null == collection || collection.size() == 0;
}
/**
* Determines whether an collection is not empty
*
* @param collection collection object
* @param <T> collection type
* @return return collection is not empty
*/
public static <T> boolean isNotEmpty(Collection<T> collection) {
return null != collection && collection.size() > 0;
}
/**
* New HashMap
*
* @param <K> HashMap Key type
* @param <V> HashMap Value type
* @return return HashMap
*/
public static <K, V> HashMap<K, V> newMap() {
return new HashMap<>();
}
/**
* New HashMap and initialCapacity
*
* @param initialCapacity initialCapacity
* @param <K> HashMap Key type
* @param <V> HashMap Value type
* @return return HashMap
*/
public static <K, V> HashMap<K, V> newMap(int initialCapacity) {
return new HashMap<>(initialCapacity);
}
/**
* New ConcurrentMap
*
* @param <K> ConcurrentMap Key type
* @param <V> ConcurrentMap Value type
* @return return ConcurrentMap
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new ConcurrentHashMap<>();
}
/**
* New ConcurrentMap and initialCapacity
*
* @param initialCapacity initialCapacity
* @param <K> ConcurrentMap Key type
* @param <V> ConcurrentMap Value type
* @return return ConcurrentMap
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap(int initialCapacity) {
return new ConcurrentHashMap<>(initialCapacity);
}
/**
* New List and add values
*
* @param values list values
* @param <T> list type
* @return return array list
*/
@SafeVarargs
public static <T> List<T> newLists(T... values) {
if(null == values || values.length == 0){
Assert.notNull(values, "values not is null.");
}
return Arrays.asList(values);
}
/**
* New Set and add values
*
* @param values set values
* @param <T> set type
* @return return HashSet
*/
@SafeVarargs
public static <T> Set<T> newSets(T... values) {<FILL_FUNCTION_BODY>}
}
|
if(null == values || values.length == 0){
Assert.notNull(values, "values not is null.");
}
return new HashSet<>(Arrays.asList(values));
| 928
| 51
| 979
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/ExceptionKit.java
|
ExceptionKit
|
rethrowBiConsumer
|
class ExceptionKit {
@FunctionalInterface
public interface ConsumerWithExceptions<T, E extends Exception> {
void accept(T t) throws E;
}
@FunctionalInterface
public interface BiConsumerWithExceptions<T, U, E extends Exception> {
void accept(T t, U u) throws E;
}
@FunctionalInterface
public interface FunctionWithExceptions<T, R, E extends Exception> {
R apply(T t) throws E;
}
@FunctionalInterface
public interface SupplierWithExceptions<T, E extends Exception> {
T get() throws E;
}
@FunctionalInterface
public interface RunnableWithExceptions<E extends Exception> {
void run() throws E;
}
/**
* .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name)))); or .forEach(rethrowConsumer(ClassNameUtil::println));
*/
public static <T, E extends Exception> Consumer<T> rethrowConsumer(ConsumerWithExceptions<T, E> consumer) throws E {
return t -> {
try {
consumer.accept(t);
} catch (Exception exception) {
throwAsUnchecked(exception);
}
};
}
public static <T, U, E extends Exception> BiConsumer<T, U> rethrowBiConsumer(BiConsumerWithExceptions<T, U, E> biConsumer) throws E {<FILL_FUNCTION_BODY>}
/**
* .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
*/
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(FunctionWithExceptions<T, R, E> function) throws E {
return t -> {
try {
return function.apply(t);
} catch (Exception exception) {
throwAsUnchecked(exception);
return null;
}
};
}
/**
* rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))),
*/
public static <T, E extends Exception> Supplier<T> rethrowSupplier(SupplierWithExceptions<T, E> function) throws E {
return () -> {
try {
return function.get();
} catch (Exception exception) {
throwAsUnchecked(exception);
return null;
}
};
}
/**
* uncheck(() -> Class.forName("xxx"));
*/
public static void uncheck(RunnableWithExceptions t) {
try {
t.run();
} catch (Exception exception) {
throwAsUnchecked(exception);
}
}
/**
* uncheck(() -> Class.forName("xxx"));
*/
public static <R, E extends Exception> R uncheck(SupplierWithExceptions<R, E> supplier) {
try {
return supplier.get();
} catch (Exception exception) {
throwAsUnchecked(exception);
return null;
}
}
/**
* uncheck(Class::forName, "xxx");
*/
public static <T, R, E extends Exception> R uncheck(FunctionWithExceptions<T, R, E> function, T t) {
try {
return function.apply(t);
} catch (Exception exception) {
throwAsUnchecked(exception);
return null;
}
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwAsUnchecked(Exception exception) throws E { throw (E) exception; }
}
|
return (t, u) -> {
try {
biConsumer.accept(t, u);
} catch (Exception exception) {
throwAsUnchecked(exception);
}
};
| 959
| 54
| 1,013
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/I18nKit.java
|
I18nKit
|
toLocaleModel
|
class I18nKit {
private static Map<String, ResourceHolder> CACHE = new ConcurrentHashMap<>();
private static Pattern pattern = Pattern.compile("_");
public static synchronized ResourceHolder getInstance(String baseName) {
return createResourceHolder(baseName, null);
}
public static synchronized ResourceHolder getInstance(Locale locale) {
return createResourceHolder(null, locale);
}
private static ResourceHolder createResourceHolder(String baseName, Locale locale) {
Tuple2<String, Locale> localeModel = toLocaleModel(baseName, locale);
ResourceHolder holder = CACHE.get(localeModel._1());
if (null != holder) {
return holder;
}
holder = new ResourceHolder(ResourceBundle.getBundle(localeModel._1(), localeModel._2()));
CACHE.putIfAbsent(localeModel._1(), holder);
return holder;
}
public static Tuple2<String, Locale> toLocaleModel(String baseName, Locale locale) {<FILL_FUNCTION_BODY>}
public static class ResourceHolder {
private ResourceBundle resourceBundle;
public ResourceHolder(ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
}
public String get(String key) {
return resourceBundle.getString(key);
}
public Object getObject(String key) {
return resourceBundle.getObject(key);
}
public boolean containsKey(String key) {
return resourceBundle.containsKey(key);
}
public String format(String key, String... params) {
return MessageFormat.format(resourceBundle.getString(key), params);
}
}
}
|
if (StringKit.isBlank(baseName)) {
if (StringKit.isEmpty(locale.getCountry())) {
return new Tuple2<>("i18n_" + locale.getLanguage(), locale);
}
return new Tuple2<>("i18n_" + locale.getLanguage() + "_" + locale.getCountry(), locale);
} else {
String[] baseNames = pattern.split(baseName);
if (baseNames != null && baseNames.length == 3) {
return new Tuple2<>(baseName, new Locale(baseNames[1], baseNames[2]));
}
throw new IllegalArgumentException("baseName illegal,name format is :i18n_{language}_{country}.properties," +
"for example:i18n_zh_CN.properties");
}
| 437
| 204
| 641
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/IOKit.java
|
IOKit
|
closeQuietly
|
class IOKit {
public static void closeQuietly(Closeable closeable) {<FILL_FUNCTION_BODY>}
public static String readToString(String file) throws IOException {
return readToString(Paths.get(file));
}
public static String readToString(BufferedReader bufferedReader) {
return bufferedReader.lines().collect(Collectors.joining(System.lineSeparator()));
}
public static String readToString(Path path) throws IOException {
BufferedReader bufferedReader = Files.newBufferedReader(path);
return bufferedReader.lines().collect(Collectors.joining(System.lineSeparator()));
}
public static String readToString(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
return buffer.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
public static void copyFile(File source, File dest) throws IOException {
try (FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel()) {
out.transferFrom(in, 0, in.size());
}
}
public static void compressGZIP(File input, File output) throws IOException {
try (GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(output))) {
try (FileInputStream in = new FileInputStream(input)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
}
}
public static byte[] compressGZIPAsString(String content, Charset charset) throws IOException {
if (content == null || content.length() == 0) {
return null;
}
GZIPOutputStream gzip;
ByteArrayOutputStream out = new ByteArrayOutputStream();
gzip = new GZIPOutputStream(out);
gzip.write(content.getBytes(charset));
gzip.close();
return out.toByteArray();
}
}
|
try {
if (null == closeable) {
return;
}
closeable.close();
} catch (Exception e) {
log.error("Close closeable error", e);
}
| 551
| 56
| 607
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/JsonKit.java
|
JsonKit
|
toJson
|
class JsonKit {
private static final Gson gson;
static {
gson = new GsonBuilder()
.disableHtmlEscaping()
.registerTypeAdapter(LocalDate.class, new JsonKit.LocalDateAdapter())
.registerTypeAdapter(LocalDateTime.class, new JsonKit.LocalDateTimeAdapter())
.registerTypeAdapter(new TypeToken<Map<String, Object>>() {
}.getType(), new MapDeserializerDoubleAsIntFix())
.create();
}
public String toString(Object object) {
return toJson(object);
}
public static <T> T fromJson(String json, Class<T> clazz) {
if (StringKit.isEmpty(json)) return null;
if (clazz == null) {
return gson.fromJson(json, new TypeToken<Map<String, Object>>() {
}.getType());
}
return gson.fromJson(json, clazz);
}
public static <T> T fromJson(String json, Type typeOfT) {
if (StringKit.isEmpty(json)) return null;
return gson.fromJson(json, typeOfT);
}
public static <T> T fromJson(String json, TypeToken<T> typeRef) {
if (StringKit.isEmpty(json)) return null;
return gson.fromJson(json, typeRef.getType());
}
public static <T> String toJson(T value) {
if (value == null) return null;
if (value instanceof String) return (String) value;
return gson.toJson(value);
}
public static <T> String toJson(T value, boolean pretty) {<FILL_FUNCTION_BODY>}
public static <T> String toJson(T value, final String... ignorePropertyNames) {
if (null == ignorePropertyNames) return toJson(value);
return new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.addSerializationExclusionStrategy(new PropertyNameExclusionStrategy(ignorePropertyNames))
.create()
.toJson(value);
}
public static GsonBuilder newBuilder() {
return gson.newBuilder();
}
final static class LocalDateAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {
@Override
public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
@Override
public LocalDate deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
String timestamp = element.getAsJsonPrimitive().getAsString();
return LocalDate.parse(timestamp, DateTimeFormatter.ISO_LOCAL_DATE);
}
}
final static class LocalDateTimeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
@Override
public JsonElement serialize(LocalDateTime date, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}
@Override
public LocalDateTime deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
String timestamp = element.getAsJsonPrimitive().getAsString();
return LocalDateTime.parse(timestamp, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
// public Ason<?, ?> toAson(String value) {
// return defaultJsonSupport.toAson(value);
// }
}
|
if (!pretty) {
return toJson(value);
}
if (value == null) return null;
if (value instanceof String) return (String) value;
return gson.newBuilder().setPrettyPrinting().create().toJson(value);
| 943
| 68
| 1,011
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/NamedThreadFactory.java
|
NamedThreadFactory
|
newThread
|
class NamedThreadFactory implements ThreadFactory {
private final String prefix;
private final LongAdder threadNumber = new LongAdder();
public NamedThreadFactory(String prefix) {
this.prefix = prefix;
}
@Override
public Thread newThread(Runnable runnable) {<FILL_FUNCTION_BODY>}
}
|
threadNumber.add(1);
return new Thread(runnable, prefix + "thread-" + threadNumber.intValue());
| 91
| 34
| 125
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/PasswordKit.java
|
PasswordKit
|
checkPassword
|
class PasswordKit {
// Define the BCrypt workload to use when generating password hashes. 10-31 is a valid value.
private static final int workload = 12;
/**
* This method can be used to generate a string representing an account password
* suitable for storing in a database. It will be an OpenBSD-style crypt(3) formatted
* hash string of length=60
* The bcrypt workload is specified in the above static variable, a value from 10 to 31.
* A workload of 12 is a very reasonable safe default as of 2013.
* This automatically handles secure 128-bit salt generation and storage within the hash.
*
* @param plaintext The account's plaintext password as provided during account creation,
* or when changing an account's password.
* @return String - a string of length 60 that is the bcrypt hashed password in crypt(3) format.
*/
public static String hashPassword(String plaintext) {
String salt = BCrypt.gensalt(workload);
return BCrypt.hashpw(plaintext, salt);
}
/**
* This method can be used to verify a computed hash from a plaintext (e.g. during a login
* request) with that of a stored hash from a database. The password hash from the database
* must be passed as the second variable.
*
* @param plaintext The account's plaintext password, as provided during a login request
* @param storedHash The account's stored password hash, retrieved from the authorization database
* @return boolean - true if the password matches the password of the stored hash, false otherwise
*/
public static boolean checkPassword(String plaintext, String storedHash) {<FILL_FUNCTION_BODY>}
}
|
boolean password_verified;
if (null == storedHash || !storedHash.startsWith("$2a$"))
throw new IllegalArgumentException("Invalid hash provided for comparison");
password_verified = BCrypt.checkpw(plaintext, storedHash);
return (password_verified);
| 451
| 76
| 527
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/PathKit.java
|
TrieRouter
|
addNode
|
class TrieRouter {
private final Node root;
public TrieRouter() {
this.root = new Node();
this.root.path = "/";
this.root.segment = "/";
}
// add route
public TrieRouter addRoute(String path) {
if (StringKit.isEmpty(path)) {
return this;
}
String strippedPath = StringKit.strip(path, "/");
String[] strings = strippedPath.split("/");
if (strings.length != 0) {
Node node = root;
// split by /
for (String segment : strings) {
node = addNode(node, segment);
if ("**".equals(segment)) {
break;
}
}
// At the end, set the path of the child node
node.path = path;
}
return this;
}
// add note
private Node addNode(Node node, String segment) {<FILL_FUNCTION_BODY>}
// match route
public String matchRoute(String path) {
if (StringKit.isEmpty(path)) {
return null;
}
String strippedPath = StringKit.strip(path, "/");
String[] strings = strippedPath.split("/");
if (strings.length != 0) {
Node node = root;
// split by /
for (String segment : strings) {
node = matchNode(node, segment);
// if no route is matched or a wildcard route is used, break:
if (node == null || node.isWildcard) {
break;
}
}
if (node != null) {
return node.path;
}
}
return null;
}
public boolean match(String path) {
return matchRoute(path) != null;
}
// match child node
private Node matchNode(Node node, String segment) {
if (node.staticRouters != null && node.staticRouters.containsKey(segment)) {
return node.staticRouters.get(segment);
}
if (node.dynamicRouter != null)
return node.dynamicRouter;
if (node.isWildcard)
return node;
return null;
}
}
|
// If it is a wildcard node, return the current node directly:
if ("**".equals(segment)) {
node.isWildcard = true;
return node;
}
// if it is a dynamic route,
// create a child node and then hang the child node under the current node:
if (segment.startsWith(":")) {
Node childNode = new Node();
childNode.segment = segment;
node.dynamicRouter = childNode;
return childNode;
}
Node childNode;
// Static route, put in a Map,
// the key of the Map is the URL segment, value is the new child node:
if (node.staticRouters == null) {
node.staticRouters = new HashMap<>();
}
if (node.staticRouters.containsKey(segment)) {
childNode = node.staticRouters.get(segment);
} else {
childNode = new Node();
childNode.segment = segment;
node.dynamicRouter = childNode;
node.staticRouters.put(segment, childNode);
}
return childNode;
| 588
| 297
| 885
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/Tuple2.java
|
Tuple2
|
equals
|
class Tuple2<K, V> implements Serializable {
private final K k;
private final V v;
public Tuple2(K k, V v) {
this.k = k;
this.v = v;
}
public K getK() {
return k;
}
public V getV() {
return v;
}
public K _1() {
return k;
}
public V _2() {
return v;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(k, v);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tuple2<?, ?> tuple2 = (Tuple2<?, ?>) o;
return Objects.equals(k, tuple2.k) &&
Objects.equals(v, tuple2.v);
| 189
| 88
| 277
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/UncheckedFnKit.java
|
UncheckedFnKit
|
biConsumer
|
class UncheckedFnKit {
@FunctionalInterface
public interface Consumer_WithExceptions<T, E extends Throwable> {
void accept(T t) throws E;
}
@FunctionalInterface
public interface BiConsumer_WithExceptions<T, U, E extends Throwable> {
void accept(T t, U u) throws E;
}
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Throwable> {
R apply(T t) throws E;
}
@FunctionalInterface
public interface Supplier_WithExceptions<T, E extends Throwable> {
T get() throws E;
}
@FunctionalInterface
public interface Runnable_WithExceptions<E extends Throwable> {
void run() throws E;
}
public static <T> Consumer<T> consumer(Consumer_WithExceptions<T, Throwable> consumer) {
return t -> {
try {
consumer.accept(t);
} catch (Throwable throwable) {
throw new BladeException(throwable);
}
};
}
public static <T, U> BiConsumer<T, U> biConsumer(BiConsumer_WithExceptions<T, U, Throwable> biConsumer) {<FILL_FUNCTION_BODY>}
public static <T, R> Function<T, R> function(Function_WithExceptions<T, R, Throwable> function) {
return t -> {
try {
return function.apply(t);
} catch (Throwable throwable) {
throw new BladeException(throwable);
}
};
}
public static <T> Supplier<T> supplier(Supplier_WithExceptions<T, Throwable> function) {
return () -> {
try {
return function.get();
} catch (Throwable throwable) {
throw new BladeException(throwable);
}
};
}
public static Runnable runnable(Runnable_WithExceptions t) {
return ()-> {
try {
t.run();
} catch (Throwable throwable) {
throw new BladeException(throwable);
}
};
}
}
|
return (t, u) -> {
try {
biConsumer.accept(t, u);
} catch (Throwable throwable) {
throw new BladeException(throwable);
}
};
| 581
| 57
| 638
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-kit/src/main/java/com/hellokaton/blade/kit/json/MapDeserializerDoubleAsIntFix.java
|
MapDeserializerDoubleAsIntFix
|
read
|
class MapDeserializerDoubleAsIntFix implements JsonDeserializer<Map<String, Object>> {
@Override
public Map<String, Object> deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return (Map<String, Object>) read(jsonElement);
}
public Object read(JsonElement in) {<FILL_FUNCTION_BODY>}
}
|
if (in.isJsonArray()) {
List<Object> list = new ArrayList<>();
JsonArray arr = in.getAsJsonArray();
for (JsonElement anArr : arr) {
list.add(read(anArr));
}
return list;
} else if (in.isJsonObject()) {
Map<String, Object> map = new LinkedTreeMap<String, Object>();
JsonObject obj = in.getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
for (Map.Entry<String, JsonElement> entry : entitySet) {
map.put(entry.getKey(), read(entry.getValue()));
}
return map;
} else if (in.isJsonPrimitive()) {
JsonPrimitive prim = in.getAsJsonPrimitive();
if (prim.isBoolean()) {
return prim.getAsBoolean();
} else if (prim.isString()) {
return prim.getAsString();
} else if (prim.isNumber()) {
Number num = prim.getAsNumber();
// here you can handle double int/long values
// and return any type you want
// this solution will transform 3.0 float to long values
if (Math.ceil(num.doubleValue()) == num.longValue())
return num.longValue();
else {
return num.doubleValue();
}
}
}
return null;
| 114
| 364
| 478
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/auth/BasicAuthMiddleware.java
|
BasicAuthMiddleware
|
before
|
class BasicAuthMiddleware implements WebHook {
private String realm;
private List<AuthPair> authPairs = new ArrayList<>();
private Set<String> urlStartExclusions;
public BasicAuthMiddleware(AuthOption authOption) {
this.urlStartExclusions = authOption.getUrlStartExclusions();
this.realm = "Basic realm=\"" + authOption.getRealm() + "\"";
authOption.getAccounts().forEach((user, pass) -> this.authPairs.add(new AuthPair(user, authorizationHeader(user, pass))));
}
private String authorizationHeader(String user, String password) {
String base = user + ":" + password;
return "Basic " + Base64.getEncoder().encodeToString(base.getBytes(StandardCharsets.UTF_8));
}
private String searchCredential(String authValue) {
if (StringKit.isEmpty(authValue)) {
return null;
}
return authPairs.stream()
.filter(authPair -> authPair.getValue().equals(authValue))
.map(AuthPair::getUser)
.findFirst().orElse(null);
}
@Override
public boolean before(RouteContext context) {<FILL_FUNCTION_BODY>}
}
|
boolean isAuth = false;
for (String startExclusion : urlStartExclusions) {
if ("/".equals(startExclusion) || context.uri().startsWith(startExclusion)) {
isAuth = true;
break;
}
}
if (!isAuth) {
return true;
}
String authorization = context.header("Authorization");
String user = this.searchCredential(authorization);
if (null == user) {
context.header("WWW-Authenticate", this.realm).status(401);
return false;
}
return true;
| 332
| 162
| 494
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/csrf/CsrfMiddleware.java
|
CsrfMiddleware
|
before
|
class CsrfMiddleware implements WebHook {
private static final String JWT_SID_KEY = "sid";
private final CsrfOptions csrfOptions;
private final SecretKey secretKey;
public CsrfMiddleware() {
this(new CsrfOptions());
}
public CsrfMiddleware(CsrfOptions csrfOptions) {
this.csrfOptions = csrfOptions;
byte[] encodeKey = Decoders.BASE64.decode(csrfOptions.getSecret());
this.secretKey = Keys.hmacShaKeyFor(encodeKey);
}
@Override
public boolean before(RouteContext context) {<FILL_FUNCTION_BODY>}
private boolean verifyToken(Request request, String token) {
if (StringKit.isEmpty(token)) {
return false;
}
Session session = request.session();
try {
Jws<Claims> jws = Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token);
Claims body = jws.getBody();
String sid = (String) body.getOrDefault(JWT_SID_KEY, "");
return session.id().equals(sid);
} catch (Exception e) {
log.error("Request IP: {}, UA: {}, Token: {} parse error",
request.remoteAddress(), request.userAgent(), token, e);
return false;
}
}
protected String parseToken(Request request) {
String headerToken = request.header(csrfOptions.getHeaderKeyName());
if (StringKit.isEmpty(headerToken)) {
headerToken = request.form(csrfOptions.getFormKeyName(), "");
}
return headerToken;
}
protected String genToken(Request request) {
JwtBuilder jwtBuilder = Jwts.builder()
.setClaims(Collections.singletonMap(JWT_SID_KEY, request.session().id()))
.signWith(secretKey);
return jwtBuilder.compact();
}
}
|
if (!csrfOptions.isEnabled()) {
return true;
}
if (null == context.session()) {
return true;
}
if (csrfOptions.isExclusion(context.uri())) {
return true;
}
HttpMethod httpMethod = context.request().httpMethod();
// create token
if (HttpMethod.GET.equals(context.request().httpMethod())) {
String token = this.genToken(context.request());
context.attribute(csrfOptions.getAttrKeyName(), token);
return true;
}
// verify token
if (csrfOptions.getVerifyMethods().contains(httpMethod)) {
String token = this.parseToken(context.request());
boolean verified = verifyToken(context.request(), token);
if (verified) {
return true;
}
if (null != csrfOptions.getErrorHandler()) {
return csrfOptions.getErrorHandler().apply(context);
} else {
context.badRequest().json(RestResponse.fail("CSRF token mismatch :("));
return false;
}
}
return true;
| 548
| 288
| 836
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/csrf/CsrfOptions.java
|
CsrfOptions
|
isExclusion
|
class CsrfOptions {
private static final Set<HttpMethod> DEFAULT_VERIFY_METHODS = new HashSet<>(
Arrays.asList(HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE)
);
/**
* Enable csrf, default is enabled by default.
* <p>
* after this function is disabled, the middleware does not take effect.
*/
private boolean enabled = true;
/**
* The attribute name that puts csrf_token into the request context.
* <p>
* you can get this value from the template engine.
*/
private String attrKeyName = "_csrf_token";
/**
* The header name that carries the token in the request header.
*/
private String headerKeyName = "X-CSRF-TOKEN";
/**
* The form input name that carries the token in the request.
*/
private String formKeyName = "_csrf_token";
/**
* To generate a token key, change the value.
* <p>
* the token is generated in JWT mode.
*/
private String secret = "UXOwbPd+P0u8YyBkQbuyXiv7UVc1JmMS061HUuaDRms=";
/**
* A list of urls to exclude, which will not be limited by the frequency of requests.
* <p>
* for example:
* <p>
* /notify/**
* /upload/**
* /admin/roles/**
*/
private PathKit.TrieRouter router;
/**
* For the following set of request methods, tokens will need to be validated.
*/
private Set<HttpMethod> verifyMethods = DEFAULT_VERIFY_METHODS;
/**
* The processor that triggers the request frequency limit will, by default, prompt you for CSRF token mismatch.
*/
private Function<RouteContext, Boolean> errorHandler;
public static CsrfOptions create() {
return new CsrfOptions();
}
public CsrfOptions exclusion(@NonNull String... urls) {
if (null == this.router) {
this.router = PathKit.createRoute();
}
for (String url : urls) {
this.router.addRoute(url);
}
return this;
}
public boolean isExclusion(@NonNull String url) {<FILL_FUNCTION_BODY>}
}
|
if (null == this.router) {
return false;
}
return router.match(url);
| 632
| 31
| 663
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/limit/LimitExpression.java
|
Limiter
|
match
|
class Limiter {
double permitsPerSecond;
long warmupPeriod;
}
public static Limiter match(String expression) {<FILL_FUNCTION_BODY>
|
Matcher matcher = EXP_PATTERN.matcher(expression);
if (!matcher.matches()) {
return null;
}
int count = Integer.parseInt(matcher.group(1));
String period = matcher.group(2);
String unit = matcher.group(3);
String mode = matcher.group(4);
if (!TIME_TO_SECONDS.containsKey(unit)) {
return null;
}
if (null == period || period.isEmpty()) {
period = "1";
}
Limiter limiter = new Limiter();
if (null != mode && !mode.isEmpty()) {
limiter.permitsPerSecond = count;
limiter.warmupPeriod = TIME_TO_SECONDS.get(unit).multiply(new BigDecimal(period)).longValue();
} else {
limiter.permitsPerSecond = new BigDecimal(count).divide(TIME_TO_SECONDS.get(unit), RoundingMode.HALF_DOWN).doubleValue();
}
return limiter;
| 46
| 279
| 325
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/limit/LimitMiddleware.java
|
LimitMiddleware
|
before
|
class LimitMiddleware implements WebHook {
private final LimitOptions limitOptions;
@SuppressWarnings("UnstableApiUsage")
private final Map<String, RateLimiter> rateLimiterMap = new ConcurrentHashMap<>();
public LimitMiddleware() {
this(LimitOptions.create());
}
public LimitMiddleware(LimitOptions limitOptions) {
this.limitOptions = limitOptions;
this.initOptions(this.limitOptions);
}
private void initOptions(LimitOptions limitOptions) {
if (null == limitOptions.getLimitHandler()) {
limitOptions.setLimitHandler(ctx -> {
ctx.json(RestResponse.fail("Too Many Request :("));
return Boolean.FALSE;
});
}
if (null == limitOptions.getKeyFunc()) {
limitOptions.setKeyFunc(req -> EncryptKit.md5(req.remoteAddress() + req.uri() + req.method()));
}
}
@Override
public boolean before(RouteContext ctx) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("UnstableApiUsage")
protected RateLimiter createLimiter(String expression) {
LimitExpression.Limiter limiter = LimitExpression.match(expression);
if (null == limiter) {
throw new InternalErrorException("invalid limit mode :(");
}
if (limiter.warmupPeriod > 0) {
return RateLimiter.create(limiter.permitsPerSecond, limiter.warmupPeriod, TimeUnit.SECONDS);
}
return RateLimiter.create(limiter.permitsPerSecond);
}
}
|
if (!limitOptions.isEnabled()) {
return true;
}
if (limitOptions.isExclusion(ctx.uri())) {
return true;
}
Method action = ctx.routeAction();
Class<?> controller = action.getDeclaringClass();
Limit limit = action.getAnnotation(Limit.class);
if (null == limit) {
limit = controller.getAnnotation(Limit.class);
}
String key = limitOptions.getKeyFunc().apply(ctx.request());
if (null == limit) {
// global limit
if (!rateLimiterMap.containsKey(key)) {
rateLimiterMap.put(key, createLimiter(limitOptions.getExpression()));
}
// limit is triggered
if (!rateLimiterMap.get(key).tryAcquire()) {
return limitOptions.getLimitHandler().apply(ctx);
}
} else {
if (limit.disable()) {
return true;
}
// specific limit
if (!rateLimiterMap.containsKey(key)) {
rateLimiterMap.put(key, createLimiter(limit.value()));
}
// limit is triggered
if (!rateLimiterMap.get(key).tryAcquire()) {
return limitOptions.getLimitHandler().apply(ctx);
}
}
return true;
| 433
| 345
| 778
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/limit/LimitOptions.java
|
LimitOptions
|
isExclusion
|
class LimitOptions {
/**
* Enable request frequency limit, default is enabled by default.
* <p>
* after this function is disabled, the middleware does not take effect.
*/
private boolean enabled = true;
/**
* To determine the uniqueness of a Request, pass in a Request object.
* <p>
* The default is the md5(remote_host+request_uri+request_method)
*/
private Function<Request, String> keyFunc;
/**
* The processor that triggers the request frequency limit will, by default, prompt you for too many requests
*/
private Function<RouteContext, Boolean> limitHandler;
/**
* Use expressions to control request frequency.
* <p>
* for example:
* <p>
* 5/s allow 5 requests per second
* 5/1s allow 5 requests per second
* 5/1m allow 60 requests per minute
* 5/3s/warmup allow 5 requests in 3 seconds.
* after startup, there is a warm-up period to gradually increase the distribution frequency to the configured rate.
*/
private String expression = "5/s";
/**
* A list of urls to exclude, which will not be limited by the frequency of requests.
* <p>
* for example:
* <p>
* /notify/**
* /upload/**
* /admin/roles/**
*/
private PathKit.TrieRouter router;
public static LimitOptions create() {
return new LimitOptions();
}
public LimitOptions exclusion(@NonNull String... urls) {
if (null == this.router) {
this.router = PathKit.createRoute();
}
for (String url : urls) {
this.router.addRoute(url);
}
return this;
}
public boolean isExclusion(@NonNull String url) {<FILL_FUNCTION_BODY>}
}
|
if (null == this.router) {
return false;
}
return router.match(url);
| 510
| 31
| 541
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/xss/XssMiddleware.java
|
XssMiddleware
|
filterParameters
|
class XssMiddleware implements WebHook {
private final static HTMLFilter HTML_FILTER = new HTMLFilter();
private XssOption xssOption = XssOption.builder().build();
public XssMiddleware(XssOption xssOption) {
this.xssOption = xssOption;
}
@Override
public boolean before(RouteContext context) {
if (xssOption.isExclusion(context.uri())) {
return true;
}
this.filterHeaders(context.headers());
this.filterParameters(context.parameters());
if (context.contentType().toLowerCase().contains("json")) {
String body = context.bodyToString();
if (StringKit.isNotEmpty(body)) {
String filterBody = stripXSS(body);
context.body(new StringBody(filterBody));
}
}
return true;
}
protected void filterHeaders(Map<String, List<String>> headers) {
headers.forEach((key, values) -> {
List<String> newHeader = new ArrayList<>();
for (String value : values) {
newHeader.add(this.stripXSS(value));
}
headers.put(key, newHeader);
});
}
protected void filterParameters(Map<String, List<String>> parameters) {<FILL_FUNCTION_BODY>}
/**
* Removes all the potentially malicious characters from a string
*
* @param value the raw string
* @return the sanitized string
*/
protected String stripXSS(String value) {
return HTML_FILTER.filter(value);
}
}
|
Set<Map.Entry<String, List<String>>> entries = parameters.entrySet();
for (Map.Entry<String, List<String>> entry : entries) {
List<String> snzValues = entry.getValue().stream().map(this::stripXSS).collect(Collectors.toList());
parameters.put(entry.getKey(), snzValues);
}
| 422
| 94
| 516
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-security/src/main/java/com/hellokaton/blade/security/xss/XssOption.java
|
XssOption
|
isExclusion
|
class XssOption {
@Builder.Default
private Set<String> urlExclusions = new HashSet<>();
public XssOption exclusion(@NonNull String... urls) {
this.urlExclusions.addAll(Arrays.asList(urls));
return this;
}
public boolean isExclusion(@NonNull String url) {<FILL_FUNCTION_BODY>}
}
|
for (String excludeURL : this.urlExclusions) {
if (url.equals(excludeURL)) {
return true;
}
}
return false;
| 105
| 47
| 152
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-websocket/src/main/java/com/hellokaton/blade/websocket/WebSocketHandlerWrapper.java
|
WebSocketHandlerWrapper
|
wrapHandler
|
class WebSocketHandlerWrapper implements WebSocketHandler {
private final Map<String,Class<?>> handlers = new HashMap<>(4);
private final Map<String, Map<Class<? extends Annotation>, Method>> methodCache = new HashMap<>(4);
private final FastThreadLocal<String> path = new FastThreadLocal<>();
private final Blade blade;
public static WebSocketHandlerWrapper init(Blade blade) {
return new WebSocketHandlerWrapper(blade);
}
private WebSocketHandlerWrapper(Blade blade) {
this.blade = blade;
}
public void setPath(String path) {
this.path.set(path);
}
/**
* add @WebSocket handler mapper
*
* @param path
* @param handler
*/
public void wrapHandler(String path, Class<?> handler) {<FILL_FUNCTION_BODY>}
private static void cacheMethod(Map<Class<? extends Annotation>, Method> cache, Method[] methods, Class<? extends Annotation> filter) {
List<Method> methodList = Stream.of(methods)
.filter(method -> method.isAnnotationPresent(filter))
.collect(Collectors.toList());
if (methodList.size() == 1) {
cache.put(filter, methodList.get(0));
} else if (methodList.size() > 1) {
throw new RuntimeException("Duplicate annotation @" + filter.getSimpleName() + " in class: " + methodList.get(0).getDeclaringClass().getName());
}
}
@Override
public void onConnect(WebSocketContext ctx) {
invoke(ctx, OnOpen.class);
}
@Override
public void onText(WebSocketContext ctx) {
invoke(ctx, OnMessage.class);
}
@Override
public void onDisConnect(WebSocketContext ctx) {
invoke(ctx, OnClose.class);
}
/**
* invoke target handler methods
*
* @param ctx WebSocket context
* @param event WebSocket event type
*/
private void invoke(WebSocketContext ctx, Class<? extends Annotation> event) {
Map<Class<? extends Annotation>, Method> methodCache = this.methodCache.get(path.get());
if (methodCache != null) {
Method method = methodCache.get(event);
if (method != null) {
Class<?>[] paramTypes = method.getParameterTypes();
Object[] param = new Object[paramTypes.length];
try {
for (int i = 0; i < paramTypes.length; i++) {
Class<?> paramType = paramTypes[i];
if (paramType == WebSocketContext.class) {
param[i] = ctx;
} else {
Object bean = this.blade.getBean(paramType);
if (bean != null) {
param[i] = bean;
} else {
param[i] = ReflectKit.newInstance(paramType);
}
}
}
method.invoke(blade.getBean(handlers.get(path.get())), param);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
}
}
|
Method[] methods = handler.getMethods();
Map<Class<? extends Annotation>, Method> cache = new HashMap<>(3);
cacheMethod(cache, methods, OnOpen.class);
cacheMethod(cache, methods, OnMessage.class);
cacheMethod(cache, methods, OnClose.class);
if (cache.size() > 0) {
methodCache.put(path, cache);
handlers.put(path,handler);
} else {
throw new RuntimeException("Do not found any annotation of [@OnOpen / @OnMessage / @OnClose] in class: " + handler.getName());
}
| 842
| 156
| 998
|
<no_super_class>
|
lets-blade_blade
|
blade/blade-websocket/src/main/java/com/hellokaton/blade/websocket/netty/WebSocketHandler.java
|
WebSocketHandler
|
handleHttpRequest
|
class WebSocketHandler extends SimpleChannelInboundHandler<Object> {
private WebSocketServerHandshaker handshaker;
private WebSocketSession session;
private com.hellokaton.blade.websocket.WebSocketHandler handler;
private String uri;
private Blade blade;
public WebSocketHandler(Blade blade) {
this.blade = blade;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
handleHttpRequest(ctx, (HttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
initHandlerWrapper();
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
} else {
ReferenceCountUtil.retain(msg);
ctx.fireChannelRead(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) {<FILL_FUNCTION_BODY>}
/**
* Only supported TextWebSocketFrame
*
* @param ctx
* @param frame
*/
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
if (frame instanceof CloseWebSocketFrame) {
this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
CompletableFuture.completedFuture(new WebSocketContext(this.session,this.handler))
.thenAcceptAsync(this.handler::onDisConnect);
return;
}
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
return;
}
if (!(frame instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException("unsupported frame type: " + frame.getClass().getName());
}
CompletableFuture.completedFuture(new WebSocketContext(this.session,this.handler,((TextWebSocketFrame) frame).text()))
.thenAcceptAsync(this.handler::onText,ctx.executor());
}
private boolean isWebSocketRequest(HttpRequest req){
// return req != null
// && (this.handler = this.blade.routeMatcher().getWebSocket(req.uri())) != null
// && req.decoderResult().isSuccess()
// && "websocket".equals(req.headers().get("Upgrade"));
return false;
}
private void initHandlerWrapper(){
if(this.handler != null && this.handler instanceof WebSocketHandlerWrapper){
((WebSocketHandlerWrapper) this.handler).setPath(this.uri);
}
}
}
|
if (isWebSocketRequest(req)) {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.uri(), null, true);
this.handshaker = wsFactory.newHandshaker(req);
if (this.handshaker == null) {
//Return that we need cannot not support the web socket version
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
this.handshaker.handshake(ctx.channel(), req);
this.session = new WebSocketSession(ctx);
this.uri = req.uri();
initHandlerWrapper();
//Allows the user to send messages in the event of onConnect
CompletableFuture.completedFuture(new WebSocketContext(this.session,this.handler))
.thenAcceptAsync(this.handler::onConnect,ctx.executor());
}
} else {
ReferenceCountUtil.retain(req);
ctx.fireChannelRead(req);
}
| 689
| 253
| 942
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-benchmarks/src/main/java/io/github/bucket4j/benchmark/BaseLineWithoutSynchronization.java
|
OneThread
|
main
|
class OneThread {
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options opt = new OptionsBuilder()
.include(BaseLineWithoutSynchronization.class.getSimpleName())
.warmupIterations(10)
.measurementIterations(10)
.threads(1)
.forks(1)
.build();
new Runner(opt).run();
| 38
| 85
| 123
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-benchmarks/src/main/java/io/github/bucket4j/benchmark/ConsumeMostlySuccess.java
|
FourThreads
|
benchmark
|
class FourThreads {
public static void main(String[] args) throws RunnerException {
benchmark(4);
}
}
private static void benchmark(int threadCount) throws RunnerException {<FILL_FUNCTION_BODY>
|
Options opt = new OptionsBuilder()
.include(ConsumeMostlySuccess.class.getSimpleName())
.warmupIterations(10)
.measurementIterations(10)
.threads(threadCount)
.forks(1)
.build();
new Runner(opt).run();
| 64
| 85
| 149
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-benchmarks/src/main/java/io/github/bucket4j/benchmark/MemoryBenchmark.java
|
MemoryBenchmark
|
main
|
class MemoryBenchmark {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
public static class Bucket4jLayoutInvestigation {
}
}
|
System.out.println("Bucket4j: " + ClassLayout.parseClass(Bucket.class).toPrintable());
System.out.println("Guava: " + ClassLayout.parseClass(RateLimiter.class).toPrintable());
System.out.println("Resilience4j: " + ClassLayout.parseClass(AtomicRateLimiter.class).toPrintable());
System.out.println("Resilience4j.semaphoreBasedRateLimiter: " + ClassLayout.parseClass(io.github.resilience4j.ratelimiter.RateLimiter.class).toPrintable());
| 54
| 155
| 209
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-benchmarks/src/main/java/io/github/bucket4j/benchmark/TryConsumeMostlySuccess.java
|
FourThreads
|
benchmark
|
class FourThreads {
public static void main(String[] args) throws RunnerException {
benchmark(4);
}
}
private static void benchmark(int threadCount) throws RunnerException {<FILL_FUNCTION_BODY>
|
Options opt = new OptionsBuilder()
.include(TryConsumeMostlySuccess.class.getSimpleName())
.warmupIterations(10)
.measurementIterations(10)
.threads(threadCount)
.forks(1)
.addProfiler(GCProfiler.class)
.build();
new Runner(opt).run();
| 64
| 100
| 164
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-caffeine/src/main/java/io/github/bucket4j/caffeine/CaffeineProxyManager.java
|
CaffeineProxyManager
|
execute
|
class CaffeineProxyManager<K> extends AbstractProxyManager<K> {
private final Cache<K, RemoteBucketState> cache;
/**
* Creates new instance of {@link CaffeineProxyManager}
*
* @param builder the builder that will be used for cache creation
* @param keepAfterRefillDuration specifies how long bucket should be held in the cache after all consumed tokens have been refilled.
*/
public CaffeineProxyManager(Caffeine<? super K, ? super RemoteBucketState> builder, Duration keepAfterRefillDuration) {
this(builder, keepAfterRefillDuration, ClientSideConfig.getDefault());
}
public CaffeineProxyManager(Caffeine<? super K, ? super RemoteBucketState> builder, Duration keepAfterRefillDuration, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.cache = builder
.expireAfter(new Expiry<K, RemoteBucketState>() {
@Override
public long expireAfterCreate(K key, RemoteBucketState bucketState, long currentTime) {
long currentTimeNanos = getCurrentTime(clientSideConfig);
long nanosToFullRefill = bucketState.calculateFullRefillingTime(currentTimeNanos);
return nanosToFullRefill + keepAfterRefillDuration.toNanos();
}
@Override
public long expireAfterUpdate(K key, RemoteBucketState bucketState, long currentTime, long currentDuration) {
long currentTimeNanos = getCurrentTime(clientSideConfig);
long nanosToFullRefill = bucketState.calculateFullRefillingTime(currentTimeNanos);
return nanosToFullRefill + keepAfterRefillDuration.toNanos();
}
@Override
public long expireAfterRead(K key, RemoteBucketState bucketState, long currentTime, long currentDuration) {
long currentTimeNanos = getCurrentTime(clientSideConfig);
long nanosToFullRefill = bucketState.calculateFullRefillingTime(currentTimeNanos);
return nanosToFullRefill + keepAfterRefillDuration.toNanos();
}
})
.build();
}
/**
* Returns the cache that is used for storing the buckets
*
* @return the cache that is used for storing the buckets
*/
public Cache<K, RemoteBucketState> getCache() {
return cache;
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {<FILL_FUNCTION_BODY>}
@Override
public boolean isAsyncModeSupported() {
return true;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
CommandResult<T> result = execute(key, request);
return CompletableFuture.completedFuture(result);
}
@Override
public void removeProxy(K key) {
cache.asMap().remove(key);
}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
cache.asMap().remove(key);
return CompletableFuture.completedFuture(null);
}
private static long getCurrentTime(ClientSideConfig clientSideConfig) {
Optional<TimeMeter> clock = clientSideConfig.getClientSideClock();
return clock.isPresent() ? clock.get().currentTimeNanos() : System.currentTimeMillis() * 1_000_000;
}
}
|
CommandResult<T>[] resultHolder = new CommandResult[1];
cache.asMap().compute(key, (K k, RemoteBucketState previousState) -> {
Long clientSideTime = request.getClientSideTime();
long timeNanos = clientSideTime != null ? clientSideTime : System.currentTimeMillis() * 1_000_000;
MutableBucketEntry entryWrapper = new MutableBucketEntry(previousState == null ? null : previousState.copy());
resultHolder[0] = request.getCommand().execute(entryWrapper, timeNanos);
return entryWrapper.exists() ? entryWrapper.get() : null;
});
return resultHolder[0];
| 898
| 179
| 1,077
|
<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-coherence/src/main/java/io/github/bucket4j/grid/coherence/CoherenceProcessor.java
|
CoherenceProcessor
|
process
|
class CoherenceProcessor<K, T> extends AbstractProcessor<K, byte[], byte[]> implements ComparableByContent {
private static final long serialVersionUID = 1L;
private final byte[] requestBytes;
public CoherenceProcessor(Request<T> request) {
this.requestBytes = InternalSerializationHelper.serializeRequest(request);
}
public CoherenceProcessor(byte[] requestBytes) {
this.requestBytes = requestBytes;
}
public byte[] getRequestBytes() {
return requestBytes;
}
@Override
public byte[] process(InvocableMap.Entry<K, byte[]> entry) {<FILL_FUNCTION_BODY>}
@Override
public boolean equalsByContent(ComparableByContent other) {
CoherenceProcessor processor = (CoherenceProcessor) other;
return Arrays.equals(requestBytes, processor.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) {
entry.setValue(newStateBytes);
}
}.execute();
| 233
| 112
| 345
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-coherence/src/main/java/io/github/bucket4j/grid/coherence/CoherenceProxyManager.java
|
CoherenceProxyManager
|
executeAsync
|
class CoherenceProxyManager<K> extends AbstractProxyManager<K> {
private final NamedCache<K, byte[]> cache;
public CoherenceProxyManager(NamedCache<K, byte[]> cache) {
this(cache, ClientSideConfig.getDefault());
}
public CoherenceProxyManager(NamedCache<K, byte[]> cache, ClientSideConfig clientSideConfig) {
super(clientSideConfig);
this.cache = cache;
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
CoherenceProcessor<K, T> entryProcessor = new CoherenceProcessor<>(request);
byte[] resultBytes = cache.invoke(key, entryProcessor);
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
return deserializeResult(resultBytes, backwardCompatibilityVersion);
}
@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) {<FILL_FUNCTION_BODY>}
@Override
protected CompletableFuture<Void> removeAsync(K key) {
return cache.async().remove(key).thenApply(oldState -> null);
}
}
|
CoherenceProcessor<K, T> entryProcessor = new CoherenceProcessor<>(request);
CompletableFuture<CommandResult<T>> future = new CompletableFuture<>();
Version backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
SingleEntryAsynchronousProcessor<K, byte[], byte[]> asyncProcessor =
new SingleEntryAsynchronousProcessor<K, byte[], byte[]>(entryProcessor) {
@Override
public void onResult(Map.Entry<K, byte[]> entry) {
super.onResult(entry);
byte[] resultBytes = entry.getValue();
future.complete(deserializeResult(resultBytes, backwardCompatibilityVersion));
}
@Override
public void onException(Throwable error) {
super.onException(error);
future.completeExceptionally(error);
}
};
cache.invoke(key, asyncProcessor);
return future;
| 360
| 223
| 583
|
<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-core/src/main/java/io/github/bucket4j/BandwidthBuilder.java
|
BandwidthBuilderImpl
|
capacity
|
class BandwidthBuilderImpl implements BandwidthBuilderCapacityStage, BandwidthBuilderRefillStage, BandwidthBuilderBuildStage {
private long capacity;
private long refillPeriodNanos;
private long refillTokens;
private long initialTokens;
private boolean refillIntervally;
private long timeOfFirstRefillMillis = UNSPECIFIED_TIME_OF_FIRST_REFILL;
private boolean useAdaptiveInitialTokens;
private String id = UNDEFINED_ID;
@Override
public BandwidthBuilderRefillStage capacity(long tokens) {<FILL_FUNCTION_BODY>}
@Override
public BandwidthBuilderBuildStage refillGreedy(long tokens, Duration period) {
setRefill(tokens, period, false);
return this;
}
@Override
public BandwidthBuilderBuildStage refillIntervally(long tokens, Duration period) {
setRefill(tokens, period, true);
return this;
}
@Override
public BandwidthBuilderBuildStage refillIntervallyAligned(long tokens, Duration period, Instant timeOfFirstRefill) {
long timeOfFirstRefillMillis = timeOfFirstRefill.toEpochMilli();
if (timeOfFirstRefillMillis < 0) {
throw BucketExceptions.nonPositiveTimeOfFirstRefill(timeOfFirstRefill);
}
setRefill(tokens, period, true);
this.timeOfFirstRefillMillis = timeOfFirstRefillMillis;
return this;
}
@Override
public BandwidthBuilderBuildStage refillIntervallyAlignedWithAdaptiveInitialTokens(long tokens, Duration period, Instant timeOfFirstRefill) {
long timeOfFirstRefillMillis = timeOfFirstRefill.toEpochMilli();
if (timeOfFirstRefillMillis < 0) {
throw BucketExceptions.nonPositiveTimeOfFirstRefill(timeOfFirstRefill);
}
setRefill(tokens, period, true);
this.timeOfFirstRefillMillis = timeOfFirstRefillMillis;
this.useAdaptiveInitialTokens = true;
return this;
}
@Override
public BandwidthBuilderBuildStage id(String id) {
this.id = id;
return this;
}
@Override
public BandwidthBuilderBuildStage initialTokens(long initialTokens) {
if (initialTokens < 0) {
throw BucketExceptions.nonPositiveInitialTokens(initialTokens);
}
if (timeOfFirstRefillMillis != UNSPECIFIED_TIME_OF_FIRST_REFILL && useAdaptiveInitialTokens) {
throw BucketExceptions.intervallyAlignedRefillWithAdaptiveInitialTokensIncompatipleWithManualSpecifiedInitialTokens();
}
this.initialTokens = initialTokens;
return this;
}
@Override
public Bandwidth build() {
return new Bandwidth(capacity, refillPeriodNanos, refillTokens, initialTokens, refillIntervally, timeOfFirstRefillMillis, useAdaptiveInitialTokens, id);
}
private void setRefill(long tokens, Duration period, boolean refillIntervally) {
if (period == null) {
throw BucketExceptions.nullRefillPeriod();
}
if (tokens <= 0) {
throw BucketExceptions.nonPositivePeriodTokens(tokens);
}
long refillPeriodNanos = period.toNanos();
if (refillPeriodNanos <= 0) {
throw BucketExceptions.nonPositivePeriod(refillPeriodNanos);
}
if (tokens > refillPeriodNanos) {
throw BucketExceptions.tooHighRefillRate(refillPeriodNanos, tokens);
}
this.refillPeriodNanos = refillPeriodNanos;
this.refillIntervally = refillIntervally;
this.refillTokens = tokens;
}
}
|
if (tokens <= 0) {
throw BucketExceptions.nonPositiveCapacity(tokens);
}
this.capacity = tokens;
this.initialTokens = tokens;
return this;
| 1,052
| 57
| 1,109
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/BucketConfiguration.java
|
BucketConfiguration
|
equalsByContent
|
class BucketConfiguration implements ComparableByContent<BucketConfiguration> {
private final Bandwidth[] bandwidths;
public BucketConfiguration(List<Bandwidth> bandwidths) {
Objects.requireNonNull(bandwidths);
if (bandwidths.isEmpty()) {
throw BucketExceptions.restrictionsNotSpecified();
}
this.bandwidths = new Bandwidth[bandwidths.size()];
for (int i = 0; i < bandwidths.size() ; i++) {
this.bandwidths[i] = Objects.requireNonNull(bandwidths.get(i));
}
for (int i = 0; i < this.bandwidths.length; i++) {
if (this.bandwidths[i].getId() != Bandwidth.UNDEFINED_ID) {
for (int j = i + 1; j < this.bandwidths.length; j++) {
if (Objects.equals(this.bandwidths[i].getId(), this.bandwidths[j].getId())) {
throw BucketExceptions.foundTwoBandwidthsWithSameId(i, j, this.bandwidths[i].getId());
}
}
}
}
}
public static ConfigurationBuilder builder() {
return new ConfigurationBuilder();
}
public Bandwidth[] getBandwidths() {
return bandwidths;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
BucketConfiguration that = (BucketConfiguration) o;
return Arrays.equals(bandwidths, that.bandwidths);
}
@Override
public int hashCode() {
return Arrays.hashCode(bandwidths);
}
@Override
public String toString() {
return "BucketConfiguration{" +
"bandwidths=" + Arrays.toString(bandwidths) +
'}';
}
public static final SerializationHandle<BucketConfiguration> SERIALIZATION_HANDLE = new SerializationHandle<BucketConfiguration>() {
@Override
public <S> BucketConfiguration deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int bandwidthAmount = adapter.readInt(input);
List<Bandwidth> bandwidths = new ArrayList<>(bandwidthAmount);
for (int ii = 0; ii < bandwidthAmount; ii++) {
Bandwidth bandwidth = Bandwidth.SERIALIZATION_HANDLE.deserialize(adapter, input);
bandwidths.add(bandwidth);
}
return new BucketConfiguration(bandwidths);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, BucketConfiguration configuration, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeInt(output, configuration.bandwidths.length);
for (Bandwidth bandwidth : configuration.bandwidths) {
Bandwidth.SERIALIZATION_HANDLE.serialize(adapter, output, bandwidth, backwardCompatibilityVersion, scope);
}
}
@Override
public int getTypeId() {
return 2;
}
@Override
public Class<BucketConfiguration> getSerializedType() {
return BucketConfiguration.class;
}
@Override
public BucketConfiguration fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
List<Map<String, Object>> bandwidthSnapshots = (List<Map<String, Object>>) snapshot.get("bandwidths");
List<Bandwidth> bandwidths = new ArrayList<>(bandwidthSnapshots.size());
for (Map<String, Object> bandwidthSnapshot : bandwidthSnapshots) {
Bandwidth bandwidth = Bandwidth.SERIALIZATION_HANDLE.fromJsonCompatibleSnapshot(bandwidthSnapshot);
bandwidths.add(bandwidth);
}
return new BucketConfiguration(bandwidths);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(BucketConfiguration configuration, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
List<Map<String, Object>> bandwidthList = new ArrayList<>(configuration.bandwidths.length);
for (Bandwidth bandwidth : configuration.bandwidths) {
bandwidthList.add(Bandwidth.SERIALIZATION_HANDLE.toJsonCompatibleSnapshot(bandwidth, backwardCompatibilityVersion, scope));
}
result.put("bandwidths", bandwidthList);
return result;
}
@Override
public String getTypeName() {
return "BucketConfiguration";
}
};
@Override
public boolean equalsByContent(BucketConfiguration other) {<FILL_FUNCTION_BODY>}
}
|
if (bandwidths.length != other.bandwidths.length) {
return false;
}
for (int i = 0; i < other.getBandwidths().length; i++) {
Bandwidth bandwidth1 = bandwidths[i];
Bandwidth bandwidth2 = other.bandwidths[i];
if (!bandwidth1.equalsByContent(bandwidth2)) {
return false;
}
}
return true;
| 1,352
| 116
| 1,468
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/ConfigurationBuilder.java
|
ConfigurationBuilder
|
addLimit
|
class ConfigurationBuilder {
private final List<Bandwidth> bandwidths;
public ConfigurationBuilder() {
this.bandwidths = new ArrayList<>(1);
}
/**
* @return configuration that used for bucket construction.
*/
public BucketConfiguration build() {
return new BucketConfiguration(this.bandwidths);
}
/**
* @see #build()
*/
@Deprecated
public BucketConfiguration buildConfiguration() {
return build();
}
/**
* Adds limited bandwidth for all buckets which will be constructed by this builder instance.
*
* @param bandwidth limitation
* @return this builder instance
*/
public ConfigurationBuilder addLimit(Bandwidth bandwidth) {
if (bandwidth == null) {
throw BucketExceptions.nullBandwidth();
}
bandwidths.add(bandwidth);
return this;
}
public ConfigurationBuilder addLimit(Function<BandwidthBuilderCapacityStage, BandwidthBuilderBuildStage> bandwidthConfigurator) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "ConfigurationBuilder{" +
"bandwidths=" + bandwidths +
'}';
}
}
|
if (bandwidthConfigurator == null) {
throw BucketExceptions.nullBuilder();
}
BandwidthBuilderBuildStage builder = bandwidthConfigurator.apply(Bandwidth.builder());
Bandwidth bandwidth = builder.build();
return addLimit(bandwidth);
| 319
| 72
| 391
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/ConsumptionProbe.java
|
ConsumptionProbe
|
toJsonCompatibleSnapshot
|
class ConsumptionProbe implements ComparableByContent<ConsumptionProbe> {
private final boolean consumed;
private final long remainingTokens;
private final long nanosToWaitForRefill;
private final long nanosToWaitForReset;
public static final SerializationHandle<ConsumptionProbe> SERIALIZATION_HANDLE = new SerializationHandle<ConsumptionProbe>() {
@Override
public <S> ConsumptionProbe deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
boolean consumed = adapter.readBoolean(input);
long remainingTokens = adapter.readLong(input);
long nanosToWaitForRefill = adapter.readLong(input);
long nanosToWaitForReset = adapter.readLong(input);
return new ConsumptionProbe(consumed, remainingTokens, nanosToWaitForRefill, nanosToWaitForReset);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ConsumptionProbe probe, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeBoolean(output, probe.consumed);
adapter.writeLong(output, probe.remainingTokens);
adapter.writeLong(output, probe.nanosToWaitForRefill);
adapter.writeLong(output, probe.nanosToWaitForReset);
}
@Override
public int getTypeId() {
return 11;
}
@Override
public Class<ConsumptionProbe> getSerializedType() {
return ConsumptionProbe.class;
}
@Override
public ConsumptionProbe fromJsonCompatibleSnapshot(Map<String, Object> snapshot) {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
boolean consumed = (boolean) snapshot.get("consumed");
long remainingTokens = readLongValue(snapshot, "remainingTokens");
long nanosToWaitForRefill = readLongValue(snapshot, "nanosToWaitForRefill");
long nanosToWaitForReset = readLongValue(snapshot, "nanosToWaitForReset");
return new ConsumptionProbe(consumed, remainingTokens, nanosToWaitForRefill, nanosToWaitForReset);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ConsumptionProbe probe, Version backwardCompatibilityVersion, Scope scope) {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "ConsumptionProbe";
}
};
public static ConsumptionProbe consumed(long remainingTokens, long nanosToWaitForReset) {
return new ConsumptionProbe(true, remainingTokens, 0, nanosToWaitForReset);
}
public static ConsumptionProbe rejected(long remainingTokens, long nanosToWaitForRefill, long nanosToWaitForReset) {
return new ConsumptionProbe(false, remainingTokens, nanosToWaitForRefill, nanosToWaitForReset);
}
private ConsumptionProbe(boolean consumed, long remainingTokens, long nanosToWaitForRefill, long nanosToWaitForReset) {
this.consumed = consumed;
this.remainingTokens = Math.max(0L, remainingTokens);
this.nanosToWaitForRefill = nanosToWaitForRefill;
this.nanosToWaitForReset = nanosToWaitForReset;
}
/**
* Flag describes result of consumption operation.
*
* @return true if tokens was consumed
*/
public boolean isConsumed() {
return consumed;
}
/**
* Return the tokens remaining in the bucket
*
* @return the tokens remaining in the bucket
*/
public long getRemainingTokens() {
return remainingTokens;
}
/**
* Returns zero if {@link #isConsumed()} returns true, else time in nanos which need to wait until requested amount of tokens will be refilled
*
* @return Zero if {@link #isConsumed()} returns true, else time in nanos which need to wait until requested amount of tokens will be refilled
*/
public long getNanosToWaitForRefill() {
return nanosToWaitForRefill;
}
/**
* Time in nanos which need to wait until bucket will be fully refilled to its maximum
*
* @return time in nanos which need to wait until bucket will be fully refilled to its maximum
*/
public long getNanosToWaitForReset() {
return nanosToWaitForReset;
}
@Override
public String toString() {
return "ConsumptionProbe{" +
"consumed=" + consumed +
", remainingTokens=" + remainingTokens +
", nanosToWaitForRefill=" + nanosToWaitForRefill +
", nanosToWaitForReset=" + nanosToWaitForReset +
'}';
}
@Override
public boolean equalsByContent(ConsumptionProbe other) {
return consumed == other.consumed &&
remainingTokens == other.remainingTokens &&
nanosToWaitForRefill == other.nanosToWaitForRefill &&
nanosToWaitForReset == other.nanosToWaitForReset;
}
}
|
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("consumed", probe.consumed);
result.put("remainingTokens", probe.remainingTokens);
result.put("nanosToWaitForRefill", probe.nanosToWaitForRefill);
result.put("nanosToWaitForReset", probe.nanosToWaitForReset);
return result;
| 1,431
| 120
| 1,551
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/EstimationProbe.java
|
EstimationProbe
|
deserialize
|
class EstimationProbe implements ComparableByContent<EstimationProbe> {
private final boolean canBeConsumed;
private final long remainingTokens;
private final long nanosToWaitForRefill;
public static final SerializationHandle<EstimationProbe> SERIALIZATION_HANDLE = new SerializationHandle<EstimationProbe>() {
@Override
public <S> EstimationProbe deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, EstimationProbe probe, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeBoolean(output, probe.canBeConsumed);
adapter.writeLong(output, probe.remainingTokens);
adapter.writeLong(output, probe.nanosToWaitForRefill);
}
@Override
public int getTypeId() {
return 12;
}
@Override
public Class<EstimationProbe> getSerializedType() {
return EstimationProbe.class;
}
@Override
public EstimationProbe fromJsonCompatibleSnapshot(Map<String, Object> snapshot) {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
boolean canBeConsumed = (boolean) snapshot.get("canBeConsumed");
long remainingTokens = readLongValue(snapshot, "remainingTokens");
long nanosToWaitForRefill = readLongValue(snapshot, "nanosToWaitForRefill");
return new EstimationProbe(canBeConsumed, remainingTokens, nanosToWaitForRefill);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(EstimationProbe state, Version backwardCompatibilityVersion, Scope scope) {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("canBeConsumed", state.canBeConsumed);
result.put("remainingTokens", state.remainingTokens);
result.put("nanosToWaitForRefill", state.nanosToWaitForRefill);
return result;
}
@Override
public String getTypeName() {
return "EstimationProbe";
}
};
public static EstimationProbe canBeConsumed(long remainingTokens) {
return new EstimationProbe(true, remainingTokens, 0);
}
public static EstimationProbe canNotBeConsumed(long remainingTokens, long nanosToWaitForRefill) {
return new EstimationProbe(false, remainingTokens, nanosToWaitForRefill);
}
private EstimationProbe(boolean canBeConsumed, long remainingTokens, long nanosToWaitForRefill) {
this.canBeConsumed = canBeConsumed;
this.remainingTokens = Math.max(0L, remainingTokens);
this.nanosToWaitForRefill = nanosToWaitForRefill;
}
/**
* Flag describes result of consumption operation.
*
* @return true if requested tokens can be consumed
*/
public boolean canBeConsumed() {
return canBeConsumed;
}
/**
* Return the tokens remaining in the bucket
*
* @return the tokens remaining in the bucket
*/
public long getRemainingTokens() {
return remainingTokens;
}
/**
* Returns zero if {@link #canBeConsumed()} returns true, else time in nanos which need to wait until requested amount of tokens will be refilled
*
* @return Zero if {@link #canBeConsumed()} returns true, else time in nanos which need to wait until requested amount of tokens will be refilled
*/
public long getNanosToWaitForRefill() {
return nanosToWaitForRefill;
}
@Override
public String toString() {
return "ConsumptionResult{" +
"isConsumed=" + canBeConsumed +
", remainingTokens=" + remainingTokens +
", nanosToWaitForRefill=" + nanosToWaitForRefill +
'}';
}
@Override
public boolean equalsByContent(EstimationProbe other) {
return canBeConsumed == other.canBeConsumed &&
remainingTokens == other.remainingTokens &&
nanosToWaitForRefill == other.nanosToWaitForRefill;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
boolean canBeConsumed = adapter.readBoolean(input);
long remainingTokens = adapter.readLong(input);
long nanosToWaitForRefill = adapter.readLong(input);
return new EstimationProbe(canBeConsumed, remainingTokens, nanosToWaitForRefill);
| 1,222
| 119
| 1,341
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/LimitChecker.java
|
LimitChecker
|
checkTokensToAdd
|
class LimitChecker {
public static long INFINITY_DURATION = Long.MAX_VALUE;
public static long UNLIMITED_AMOUNT = Long.MAX_VALUE;
public static void checkTokensToAdd(long tokensToAdd) {<FILL_FUNCTION_BODY>}
public static void checkTokensToConsume(long tokensToConsume) {
if (tokensToConsume <= 0) {
throw BucketExceptions.nonPositiveTokensToConsume(tokensToConsume);
}
}
public static void checkMaxWaitTime(long maxWaitTimeNanos) {
if (maxWaitTimeNanos <= 0) {
throw BucketExceptions.nonPositiveNanosToWait(maxWaitTimeNanos);
}
}
public static void checkScheduler(ScheduledExecutorService scheduler) {
if (scheduler == null) {
throw BucketExceptions.nullScheduler();
}
}
public static void checkConfiguration(BucketConfiguration newConfiguration) {
if (newConfiguration == null) {
throw BucketExceptions.nullConfiguration();
}
}
public static void checkMigrationMode(TokensInheritanceStrategy tokensInheritanceStrategy) {
if (tokensInheritanceStrategy == null) {
throw BucketExceptions.nullTokensInheritanceStrategy();
}
}
}
|
if (tokensToAdd <= 0) {
throw new IllegalArgumentException("tokensToAdd should be >= 0");
}
| 356
| 34
| 390
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/Refill.java
|
Refill
|
intervallyAligned
|
class Refill {
final long periodNanos;
final long tokens;
final boolean refillIntervally;
final long timeOfFirstRefillMillis;
final boolean useAdaptiveInitialTokens;
private Refill(long tokens, Duration period, boolean refillIntervally, long timeOfFirstRefillMillis, boolean useAdaptiveInitialTokens) {
if (period == null) {
throw BucketExceptions.nullRefillPeriod();
}
if (tokens <= 0) {
throw BucketExceptions.nonPositivePeriodTokens(tokens);
}
this.periodNanos = period.toNanos();
if (periodNanos <= 0) {
throw BucketExceptions.nonPositivePeriod(periodNanos);
}
if (tokens > periodNanos) {
throw BucketExceptions.tooHighRefillRate(periodNanos, tokens);
}
this.tokens = tokens;
this.refillIntervally = refillIntervally;
this.timeOfFirstRefillMillis = timeOfFirstRefillMillis;
this.useAdaptiveInitialTokens = useAdaptiveInitialTokens;
}
@Deprecated
public static Refill of(long tokens, Duration period) {
return greedy(tokens, period);
}
@Deprecated
public static Refill smooth(long tokens, Duration period) {
return greedy(tokens, period);
}
/**
* This method is deprecated, you should use {@link BandwidthBuilderRefillStage#refillGreedy(long, Duration)}
*
* @deprecated
*/
@Deprecated
public static Refill greedy(long tokens, Duration period) {
return new Refill(tokens, period, false, Bandwidth.UNSPECIFIED_TIME_OF_FIRST_REFILL, false);
}
/**
* This method is deprecated, you should use {@link BandwidthBuilderRefillStage#refillIntervally(long, Duration)}
*
* @deprecated
*/
@Deprecated
public static Refill intervally(long tokens, Duration period) {
return new Refill(tokens, period, true, Bandwidth.UNSPECIFIED_TIME_OF_FIRST_REFILL, false);
}
/**
* This method is deprecated, you should use {@link BandwidthBuilderRefillStage#refillIntervallyAligned(long, Duration, Instant)} or
* {@link BandwidthBuilderRefillStage#refillIntervallyAlignedWithAdaptiveInitialTokens(long, Duration, Instant)}
*
* @deprecated
*/
@Deprecated
public static Refill intervallyAligned(long tokens, Duration period, Instant timeOfFirstRefill, boolean useAdaptiveInitialTokens) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Refill{");
sb.append("periodNanos=").append(periodNanos);
sb.append(", tokens=").append(tokens);
sb.append(", refillIntervally=").append(refillIntervally);
sb.append(", timeOfFirstRefillMillis=").append(timeOfFirstRefillMillis);
sb.append(", useAdaptiveInitialTokens=").append(useAdaptiveInitialTokens);
sb.append('}');
return sb.toString();
}
}
|
long timeOfFirstRefillMillis = timeOfFirstRefill.toEpochMilli();
if (timeOfFirstRefillMillis < 0) {
throw BucketExceptions.nonPositiveTimeOfFirstRefill(timeOfFirstRefill);
}
return new Refill(tokens, period, true, timeOfFirstRefillMillis, useAdaptiveInitialTokens);
| 902
| 97
| 999
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/VerboseResult.java
|
VerboseResult
|
getDiagnostics
|
class VerboseResult<T> implements ComparableByContent<VerboseResult<?>> {
private final long operationTimeNanos;
private final T value;
private final BucketState state;
public VerboseResult(long operationTimeNanos, T value, BucketState state) {
this.operationTimeNanos = operationTimeNanos;
this.value = value;
this.state = state;
}
/**
* @return result of operation with bucket
*/
public T getValue() {
return value;
}
/**
* @return snapshot of configuration which was actual at operation time
*/
public BucketConfiguration getConfiguration() {
return state.getConfiguration();
}
/**
* @return snapshot of internal bucket state which was actual at operation time
*/
public BucketState getState() {
return state;
}
/**
* @return time which was used by the bucket at the moment of handling a request
*/
public long getOperationTimeNanos() {
return operationTimeNanos;
}
/**
* @return internal state describer
*/
public Diagnostics getDiagnostics() {<FILL_FUNCTION_BODY>}
/**
* Describer of internal bucket state
*/
public interface Diagnostics {
/**
* Returns time in nanoseconds that need to wait until bucket will be fully refilled to its maximum
*
* @return time in nanoseconds that need to wait until bucket will be fully refilled to its maximum
*/
long calculateFullRefillingTime();
/**
* Returns currently available tokens
*
* @return currently available tokens
*/
long getAvailableTokens();
/**
* Returns currently available tokens per each bandwidth.
* Element's order inside resulted array depends from order in which bandwidth is specified inside {@link BucketConfiguration}.
*
* @return currently available tokens per each bandwidth
*/
long[] getAvailableTokensPerEachBandwidth();
}
public <R> VerboseResult<R> map(Function<T, R> mapper) {
return new VerboseResult<R>(operationTimeNanos, mapper.apply(value), state);
}
@Override
public boolean equalsByContent(VerboseResult<?> other) {
return operationTimeNanos == other.operationTimeNanos
&& ComparableByContent.equals(value, other.value)
&& state.getConfiguration().equalsByContent(other.getState().getConfiguration())
&& ComparableByContent.equals(state, other.state);
}
}
|
return new Diagnostics() {
@Override
public long calculateFullRefillingTime() {
return state.calculateFullRefillingTime(operationTimeNanos);
}
@Override
public long getAvailableTokens() {
return state.getAvailableTokens();
}
@Override
public long[] getAvailableTokensPerEachBandwidth() {
Bandwidth[] bandwidths = state.getConfiguration().getBandwidths();
long[] availableTokens = new long[bandwidths.length];
for (int i = 0; i < bandwidths.length; i++) {
availableTokens[i] = state.getCurrentSize(i);
}
return availableTokens;
}
};
| 670
| 185
| 855
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/AsyncBucketProxyAdapter.java
|
AsyncBucketProxyAdapter
|
replaceConfiguration
|
class AsyncBucketProxyAdapter implements AsyncBucketProxy, AsyncOptimizationController {
private final Bucket target;
private final AsyncVerboseBucket verboseView = new AsyncVerboseBucket() {
@Override
public CompletableFuture<VerboseResult<Boolean>> tryConsume(long numTokens) {
return completedFuture(() -> target.asVerbose().tryConsume(numTokens));
}
@Override
public CompletableFuture<VerboseResult<Long>> consumeIgnoringRateLimits(long tokens) {
return completedFuture(() -> target.asVerbose().consumeIgnoringRateLimits(tokens));
}
@Override
public CompletableFuture<VerboseResult<ConsumptionProbe>> tryConsumeAndReturnRemaining(long numTokens) {
return completedFuture(() -> target.asVerbose().tryConsumeAndReturnRemaining(numTokens));
}
@Override
public CompletableFuture<VerboseResult<EstimationProbe>> estimateAbilityToConsume(long numTokens) {
return completedFuture(() -> target.asVerbose().estimateAbilityToConsume(numTokens));
}
@Override
public CompletableFuture<VerboseResult<Long>> tryConsumeAsMuchAsPossible() {
return completedFuture(() -> target.asVerbose().tryConsumeAsMuchAsPossible());
}
@Override
public CompletableFuture<VerboseResult<Long>> tryConsumeAsMuchAsPossible(long limit) {
return completedFuture(() -> target.asVerbose().tryConsumeAsMuchAsPossible(limit));
}
@Override
public CompletableFuture<VerboseResult<Nothing>> addTokens(long tokensToAdd) {
return completedFuture(() -> target.asVerbose().addTokens(tokensToAdd));
}
@Override
public CompletableFuture<VerboseResult<Nothing>> forceAddTokens(long tokensToAdd) {
return completedFuture(() -> target.asVerbose().forceAddTokens(tokensToAdd));
}
@Override
public CompletableFuture<VerboseResult<Nothing>> reset() {
return completedFuture(() -> target.asVerbose().reset());
}
@Override
public CompletableFuture<VerboseResult<Nothing>> replaceConfiguration(BucketConfiguration newConfiguration, TokensInheritanceStrategy tokensInheritanceStrategy) {
LimitChecker.checkConfiguration(newConfiguration);
LimitChecker.checkMigrationMode(tokensInheritanceStrategy);
return completedFuture(() -> target.asVerbose().replaceConfiguration(newConfiguration, tokensInheritanceStrategy));
}
@Override
public CompletableFuture<VerboseResult<Long>> getAvailableTokens() {
return completedFuture(() -> target.asVerbose().getAvailableTokens());
}
};
/**
* TODO
*
* @param bucket
* @return
*/
public static AsyncBucketProxy fromSync(Bucket bucket) {
return new AsyncBucketProxyAdapter(bucket);
}
public AsyncBucketProxyAdapter(Bucket target) {
this.target = Objects.requireNonNull(target);
}
@Override
public SchedulingBucket asScheduler() {
return target.asScheduler();
}
@Override
public AsyncVerboseBucket asVerbose() {
return verboseView;
}
@Override
public CompletableFuture<Boolean> tryConsume(long numTokens) {
return completedFuture(() -> target.tryConsume(numTokens));
}
@Override
public CompletableFuture<Long> consumeIgnoringRateLimits(long tokens) {
return completedFuture(() -> target.consumeIgnoringRateLimits(tokens));
}
@Override
public CompletableFuture<ConsumptionProbe> tryConsumeAndReturnRemaining(long numTokens) {
return completedFuture(() -> target.tryConsumeAndReturnRemaining(numTokens));
}
@Override
public CompletableFuture<EstimationProbe> estimateAbilityToConsume(long numTokens) {
return completedFuture(() -> target.estimateAbilityToConsume(numTokens));
}
@Override
public CompletableFuture<Long> tryConsumeAsMuchAsPossible() {
return completedFuture(() -> target.tryConsumeAsMuchAsPossible());
}
@Override
public CompletableFuture<Long> tryConsumeAsMuchAsPossible(long limit) {
return completedFuture(() -> target.tryConsumeAsMuchAsPossible(limit));
}
@Override
public CompletableFuture<Void> addTokens(long tokensToAdd) {
return completedFuture(() -> {
target.addTokens(tokensToAdd);
return null;
});
}
@Override
public CompletableFuture<Void> forceAddTokens(long tokensToAdd) {
return completedFuture(() -> {
target.forceAddTokens(tokensToAdd);
return null;
});
}
@Override
public CompletableFuture<Void> reset() {
return completedFuture(() -> {
target.reset();
return null;
});
}
@Override
public CompletableFuture<Void> replaceConfiguration(BucketConfiguration newConfiguration, TokensInheritanceStrategy tokensInheritanceStrategy) {<FILL_FUNCTION_BODY>}
@Override
public CompletableFuture<Long> getAvailableTokens() {
return completedFuture(() -> target.getAvailableTokens());
}
@Override
public AsyncOptimizationController getOptimizationController() {
return this;
}
@Override
public CompletableFuture<Void> syncImmediately() {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Void> syncByCondition(long unsynchronizedTokens, Duration timeSinceLastSync) {
return CompletableFuture.completedFuture(null);
}
@Override
public AsyncBucketProxy toListenable(BucketListener listener) {
return new AsyncBucketProxyAdapter(target.toListenable(listener));
}
}
|
LimitChecker.checkConfiguration(newConfiguration);
LimitChecker.checkMigrationMode(tokensInheritanceStrategy);
return completedFuture(() -> {
target.replaceConfiguration(newConfiguration, tokensInheritanceStrategy);
return null;
});
| 1,571
| 68
| 1,639
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/expiration/BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy.java
|
BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy
|
fromJsonCompatibleSnapshot
|
class BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy implements ExpirationAfterWriteStrategy, ComparableByContent<BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy> {
private final long keepAfterRefillDurationMillis;
public BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy(Duration keepAfterRefillDuration) {
keepAfterRefillDurationMillis = keepAfterRefillDuration.toMillis();
if (keepAfterRefillDurationMillis < 0) {
throw new IllegalArgumentException("keepAfterRefillDurationMillis should be positive");
}
}
@Override
public long calculateTimeToLiveMillis(RemoteBucketState state, long currentTimeNanos) {
long millisToFullRefill = state.calculateFullRefillingTime(currentTimeNanos) / 1_000_000;
long result = keepAfterRefillDurationMillis + millisToFullRefill;
return result <= 0 ? 1 : result;
}
public static final SerializationHandle<BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy> SERIALIZATION_HANDLE = new SerializationHandle<>() {
@Override
public <S> BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_8_10_0, v_8_10_0);
long keepAfterRefillDurationMillis = adapter.readLong(input);
return new BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy(Duration.ofMillis(keepAfterRefillDurationMillis));
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy strategy, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_8_10_0.getNumber());
adapter.writeLong(output, strategy.keepAfterRefillDurationMillis);
}
@Override
public int getTypeId() {
return 70;
}
@Override
public Class<BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy> getSerializedType() {
return BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy.class;
}
@Override
public BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy strategy, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_8_10_0.getNumber());
result.put("keepAfterRefillDurationMillis", strategy.keepAfterRefillDurationMillis);
return result;
}
@Override
public String getTypeName() {
return "BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy";
}
};
@Override
public SerializationHandle<ExpirationAfterWriteStrategy> getSerializationHandle() {
return (SerializationHandle) SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy other) {
return this.keepAfterRefillDurationMillis == other.keepAfterRefillDurationMillis;
}
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_8_10_0, v_8_10_0);
long keepAfterRefillDurationMillis = readLongValue(snapshot, "keepAfterRefillDurationMillis");
return new BasedOnTimeForRefillingBucketUpToMaxExpirationAfterWriteStrategy(Duration.ofMillis(keepAfterRefillDurationMillis));
| 939
| 110
| 1,049
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/expiration/FixedTtlExpirationAfterWriteStrategy.java
|
FixedTtlExpirationAfterWriteStrategy
|
deserialize
|
class FixedTtlExpirationAfterWriteStrategy implements ExpirationAfterWriteStrategy, ComparableByContent<FixedTtlExpirationAfterWriteStrategy> {
private final long ttlMillis;
public FixedTtlExpirationAfterWriteStrategy(Duration ttl) {
long ttlMillis = ttl.toMillis();
if (ttlMillis <= 0) {
throw new IllegalArgumentException("ttl should be positive");
}
this.ttlMillis = ttlMillis;
}
@Override
public long calculateTimeToLiveMillis(RemoteBucketState state, long currentTimeNanos) {
return ttlMillis;
}
public static final SerializationHandle<FixedTtlExpirationAfterWriteStrategy> SERIALIZATION_HANDLE = new SerializationHandle<>() {
@Override
public <S> FixedTtlExpirationAfterWriteStrategy deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, FixedTtlExpirationAfterWriteStrategy strategy, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_8_10_0.getNumber());
adapter.writeLong(output, strategy.ttlMillis);
}
@Override
public int getTypeId() {
return 71;
}
@Override
public Class<FixedTtlExpirationAfterWriteStrategy> getSerializedType() {
return FixedTtlExpirationAfterWriteStrategy.class;
}
@Override
public FixedTtlExpirationAfterWriteStrategy fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_8_10_0, v_8_10_0);
long keepAfterRefillDurationMillis = readLongValue(snapshot, "ttlMillis");
return new FixedTtlExpirationAfterWriteStrategy(Duration.ofMillis(keepAfterRefillDurationMillis));
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(FixedTtlExpirationAfterWriteStrategy strategy, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_8_10_0.getNumber());
result.put("ttlMillis", strategy.ttlMillis);
return result;
}
@Override
public String getTypeName() {
return "FixedTtlExpirationAfterWriteStrategy";
}
};
@Override
public SerializationHandle<ExpirationAfterWriteStrategy> getSerializationHandle() {
return (SerializationHandle) SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(FixedTtlExpirationAfterWriteStrategy other) {
return this.ttlMillis == other.ttlMillis;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_8_10_0, v_8_10_0);
long keepAfterRefillDurationMillis = adapter.readLong(input);
return new FixedTtlExpirationAfterWriteStrategy(Duration.ofMillis(keepAfterRefillDurationMillis));
| 763
| 90
| 853
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/expiration/NoneExpirationAfterWriteStrategy.java
|
NoneExpirationAfterWriteStrategy
|
fromJsonCompatibleSnapshot
|
class NoneExpirationAfterWriteStrategy implements ExpirationAfterWriteStrategy, ComparableByContent<NoneExpirationAfterWriteStrategy> {
public static final NoneExpirationAfterWriteStrategy INSTANCE = new NoneExpirationAfterWriteStrategy();
@Override
public long calculateTimeToLiveMillis(RemoteBucketState state, long currentTimeNanos) {
return -1;
}
public static final SerializationHandle<NoneExpirationAfterWriteStrategy> SERIALIZATION_HANDLE = new SerializationHandle<>() {
@Override
public <S> NoneExpirationAfterWriteStrategy deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_8_10_0, v_8_10_0);
return NoneExpirationAfterWriteStrategy.INSTANCE;
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, NoneExpirationAfterWriteStrategy strategy, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_8_10_0.getNumber());
}
@Override
public int getTypeId() {
return 72;
}
@Override
public Class<NoneExpirationAfterWriteStrategy> getSerializedType() {
return NoneExpirationAfterWriteStrategy.class;
}
@Override
public NoneExpirationAfterWriteStrategy fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(NoneExpirationAfterWriteStrategy strategy, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_8_10_0.getNumber());
return result;
}
@Override
public String getTypeName() {
return "NoneExpirationAfterWriteStrategy";
}
};
@Override
public SerializationHandle<ExpirationAfterWriteStrategy> getSerializationHandle() {
return (SerializationHandle) SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(NoneExpirationAfterWriteStrategy other) {
return true;
}
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_8_10_0, v_8_10_0);
return NoneExpirationAfterWriteStrategy.INSTANCE;
| 584
| 60
| 644
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/jdbc/SQLProxyConfigurationBuilder.java
|
SQLProxyConfigurationBuilder
|
build
|
class SQLProxyConfigurationBuilder<K> {
ClientSideConfig clientSideConfig;
BucketTableSettings tableSettings;
PrimaryKeyMapper<K> primaryKeyMapper;
SQLProxyConfigurationBuilder(PrimaryKeyMapper<K> primaryKeyMapper) {
this.primaryKeyMapper = primaryKeyMapper;
this.tableSettings = BucketTableSettings.getDefault();
this.clientSideConfig = ClientSideConfig.getDefault();
}
/**
* @deprecated use {@link SQLProxyConfiguration#builder()}
*
* @return the new instance of {@link SQLProxyConfigurationBuilder} configured with {@link PrimaryKeyMapper#LONG} primary key mapper
*/
public static SQLProxyConfigurationBuilder<Long> builder() {
return new SQLProxyConfigurationBuilder<>(PrimaryKeyMapper.LONG);
}
/**
* @param clientSideConfig {@link ClientSideConfig} client-side configuration for proxy-manager.
* By default, under the hood uses {@link ClientSideConfig#getDefault}
* @return {@link SQLProxyConfigurationBuilder}
*/
public SQLProxyConfigurationBuilder<K> withClientSideConfig(ClientSideConfig clientSideConfig) {
this.clientSideConfig = Objects.requireNonNull(clientSideConfig);
return this;
}
/**
* @param tableSettings {@link BucketTableSettings} define a configuration of the table to use as a Buckets store.
* By default, under the hood uses {@link BucketTableSettings#getDefault}
* @return {@link SQLProxyConfigurationBuilder}
*/
public SQLProxyConfigurationBuilder<K> withTableSettings(BucketTableSettings tableSettings) {
this.tableSettings = Objects.requireNonNull(tableSettings);
return this;
}
/**
* @param primaryKeyMapper Specifies the type of primary key.
* By default, under the hood uses {@link PrimaryKeyMapper#LONG}
* @return {@link SQLProxyConfigurationBuilder}
*/
public <T> SQLProxyConfigurationBuilder<T> withPrimaryKeyMapper(PrimaryKeyMapper<T> primaryKeyMapper) {
this.primaryKeyMapper = (PrimaryKeyMapper<K>) Objects.requireNonNull(primaryKeyMapper);
return (SQLProxyConfigurationBuilder<T>) this;
}
/**
* The method takes a {@link DataSource} as a required parameter
*
* @param dataSource - a database configuration
* @return {@link SQLProxyConfiguration}
*/
public SQLProxyConfiguration<K> build(DataSource dataSource) {<FILL_FUNCTION_BODY>}
}
|
if (dataSource == null) {
throw new BucketExceptions.BucketExecutionException("DataSource cannot be null");
}
return new SQLProxyConfiguration<>(this, dataSource);
| 628
| 50
| 678
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/AbstractProxyManager.java
|
DefaultAsyncRemoteBucketBuilder
|
executeAsync
|
class DefaultAsyncRemoteBucketBuilder implements RemoteAsyncBucketBuilder<K> {
private RecoveryStrategy recoveryStrategy = DEFAULT_RECOVERY_STRATEGY;
private Optimization asyncRequestOptimizer = DEFAULT_REQUEST_OPTIMIZER;
private ImplicitConfigurationReplacement implicitConfigurationReplacement;
@Override
public DefaultAsyncRemoteBucketBuilder withRecoveryStrategy(RecoveryStrategy recoveryStrategy) {
this.recoveryStrategy = requireNonNull(recoveryStrategy);
return this;
}
@Override
public DefaultAsyncRemoteBucketBuilder withOptimization(Optimization requestOptimizer) {
this.asyncRequestOptimizer = requireNonNull(requestOptimizer);
return this;
}
@Override
public DefaultAsyncRemoteBucketBuilder withImplicitConfigurationReplacement(long desiredConfigurationVersion, TokensInheritanceStrategy tokensInheritanceStrategy) {
this.implicitConfigurationReplacement = new ImplicitConfigurationReplacement(desiredConfigurationVersion, requireNonNull(tokensInheritanceStrategy));
return this;
}
@Override
public AsyncBucketProxy build(K key, BucketConfiguration configuration) {
if (configuration == null) {
throw BucketExceptions.nullConfiguration();
}
return build(key, () -> CompletableFuture.completedFuture(configuration));
}
@Override
public AsyncBucketProxy build(K key, Supplier<CompletableFuture<BucketConfiguration>> configurationSupplier) {
if (configurationSupplier == null) {
throw BucketExceptions.nullConfigurationSupplier();
}
AsyncCommandExecutor commandExecutor = new AsyncCommandExecutor() {
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(RemoteCommand<T> command) {<FILL_FUNCTION_BODY>}
};
commandExecutor = asyncRequestOptimizer.apply(commandExecutor);
return new DefaultAsyncBucketProxy(commandExecutor, recoveryStrategy, configurationSupplier, implicitConfigurationReplacement);
}
}
|
ExpirationAfterWriteStrategy expirationStrategy = clientSideConfig.getExpirationAfterWriteStrategy().orElse(null);
Request<T> request = new Request<>(command, getBackwardCompatibilityVersion(), getClientSideTime(), expirationStrategy);
Supplier<CompletableFuture<CommandResult<T>>> futureSupplier = () -> AbstractProxyManager.this.executeAsync(key, request);
return clientSideConfig.getExecutionStrategy().executeAsync(futureSupplier);
| 499
| 113
| 612
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/ClientSideConfig.java
|
ClientSideConfig
|
withRequestTimeout
|
class ClientSideConfig {
private static final ClientSideConfig defaultConfig = new ClientSideConfig(Versions.getLatest(), Optional.empty(),
ExecutionStrategy.SAME_TREAD, Optional.empty(), Optional.empty());
private final Version backwardCompatibilityVersion;
private final Optional<TimeMeter> clientSideClock;
private final ExecutionStrategy executionStrategy;
private final Optional<Long> requestTimeoutNanos;
private final Optional<ExpirationAfterWriteStrategy> expirationStrategy;
protected ClientSideConfig(Version backwardCompatibilityVersion, Optional<TimeMeter> clientSideClock,
ExecutionStrategy executionStrategy,
Optional<Long> requestTimeoutNanos,
Optional<ExpirationAfterWriteStrategy> expirationStrategy
) {
this.backwardCompatibilityVersion = Objects.requireNonNull(backwardCompatibilityVersion);
this.clientSideClock = Objects.requireNonNull(clientSideClock);
this.executionStrategy = executionStrategy;
this.requestTimeoutNanos = requestTimeoutNanos;
this.expirationStrategy = expirationStrategy;
}
/**
* Returns default client-side configuration for proxy-manager that configured with following parameters:
* <ul>
* <li><b>Client-clock:</b> is null. This means that server-side clock is always used.</li>
* <li><b>Backward compatibility version:</b> is {@code Versions.getLatest()}. This means that compatibility with legacy versions is switched off.</li>
* </ul>
*
* @return default client-side configuration for proxy-manager
*/
public static ClientSideConfig getDefault() {
return defaultConfig;
}
/**
* Returns new instance of {@link ClientSideConfig} with configured {@code backwardCompatibilityVersion}.
*
* <p>
* Use this method in case of rolling upgrades, when you want from already new nodes to continue communication using
* the legacy protocol version which is compatible with {@code backwardCompatibilityVersion}.
*
* <p> By default backward compatibility version is {@code Versions.getLatest()}. This means that compatibility with legacy versions is switched off.
*
* @param backwardCompatibilityVersion the Bucket4j protocol version to be backward compatible with other nodes in the cluster.
*
* @return new instance of {@link ClientSideConfig} with configured {@code backwardCompatibilityVersion}.
*/
public ClientSideConfig backwardCompatibleWith(Version backwardCompatibilityVersion) {
return new ClientSideConfig(backwardCompatibilityVersion, clientSideClock, executionStrategy, requestTimeoutNanos, expirationStrategy);
}
/**
* Returns new instance of {@link ClientSideConfig} with configured {@code clientClock}.
*
* <p>
* Use this method when you want to measure current time by yourself. In normal scenarios you should not use this functionality,
* but sometimes it can be useful, especially for testing and modeling.
*
* <p>
* By default client-clock is null. This means that server-side clock is always used.
*
* @param clientClock the clock that will be used for time measuring instead of server-side clock.
*
* @return new instance of {@link ClientSideConfig} with configured {@code clientClock}.
*/
public ClientSideConfig withClientClock(TimeMeter clientClock) {
return new ClientSideConfig(backwardCompatibilityVersion, Optional.of(clientClock), executionStrategy, requestTimeoutNanos, expirationStrategy);
}
/**
* Returns new instance of {@link ClientSideConfig} with configured {@code executionStrategy}.
*
* <p>
* The default executionStrategy is {@link ExecutionStrategy#SAME_TREAD}.
*
* @param executionStrategy the strategy for request execution.
*
* @return new instance of {@link ClientSideConfig} with configured {@code clientClock}.
*/
public ClientSideConfig withExecutionStrategy(ExecutionStrategy executionStrategy) {
return new ClientSideConfig(backwardCompatibilityVersion, clientSideClock, executionStrategy, requestTimeoutNanos, expirationStrategy);
}
/**
* Returns new instance of {@link ClientSideConfig} with configured timeout for remote operations.
*
* <p>
* The way in which timeout is applied depends on concrete implementation of {@link ProxyManager}. It can be three possible cases:
* <ol>
* <li>If underlying technology supports per request timeouts(like timeouts on prepared JDBC statements) then this feature is used by ProxyManager to satisfy requested timeout</li>
* <li>If timeouts is not supported by underlying technology, but it is possible to deal with timeout on Bucket4j library level(like specifying timeouts on CompletableFuture), then this way is applied.</li>
* <li>If nothing from above can be applied, then specified {@code requestTimeout} is totally ignored by {@link ProxyManager}</li>
* </ol>
*
* @param requestTimeout timeout for remote operations.
*
* @return new instance of {@link ClientSideConfig} with configured {@code requestTimeout}.
*/
public ClientSideConfig withRequestTimeout(Duration requestTimeout) {<FILL_FUNCTION_BODY>}
/**
* Returns new instance of {@link ClientSideConfig} with configured strategy for choosing time to live for buckets.
* If particular {@link ProxyManager} does not support {@link ExpirationAfterWriteStrategy}
* then exception will be thrown in attempt to construct such ProxyManager with this instance of {@link ClientSideConfig}.
*
* @param expirationStrategy the strategy for choosing time to live for buckets.
*
* @return new instance of {@link ClientSideConfig} with configured {@code expirationStrategy}.
*/
public ClientSideConfig withExpirationAfterWriteStrategy(ExpirationAfterWriteStrategy expirationStrategy) {
return new ClientSideConfig(backwardCompatibilityVersion, clientSideClock, executionStrategy, requestTimeoutNanos, Optional.of(expirationStrategy));
}
/**
* Returns the strategy for choosing time to live for buckets.
*
* @return the strategy for choosing time to live for buckets
*/
public Optional<ExpirationAfterWriteStrategy> getExpirationAfterWriteStrategy() {
return expirationStrategy;
}
/**
* Returns clock that will be used for time measurement.
*
* @return clock that will be used for time measurement.
*
* @see #withClientClock(TimeMeter)
*/
public Optional<TimeMeter> getClientSideClock() {
return clientSideClock;
}
/**
* Returns timeout for remote operations
*
* @return timeout for remote operations
*/
public Optional<Long> getRequestTimeoutNanos() {
return requestTimeoutNanos;
}
/**
* Returns the Bucket4j protocol version is used to be backward compatible with other nodes in the cluster.
*
* @return the Bucket4j protocol version is used to be backward compatible with other nodes in the cluster.
*
* @see #backwardCompatibleWith(Version)
*/
public Version getBackwardCompatibilityVersion() {
return backwardCompatibilityVersion;
}
/**
* Returns the strategy for request execution
*
* @return the strategy for request execution
*/
public ExecutionStrategy getExecutionStrategy() {
return executionStrategy;
}
}
|
if (requestTimeout.isZero() || requestTimeout.isNegative()) {
throw BucketExceptions.nonPositiveRequestTimeout(requestTimeout);
}
long requestTimeoutNanos = requestTimeout.toNanos();
return new ClientSideConfig(backwardCompatibilityVersion, clientSideClock, executionStrategy, Optional.of(requestTimeoutNanos), expirationStrategy);
| 1,833
| 95
| 1,928
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/generic/compare_and_swap/AbstractCompareAndSwapBasedProxyManager.java
|
AbstractCompareAndSwapBasedProxyManager
|
execute
|
class AbstractCompareAndSwapBasedProxyManager<K> extends AbstractProxyManager<K> {
private static final CommandResult<?> UNSUCCESSFUL_CAS_RESULT = null;
protected AbstractCompareAndSwapBasedProxyManager(ClientSideConfig clientSideConfig) {
super(injectTimeClock(clientSideConfig));
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
Timeout timeout = Timeout.of(getClientSideConfig());
CompareAndSwapOperation operation = timeout.call(requestTimeout -> beginCompareAndSwapOperation(key));
while (true) {
CommandResult<T> result = execute(request, operation, timeout);
if (result != UNSUCCESSFUL_CAS_RESULT) {
return result;
}
}
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
Timeout timeout = Timeout.of(getClientSideConfig());
AsyncCompareAndSwapOperation operation = beginAsyncCompareAndSwapOperation(key);
CompletableFuture<CommandResult<T>> result = executeAsync(request, operation, timeout);
return result.thenCompose((CommandResult<T> response) -> retryIfCasWasUnsuccessful(operation, request, response, timeout));
}
protected abstract CompareAndSwapOperation beginCompareAndSwapOperation(K key);
protected abstract AsyncCompareAndSwapOperation beginAsyncCompareAndSwapOperation(K key);
private <T> CommandResult<T> execute(Request<T> request, CompareAndSwapOperation operation, Timeout timeout) {<FILL_FUNCTION_BODY>}
private <T> CompletableFuture<CommandResult<T>> retryIfCasWasUnsuccessful(AsyncCompareAndSwapOperation operation, Request<T> request, CommandResult<T> casResponse, Timeout timeout) {
if (casResponse != UNSUCCESSFUL_CAS_RESULT) {
return CompletableFuture.completedFuture(casResponse);
} else {
return executeAsync(request, operation, timeout).thenCompose((CommandResult<T> response) -> retryIfCasWasUnsuccessful(operation, request, response, timeout));
}
}
private <T> CompletableFuture<CommandResult<T>> executeAsync(Request<T> request, AsyncCompareAndSwapOperation operation, Timeout timeout) {
return timeout.callAsync(operation::getStateData)
.thenApply((Optional<byte[]> originalStateBytes) -> originalStateBytes.orElse(null))
.thenCompose((byte[] originalStateBytes) -> {
RemoteCommand<T> command = request.getCommand();
MutableBucketEntry entry = new MutableBucketEntry(originalStateBytes);
CommandResult<T> result = command.execute(entry, getClientSideTime());
if (!entry.isStateModified()) {
return CompletableFuture.completedFuture(result);
}
byte[] newStateBytes = entry.getStateBytes(request.getBackwardCompatibilityVersion());
return timeout.callAsync(requestTimeout -> operation.compareAndSwap(originalStateBytes, newStateBytes, entry.get(), requestTimeout))
.thenApply((casWasSuccessful) -> casWasSuccessful? result : null);
});
}
private static ClientSideConfig injectTimeClock(ClientSideConfig clientSideConfig) {
if (clientSideConfig.getClientSideClock().isPresent()) {
return clientSideConfig;
}
return clientSideConfig.withClientClock(TimeMeter.SYSTEM_MILLISECONDS);
}
}
|
RemoteCommand<T> command = request.getCommand();
byte[] originalStateBytes = timeout.call(operation::getStateData).orElse(null);
MutableBucketEntry entry = new MutableBucketEntry(originalStateBytes);
CommandResult<T> result = command.execute(entry, getClientSideTime());
if (!entry.isStateModified()) {
return result;
}
byte[] newStateBytes = entry.getStateBytes(request.getBackwardCompatibilityVersion());
if (timeout.call(requestTimeout -> operation.compareAndSwap(originalStateBytes, newStateBytes, entry.get(), requestTimeout))) {
return result;
} else {
return null;
}
| 916
| 178
| 1,094
|
<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-core/src/main/java/io/github/bucket4j/distributed/proxy/generic/pessimistic_locking/AbstractLockBasedProxyManager.java
|
AbstractLockBasedProxyManager
|
execute
|
class AbstractLockBasedProxyManager<K> extends AbstractProxyManager<K> {
protected AbstractLockBasedProxyManager(ClientSideConfig clientSideConfig) {
super(injectTimeClock(clientSideConfig));
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
Timeout timeout = Timeout.of(getClientSideConfig());
LockBasedTransaction transaction = timeout.call(requestTimeout -> allocateTransaction(key, requestTimeout));
try {
return execute(request, transaction, timeout);
} finally {
transaction.release();
}
}
@Override
public boolean isAsyncModeSupported() {
return false;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
throw new UnsupportedOperationException();
}
@Override
protected CompletableFuture<Void> removeAsync(Object key) {
return null;
}
protected abstract LockBasedTransaction allocateTransaction(K key, Optional<Long> timeoutNanos);
private <T> CommandResult<T> execute(Request<T> request, LockBasedTransaction transaction, Timeout timeout) {<FILL_FUNCTION_BODY>}
private void unlockAndRollback(LockBasedTransaction transaction) {
try {
transaction.unlock();
} finally {
transaction.rollback();
}
}
private static ClientSideConfig injectTimeClock(ClientSideConfig clientSideConfig) {
if (clientSideConfig.getClientSideClock().isPresent()) {
return clientSideConfig;
}
return clientSideConfig.withClientClock(TimeMeter.SYSTEM_MILLISECONDS);
}
protected void applyTimeout(PreparedStatement statement, Optional<Long> requestTimeoutNanos) throws SQLException {
if (requestTimeoutNanos.isPresent()) {
int timeoutSeconds = (int) Math.max(1, TimeUnit.NANOSECONDS.toSeconds(requestTimeoutNanos.get()));
statement.setQueryTimeout(timeoutSeconds);
}
}
}
|
RemoteCommand<T> command = request.getCommand();
timeout.run(transaction::begin);
// lock and get data
byte[] persistedDataOnBeginOfTransaction;
try {
persistedDataOnBeginOfTransaction = timeout.call(transaction::lockAndGet);
} catch (Throwable t) {
unlockAndRollback(transaction);
throw BucketExceptions.from(t);
}
// check that command is able to provide initial state in case of bucket does not exist
if (persistedDataOnBeginOfTransaction == null && !request.getCommand().isInitializationCommand()) {
unlockAndRollback(transaction);
return CommandResult.bucketNotFound();
}
try {
MutableBucketEntry entry = new MutableBucketEntry(persistedDataOnBeginOfTransaction);
CommandResult<T> result = command.execute(entry, super.getClientSideTime());
if (entry.isStateModified()) {
byte[] bytes = entry.getStateBytes(request.getBackwardCompatibilityVersion());
if (persistedDataOnBeginOfTransaction == null) {
timeout.run(requestTimeout -> transaction.create(bytes, entry.get(), requestTimeout));
} else {
timeout.run(requestTimeout -> transaction.update(bytes, entry.get(), requestTimeout));
}
}
transaction.unlock();
timeout.run(transaction::commit);
return result;
} catch (Throwable t) {
unlockAndRollback(transaction);
throw BucketExceptions.from(t);
}
| 541
| 387
| 928
|
<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-core/src/main/java/io/github/bucket4j/distributed/proxy/generic/select_for_update/AbstractSelectForUpdateBasedProxyManager.java
|
AbstractSelectForUpdateBasedProxyManager
|
execute
|
class AbstractSelectForUpdateBasedProxyManager<K> extends AbstractProxyManager<K> {
private static final CommandResult RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION = CommandResult.success(true, 666);
protected AbstractSelectForUpdateBasedProxyManager(ClientSideConfig clientSideConfig) {
super(injectTimeClock(clientSideConfig));
}
@Override
public <T> CommandResult<T> execute(K key, Request<T> request) {
Timeout timeout = Timeout.of(getClientSideConfig());
while (true) {
SelectForUpdateBasedTransaction transaction = timeout.call(timeoutNanos -> allocateTransaction(key, timeoutNanos));
CommandResult<T> result;
try {
result = execute(request, transaction, timeout);
} finally {
transaction.release();
}
if (result != RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION) {
return result;
}
}
}
@Override
public boolean isAsyncModeSupported() {
return false;
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(K key, Request<T> request) {
throw new UnsupportedOperationException();
}
@Override
protected CompletableFuture<Void> removeAsync(Object key) {
return null;
}
protected abstract SelectForUpdateBasedTransaction allocateTransaction(K key, Optional<Long> timeoutNanos);
private <T> CommandResult<T> execute(Request<T> request, SelectForUpdateBasedTransaction transaction, Timeout timeout) {<FILL_FUNCTION_BODY>}
private static ClientSideConfig injectTimeClock(ClientSideConfig clientSideConfig) {
if (clientSideConfig.getClientSideClock().isPresent()) {
return clientSideConfig;
}
return clientSideConfig.withClientClock(TimeMeter.SYSTEM_MILLISECONDS);
}
protected void applyTimeout(PreparedStatement statement, Optional<Long> requestTimeoutNanos) throws SQLException {
if (requestTimeoutNanos.isPresent()) {
int timeoutSeconds = (int) Math.max(1, TimeUnit.NANOSECONDS.toSeconds(requestTimeoutNanos.get()));
statement.setQueryTimeout(timeoutSeconds);
}
}
}
|
RemoteCommand<T> command = request.getCommand();
timeout.run(transaction::begin);
// lock and get data
LockAndGetResult lockResult;
byte[] persistedDataOnBeginOfTransaction;
try {
lockResult = timeout.call(transaction::tryLockAndGet);
} catch (Throwable t) {
transaction.rollback();
throw BucketExceptions.from(t);
}
// insert data that can be locked in next transaction if data does not exist
if (!lockResult.isLocked()) {
try {
if (timeout.call(transaction::tryInsertEmptyData)) {
timeout.run(transaction::commit);
} else {
transaction.rollback();
}
return RETRY_IN_THE_SCOPE_OF_NEW_TRANSACTION;
} catch (Throwable t) {
transaction.rollback();
throw BucketExceptions.from(t);
}
}
// check that command is able to provide initial state in case of bucket does not exist
persistedDataOnBeginOfTransaction = lockResult.getData();
if (persistedDataOnBeginOfTransaction == null && !request.getCommand().isInitializationCommand()) {
transaction.rollback();
return CommandResult.bucketNotFound();
}
try {
MutableBucketEntry entry = new MutableBucketEntry(persistedDataOnBeginOfTransaction);
CommandResult<T> result = command.execute(entry, super.getClientSideTime());
if (entry.isStateModified()) {
RemoteBucketState modifiedState = entry.get();
byte[] bytes = entry.getStateBytes(request.getBackwardCompatibilityVersion());
timeout.run(threshold -> transaction.update(bytes, modifiedState, threshold));
}
timeout.run(transaction::commit);
return result;
} catch (Throwable t) {
transaction.rollback();
throw BucketExceptions.from(t);
}
| 610
| 493
| 1,103
|
<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-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/Optimizations.java
|
Optimizations
|
predicting
|
class Optimizations {
/**
* Creates optimization that combines independent requests to same bucket into batches in order to reduce request count to remote storage.
*
* @return new instance of {@link BatchingOptimization}
*
* @see BatchingOptimization
*/
public static Optimization batching() {
return new BatchingOptimization(NopeOptimizationListener.INSTANCE);
}
/**
* Creates optimization that can serve requests locally without synchronization with external storage until thresholds are not violated.
*
* @param delayParameters thresholds that control whether or not request can be served locally without synchronization with external storage
*
* @return new instance of {@link DelayOptimization}
*
* @see DelayOptimization
*/
public static Optimization delaying(DelayParameters delayParameters) {
return new DelayOptimization(delayParameters, NopeOptimizationListener.INSTANCE, TimeMeter.SYSTEM_MILLISECONDS);
}
/**
* Creates optimization that can serve requests locally without synchronization with external storage until thresholds are not violated,
* and additionally tries to predict aggregated consumption rate in whole cluster in order to reduce the risk of overconsumption that caused by {@link DelayOptimization}.
*
* @param delayParameters thresholds that control whether or not request can be served locally without synchronization with external storage
* @param predictionParameters parameters that control the quality of prediction of distributed consumption rate
*
* @return new instance of {@link PredictiveOptimization}
*
* @see PredictiveOptimization
* @see PredictionParameters
* @see DelayParameters
*/
public static Optimization predicting(DelayParameters delayParameters, PredictionParameters predictionParameters) {
return new PredictiveOptimization(predictionParameters, delayParameters, NopeOptimizationListener.INSTANCE, TimeMeter.SYSTEM_MILLISECONDS);
}
/**
* Has the same semantic as {@link #predicting(DelayParameters, PredictionParameters)} but uses default {@link PredictionParameters}.
*
* @param delayParameters thresholds that control whether or not request can be served locally without synchronization with external storage
*
* @return new instance of {@link PredictiveOptimization}
*
* @see PredictiveOptimization
* @see PredictionParameters
*/
public static Optimization predicting(DelayParameters delayParameters) {<FILL_FUNCTION_BODY>}
}
|
PredictionParameters defaultPrediction = PredictionParameters.createDefault(delayParameters);
return new PredictiveOptimization(defaultPrediction, delayParameters, NopeOptimizationListener.INSTANCE, TimeMeter.SYSTEM_MILLISECONDS);
| 623
| 63
| 686
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/PredictionParameters.java
|
PredictionParameters
|
createDefault
|
class PredictionParameters {
public static final int DEFAULT_MIN_SAMPLES = 2;
public static final int DEFAULT_MAX_SAMPLES = 10;
public final int minSamples;
public final int maxSamples;
public final long sampleMaxAgeNanos;
/**
* Creates new instance of {@link PredictionParameters}
*
* @param minSamples the minimum amount of samples that requred to make prediction about distributed consumption rate.
* @param maxSamples the maximum amount of samples to store.
* @param sampleMaxAge the maximum period of time that sample is stored.
*/
public PredictionParameters(int minSamples, int maxSamples, Duration sampleMaxAge) {
this(minSamples, maxSamples, sampleMaxAge.toNanos());
}
public PredictionParameters(int minSamples, int maxSamples, long maxUnsynchronizedTimeoutNanos) {
if (minSamples < 2) {
throw BucketExceptions.wrongValueOfMinSamplesForPredictionParameters(minSamples);
}
this.minSamples = minSamples;
if (maxSamples < minSamples) {
throw BucketExceptions.maxSamplesForPredictionParametersCanNotBeLessThanMinSamples(minSamples, maxSamples);
}
this.maxSamples = maxSamples;
if (maxUnsynchronizedTimeoutNanos <= 0) {
throw BucketExceptions.nonPositiveSampleMaxAgeForPredictionParameters(maxUnsynchronizedTimeoutNanos);
}
this.sampleMaxAgeNanos = maxUnsynchronizedTimeoutNanos;
}
public static PredictionParameters createDefault(DelayParameters delayParameters) {<FILL_FUNCTION_BODY>}
public int getMinSamples() {
return minSamples;
}
public int getMaxSamples() {
return maxSamples;
}
public long getSampleMaxAgeNanos() {
return sampleMaxAgeNanos;
}
}
|
long sampleMaxAge = delayParameters.maxUnsynchronizedTimeoutNanos * 2;
return new PredictionParameters(DEFAULT_MIN_SAMPLES, DEFAULT_MAX_SAMPLES, sampleMaxAge);
| 527
| 56
| 583
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/batch/AsyncBatchingExecutor.java
|
AsyncBatchingExecutor
|
apply
|
class AsyncBatchingExecutor implements AsyncCommandExecutor {
private final AsyncBatchHelper<RemoteCommand<?>, CommandResult<?>, MultiCommand, CommandResult<MultiResult>> batchingHelper;
private final AsyncCommandExecutor wrappedExecutor;
private final OptimizationListener listener;
private final Function<List<RemoteCommand<?>>, MultiCommand> taskCombiner = new Function<>() {
@Override
public MultiCommand apply(List<RemoteCommand<?>> commands) {
if (commands.size() > 1) {
listener.incrementMergeCount(commands.size() - 1);
}
return MultiCommand.merge(commands);
}
};
private final Function<MultiCommand, CompletableFuture<CommandResult<MultiResult>>> combinedTaskExecutor = new Function<>() {
@Override
public CompletableFuture<CommandResult<MultiResult>> apply(MultiCommand multiCommand) {
return wrappedExecutor.executeAsync(multiCommand);
}
};
private final Function<RemoteCommand<?>, CompletableFuture<CommandResult<?>>> taskExecutor = new Function<>() {
@Override
public CompletableFuture<CommandResult<?>> apply(RemoteCommand<?> remoteCommand) {<FILL_FUNCTION_BODY>}
};
private final BiFunction<MultiCommand, CommandResult<MultiResult>, List<CommandResult<?>>> combinedResultSplitter = new BiFunction<>() {
@Override
public List<CommandResult<?>> apply(MultiCommand multiCommand, CommandResult<MultiResult> multiResult) {
return multiCommand.unwrap(multiResult);
}
};
public AsyncBatchingExecutor(AsyncCommandExecutor originalExecutor, OptimizationListener listener) {
this.wrappedExecutor = originalExecutor;
this.listener = listener;
this.batchingHelper = AsyncBatchHelper.create(taskCombiner, combinedTaskExecutor, taskExecutor, combinedResultSplitter);
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(RemoteCommand<T> command) {
CompletableFuture<T> future = (CompletableFuture<T>) batchingHelper.executeAsync(command);
return (CompletableFuture<CommandResult<T>>) future;
}
}
|
CompletableFuture<? extends CommandResult<?>> future = wrappedExecutor.executeAsync(remoteCommand);
return (CompletableFuture<CommandResult<?>>) future;
| 557
| 43
| 600
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/batch/BatchingExecutor.java
|
BatchingExecutor
|
apply
|
class BatchingExecutor implements CommandExecutor {
private final BatchHelper<RemoteCommand<?>, CommandResult<?>, MultiCommand, CommandResult<MultiResult>> batchingHelper;
private final CommandExecutor wrappedExecutor;
private final OptimizationListener listener;
private final Function<List<RemoteCommand<?>>, MultiCommand> taskCombiner = new Function<>() {
@Override
public MultiCommand apply(List<RemoteCommand<?>> commands) {<FILL_FUNCTION_BODY>}
};
private final Function<MultiCommand, CommandResult<MultiResult>> combinedTaskExecutor = new Function<>() {
@Override
public CommandResult<MultiResult> apply(MultiCommand multiCommand) {
return wrappedExecutor.execute(multiCommand);
}
};
private final Function<RemoteCommand<?>, CommandResult<?>> taskExecutor = new Function<>() {
@Override
public CommandResult<?> apply(RemoteCommand<?> remoteCommand) {
return wrappedExecutor.execute(remoteCommand);
}
};
private final BiFunction<MultiCommand, CommandResult<MultiResult>, List<CommandResult<?>>> combinedResultSplitter = new BiFunction<>() {
@Override
public List<CommandResult<?>> apply(MultiCommand multiCommand, CommandResult<MultiResult> multiResult) {
return multiCommand.unwrap(multiResult);
}
};
public BatchingExecutor(CommandExecutor originalExecutor, OptimizationListener listener) {
this.wrappedExecutor = originalExecutor;
this.listener = listener;
this.batchingHelper = BatchHelper.create(taskCombiner, combinedTaskExecutor, taskExecutor, combinedResultSplitter);
}
@Override
public <T> CommandResult<T> execute(RemoteCommand<T> command) {
return (CommandResult<T>) batchingHelper.execute(command);
}
}
|
if (commands.size() > 1) {
listener.incrementMergeCount(commands.size() - 1);
}
return MultiCommand.merge(commands);
| 464
| 49
| 513
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/delay/DelayOptimization.java
|
DelayOptimization
|
apply
|
class DelayOptimization implements Optimization {
private final DelayParameters delayParameters;
private final OptimizationListener listener;
private final TimeMeter timeMeter;
public DelayOptimization(DelayParameters delayParameters, OptimizationListener listener, TimeMeter timeMeter) {
this.delayParameters = delayParameters;
this.timeMeter = timeMeter;
this.listener = listener;
}
@Override
public Optimization withListener(OptimizationListener listener) {
return new DelayOptimization(delayParameters, listener, timeMeter);
}
@Override
public CommandExecutor apply(CommandExecutor originalExecutor) {<FILL_FUNCTION_BODY>}
@Override
public AsyncCommandExecutor apply(AsyncCommandExecutor originalExecutor) {
DelayedCommandExecutor predictiveCommandExecutor = new DelayedCommandExecutor(originalExecutor, delayParameters, listener, timeMeter);
return new AsyncBatchingExecutor(predictiveCommandExecutor, listener);
}
}
|
DelayedCommandExecutor predictiveCommandExecutor = new DelayedCommandExecutor(originalExecutor, delayParameters, listener, timeMeter);
return new BatchingExecutor(predictiveCommandExecutor, listener);
| 251
| 50
| 301
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/delay/DelayedCommandExecutor.java
|
DelayedCommandExecutor
|
executeAsync
|
class DelayedCommandExecutor implements CommandExecutor, AsyncCommandExecutor {
private static final int ORIGINAL_COMMAND_INDEX = 1;
private static final int GET_SNAPSHOT_COMMAND_INDEX = 2;
private final CommandExecutor originalExecutor;
private final AsyncCommandExecutor originalAsyncExecutor;
private final DelayParameters delayParameters;
private final OptimizationListener listener;
private final TimeMeter timeMeter;
private RemoteBucketState state;
private long lastSyncTimeNanos;
private long postponedToConsumeTokens;
DelayedCommandExecutor(CommandExecutor originalExecutor, DelayParameters delayParameters, OptimizationListener listener, TimeMeter timeMeter) {
this.originalExecutor = originalExecutor;
this.originalAsyncExecutor = null;
this.delayParameters = delayParameters;
this.listener = listener;
this.timeMeter = timeMeter;
}
DelayedCommandExecutor(AsyncCommandExecutor originalAsyncExecutor, DelayParameters delayParameters, OptimizationListener listener, TimeMeter timeMeter) {
this.originalExecutor = null;
this.originalAsyncExecutor = originalAsyncExecutor;
this.delayParameters = delayParameters;
this.listener = listener;
this.timeMeter = timeMeter;
}
@Override
public <T> CommandResult<T> execute(RemoteCommand<T> command) {
CommandResult<T> localResult = tryConsumeLocally(command);
if (localResult != null) {
// remote call is not needed
listener.incrementSkipCount(1);
return localResult;
}
MultiCommand remoteCommand = prepareRemoteCommand(command);
CommandResult<MultiResult> commandResult = originalExecutor.execute(remoteCommand);
rememberRemoteCommandResult(commandResult);
return commandResult.isError() ?
(CommandResult<T>) commandResult :
(CommandResult<T>) commandResult.getData().getResults().get(ORIGINAL_COMMAND_INDEX);
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(RemoteCommand<T> command) {<FILL_FUNCTION_BODY>}
private <T> CommandResult<T> tryConsumeLocally(RemoteCommand<T> command) {
long currentTimeNanos = timeMeter.currentTimeNanos();
if (isNeedToExecuteRemoteImmediately(command, currentTimeNanos)) {
return null;
}
// execute local command
MutableBucketEntry entry = new MutableBucketEntry(state.copy());
CommandResult<T> result = command.execute(entry, currentTimeNanos);
if (result.isConfigurationNeedToBeReplaced()) {
return null;
}
long locallyConsumedTokens = command.getConsumedTokens(result.getData());
if (locallyConsumedTokens == Long.MAX_VALUE) {
return null;
}
if (!isLocalExecutionResultSatisfiesThreshold(locallyConsumedTokens)) {
return null;
}
postponedToConsumeTokens += locallyConsumedTokens;
if (entry.isStateModified()) {
state = entry.get();
}
return result;
}
private boolean isLocalExecutionResultSatisfiesThreshold(long locallyConsumedTokens) {
if (locallyConsumedTokens == Long.MAX_VALUE || postponedToConsumeTokens + locallyConsumedTokens < 0) {
// math overflow
return false;
}
return postponedToConsumeTokens + locallyConsumedTokens <= delayParameters.maxUnsynchronizedTokens;
}
private <T> boolean isNeedToExecuteRemoteImmediately(RemoteCommand<T> command, long currentTimeNanos) {
if (state == null) {
// was never synchronized before
return true;
}
if (currentTimeNanos - lastSyncTimeNanos > delayParameters.maxUnsynchronizedTimeoutNanos) {
// too long period passed since last sync
return true;
}
if (command.isImmediateSyncRequired(postponedToConsumeTokens, currentTimeNanos - lastSyncTimeNanos)) {
// need to execute immediately because of special command
return true;
}
long commandTokens = command.estimateTokensToConsume();
if (commandTokens == Long.MAX_VALUE || commandTokens + postponedToConsumeTokens < 0) {
// math overflow
return true;
}
return commandTokens + postponedToConsumeTokens > delayParameters.maxUnsynchronizedTokens;
}
private <T> MultiCommand prepareRemoteCommand(RemoteCommand<T> command) {
List<RemoteCommand<?>> commands = new ArrayList<>(3);
commands.add(new ConsumeIgnoringRateLimitsCommand(this.postponedToConsumeTokens));
commands.add(command);
commands.add(new CreateSnapshotCommand());
return new MultiCommand(commands);
}
private void rememberRemoteCommandResult(CommandResult<MultiResult> multiResult) {
postponedToConsumeTokens = 0;
lastSyncTimeNanos = timeMeter.currentTimeNanos();
CommandResult<?> snapshotResult = multiResult.isError() ? multiResult : multiResult.getData().getResults().get(GET_SNAPSHOT_COMMAND_INDEX);
if (snapshotResult.isError()) {
state = null;
return;
}
this.state = (RemoteBucketState) snapshotResult.getData();
}
}
|
CommandResult<T> result = tryConsumeLocally(command);
if (result != null) {
// remote call is not needed
listener.incrementSkipCount(1);
return CompletableFuture.completedFuture(result);
}
MultiCommand remoteCommand = prepareRemoteCommand(command);
CompletableFuture<CommandResult<MultiResult>> resultFuture = originalAsyncExecutor.executeAsync(remoteCommand);
return resultFuture.thenApply((CommandResult<MultiResult> remoteResult) -> {
rememberRemoteCommandResult(remoteResult);
return remoteResult.isError() ?
(CommandResult<T>) remoteResult :
(CommandResult<T>) remoteResult.getData().getResults().get(ORIGINAL_COMMAND_INDEX);
});
| 1,425
| 190
| 1,615
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/manual/ManuallySyncingCommandExecutor.java
|
ManuallySyncingCommandExecutor
|
prepareRemoteCommand
|
class ManuallySyncingCommandExecutor implements CommandExecutor, AsyncCommandExecutor {
private static final int ORIGINAL_COMMAND_INDEX = 1;
private static final int GET_SNAPSHOT_COMMAND_INDEX = 2;
private final CommandExecutor originalExecutor;
private final AsyncCommandExecutor originalAsyncExecutor;
private final OptimizationListener listener;
private final TimeMeter timeMeter;
private RemoteBucketState state;
private long lastSyncTimeNanos;
private long postponedToConsumeTokens;
private final ReentrantLock localStateMutationLock = new ReentrantLock();
private final ReentrantLock remoteExecutionLock = new ReentrantLock();
private CompletableFuture<?> inProgressSynchronizationFuture = CompletableFuture.completedFuture(null);
ManuallySyncingCommandExecutor(CommandExecutor originalExecutor, OptimizationListener listener, TimeMeter timeMeter) {
this.originalExecutor = originalExecutor;
this.originalAsyncExecutor = null;
this.listener = listener;
this.timeMeter = timeMeter;
}
ManuallySyncingCommandExecutor(AsyncCommandExecutor originalAsyncExecutor, OptimizationListener listener, TimeMeter timeMeter) {
this.originalExecutor = null;
this.originalAsyncExecutor = originalAsyncExecutor;
this.listener = listener;
this.timeMeter = timeMeter;
}
@Override
public <T> CommandResult<T> execute(RemoteCommand<T> command) {
MultiCommand remoteCommand;
localStateMutationLock.lock();
try {
CommandResult<T> localResult = tryConsumeLocally(command);
if (localResult != null) {
// remote call is not needed
listener.incrementSkipCount(1);
return localResult;
} else {
remoteCommand = prepareRemoteCommand(command);
}
} finally {
localStateMutationLock.unlock();
}
remoteExecutionLock.lock();
try {
CommandResult<MultiResult> remoteResult = originalExecutor.execute(remoteCommand);
rememberRemoteCommandResult(remoteResult);
return remoteResult.isError() ?
(CommandResult<T>) remoteResult :
(CommandResult<T>) remoteResult.getData().getResults().get(ORIGINAL_COMMAND_INDEX);
} finally {
remoteExecutionLock.unlock();
}
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(RemoteCommand<T> command) {
MultiCommand remoteCommand;
localStateMutationLock.lock();
try {
CommandResult<T> result = tryConsumeLocally(command);
if (result != null) {
// remote call is not needed
listener.incrementSkipCount(1);
return CompletableFuture.completedFuture(result);
} else {
remoteCommand = prepareRemoteCommand(command);
}
} finally {
localStateMutationLock.unlock();
}
remoteExecutionLock.lock();
CompletableFuture<CommandResult<MultiResult>> resultFuture;
try {
resultFuture = inProgressSynchronizationFuture.thenCompose(f -> originalAsyncExecutor.executeAsync(remoteCommand));
inProgressSynchronizationFuture = resultFuture.exceptionally((Throwable ex) -> null);
} finally {
remoteExecutionLock.unlock();
}
return resultFuture.thenApply((CommandResult<MultiResult> remoteResult) -> {
rememberRemoteCommandResult(remoteResult);
return remoteResult.isError() ?
(CommandResult<T>) remoteResult :
(CommandResult<T>) remoteResult.getData().getResults().get(ORIGINAL_COMMAND_INDEX);
});
}
private <T> CommandResult<T> tryConsumeLocally(RemoteCommand<T> command) {
long currentTimeNanos = timeMeter.currentTimeNanos();
if (isNeedToExecuteRemoteImmediately(command, currentTimeNanos)) {
return null;
}
// execute local command
MutableBucketEntry entry = new MutableBucketEntry(state.copy());
CommandResult<T> result = command.execute(entry, currentTimeNanos);
if (result.isConfigurationNeedToBeReplaced()) {
return null;
}
long locallyConsumedTokens = command.getConsumedTokens(result.getData());
if (locallyConsumedTokens == Long.MAX_VALUE) {
return null;
}
if (!isLocalExecutionResultSatisfiesThreshold(locallyConsumedTokens)) {
return null;
}
postponedToConsumeTokens += locallyConsumedTokens;
if (entry.isStateModified()) {
state = entry.get();
}
return result;
}
private boolean isLocalExecutionResultSatisfiesThreshold(long locallyConsumedTokens) {
if (locallyConsumedTokens == Long.MAX_VALUE || postponedToConsumeTokens + locallyConsumedTokens < 0) {
// math overflow
return false;
}
return true;
}
private <T> boolean isNeedToExecuteRemoteImmediately(RemoteCommand<T> command, long currentTimeNanos) {
if (state == null) {
// was never synchronized before
return true;
}
if (command.isImmediateSyncRequired(postponedToConsumeTokens, currentTimeNanos - lastSyncTimeNanos)) {
// need to execute immediately because of special command
return true;
}
long commandTokens = command.estimateTokensToConsume();
if (commandTokens == Long.MAX_VALUE || commandTokens + postponedToConsumeTokens < 0) {
// math overflow
return true;
}
return false;
}
private <T> MultiCommand prepareRemoteCommand(RemoteCommand<T> command) {<FILL_FUNCTION_BODY>}
private void rememberRemoteCommandResult(CommandResult<MultiResult> remoteResult) {
localStateMutationLock.lock();
try {
lastSyncTimeNanos = timeMeter.currentTimeNanos();
CommandResult<?> snapshotResult = remoteResult.isError() ? remoteResult : remoteResult.getData().getResults().get(GET_SNAPSHOT_COMMAND_INDEX);
if (snapshotResult.isError()) {
state = null;
return;
}
this.state = (RemoteBucketState) snapshotResult.getData();
// decrease available tokens by amount that consumed while remote request was in progress
if (postponedToConsumeTokens > 0) {
this.state.consume(postponedToConsumeTokens);
}
} finally {
localStateMutationLock.unlock();
}
}
}
|
List<RemoteCommand<?>> commands = new ArrayList<>(3);
commands.add(new ConsumeIgnoringRateLimitsCommand(this.postponedToConsumeTokens));
this.postponedToConsumeTokens = 0;
commands.add(command);
commands.add(new CreateSnapshotCommand());
return new MultiCommand(commands);
| 1,723
| 91
| 1,814
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/predictive/PredictiveOptimization.java
|
PredictiveOptimization
|
apply
|
class PredictiveOptimization implements Optimization {
private final DelayParameters delayParameters;
private final PredictionParameters predictionParameters;
private final OptimizationListener listener;
private final TimeMeter timeMeter;
public PredictiveOptimization(PredictionParameters predictionParameters, DelayParameters delayParameters, OptimizationListener listener, TimeMeter timeMeter) {
this.delayParameters = delayParameters;
this.predictionParameters = predictionParameters;
this.listener = listener;
this.timeMeter = timeMeter;
}
@Override
public Optimization withListener(OptimizationListener listener) {
return new PredictiveOptimization(predictionParameters, delayParameters, listener, timeMeter);
}
@Override
public CommandExecutor apply(CommandExecutor originalExecutor) {
PredictiveCommandExecutor predictiveCommandExecutor = new PredictiveCommandExecutor(originalExecutor, delayParameters, predictionParameters, listener, timeMeter);
return new BatchingExecutor(predictiveCommandExecutor, listener);
}
@Override
public AsyncCommandExecutor apply(AsyncCommandExecutor originalExecutor) {<FILL_FUNCTION_BODY>}
}
|
PredictiveCommandExecutor predictiveCommandExecutor = new PredictiveCommandExecutor(originalExecutor, delayParameters, predictionParameters, listener, timeMeter);
return new AsyncBatchingExecutor(predictiveCommandExecutor, listener);
| 288
| 54
| 342
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/predictive/Sampling.java
|
Sampling
|
predictedConsumptionByOthersSinceLastSync
|
class Sampling {
private final PredictionParameters predictionParameters;
private LinkedList<Sample> samples = new LinkedList<>();
private double othersRate;
public Sampling(PredictionParameters predictionParameters) {
this.predictionParameters = predictionParameters;
}
public boolean isNeedToExecuteRemoteImmediately(long currentTimeNanos) {
while (!samples.isEmpty()) {
Sample sample = samples.getFirst();
long sampleAge = currentTimeNanos - sample.syncTimeNanos;
if (sampleAge > predictionParameters.sampleMaxAgeNanos) {
samples.removeFirst();
} else {
break;
}
}
return othersRate == Double.POSITIVE_INFINITY || samples.size() < predictionParameters.minSamples;
}
public long predictedConsumptionByOthersSinceLastSync(long currentTimeNanos) {<FILL_FUNCTION_BODY>}
public void rememberRemoteCommandResult(long selfConsumedTokens, long consumedTokensCounter, long now) {
othersRate = 0.0;
Sample freshSample = new Sample(now, consumedTokensCounter, selfConsumedTokens);
Iterator<Sample> samplesIterator = samples.iterator();
while (samplesIterator.hasNext()) {
Sample sample = samplesIterator.next();
if (freshSample.observedConsumptionCounter < sample.observedConsumptionCounter) {
samplesIterator.remove();
} else if (now - sample.syncTimeNanos > predictionParameters.sampleMaxAgeNanos) {
samplesIterator.remove();
} else if (freshSample.syncTimeNanos < sample.syncTimeNanos) {
samplesIterator.remove();
} else if (freshSample.syncTimeNanos == sample.syncTimeNanos) {
if (sample != samples.getFirst()) {
freshSample.selfConsumedTokens += sample.selfConsumedTokens;
samplesIterator.remove();
}
}
}
samples.addLast(freshSample);
if (samples.size() > predictionParameters.maxSamples) {
samples.removeFirst();
} else if (samples.size() < predictionParameters.minSamples) {
return;
}
// let's predict consumption rate in the cluster
Sample oldestSample = samples.getFirst();
long tokensSelfConsumedDuringSamplePeriod = 0;
for (Sample sample : samples) {
if (sample != oldestSample) {
tokensSelfConsumedDuringSamplePeriod += sample.selfConsumedTokens;
}
}
long tokensConsumedByOthersDuringSamplingPeriod = freshSample.observedConsumptionCounter - oldestSample.observedConsumptionCounter - tokensSelfConsumedDuringSamplePeriod;
if (tokensConsumedByOthersDuringSamplingPeriod <= 0) {
return;
}
long timeBetweenSynchronizations = freshSample.syncTimeNanos - oldestSample.syncTimeNanos;
if (timeBetweenSynchronizations == 0) {
// should never be there in real cases.
// cannot divide by zero
othersRate = Double.POSITIVE_INFINITY;
return;
}
this.othersRate = (double) tokensConsumedByOthersDuringSamplingPeriod / (double) timeBetweenSynchronizations;
}
public long getLastSyncTimeNanos() {
return samples.getLast().syncTimeNanos;
}
public void clear() {
samples.clear();
}
private static class Sample {
private long syncTimeNanos;
private long observedConsumptionCounter;
private long selfConsumedTokens;
public Sample(long syncTimeNanos, long observedConsumptionCounter, long selfConsumedTokens) {
this.syncTimeNanos = syncTimeNanos;
this.observedConsumptionCounter = observedConsumptionCounter;
this.selfConsumedTokens = selfConsumedTokens;
}
}
}
|
Sample freshSample = samples.getLast();
long timeSinceLastSync = currentTimeNanos - freshSample.syncTimeNanos;
if (timeSinceLastSync <= 0 || othersRate == 0.0) {
return 0L;
}
double predictedConsumptionSinceLastSync = othersRate * timeSinceLastSync;
if (predictedConsumptionSinceLastSync >= Long.MAX_VALUE) {
return Long.MAX_VALUE;
}
return (long) predictedConsumptionSinceLastSync;
| 1,018
| 129
| 1,147
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/skiponzero/SkipSyncOnZeroCommandExecutor.java
|
SkipSyncOnZeroCommandExecutor
|
rememberRemoteCommandResult
|
class SkipSyncOnZeroCommandExecutor implements CommandExecutor, AsyncCommandExecutor {
private static final int ORIGINAL_COMMAND_INDEX = 0;
private static final int GET_SNAPSHOT_COMMAND_INDEX = 1;
private final CommandExecutor originalExecutor;
private final AsyncCommandExecutor originalAsyncExecutor;
private final OptimizationListener listener;
private final TimeMeter timeMeter;
private RemoteBucketState state;
private long lastSyncTimeNanos;
SkipSyncOnZeroCommandExecutor(CommandExecutor originalExecutor, OptimizationListener listener, TimeMeter timeMeter) {
this.originalExecutor = originalExecutor;
this.originalAsyncExecutor = null;
this.listener = listener;
this.timeMeter = timeMeter;
}
SkipSyncOnZeroCommandExecutor(AsyncCommandExecutor originalAsyncExecutor, OptimizationListener listener, TimeMeter timeMeter) {
this.originalExecutor = null;
this.originalAsyncExecutor = originalAsyncExecutor;
this.listener = listener;
this.timeMeter = timeMeter;
}
@Override
public <T> CommandResult<T> execute(RemoteCommand<T> command) {
CommandResult<T> localResult = tryExecuteLocally(command);
if (localResult != null) {
// remote call is not needed
listener.incrementSkipCount(1);
return localResult;
}
MultiCommand remoteCommand = prepareRemoteCommand(command);
CommandResult<MultiResult> remoteResult = originalExecutor.execute(remoteCommand);
rememberRemoteCommandResult(remoteResult);
return remoteResult.isError() ?
(CommandResult<T>) remoteResult :
(CommandResult<T>) remoteResult.getData().getResults().get(ORIGINAL_COMMAND_INDEX);
}
@Override
public <T> CompletableFuture<CommandResult<T>> executeAsync(RemoteCommand<T> command) {
CommandResult<T> result = tryExecuteLocally(command);
if (result != null) {
// remote call is not needed
listener.incrementSkipCount(1);
return CompletableFuture.completedFuture(result);
}
MultiCommand remoteCommand = prepareRemoteCommand(command);
CompletableFuture<CommandResult<MultiResult>> resultFuture = originalAsyncExecutor.executeAsync(remoteCommand);
return resultFuture.thenApply((CommandResult<MultiResult> remoteResult) -> {
rememberRemoteCommandResult(remoteResult);
return remoteResult.isError() ?
(CommandResult<T>) remoteResult :
(CommandResult<T>) remoteResult.getData().getResults().get(ORIGINAL_COMMAND_INDEX);
});
}
private <T> CommandResult<T> tryExecuteLocally(RemoteCommand<T> command) {
long currentTimeNanos = timeMeter.currentTimeNanos();
long commandConsumeTokens = command.estimateTokensToConsume();
if (isNeedToExecuteRemoteImmediately(command, commandConsumeTokens, currentTimeNanos)) {
return null;
}
// execute local command
MutableBucketEntry entry = new MutableBucketEntry(state.copy());
CommandResult<T> result = command.execute(entry, currentTimeNanos);
if (result.isConfigurationNeedToBeReplaced()) {
return null;
}
long locallyConsumedTokens = command.getConsumedTokens(result.getData());
if (locallyConsumedTokens == Long.MAX_VALUE) {
return null;
}
if (!isLocalExecutionResultSatisfiesThreshold(locallyConsumedTokens)) {
return null;
}
if (entry.isStateModified()) {
state = entry.get();
}
if (locallyConsumedTokens > 0) {
// something can be consumed, it needs to execute request on server
return null;
}
return result;
}
private boolean isLocalExecutionResultSatisfiesThreshold(long locallyConsumedTokens) {
if (locallyConsumedTokens == Long.MAX_VALUE || locallyConsumedTokens < 0) {
// math overflow
return false;
}
return true;
}
private <T> boolean isNeedToExecuteRemoteImmediately(RemoteCommand<T> command, long commandConsumeTokens, long currentTimeNanos) {
if (state == null) {
// was never synchronized before
return true;
}
if (commandConsumeTokens == 0) {
// it is not consumption command
return true;
}
if (command.isImmediateSyncRequired(0, currentTimeNanos - lastSyncTimeNanos)) {
// need to execute immediately because of special command
return true;
}
if (commandConsumeTokens == Long.MAX_VALUE || commandConsumeTokens < 0) {
// math overflow
return true;
}
return false;
}
private <T> MultiCommand prepareRemoteCommand(RemoteCommand<T> command) {
List<RemoteCommand<?>> commands = new ArrayList<>(3);
commands.add(command);
commands.add(new CreateSnapshotCommand());
return new MultiCommand(commands);
}
private void rememberRemoteCommandResult(CommandResult<MultiResult> remoteResult) {<FILL_FUNCTION_BODY>}
}
|
lastSyncTimeNanos = timeMeter.currentTimeNanos();
CommandResult<?> snapshotResult = remoteResult.isError() ? remoteResult : remoteResult.getData().getResults().get(GET_SNAPSHOT_COMMAND_INDEX);
if (snapshotResult.isError()) {
state = null;
return;
}
this.state = (RemoteBucketState) snapshotResult.getData();
| 1,360
| 108
| 1,468
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/optimization/skiponzero/SkipSyncOnZeroOptimization.java
|
SkipSyncOnZeroOptimization
|
apply
|
class SkipSyncOnZeroOptimization implements Optimization {
private final OptimizationListener listener;
private final TimeMeter timeMeter;
public SkipSyncOnZeroOptimization(OptimizationListener listener, TimeMeter timeMeter) {
this.timeMeter = timeMeter;
this.listener = listener;
}
@Override
public Optimization withListener(OptimizationListener listener) {
return new SkipSyncOnZeroOptimization(listener, timeMeter);
}
@Override
public CommandExecutor apply(CommandExecutor originalExecutor) {
SkipSyncOnZeroCommandExecutor predictiveCommandExecutor = new SkipSyncOnZeroCommandExecutor(originalExecutor, listener, timeMeter);
return new BatchingExecutor(predictiveCommandExecutor, listener);
}
@Override
public AsyncCommandExecutor apply(AsyncCommandExecutor originalExecutor) {<FILL_FUNCTION_BODY>}
}
|
SkipSyncOnZeroCommandExecutor predictiveCommandExecutor = new SkipSyncOnZeroCommandExecutor(originalExecutor, listener, timeMeter);
return new AsyncBatchingExecutor(predictiveCommandExecutor, listener);
| 234
| 52
| 286
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/AbstractBinaryTransaction.java
|
AbstractBinaryTransaction
|
execute
|
class AbstractBinaryTransaction {
private final byte[] requestBytes;
private Version backwardCompatibilityVersion;
private Request<?> request;
private long currentTimeNanos;
protected AbstractBinaryTransaction(byte[] requestBytes) {
this.requestBytes = requestBytes;
}
public byte[] execute() {<FILL_FUNCTION_BODY>}
protected abstract byte[] getRawState();
protected abstract void setRawState(byte[] newStateBytes, RemoteBucketState newState);
public abstract boolean exists();
protected Request<?> getRequest() {
return request;
}
protected ExpirationAfterWriteStrategy getExpirationStrategy() {
return request.getExpirationStrategy();
}
protected long getCurrentTimeNanos() {
return currentTimeNanos;
}
}
|
try {
request = InternalSerializationHelper.deserializeRequest(requestBytes);
} catch (UnsupportedTypeException e) {
return serializeResult(CommandResult.unsupportedType(e.getTypeId()), Versions.getOldest());
} catch (UsageOfUnsupportedApiException e) {
return serializeResult(CommandResult.usageOfUnsupportedApiException(e.getRequestedFormatNumber(), e.getMaxSupportedFormatNumber()), Versions.getOldest());
} catch (UsageOfObsoleteApiException e) {
return serializeResult(CommandResult.usageOfObsoleteApiException(e.getRequestedFormatNumber(), e.getMinSupportedFormatNumber()), Versions.getOldest());
}
backwardCompatibilityVersion = request.getBackwardCompatibilityVersion();
try {
RemoteBucketState currentState = null;
if (exists()) {
byte[] stateBytes = getRawState();
currentState = deserializeState(stateBytes);
}
MutableBucketEntry entryWrapper = new MutableBucketEntry(currentState);
currentTimeNanos = request.getClientSideTime() != null? request.getClientSideTime(): System.currentTimeMillis() * 1_000_000;
RemoteCommand<?> command = request.getCommand();
CommandResult<?> result = command.execute(entryWrapper, currentTimeNanos);
if (entryWrapper.isStateModified()) {
RemoteBucketState newState = entryWrapper.get();
setRawState(serializeState(newState, backwardCompatibilityVersion), newState);
}
return serializeResult(result, request.getBackwardCompatibilityVersion());
} catch (UnsupportedTypeException e) {
return serializeResult(CommandResult.unsupportedType(e.getTypeId()), backwardCompatibilityVersion);
} catch (UsageOfUnsupportedApiException e) {
return serializeResult(CommandResult.usageOfUnsupportedApiException(e.getRequestedFormatNumber(), e.getMaxSupportedFormatNumber()), backwardCompatibilityVersion);
} catch (UsageOfObsoleteApiException e) {
return serializeResult(CommandResult.usageOfObsoleteApiException(e.getRequestedFormatNumber(), e.getMinSupportedFormatNumber()), backwardCompatibilityVersion);
}
| 209
| 566
| 775
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/BucketNotFoundError.java
|
BucketNotFoundError
|
deserialize
|
class BucketNotFoundError implements CommandError, ComparableByContent<BucketNotFoundError> {
private static final BucketNotFoundError INSTANCE = new BucketNotFoundError();
@Override
public RuntimeException asException() {
return new BucketNotFoundException();
}
public static SerializationHandle<BucketNotFoundError> SERIALIZATION_HANDLE = new SerializationHandle<BucketNotFoundError>() {
@Override
public <S> BucketNotFoundError deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, BucketNotFoundError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
}
@Override
public int getTypeId() {
return 15;
}
@Override
public Class<BucketNotFoundError> getSerializedType() {
return (Class) BucketNotFoundError.class;
}
@Override
public BucketNotFoundError fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return INSTANCE;
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(BucketNotFoundError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
return result;
}
@Override
public String getTypeName() {
return "BucketNotFoundError";
}
};
@Override
public boolean equalsByContent(BucketNotFoundError other) {
return true;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return INSTANCE;
| 500
| 49
| 549
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/CommandResult.java
|
CommandResult
|
toJsonCompatibleSnapshot
|
class CommandResult<T> implements ComparableByContent<CommandResult> {
public static final CommandResult<Nothing> NOTHING = CommandResult.success(Nothing.INSTANCE, NULL_HANDLE);
public static final CommandResult<Long> ZERO = CommandResult.success(0L, LONG_HANDLE);
public static final CommandResult<Long> MAX_VALUE = CommandResult.success(Long.MAX_VALUE, LONG_HANDLE);
public static final CommandResult<Boolean> TRUE = CommandResult.success(true, BOOLEAN_HANDLE);
public static final CommandResult<Boolean> FALSE = CommandResult.success(false, BOOLEAN_HANDLE);
private static final CommandResult<?> NOT_FOUND = new CommandResult<>(new BucketNotFoundError(), BucketNotFoundError.SERIALIZATION_HANDLE.getTypeId());
private static final CommandResult<?> CONFIGURATION_NEED_TO_BE_REPLACED = new CommandResult<>(new ConfigurationNeedToBeReplacedError(), ConfigurationNeedToBeReplacedError.SERIALIZATION_HANDLE.getTypeId());
private static final CommandResult<?> NULL = new CommandResult<>(null, NULL_HANDLE.getTypeId());
private T data;
private int resultTypeId;
public static SerializationHandle<CommandResult<?>> SERIALIZATION_HANDLE = new SerializationHandle<CommandResult<?>>() {
@Override
public <S> CommandResult<?> deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int typeId = adapter.readInt(input);
SerializationHandle handle = SerializationHandles.CORE_HANDLES.getHandleByTypeId(typeId);
Object resultData = handle.deserialize(adapter, input);
return CommandResult.success(resultData, typeId);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, CommandResult<?> result, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeInt(output, result.resultTypeId);
SerializationHandle handle = SerializationHandles.CORE_HANDLES.getHandleByTypeId(result.resultTypeId);
handle.serialize(adapter, output, result.data, backwardCompatibilityVersion, scope);
}
@Override
public int getTypeId() {
return 10;
}
@Override
public Class<CommandResult<?>> getSerializedType() {
return (Class) CommandResult.class;
}
@Override
public CommandResult<?> fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
Map<String, Object> dataSnapshot = (Map<String, Object>) snapshot.get("data");
String typeName = (String) dataSnapshot.get("type");
SerializationHandle handle = SerializationHandles.CORE_HANDLES.getHandleByTypeName(typeName);
Object resultData = handle.fromJsonCompatibleSnapshot(dataSnapshot);
return CommandResult.success(resultData, handle.getTypeId());
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(CommandResult<?> result, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "CommandResult";
}
};
public CommandResult(T data, int resultTypeId) {
this.data = data;
this.resultTypeId = resultTypeId;
}
public static <R> CommandResult<R> success(R data, SerializationHandle dataSerializer) {
return new CommandResult<>(data, dataSerializer.getTypeId());
}
public static <R> CommandResult<R> success(R data, int resultTypeId) {
return new CommandResult<>(data, resultTypeId);
}
public static <R> CommandResult<R> bucketNotFound() {
return (CommandResult<R>) NOT_FOUND;
}
public static <R> CommandResult<R> configurationNeedToBeReplaced() {
return (CommandResult<R>) CONFIGURATION_NEED_TO_BE_REPLACED;
}
public static <R> CommandResult<R> empty() {
return (CommandResult<R>) NULL;
}
public static CommandResult<?> unsupportedType(int typeId) {
UnsupportedTypeError error = new UnsupportedTypeError(typeId);
return new CommandResult<>(error, UnsupportedTypeError.SERIALIZATION_HANDLE.getTypeId());
}
public static CommandResult<?> unsupportedNamedType(String typeName) {
UnsupportedNamedTypeError error = new UnsupportedNamedTypeError(typeName);
return new CommandResult<>(error, UnsupportedNamedTypeError.SERIALIZATION_HANDLE.getTypeId());
}
public static CommandResult<?> usageOfUnsupportedApiException(int requestedFormatNumber, int maxSupportedFormatNumber) {
UsageOfUnsupportedApiError error = new UsageOfUnsupportedApiError(requestedFormatNumber, maxSupportedFormatNumber);
return new CommandResult<>(error, UsageOfUnsupportedApiError.SERIALIZATION_HANDLE.getTypeId());
}
public static CommandResult<?> usageOfObsoleteApiException(int requestedFormatNumber, int minSupportedFormatNumber) {
UsageOfObsoleteApiError error = new UsageOfObsoleteApiError(requestedFormatNumber, minSupportedFormatNumber);
return new CommandResult<>(error, UsageOfObsoleteApiError.SERIALIZATION_HANDLE.getTypeId());
}
public T getData() {
if (data instanceof CommandError) {
CommandError error = (CommandError) data;
throw error.asException();
}
return data;
}
public boolean isBucketNotFound() {
return data instanceof BucketNotFoundError;
}
public boolean isConfigurationNeedToBeReplaced() {
return data instanceof ConfigurationNeedToBeReplacedError;
}
public boolean isError() {
return data instanceof CommandError;
}
public int getResultTypeId() {
return resultTypeId;
}
@Override
public boolean equalsByContent(CommandResult other) {
return resultTypeId == other.resultTypeId &&
ComparableByContent.equals(data, other.data);
}
}
|
Map<String, Object> snapshot = new HashMap<>();
snapshot.put("version", v_7_0_0.getNumber());
SerializationHandle<Object> handle = SerializationHandles.CORE_HANDLES.getHandleByTypeId(result.resultTypeId);
Map<String, Object> valueSnapshot = handle.toJsonCompatibleSnapshot(result.data, backwardCompatibilityVersion, scope);
valueSnapshot.put("type", handle.getTypeName());
snapshot.put("data", valueSnapshot);
return snapshot;
| 1,732
| 132
| 1,864
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/ConfigurationNeedToBeReplacedError.java
|
ConfigurationNeedToBeReplacedError
|
fromJsonCompatibleSnapshot
|
class ConfigurationNeedToBeReplacedError implements CommandError, ComparableByContent<ConfigurationNeedToBeReplacedError> {
private static final ConfigurationNeedToBeReplacedError INSTANCE = new ConfigurationNeedToBeReplacedError();
@Override
public RuntimeException asException() {
return new ConfigurationNeedToBeReplacedException();
}
public static SerializationHandle<ConfigurationNeedToBeReplacedError> SERIALIZATION_HANDLE = new SerializationHandle<>() {
@Override
public <S> ConfigurationNeedToBeReplacedError deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_8_1_0, v_8_1_0);
return INSTANCE;
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ConfigurationNeedToBeReplacedError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_8_1_0.getNumber());
}
@Override
public int getTypeId() {
return 40;
}
@Override
public Class<ConfigurationNeedToBeReplacedError> getSerializedType() {
return ConfigurationNeedToBeReplacedError.class;
}
@Override
public ConfigurationNeedToBeReplacedError fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ConfigurationNeedToBeReplacedError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_8_1_0.getNumber());
return result;
}
@Override
public String getTypeName() {
return "ConfigurationNeedToBeReplacedError";
}
};
@Override
public boolean equalsByContent(ConfigurationNeedToBeReplacedError other) {
return true;
}
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_8_1_0, v_8_1_0);
return INSTANCE;
| 531
| 52
| 583
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/MultiResult.java
|
MultiResult
|
deserialize
|
class MultiResult implements ComparableByContent<MultiResult> {
private List<CommandResult<?>> results;
public static SerializationHandle<MultiResult> SERIALIZATION_HANDLE = new SerializationHandle<MultiResult>() {
@Override
public <S> MultiResult deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, MultiResult multiResult, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeInt(output, multiResult.results.size());
for (CommandResult<?> result : multiResult.results) {
CommandResult.SERIALIZATION_HANDLE.serialize(adapter, output, result, backwardCompatibilityVersion, scope);
}
}
@Override
public int getTypeId() {
return 13;
}
@Override
public Class<MultiResult> getSerializedType() {
return MultiResult.class;
}
@Override
public MultiResult fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
List<Map<String, Object>> resultSnapshots = (List<Map<String, Object>>) snapshot.get("results");
List<CommandResult<?>> results = new ArrayList<>(resultSnapshots.size());
for (Map<String, Object> resultSnapshot : resultSnapshots) {
CommandResult<?> result = CommandResult.SERIALIZATION_HANDLE.fromJsonCompatibleSnapshot(resultSnapshot);
results.add(result);
}
return new MultiResult(results);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(MultiResult multiResult, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> snapshot = new HashMap<>();
snapshot.put("version", v_7_0_0.getNumber());
List<Map<String, Object>> resultSnapshots = new ArrayList<>(multiResult.results.size());
for (CommandResult<?> result : multiResult.results) {
Map<String, Object> resultSnapshot = CommandResult.SERIALIZATION_HANDLE.toJsonCompatibleSnapshot(result, backwardCompatibilityVersion, scope);
resultSnapshots.add(resultSnapshot);
}
snapshot.put("results", resultSnapshots);
return snapshot;
}
@Override
public String getTypeName() {
return "MultiResult";
}
};
public MultiResult(List<CommandResult<?>> results) {
this.results = results;
}
public List<CommandResult<?>> getResults() {
return results;
}
@Override
public boolean equalsByContent(MultiResult other) {
if (results.size() != other.results.size()) {
return false;
}
for (int i = 0; i < results.size(); i++) {
CommandResult<?> result1 = results.get(i);
CommandResult<?> result2 = other.results.get(i);
if (!ComparableByContent.equals(result1, result2)) {
return false;
}
}
return true;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int size = adapter.readInt(input);
List<CommandResult<?>> results = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
CommandResult<?> result = CommandResult.SERIALIZATION_HANDLE.deserialize(adapter, input);
results.add(result);
}
return new MultiResult(results);
| 887
| 139
| 1,026
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/MutableBucketEntry.java
|
MutableBucketEntry
|
get
|
class MutableBucketEntry {
private RemoteBucketState state;
private boolean stateModified;
public MutableBucketEntry(RemoteBucketState state) {
this.state = state;
}
public MutableBucketEntry(byte[] originalStateBytes) {
this.state = originalStateBytes == null? null : deserializeState(originalStateBytes);
}
public boolean exists() {
return state != null;
}
public boolean isStateModified() {
return stateModified;
}
public void set(RemoteBucketState state) {
this.state = Objects.requireNonNull(state);
this.stateModified = true;
}
public RemoteBucketState get() {<FILL_FUNCTION_BODY>}
public byte[] getStateBytes(Version backwardCompatibilityVersion) {
return serializeState(get(), backwardCompatibilityVersion);
}
}
|
if (state == null) {
throw new IllegalStateException("'exists' must be called before 'get'");
}
return state;
| 239
| 39
| 278
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/RemoteStat.java
|
RemoteStat
|
deserialize
|
class RemoteStat implements ComparableByContent<RemoteStat> {
private long consumedTokens;
public RemoteStat(long consumedTokens) {
this.consumedTokens = consumedTokens;
}
public long getConsumedTokens() {
return consumedTokens;
}
public void addConsumedTokens(long consumedTokens) {
this.consumedTokens += consumedTokens;
}
public static final SerializationHandle<RemoteStat> SERIALIZATION_HANDLE = new SerializationHandle<RemoteStat>() {
@Override
public <S> RemoteStat deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, RemoteStat stat, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, stat.consumedTokens);
}
@Override
public int getTypeId() {
return 6;
}
@Override
public Class<RemoteStat> getSerializedType() {
return RemoteStat.class;
}
@Override
public RemoteStat fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long consumedTokens = readLongValue(snapshot, "consumedTokens");
return new RemoteStat(consumedTokens);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(RemoteStat stat, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("consumedTokens", stat.consumedTokens);
return result;
}
@Override
public String getTypeName() {
return "RemoteStat";
}
};
public RemoteStat copy() {
return new RemoteStat(consumedTokens);
}
@Override
public boolean equalsByContent(RemoteStat other) {
return consumedTokens == other.consumedTokens;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long consumedTokens = adapter.readLong(input);
return new RemoteStat(consumedTokens);
| 613
| 69
| 682
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/RemoteVerboseResult.java
|
RemoteVerboseResult
|
toJsonCompatibleSnapshot
|
class RemoteVerboseResult<T> implements ComparableByContent<RemoteVerboseResult<?>> {
private final long operationTimeNanos;
private final int resultTypeId;
private final T value;
private final RemoteBucketState state;
public RemoteVerboseResult(long operationTimeNanos, int resultTypeId, T value, RemoteBucketState state) {
this.operationTimeNanos = operationTimeNanos;
this.resultTypeId = resultTypeId;
this.value = value;
this.state = state;
}
/**
* @return result of operation with bucket
*/
public T getValue() {
return value;
}
/**
* @return snapshot of internal bucket state which was actual at operation time
*/
public RemoteBucketState getState() {
return state;
}
/**
* @return time which was used by the bucket at the moment of handling a request
*/
public long getOperationTimeNanos() {
return operationTimeNanos;
}
public VerboseResult<T> asLocal() {
return new VerboseResult<>(operationTimeNanos, value, state.copyBucketState());
}
public <R> RemoteVerboseResult<R> map(Function<T, R> mapper) {
return new RemoteVerboseResult<R>(operationTimeNanos, resultTypeId, mapper.apply(value), state);
}
public static final SerializationHandle<RemoteVerboseResult<?>> SERIALIZATION_HANDLE = new SerializationHandle<RemoteVerboseResult<?>>() {
@Override
public <I> RemoteVerboseResult<?> deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long operationTimeNanos = adapter.readLong(input);
int typeId = adapter.readInt(input);
SerializationHandle<?> handle = SerializationHandles.CORE_HANDLES.getHandleByTypeId(typeId);
Object result = handle.deserialize(adapter, input);
RemoteBucketState state = RemoteBucketState.SERIALIZATION_HANDLE.deserialize(adapter, input);
return new RemoteVerboseResult<>(operationTimeNanos, typeId, result, state);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, RemoteVerboseResult<?> result, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, result.operationTimeNanos);
adapter.writeInt(output, result.resultTypeId);
SerializationHandle handle = SerializationHandles.CORE_HANDLES.getHandleByTypeId(result.resultTypeId);
handle.serialize(adapter, output, result.value, backwardCompatibilityVersion, scope);
RemoteBucketState.SERIALIZATION_HANDLE.serialize(adapter, output, result.state, backwardCompatibilityVersion, scope);
}
@Override
public int getTypeId() {
return 14;
}
@Override
public Class<RemoteVerboseResult<?>> getSerializedType() {
return (Class) RemoteVerboseResult.class;
}
@Override
public RemoteVerboseResult<?> fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long operationTimeNanos = readLongValue(snapshot, "operationTimeNanos");
Map<String, Object> valueSnapshot = (Map<String, Object>) snapshot.get("result");
String valueTypeName = (String) valueSnapshot.get("type");
SerializationHandle valueHandle = SerializationHandles.CORE_HANDLES.getHandleByTypeName(valueTypeName);
Object result = valueHandle.fromJsonCompatibleSnapshot(valueSnapshot);
Map<String, Object> stateSnapshot = (Map<String, Object>) snapshot.get("remoteState");
RemoteBucketState state = RemoteBucketState.SERIALIZATION_HANDLE.fromJsonCompatibleSnapshot(stateSnapshot);
return new RemoteVerboseResult(operationTimeNanos, valueHandle.getTypeId(), result, state);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(RemoteVerboseResult<?> verboseResult, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "RemoteVerboseResult";
}
};
@Override
public boolean equalsByContent(RemoteVerboseResult<?> other) {
return operationTimeNanos == other.operationTimeNanos
&& resultTypeId == other.resultTypeId
&& ComparableByContent.equals(value, other.value)
&& ComparableByContent.equals(state, other.state);
}
}
|
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("operationTimeNanos", verboseResult.operationTimeNanos);
SerializationHandle<Object> valueHandle = SerializationHandles.CORE_HANDLES.getHandleByTypeId(verboseResult.resultTypeId);
Map<String, Object> valueSnapshot = valueHandle.toJsonCompatibleSnapshot(verboseResult.value, backwardCompatibilityVersion, scope);
valueSnapshot.put("type", valueHandle.getTypeName());
result.put("result", valueSnapshot);
Map<String, Object> stateSnapshot = RemoteBucketState.SERIALIZATION_HANDLE.toJsonCompatibleSnapshot(verboseResult.state, backwardCompatibilityVersion, scope);
result.put("remoteState", stateSnapshot);
return result;
| 1,328
| 219
| 1,547
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/Request.java
|
Request
|
serialize
|
class Request<T> implements ComparableByContent<Request<T>> {
private final Version backwardCompatibilityVersion;
private final RemoteCommand<T> command;
private final Long clientSideTime;
private final ExpirationAfterWriteStrategy expirationStrategy;
public Request(RemoteCommand<T> command, Version backwardCompatibilityVersion, Long clientSideTime, ExpirationAfterWriteStrategy expirationStrategy) {
this.command = command;
this.clientSideTime = clientSideTime;
this.backwardCompatibilityVersion = backwardCompatibilityVersion;
this.expirationStrategy = expirationStrategy;
}
public RemoteCommand<T> getCommand() {
return command;
}
public Version getBackwardCompatibilityVersion() {
return backwardCompatibilityVersion;
}
public Long getClientSideTime() {
return clientSideTime;
}
public ExpirationAfterWriteStrategy getExpirationStrategy() {
return expirationStrategy;
}
public static SerializationHandle<Request<?>> SERIALIZATION_HANDLE = new SerializationHandle<>() {
@Override
public <S> Request<?> deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_8_10_0);
int backwardCompatibilityNumber = adapter.readInt(input);
Version requestBackwardCompatibilityVersion = Versions.byNumber(backwardCompatibilityNumber);
RemoteCommand<?> command = RemoteCommand.deserialize(adapter, input);
Long clientTime = null;
boolean clientTimeProvided = adapter.readBoolean(input);
if (clientTimeProvided) {
clientTime = adapter.readLong(input);
}
ExpirationAfterWriteStrategy expireStrategy = null;
if (formatNumber >= v_8_10_0.getNumber()) {
boolean hasExpireStrategy = adapter.readBoolean(input);
if (hasExpireStrategy) {
expireStrategy = ExpirationAfterWriteStrategy.deserialize(adapter, input);
}
}
return new Request<>(command, requestBackwardCompatibilityVersion, clientTime, expireStrategy);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, Request<?> request, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int getTypeId() {
return 37;
}
@Override
public Class<Request<?>> getSerializedType() {
return (Class) Request.class;
}
@Override
public Request<?> fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_8_10_0);
int backwardCompatibilityNumber = readIntValue(snapshot, "backwardCompatibilityNumber");
Version requestBackwardCompatibilityVersion = Versions.byNumber(backwardCompatibilityNumber);
RemoteCommand<?> command = RemoteCommand.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("command"));
Long clientTime = null;
if (snapshot.containsKey("clientTime")) {
clientTime = readLongValue(snapshot, "clientTime");
}
ExpirationAfterWriteStrategy expireStrategy = null;
if (snapshot.containsKey("expireAfterWriteStrategy")) {
expireStrategy = ExpirationAfterWriteStrategy.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("expireAfterWriteStrategy"));
}
return new Request<>(command, requestBackwardCompatibilityVersion, clientTime, expireStrategy);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(Request<?> request, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Version effectiveVersion = Versions.max(request.command.getRequiredVersion(), request.getSelfVersion());;
Versions.check(effectiveVersion.getNumber(), v_7_0_0, request.backwardCompatibilityVersion);
Version selfVersion = request.getSelfVersion();
Map<String, Object> result = new HashMap<>();
result.put("version", selfVersion.getNumber());
result.put("backwardCompatibilityNumber", effectiveVersion.getNumber());
result.put("command", RemoteCommand.toJsonCompatibleSnapshot(request.command, backwardCompatibilityVersion, scope));
if (request.clientSideTime != null) {
result.put("clientTime", request.clientSideTime);
}
if (request.expirationStrategy != null) {
result.put("expireAfterWriteStrategy", ExpirationAfterWriteStrategy.toJsonCompatibleSnapshot(request.expirationStrategy, backwardCompatibilityVersion, scope));
}
return result;
}
@Override
public String getTypeName() {
return "Request";
}
};
private Version getSelfVersion() {
return expirationStrategy != null ? v_8_10_0 : v_7_0_0;
}
@Override
public boolean equalsByContent(Request<T> other) {
return // backwardCompatibilityVersion.equals(other.backwardCompatibilityVersion) &&
ComparableByContent.equals(command, other.command)
&& Objects.equals(clientSideTime, other.clientSideTime);
}
}
|
Version selfVersion = request.getSelfVersion();
Version effectiveVersion = Versions.max(request.command.getRequiredVersion(), selfVersion);
Versions.check(effectiveVersion.getNumber(), v_7_0_0, request.backwardCompatibilityVersion);
adapter.writeInt(output, selfVersion.getNumber());
adapter.writeInt(output, effectiveVersion.getNumber());
RemoteCommand.serialize(adapter, output, request.command, backwardCompatibilityVersion, scope);
if (request.clientSideTime != null) {
adapter.writeBoolean(output, true);
adapter.writeLong(output, request.clientSideTime);
} else {
adapter.writeBoolean(output, false);
}
if (selfVersion.getNumber() >= v_8_10_0.getNumber()) {
if (request.expirationStrategy != null) {
adapter.writeBoolean(output, true);
ExpirationAfterWriteStrategy.serialize(adapter, output, request.expirationStrategy, backwardCompatibilityVersion, scope);
} else {
adapter.writeBoolean(output, false);
}
}
| 1,385
| 282
| 1,667
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/UnsupportedNamedTypeError.java
|
UnsupportedNamedTypeError
|
toJsonCompatibleSnapshot
|
class UnsupportedNamedTypeError implements CommandError, ComparableByContent<UnsupportedNamedTypeError> {
private final String typeName;
public UnsupportedNamedTypeError(String typeName) {
this.typeName = typeName;
}
public String getTypeName() {
return typeName;
}
@Override
public RuntimeException asException() {
return new UnsupportedNamedTypeException(typeName);
}
@Override
public boolean equalsByContent(UnsupportedNamedTypeError other) {
return other.typeName.equals(typeName);
}
public static SerializationHandle<UnsupportedNamedTypeError> SERIALIZATION_HANDLE = new SerializationHandle<UnsupportedNamedTypeError>() {
@Override
public <S> UnsupportedNamedTypeError deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
String typeName = adapter.readString(input);
return new UnsupportedNamedTypeError(typeName);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, UnsupportedNamedTypeError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeString(output, error.typeName);
}
@Override
public int getTypeId() {
return 19;
}
@Override
public Class<UnsupportedNamedTypeError> getSerializedType() {
return (Class) UnsupportedNamedTypeError.class;
}
@Override
public UnsupportedNamedTypeError fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
String typeName = (String) snapshot.get("typeName");
return new UnsupportedNamedTypeError(typeName);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(UnsupportedNamedTypeError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "UnsupportedNamedTypeError";
}
};
}
|
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("typeName", error.typeName);
return result;
| 623
| 56
| 679
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/UnsupportedTypeError.java
|
UnsupportedTypeError
|
fromJsonCompatibleSnapshot
|
class UnsupportedTypeError implements CommandError, ComparableByContent<UnsupportedTypeError> {
private final int typeId;
public UnsupportedTypeError(int typeId) {
this.typeId = typeId;
}
public int getTypeId() {
return typeId;
}
@Override
public RuntimeException asException() {
return new UnsupportedTypeException(typeId);
}
@Override
public boolean equalsByContent(UnsupportedTypeError other) {
return other.typeId == typeId;
}
public static SerializationHandle<UnsupportedTypeError> SERIALIZATION_HANDLE = new SerializationHandle<UnsupportedTypeError>() {
@Override
public <S> UnsupportedTypeError deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int typeId = adapter.readInt(input);
return new UnsupportedTypeError(typeId);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, UnsupportedTypeError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeInt(output, error.typeId);
}
@Override
public int getTypeId() {
return 16;
}
@Override
public Class<UnsupportedTypeError> getSerializedType() {
return (Class) UnsupportedTypeError.class;
}
@Override
public UnsupportedTypeError fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(UnsupportedTypeError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("typeId", error.typeId);
return result;
}
@Override
public String getTypeName() {
return "UnsupportedTypeError";
}
};
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int typeId = readIntValue(snapshot, "typeId");
return new UnsupportedTypeError(typeId);
| 588
| 74
| 662
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/UsageOfObsoleteApiError.java
|
UsageOfObsoleteApiError
|
fromJsonCompatibleSnapshot
|
class UsageOfObsoleteApiError implements ComparableByContent<UsageOfObsoleteApiError>, CommandError {
private final int requestedFormatNumber;
private final int minSupportedFormatNumber;
public UsageOfObsoleteApiError(int requestedFormatNumber, int minSupportedFormatNumber) {
this.requestedFormatNumber = requestedFormatNumber;
this.minSupportedFormatNumber = minSupportedFormatNumber;
}
public int getRequestedFormatNumber() {
return requestedFormatNumber;
}
public int getMinSupportedFormatNumber() {
return minSupportedFormatNumber;
}
@Override
public RuntimeException asException() {
return new UsageOfObsoleteApiException(requestedFormatNumber, minSupportedFormatNumber);
}
@Override
public boolean equalsByContent(UsageOfObsoleteApiError other) {
return other.requestedFormatNumber == requestedFormatNumber
&& other.minSupportedFormatNumber == minSupportedFormatNumber;
}
public static SerializationHandle<UsageOfObsoleteApiError> SERIALIZATION_HANDLE = new SerializationHandle<UsageOfObsoleteApiError>() {
@Override
public <S> UsageOfObsoleteApiError deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int requestedFormatNumber = adapter.readInt(input);
int minSupportedFormatNumber = adapter.readInt(input);
return new UsageOfObsoleteApiError(requestedFormatNumber, minSupportedFormatNumber);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, UsageOfObsoleteApiError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeInt(output, error.requestedFormatNumber);
adapter.writeInt(output, error.minSupportedFormatNumber);
}
@Override
public int getTypeId() {
return 17;
}
@Override
public Class<UsageOfObsoleteApiError> getSerializedType() {
return (Class) UsageOfObsoleteApiError.class;
}
@Override
public UsageOfObsoleteApiError fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(UsageOfObsoleteApiError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("requestedFormatNumber", error.requestedFormatNumber);
result.put("minSupportedFormatNumber", error.minSupportedFormatNumber);
return result;
}
@Override
public String getTypeName() {
return "UsageOfObsoleteApiError";
}
};
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int requestedFormatNumber = readIntValue(snapshot, "requestedFormatNumber");
int minSupportedFormatNumber = readIntValue(snapshot, "minSupportedFormatNumber");
return new UsageOfObsoleteApiError(requestedFormatNumber, minSupportedFormatNumber);
| 804
| 114
| 918
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/UsageOfUnsupportedApiError.java
|
UsageOfUnsupportedApiError
|
deserialize
|
class UsageOfUnsupportedApiError implements CommandError, ComparableByContent<UsageOfUnsupportedApiError> {
private final int requestedFormatNumber;
private final int maxSupportedFormatNumber;
public UsageOfUnsupportedApiError(int requestedFormatNumber, int maxSupportedFormatNumber) {
this.requestedFormatNumber = requestedFormatNumber;
this.maxSupportedFormatNumber = maxSupportedFormatNumber;
}
public int getRequestedFormatNumber() {
return requestedFormatNumber;
}
public int getMaxSupportedFormatNumber() {
return maxSupportedFormatNumber;
}
@Override
public RuntimeException asException() {
return new UsageOfUnsupportedApiException(requestedFormatNumber, maxSupportedFormatNumber);
}
@Override
public boolean equalsByContent(UsageOfUnsupportedApiError other) {
return requestedFormatNumber == other.requestedFormatNumber &&
maxSupportedFormatNumber == other.maxSupportedFormatNumber;
}
public static SerializationHandle<UsageOfUnsupportedApiError> SERIALIZATION_HANDLE = new SerializationHandle<UsageOfUnsupportedApiError>() {
@Override
public <S> UsageOfUnsupportedApiError deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, UsageOfUnsupportedApiError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeInt(output, error.requestedFormatNumber);
adapter.writeInt(output, error.maxSupportedFormatNumber);
}
@Override
public int getTypeId() {
return 18;
}
@Override
public Class<UsageOfUnsupportedApiError> getSerializedType() {
return (Class) UsageOfUnsupportedApiError.class;
}
@Override
public UsageOfUnsupportedApiError fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int requestedFormatNumber = readIntValue(snapshot, "requestedFormatNumber");
int maxSupportedFormatNumber = readIntValue(snapshot, "maxSupportedFormatNumber");
return new UsageOfUnsupportedApiError(requestedFormatNumber, maxSupportedFormatNumber);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(UsageOfUnsupportedApiError error, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("requestedFormatNumber", error.requestedFormatNumber);
result.put("maxSupportedFormatNumber", error.maxSupportedFormatNumber);
return result;
}
@Override
public String getTypeName() {
return "UsageOfUnsupportedApiError";
}
};
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
int requestedFormatNumber = adapter.readInt(input);
int maxSupportedFormatNumber = adapter.readInt(input);
return new UsageOfUnsupportedApiError(requestedFormatNumber, maxSupportedFormatNumber);
| 805
| 96
| 901
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/AddTokensCommand.java
|
AddTokensCommand
|
fromJsonCompatibleSnapshot
|
class AddTokensCommand implements RemoteCommand<Nothing>, ComparableByContent<AddTokensCommand> {
private long tokensToAdd;
public static final SerializationHandle<AddTokensCommand> SERIALIZATION_HANDLE = new SerializationHandle<AddTokensCommand>() {
@Override
public <S> AddTokensCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToAdd = adapter.readLong(input);
return new AddTokensCommand(tokensToAdd);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, AddTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.tokensToAdd);
}
@Override
public int getTypeId() {
return 24;
}
@Override
public Class<AddTokensCommand> getSerializedType() {
return AddTokensCommand.class;
}
@Override
public AddTokensCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(AddTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensToAdd", command.tokensToAdd);
return result;
}
@Override
public String getTypeName() {
return "AddTokensCommand";
}
};
public AddTokensCommand(long tokensToAdd) {
this.tokensToAdd = tokensToAdd;
}
@Override
public CommandResult<Nothing> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
state.addTokens(tokensToAdd);
mutableEntry.set(state);
return CommandResult.NOTHING;
}
public long getTokensToAdd() {
return tokensToAdd;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(AddTokensCommand other) {
return tokensToAdd == other.tokensToAdd;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return true;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(Nothing result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToAdd = readLongValue(snapshot, "tokensToAdd");
return new AddTokensCommand(tokensToAdd);
| 856
| 80
| 936
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/CheckConfigurationVersionAndExecuteCommand.java
|
CheckConfigurationVersionAndExecuteCommand
|
execute
|
class CheckConfigurationVersionAndExecuteCommand<T> implements RemoteCommand<T>, ComparableByContent<CheckConfigurationVersionAndExecuteCommand<?>> {
private final RemoteCommand<T> targetCommand;
private final long desiredConfigurationVersion;
public CheckConfigurationVersionAndExecuteCommand(RemoteCommand<T> targetCommand, long desiredConfigurationVersion) {
this.targetCommand = targetCommand;
this.desiredConfigurationVersion = desiredConfigurationVersion;
}
@Override
public boolean canBeMerged(RemoteCommand<?> another) {
if (!(another instanceof CheckConfigurationVersionAndExecuteCommand)) {
return false;
}
CheckConfigurationVersionAndExecuteCommand<?> anotherCmd = (CheckConfigurationVersionAndExecuteCommand<?>) another;
return desiredConfigurationVersion == anotherCmd.desiredConfigurationVersion && targetCommand.canBeMerged(anotherCmd.targetCommand);
}
@Override
public RemoteCommand<?> toMergedCommand() {
return new CheckConfigurationVersionAndExecuteCommand<>(targetCommand.toMergedCommand(), desiredConfigurationVersion);
}
@Override
public void mergeInto(RemoteCommand<?> mergedCommand) {
targetCommand.mergeInto(((CheckConfigurationVersionAndExecuteCommand) mergedCommand).targetCommand);
}
@Override
public boolean isMerged() {
return targetCommand.isMerged();
}
@Override
public int getMergedCommandsCount() {
return targetCommand.getMergedCommandsCount();
}
@Override
public CommandResult<?> unwrapOneResult(T result, int indice) {
return targetCommand.unwrapOneResult(result, indice);
}
public RemoteCommand<T> getTargetCommand() {
return targetCommand;
}
public long getDesiredConfigurationVersion() {
return desiredConfigurationVersion;
}
@Override
public CommandResult<T> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {<FILL_FUNCTION_BODY>}
@Override
public SerializationHandle<RemoteCommand<?>> getSerializationHandle() {
return (SerializationHandle) SERIALIZATION_HANDLE;
}
public static final SerializationHandle<CheckConfigurationVersionAndExecuteCommand<?>> SERIALIZATION_HANDLE = new SerializationHandle<CheckConfigurationVersionAndExecuteCommand<?>>() {
@Override
public <I> CheckConfigurationVersionAndExecuteCommand<?> deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_8_1_0, v_8_1_0);
RemoteCommand<?> targetCommand = RemoteCommand.deserialize(adapter, input);
long desiredConfigurationVersion = adapter.readLong(input);
return new CheckConfigurationVersionAndExecuteCommand<>(targetCommand, desiredConfigurationVersion);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, CheckConfigurationVersionAndExecuteCommand<?> command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_8_1_0.getNumber());
RemoteCommand.serialize(adapter, output, command.targetCommand, backwardCompatibilityVersion, scope);
adapter.writeLong(output, command.desiredConfigurationVersion);
}
@Override
public int getTypeId() {
return 42;
}
@Override
public Class<CheckConfigurationVersionAndExecuteCommand<?>> getSerializedType() {
return (Class) CheckConfigurationVersionAndExecuteCommand.class;
}
@Override
public CheckConfigurationVersionAndExecuteCommand<?> fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_8_1_0, v_8_1_0);
RemoteCommand<?> targetCommand = RemoteCommand.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("targetCommand"));
long desiredConfigurationVersion = readLongValue(snapshot, "desiredConfigurationVersion");
return new CheckConfigurationVersionAndExecuteCommand<>(targetCommand, desiredConfigurationVersion);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(CheckConfigurationVersionAndExecuteCommand<?> command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_8_1_0.getNumber());
result.put("targetCommand", RemoteCommand.toJsonCompatibleSnapshot(command.targetCommand, backwardCompatibilityVersion, scope));
result.put("desiredConfigurationVersion", command.desiredConfigurationVersion);
return result;
}
@Override
public String getTypeName() {
return "CheckConfigurationVersionAndExecuteCommand";
}
};
@Override
public boolean equalsByContent(CheckConfigurationVersionAndExecuteCommand<?> other) {
return ComparableByContent.equals(targetCommand, other.targetCommand);
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return targetCommand.isImmediateSyncRequired(unsynchronizedTokens, nanosSinceLastSync);
}
@Override
public long estimateTokensToConsume() {
return targetCommand.estimateTokensToConsume();
}
@Override
public long getConsumedTokens(T result) {
return targetCommand.getConsumedTokens(result);
}
@Override
public Version getRequiredVersion() {
return Versions.max(v_8_1_0, targetCommand.getRequiredVersion());
}
}
|
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
Long actualConfigurationVersion = state.getConfigurationVersion();
if (actualConfigurationVersion == null || actualConfigurationVersion < desiredConfigurationVersion) {
return CommandResult.configurationNeedToBeReplaced();
}
return targetCommand.execute(mutableEntry, currentTimeNanos);
| 1,449
| 107
| 1,556
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/ConsumeAsMuchAsPossibleCommand.java
|
ConsumeAsMuchAsPossibleCommand
|
execute
|
class ConsumeAsMuchAsPossibleCommand implements RemoteCommand<Long>, ComparableByContent<ConsumeAsMuchAsPossibleCommand> {
private long limit;
private boolean merged;
public static final SerializationHandle<ConsumeAsMuchAsPossibleCommand> SERIALIZATION_HANDLE = new SerializationHandle<ConsumeAsMuchAsPossibleCommand>() {
@Override
public <S> ConsumeAsMuchAsPossibleCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long limit = adapter.readLong(input);
return new ConsumeAsMuchAsPossibleCommand(limit);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ConsumeAsMuchAsPossibleCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.limit);
}
@Override
public int getTypeId() {
return 25;
}
@Override
public Class<ConsumeAsMuchAsPossibleCommand> getSerializedType() {
return ConsumeAsMuchAsPossibleCommand.class;
}
@Override
public ConsumeAsMuchAsPossibleCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long limit = readLongValue(snapshot, "limit");
return new ConsumeAsMuchAsPossibleCommand(limit);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ConsumeAsMuchAsPossibleCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("limit", command.limit);
return result;
}
@Override
public String getTypeName() {
return "ConsumeAsMuchAsPossibleCommand";
}
};
public ConsumeAsMuchAsPossibleCommand(long limit) {
this.limit = limit;
}
@Override
public CommandResult<Long> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {<FILL_FUNCTION_BODY>}
public long getLimit() {
return limit;
}
public void setLimit(long limit) {
this.limit = limit;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(ConsumeAsMuchAsPossibleCommand other) {
return limit == other.limit;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return limit == Long.MAX_VALUE;
}
@Override
public long estimateTokensToConsume() {
return limit;
}
@Override
public long getConsumedTokens(Long result) {
return result;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
@Override
public boolean isMerged() {
return merged;
}
@Override
public int getMergedCommandsCount() {
return (int) limit;
}
@Override
public CommandResult<?> unwrapOneResult(Long consumedTokens, int indice) {
boolean wasConsumed = indice <= consumedTokens;
return CommandResult.success(wasConsumed, BOOLEAN_HANDLE);
}
public void setMerged(boolean merged) {
this.merged = merged;
}
}
|
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
long availableToConsume = state.getAvailableTokens();
long toConsume = Math.min(limit, availableToConsume);
if (toConsume <= 0) {
return CommandResult.ZERO;
}
state.consume(toConsume);
mutableEntry.set(state);
return CommandResult.success(toConsume, LONG_HANDLE);
| 1,044
| 155
| 1,199
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/ConsumeIgnoringRateLimitsCommand.java
|
ConsumeIgnoringRateLimitsCommand
|
execute
|
class ConsumeIgnoringRateLimitsCommand implements RemoteCommand<Long>, ComparableByContent<ConsumeIgnoringRateLimitsCommand> {
private long tokensToConsume;
public static final SerializationHandle<ConsumeIgnoringRateLimitsCommand> SERIALIZATION_HANDLE = new SerializationHandle<ConsumeIgnoringRateLimitsCommand>() {
@Override
public <S> ConsumeIgnoringRateLimitsCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = adapter.readLong(input);
return new ConsumeIgnoringRateLimitsCommand(tokensToConsume);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ConsumeIgnoringRateLimitsCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.tokensToConsume);
}
@Override
public int getTypeId() {
return 34;
}
@Override
public Class<ConsumeIgnoringRateLimitsCommand> getSerializedType() {
return ConsumeIgnoringRateLimitsCommand.class;
}
@Override
public ConsumeIgnoringRateLimitsCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = readLongValue(snapshot, "tokensToConsume");
return new ConsumeIgnoringRateLimitsCommand(tokensToConsume);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ConsumeIgnoringRateLimitsCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensToConsume", command.tokensToConsume);
return result;
}
@Override
public String getTypeName() {
return "ConsumeIgnoringRateLimitsCommand";
}
};
public ConsumeIgnoringRateLimitsCommand(long limit) {
this.tokensToConsume = limit;
}
public long getTokensToConsume() {
return tokensToConsume;
}
@Override
public CommandResult<Long> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {<FILL_FUNCTION_BODY>}
@Override
public SerializationHandle<RemoteCommand<?>> getSerializationHandle() {
return (SerializationHandle) SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(ConsumeIgnoringRateLimitsCommand other) {
return tokensToConsume == other.tokensToConsume;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return tokensToConsume;
}
@Override
public long getConsumedTokens(Long result) {
return result == Long.MAX_VALUE? 0l: tokensToConsume;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
long nanosToCloseDeficit = state.calculateDelayNanosAfterWillBePossibleToConsume(tokensToConsume, currentTimeNanos, false);
if (nanosToCloseDeficit == Long.MAX_VALUE) {
return CommandResult.success(Long.MAX_VALUE, LONG_HANDLE);
}
state.consume(tokensToConsume);
mutableEntry.set(state);
return CommandResult.success(nanosToCloseDeficit, LONG_HANDLE);
| 943
| 187
| 1,130
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/CreateInitialStateAndExecuteCommand.java
|
CreateInitialStateAndExecuteCommand
|
serialize
|
class CreateInitialStateAndExecuteCommand<T> implements RemoteCommand<T>, ComparableByContent<CreateInitialStateAndExecuteCommand> {
private RemoteCommand<T> targetCommand;
private BucketConfiguration configuration;
public static SerializationHandle<CreateInitialStateAndExecuteCommand> SERIALIZATION_HANDLE = new SerializationHandle<CreateInitialStateAndExecuteCommand>() {
@Override
public <S> CreateInitialStateAndExecuteCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
BucketConfiguration configuration = BucketConfiguration.SERIALIZATION_HANDLE.deserialize(adapter, input);
RemoteCommand<?> targetCommand = RemoteCommand.deserialize(adapter, input);
return new CreateInitialStateAndExecuteCommand(configuration, targetCommand);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, CreateInitialStateAndExecuteCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int getTypeId() {
return 21;
}
@Override
public Class<CreateInitialStateAndExecuteCommand> getSerializedType() {
return CreateInitialStateAndExecuteCommand.class;
}
@Override
public CreateInitialStateAndExecuteCommand<?> fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
BucketConfiguration configuration = BucketConfiguration.SERIALIZATION_HANDLE
.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("configuration"));
RemoteCommand<?> targetCommand = RemoteCommand.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("targetCommand"));
return new CreateInitialStateAndExecuteCommand<>(configuration, targetCommand);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(CreateInitialStateAndExecuteCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("configuration", BucketConfiguration.SERIALIZATION_HANDLE.toJsonCompatibleSnapshot(command.configuration, backwardCompatibilityVersion, scope));
result.put("targetCommand", RemoteCommand.toJsonCompatibleSnapshot(command.targetCommand, backwardCompatibilityVersion, scope));
return result;
}
@Override
public String getTypeName() {
return "CreateInitialStateAndExecuteCommand";
}
};
public CreateInitialStateAndExecuteCommand(BucketConfiguration configuration, RemoteCommand<T> targetCommand) {
this.configuration = configuration;
this.targetCommand = targetCommand;
}
@Override
public CommandResult<T> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
RemoteBucketState state;
if (!mutableEntry.exists()) {
BucketState bucketState = BucketState.createInitialState(configuration, MathType.INTEGER_64_BITS, currentTimeNanos);
state = new RemoteBucketState(bucketState, new RemoteStat(0), null);
mutableEntry.set(state);
}
return targetCommand.execute(mutableEntry, currentTimeNanos);
}
public BucketConfiguration getConfiguration() {
return configuration;
}
public RemoteCommand<T> getTargetCommand() {
return targetCommand;
}
@Override
public boolean isInitializationCommand() {
return true;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(CreateInitialStateAndExecuteCommand other) {
return ComparableByContent.equals(configuration, other.configuration) &&
ComparableByContent.equals(targetCommand, other.targetCommand);
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return true;
}
@Override
public long estimateTokensToConsume() {
return targetCommand.estimateTokensToConsume();
}
@Override
public long getConsumedTokens(T result) {
return targetCommand.getConsumedTokens(result);
}
@Override
public Version getRequiredVersion() {
return Versions.max(v_7_0_0, targetCommand.getRequiredVersion());
}
}
|
adapter.writeInt(output, v_7_0_0.getNumber());
BucketConfiguration.SERIALIZATION_HANDLE.serialize(adapter, output, command.configuration, backwardCompatibilityVersion, scope);
RemoteCommand.serialize(adapter, output, command.targetCommand, backwardCompatibilityVersion, scope);
| 1,211
| 83
| 1,294
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand.java
|
CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand
|
execute
|
class CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<T> implements RemoteCommand<T>, ComparableByContent<CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand> {
private RemoteCommand<T> targetCommand;
private BucketConfiguration configuration;
private long desiredConfigurationVersion;
private TokensInheritanceStrategy tokensInheritanceStrategy;
public static SerializationHandle<CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<?>> SERIALIZATION_HANDLE = new SerializationHandle<>() {
@Override
public <S> CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<?> deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_8_1_0, v_8_1_0);
BucketConfiguration configuration = BucketConfiguration.SERIALIZATION_HANDLE.deserialize(adapter, input);
RemoteCommand<?> targetCommand = RemoteCommand.deserialize(adapter, input);
long desiredConfigurationVersion = adapter.readLong(input);
TokensInheritanceStrategy tokensInheritanceStrategy = TokensInheritanceStrategy.getById(adapter.readByte(input));
return new CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<>(configuration, targetCommand, desiredConfigurationVersion, tokensInheritanceStrategy);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<?> command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_8_1_0.getNumber());
BucketConfiguration.SERIALIZATION_HANDLE.serialize(adapter, output, command.configuration, backwardCompatibilityVersion, scope);
RemoteCommand.serialize(adapter, output, command.targetCommand, backwardCompatibilityVersion, scope);
adapter.writeLong(output, command.desiredConfigurationVersion);
adapter.writeByte(output, command.tokensInheritanceStrategy.getId());
}
@Override
public int getTypeId() {
return 41;
}
@Override
public Class<CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<?>> getSerializedType() {
return (Class) CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand.class;
}
@Override
public CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<?> fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_8_1_0, v_8_1_0);
BucketConfiguration configuration = BucketConfiguration.SERIALIZATION_HANDLE
.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("configuration"));
RemoteCommand<?> targetCommand = RemoteCommand.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("targetCommand"));
TokensInheritanceStrategy tokensInheritanceStrategy = TokensInheritanceStrategy.valueOf((String) snapshot.get("tokensInheritanceStrategy"));
long desiredConfigurationVersion = readLongValue(snapshot, "desiredConfigurationVersion");
return new CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<>(configuration, targetCommand, desiredConfigurationVersion, tokensInheritanceStrategy);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand<?> command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_8_1_0.getNumber());
result.put("configuration", BucketConfiguration.SERIALIZATION_HANDLE.toJsonCompatibleSnapshot(command.configuration, backwardCompatibilityVersion, scope));
result.put("targetCommand", RemoteCommand.toJsonCompatibleSnapshot(command.targetCommand, backwardCompatibilityVersion, scope));
result.put("desiredConfigurationVersion", command.desiredConfigurationVersion);
result.put("tokensInheritanceStrategy", command.tokensInheritanceStrategy.toString());
return result;
}
@Override
public String getTypeName() {
return "CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand";
}
};
public CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand(BucketConfiguration configuration, RemoteCommand<T> targetCommand, long desiredConfigurationVersion, TokensInheritanceStrategy tokensInheritanceStrategy) {
this.configuration = configuration;
this.targetCommand = targetCommand;
this.desiredConfigurationVersion = desiredConfigurationVersion;
this.tokensInheritanceStrategy = tokensInheritanceStrategy;
}
@Override
public CommandResult<T> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {<FILL_FUNCTION_BODY>}
public BucketConfiguration getConfiguration() {
return configuration;
}
public RemoteCommand<T> getTargetCommand() {
return targetCommand;
}
public long getDesiredConfigurationVersion() {
return desiredConfigurationVersion;
}
public TokensInheritanceStrategy getTokensInheritanceStrategy() {
return tokensInheritanceStrategy;
}
@Override
public boolean isInitializationCommand() {
return true;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(CreateInitialStateWithVersionOrReplaceConfigurationAndExecuteCommand other) {
return ComparableByContent.equals(configuration, other.configuration) &&
ComparableByContent.equals(targetCommand, other.targetCommand) &&
desiredConfigurationVersion == other.desiredConfigurationVersion &&
tokensInheritanceStrategy == other.tokensInheritanceStrategy;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return true;
}
@Override
public long estimateTokensToConsume() {
return targetCommand.estimateTokensToConsume();
}
@Override
public long getConsumedTokens(T result) {
return targetCommand.getConsumedTokens(result);
}
@Override
public Version getRequiredVersion() {
return Versions.max(v_8_1_0, targetCommand.getRequiredVersion());
}
}
|
if (mutableEntry.exists()) {
RemoteBucketState state = mutableEntry.get();
Long actualConfigurationVersion = state.getConfigurationVersion();
if (actualConfigurationVersion == null || actualConfigurationVersion < desiredConfigurationVersion) {
ReplaceConfigurationCommand replaceConfigurationCommand = new ReplaceConfigurationCommand(configuration, tokensInheritanceStrategy);
replaceConfigurationCommand.execute(mutableEntry, currentTimeNanos);
state.setConfigurationVersion(desiredConfigurationVersion);
}
} else {
BucketState bucketState = BucketState.createInitialState(configuration, MathType.INTEGER_64_BITS, currentTimeNanos);
RemoteBucketState state = new RemoteBucketState(bucketState, new RemoteStat(0), desiredConfigurationVersion);
mutableEntry.set(state);
}
return targetCommand.execute(mutableEntry, currentTimeNanos);
| 1,620
| 217
| 1,837
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/CreateSnapshotCommand.java
|
CreateSnapshotCommand
|
deserialize
|
class CreateSnapshotCommand implements RemoteCommand<RemoteBucketState>, ComparableByContent<CreateSnapshotCommand> {
public static final SerializationHandle<CreateSnapshotCommand> SERIALIZATION_HANDLE = new SerializationHandle<CreateSnapshotCommand>() {
@Override
public <S> CreateSnapshotCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, CreateSnapshotCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
// do nothing
}
@Override
public int getTypeId() {
return 26;
}
@Override
public Class<CreateSnapshotCommand> getSerializedType() {
return CreateSnapshotCommand.class;
}
@Override
public CreateSnapshotCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new CreateSnapshotCommand();
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(CreateSnapshotCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
return result;
}
@Override
public String getTypeName() {
return "CreateSnapshotCommand";
}
};
@Override
public CommandResult<RemoteBucketState> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
return CommandResult.success(state, RemoteBucketState.SERIALIZATION_HANDLE);
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(CreateSnapshotCommand other) {
return true;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(RemoteBucketState result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new CreateSnapshotCommand();
| 727
| 51
| 778
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/EstimateAbilityToConsumeCommand.java
|
EstimateAbilityToConsumeCommand
|
toJsonCompatibleSnapshot
|
class EstimateAbilityToConsumeCommand implements RemoteCommand<EstimationProbe>, ComparableByContent<EstimateAbilityToConsumeCommand> {
private long tokensToConsume;
public static final SerializationHandle<EstimateAbilityToConsumeCommand> SERIALIZATION_HANDLE = new SerializationHandle<EstimateAbilityToConsumeCommand>() {
@Override
public <S> EstimateAbilityToConsumeCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = adapter.readLong(input);
return new EstimateAbilityToConsumeCommand(tokensToConsume);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, EstimateAbilityToConsumeCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.tokensToConsume);
}
@Override
public int getTypeId() {
return 28;
}
@Override
public Class<EstimateAbilityToConsumeCommand> getSerializedType() {
return EstimateAbilityToConsumeCommand.class;
}
@Override
public EstimateAbilityToConsumeCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = readLongValue(snapshot, "tokensToConsume");
return new EstimateAbilityToConsumeCommand(tokensToConsume);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(EstimateAbilityToConsumeCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "EstimateAbilityToConsumeCommand";
}
};
public EstimateAbilityToConsumeCommand(long tokensToEstimate) {
this.tokensToConsume = tokensToEstimate;
}
@Override
public CommandResult<EstimationProbe> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
long availableToConsume = state.getAvailableTokens();
if (tokensToConsume <= availableToConsume) {
EstimationProbe estimationProbe = EstimationProbe.canBeConsumed(availableToConsume);
return CommandResult.success(estimationProbe, EstimationProbe.SERIALIZATION_HANDLE);
} else {
long nanosToWaitForRefill = state.calculateDelayNanosAfterWillBePossibleToConsume(tokensToConsume, currentTimeNanos, true);
EstimationProbe estimationProbe = EstimationProbe.canNotBeConsumed(availableToConsume, nanosToWaitForRefill);
return CommandResult.success(estimationProbe, EstimationProbe.SERIALIZATION_HANDLE);
}
}
public long getTokensToConsume() {
return tokensToConsume;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(EstimateAbilityToConsumeCommand other) {
return tokensToConsume == other.tokensToConsume;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(EstimationProbe result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensToConsume", command.tokensToConsume);
return result;
| 1,123
| 62
| 1,185
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/ForceAddTokensCommand.java
|
ForceAddTokensCommand
|
fromJsonCompatibleSnapshot
|
class ForceAddTokensCommand implements RemoteCommand<Nothing>, ComparableByContent<ForceAddTokensCommand> {
private static final long serialVersionUID = 1L;
private long tokensToAdd;
public static final SerializationHandle<ForceAddTokensCommand> SERIALIZATION_HANDLE = new SerializationHandle<ForceAddTokensCommand>() {
@Override
public <I> ForceAddTokensCommand deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToAdd = adapter.readLong(input);
return new ForceAddTokensCommand(tokensToAdd);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ForceAddTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.tokensToAdd);
}
@Override
public int getTypeId() {
return 38;
}
@Override
public Class<ForceAddTokensCommand> getSerializedType() {
return ForceAddTokensCommand.class;
}
@Override
public ForceAddTokensCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ForceAddTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensToAdd", command.tokensToAdd);
return result;
}
@Override
public String getTypeName() {
return "ForceAddTokensCommand";
}
};
public ForceAddTokensCommand(long tokensToAdd) {
this.tokensToAdd = tokensToAdd;
}
public long getTokensToAdd() {
return tokensToAdd;
}
@Override
public CommandResult<Nothing> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
state.forceAddTokens(tokensToAdd);
mutableEntry.set(state);
return CommandResult.NOTHING;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return true;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(Nothing result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
@Override
public boolean equalsByContent(ForceAddTokensCommand other) {
return tokensToAdd == other.tokensToAdd;
}
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToAdd = readLongValue(snapshot, "tokensToAdd");
return new ForceAddTokensCommand(tokensToAdd);
| 886
| 81
| 967
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/GetAvailableTokensCommand.java
|
GetAvailableTokensCommand
|
fromJsonCompatibleSnapshot
|
class GetAvailableTokensCommand implements RemoteCommand<Long>, ComparableByContent<GetAvailableTokensCommand> {
public static final SerializationHandle<GetAvailableTokensCommand> SERIALIZATION_HANDLE = new SerializationHandle<GetAvailableTokensCommand>() {
@Override
public <S> GetAvailableTokensCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new GetAvailableTokensCommand();
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, GetAvailableTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
// do nothing
}
@Override
public int getTypeId() {
return 27;
}
@Override
public Class<GetAvailableTokensCommand> getSerializedType() {
return GetAvailableTokensCommand.class;
}
@Override
public GetAvailableTokensCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(GetAvailableTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
return result;
}
@Override
public String getTypeName() {
return "GetAvailableTokensCommand";
}
};
@Override
public CommandResult<Long> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
return CommandResult.success(state.getAvailableTokens(), LONG_HANDLE);
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(GetAvailableTokensCommand other) {
return true;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(Long result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new GetAvailableTokensCommand();
| 739
| 56
| 795
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/GetConfigurationCommand.java
|
GetConfigurationCommand
|
toJsonCompatibleSnapshot
|
class GetConfigurationCommand implements RemoteCommand<BucketConfiguration>, ComparableByContent<GetConfigurationCommand> {
@Override
public CommandResult<BucketConfiguration> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
return CommandResult.success(state.getConfiguration(), BucketConfiguration.SERIALIZATION_HANDLE);
}
public static SerializationHandle<GetConfigurationCommand> SERIALIZATION_HANDLE = new SerializationHandle<GetConfigurationCommand>() {
@Override
public <S> GetConfigurationCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new GetConfigurationCommand();
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, GetConfigurationCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
// do nothing
}
@Override
public int getTypeId() {
return 33;
}
@Override
public Class<GetConfigurationCommand> getSerializedType() {
return GetConfigurationCommand.class;
}
@Override
public GetConfigurationCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new GetConfigurationCommand();
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(GetConfigurationCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "GetConfigurationCommand";
}
};
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(GetConfigurationCommand other) {
return true;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(BucketConfiguration result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
return result;
| 719
| 42
| 761
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/ReplaceConfigurationCommand.java
|
ReplaceConfigurationCommand
|
deserialize
|
class ReplaceConfigurationCommand implements RemoteCommand<Nothing>, ComparableByContent<ReplaceConfigurationCommand> {
private final TokensInheritanceStrategy tokensInheritanceStrategy;
private final BucketConfiguration newConfiguration;
public static final SerializationHandle<ReplaceConfigurationCommand> SERIALIZATION_HANDLE = new SerializationHandle<ReplaceConfigurationCommand>() {
@Override
public <S> ReplaceConfigurationCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ReplaceConfigurationCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
BucketConfiguration.SERIALIZATION_HANDLE.serialize(adapter, output, command.newConfiguration, backwardCompatibilityVersion, scope);
adapter.writeByte(output, command.tokensInheritanceStrategy.getId());
}
@Override
public int getTypeId() {
return 32;
}
@Override
public Class<ReplaceConfigurationCommand> getSerializedType() {
return ReplaceConfigurationCommand.class;
}
@Override
public ReplaceConfigurationCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
TokensInheritanceStrategy tokensInheritanceStrategy = TokensInheritanceStrategy.valueOf((String) snapshot.get("tokensInheritanceStrategy"));
BucketConfiguration newConfiguration = BucketConfiguration.SERIALIZATION_HANDLE
.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("newConfiguration"));
return new ReplaceConfigurationCommand(newConfiguration, tokensInheritanceStrategy);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ReplaceConfigurationCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensInheritanceStrategy", command.tokensInheritanceStrategy.toString());
result.put("newConfiguration", BucketConfiguration.SERIALIZATION_HANDLE.toJsonCompatibleSnapshot(command.newConfiguration, backwardCompatibilityVersion, scope));
return result;
}
@Override
public String getTypeName() {
return "ReplaceConfigurationCommand";
}
};
public ReplaceConfigurationCommand(BucketConfiguration newConfiguration, TokensInheritanceStrategy tokensInheritanceStrategy) {
this.newConfiguration = newConfiguration;
this.tokensInheritanceStrategy = tokensInheritanceStrategy;
}
@Override
public CommandResult<Nothing> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
state.replaceConfiguration(newConfiguration, tokensInheritanceStrategy, currentTimeNanos);
mutableEntry.set(state);
return CommandResult.empty();
}
public BucketConfiguration getNewConfiguration() {
return newConfiguration;
}
public TokensInheritanceStrategy getTokensInheritanceStrategy() {
return tokensInheritanceStrategy;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(ReplaceConfigurationCommand other) {
return ComparableByContent.equals(newConfiguration, other.newConfiguration) &&
tokensInheritanceStrategy == other.tokensInheritanceStrategy;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return true;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(Nothing result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
BucketConfiguration newConfiguration = BucketConfiguration.SERIALIZATION_HANDLE.deserialize(adapter, input);
TokensInheritanceStrategy tokensInheritanceStrategy = TokensInheritanceStrategy.getById(adapter.readByte(input));
return new ReplaceConfigurationCommand(newConfiguration, tokensInheritanceStrategy);
| 1,112
| 123
| 1,235
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/ReserveAndCalculateTimeToSleepCommand.java
|
ReserveAndCalculateTimeToSleepCommand
|
deserialize
|
class ReserveAndCalculateTimeToSleepCommand implements RemoteCommand<Long>, ComparableByContent<ReserveAndCalculateTimeToSleepCommand> {
private long tokensToConsume;
private long waitIfBusyNanosLimit;
public static final SerializationHandle<ReserveAndCalculateTimeToSleepCommand> SERIALIZATION_HANDLE = new SerializationHandle<ReserveAndCalculateTimeToSleepCommand>() {
@Override
public <S> ReserveAndCalculateTimeToSleepCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ReserveAndCalculateTimeToSleepCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.tokensToConsume);
adapter.writeLong(output, command.waitIfBusyNanosLimit);
}
@Override
public int getTypeId() {
return 23;
}
@Override
public Class<ReserveAndCalculateTimeToSleepCommand> getSerializedType() {
return ReserveAndCalculateTimeToSleepCommand.class;
}
@Override
public ReserveAndCalculateTimeToSleepCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = readLongValue(snapshot, "tokensToConsume");
long waitIfBusyNanosLimit = readLongValue(snapshot, "waitIfBusyNanosLimit");
return new ReserveAndCalculateTimeToSleepCommand(tokensToConsume, waitIfBusyNanosLimit);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ReserveAndCalculateTimeToSleepCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensToConsume", command.tokensToConsume);
result.put("waitIfBusyNanosLimit", command.waitIfBusyNanosLimit);
return result;
}
@Override
public String getTypeName() {
return "ReserveAndCalculateTimeToSleepCommand";
}
};
public ReserveAndCalculateTimeToSleepCommand(long tokensToConsume, long waitIfBusyNanosLimit) {
this.tokensToConsume = tokensToConsume;
this.waitIfBusyNanosLimit = waitIfBusyNanosLimit;
}
@Override
public CommandResult<Long> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
long nanosToCloseDeficit = state.calculateDelayNanosAfterWillBePossibleToConsume(tokensToConsume, currentTimeNanos, false);
if (nanosToCloseDeficit == Long.MAX_VALUE || nanosToCloseDeficit > waitIfBusyNanosLimit) {
return CommandResult.MAX_VALUE;
} else {
state.consume(tokensToConsume);
mutableEntry.set(state);
return CommandResult.success(nanosToCloseDeficit, LONG_HANDLE);
}
}
public long getTokensToConsume() {
return tokensToConsume;
}
public long getWaitIfBusyNanosLimit() {
return waitIfBusyNanosLimit;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(ReserveAndCalculateTimeToSleepCommand other) {
return tokensToConsume == other.tokensToConsume &&
waitIfBusyNanosLimit == other.waitIfBusyNanosLimit;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return tokensToConsume;
}
@Override
public long getConsumedTokens(Long result) {
return result;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = adapter.readLong(input);
long waitIfBusyNanosLimit = adapter.readLong(input);
return new ReserveAndCalculateTimeToSleepCommand(tokensToConsume, waitIfBusyNanosLimit);
| 1,245
| 107
| 1,352
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/ResetCommand.java
|
ResetCommand
|
toJsonCompatibleSnapshot
|
class ResetCommand implements RemoteCommand<Nothing>, ComparableByContent<ResetCommand> {
public static final SerializationHandle<ResetCommand> SERIALIZATION_HANDLE = new SerializationHandle<ResetCommand>() {
@Override
public <S> ResetCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new ResetCommand();
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, ResetCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
}
@Override
public int getTypeId() {
return 39;
}
@Override
public Class<ResetCommand> getSerializedType() {
return ResetCommand.class;
}
@Override
public ResetCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
return new ResetCommand();
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(ResetCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "ResetCommand";
}
};
public ResetCommand() {
}
@Override
public CommandResult<Nothing> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
state.reset();
mutableEntry.set(state);
return CommandResult.empty();
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(ResetCommand other) {
return true;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return true;
}
@Override
public long estimateTokensToConsume() {
return 0;
}
@Override
public long getConsumedTokens(Nothing result) {
return 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
return result;
| 726
| 42
| 768
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/SyncCommand.java
|
SyncCommand
|
deserialize
|
class SyncCommand implements RemoteCommand<Nothing>, ComparableByContent<SyncCommand> {
private final long unsynchronizedTokens;
private final long nanosSinceLastSync;
public static final SerializationHandle<SyncCommand> SERIALIZATION_HANDLE = new SerializationHandle<SyncCommand>() {
@Override
public <S> SyncCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, SyncCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.unsynchronizedTokens);
adapter.writeLong(output, command.nanosSinceLastSync);
}
@Override
public int getTypeId() {
return 36;
}
@Override
public Class<SyncCommand> getSerializedType() {
return SyncCommand.class;
}
@Override
public SyncCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long unsynchronizedTokens = readLongValue(snapshot, "unsynchronizedTokens");
long nanosSinceLastSync = readLongValue(snapshot, "nanosSinceLastSync");
return new SyncCommand(unsynchronizedTokens, nanosSinceLastSync);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(SyncCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("unsynchronizedTokens", command.unsynchronizedTokens);
result.put("nanosSinceLastSync", command.nanosSinceLastSync);
return result;
}
@Override
public String getTypeName() {
return "SyncCommand";
}
};
public SyncCommand(long unsynchronizedTokens, long nanosSinceLastSync) {
if (unsynchronizedTokens < 0) {
throw BucketExceptions.nonPositiveTokensLimitToSync(unsynchronizedTokens);
}
if (nanosSinceLastSync < 0) {
throw BucketExceptions.nonPositiveLimitToSync(nanosSinceLastSync);
}
this.unsynchronizedTokens = unsynchronizedTokens;
this.nanosSinceLastSync = nanosSinceLastSync;
}
public long getNanosSinceLastSync() {
return nanosSinceLastSync;
}
public long getUnsynchronizedTokens() {
return unsynchronizedTokens;
}
@Override
public CommandResult<Nothing> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
mutableEntry.set(state);
return CommandResult.NOTHING;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(SyncCommand other) {
return unsynchronizedTokens == other.unsynchronizedTokens
&& nanosSinceLastSync == other.nanosSinceLastSync;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return this.unsynchronizedTokens <= unsynchronizedTokens
&& this.nanosSinceLastSync <= nanosSinceLastSync;
}
@Override
public long estimateTokensToConsume() {
return 0L;
}
@Override
public long getConsumedTokens(Nothing result) {
return 0L;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long unsynchronizedTokens = adapter.readLong(input);
long nanosSinceLastSync = adapter.readLong(input);
return new SyncCommand(unsynchronizedTokens, nanosSinceLastSync);
| 1,100
| 95
| 1,195
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/TryConsumeAndReturnRemainingTokensCommand.java
|
TryConsumeAndReturnRemainingTokensCommand
|
fromJsonCompatibleSnapshot
|
class TryConsumeAndReturnRemainingTokensCommand implements RemoteCommand<ConsumptionProbe>, ComparableByContent<TryConsumeAndReturnRemainingTokensCommand> {
private long tokensToConsume;
public static final SerializationHandle<TryConsumeAndReturnRemainingTokensCommand> SERIALIZATION_HANDLE = new SerializationHandle<TryConsumeAndReturnRemainingTokensCommand>() {
@Override
public <S> TryConsumeAndReturnRemainingTokensCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = adapter.readLong(input);
return new TryConsumeAndReturnRemainingTokensCommand(tokensToConsume);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, TryConsumeAndReturnRemainingTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.tokensToConsume);
}
@Override
public int getTypeId() {
return 30;
}
@Override
public Class<TryConsumeAndReturnRemainingTokensCommand> getSerializedType() {
return TryConsumeAndReturnRemainingTokensCommand.class;
}
@Override
public TryConsumeAndReturnRemainingTokensCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(TryConsumeAndReturnRemainingTokensCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensToConsume", command.tokensToConsume);
return result;
}
@Override
public String getTypeName() {
return "TryConsumeAndReturnRemainingTokensCommand";
}
};
public TryConsumeAndReturnRemainingTokensCommand(long tokensToConsume) {
this.tokensToConsume = tokensToConsume;
}
@Override
public CommandResult<ConsumptionProbe> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
long availableToConsume = state.getAvailableTokens();
if (tokensToConsume <= availableToConsume) {
state.consume(tokensToConsume);
mutableEntry.set(state);
long nanosToWaitForReset = state.calculateFullRefillingTime(currentTimeNanos);
long remainingTokens = availableToConsume - tokensToConsume;
ConsumptionProbe probe = ConsumptionProbe.consumed(remainingTokens, nanosToWaitForReset);
return CommandResult.success(probe, ConsumptionProbe.SERIALIZATION_HANDLE);
} else {
long nanosToWaitForReset = state.calculateFullRefillingTime(currentTimeNanos);
long nanosToWaitForRefill = state.calculateDelayNanosAfterWillBePossibleToConsume(tokensToConsume, currentTimeNanos, true);
ConsumptionProbe probe = ConsumptionProbe.rejected(availableToConsume, nanosToWaitForRefill, nanosToWaitForReset);
return CommandResult.success(probe, ConsumptionProbe.SERIALIZATION_HANDLE);
}
}
public long getTokensToConsume() {
return tokensToConsume;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(TryConsumeAndReturnRemainingTokensCommand other) {
return tokensToConsume == other.tokensToConsume;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return tokensToConsume;
}
@Override
public long getConsumedTokens(ConsumptionProbe result) {
return result.isConsumed() ? tokensToConsume : 0L;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = readLongValue(snapshot, "tokensToConsume");
return new TryConsumeAndReturnRemainingTokensCommand(tokensToConsume);
| 1,229
| 89
| 1,318
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/TryConsumeCommand.java
|
TryConsumeCommand
|
execute
|
class TryConsumeCommand implements RemoteCommand<Boolean>, ComparableByContent<TryConsumeCommand> {
public static final TryConsumeCommand TRY_CONSUME_ONE = new TryConsumeCommand(1);
private long tokensToConsume;
public static final SerializationHandle<TryConsumeCommand> SERIALIZATION_HANDLE = new SerializationHandle<TryConsumeCommand>() {
@Override
public <S> TryConsumeCommand deserialize(DeserializationAdapter<S> adapter, S input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = adapter.readLong(input);
return TryConsumeCommand.create(tokensToConsume);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, TryConsumeCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeLong(output, command.tokensToConsume);
}
@Override
public int getTypeId() {
return 29;
}
@Override
public Class<TryConsumeCommand> getSerializedType() {
return TryConsumeCommand.class;
}
@Override
public TryConsumeCommand fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
long tokensToConsume = readLongValue(snapshot, "tokensToConsume");
return TryConsumeCommand.create(tokensToConsume);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(TryConsumeCommand command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("tokensToConsume", command.tokensToConsume);
return result;
}
@Override
public String getTypeName() {
return "TryConsumeCommand";
}
};
private TryConsumeCommand(long tokensToConsume) {
this.tokensToConsume = tokensToConsume;
}
@Override
public RemoteCommand<?> toMergedCommand() {
ConsumeAsMuchAsPossibleCommand merged = new ConsumeAsMuchAsPossibleCommand(1);
merged.setMerged(true);
return merged;
}
@Override
public boolean canBeMerged(RemoteCommand<?> another) {
return this == TRY_CONSUME_ONE && another == TRY_CONSUME_ONE;
}
@Override
public void mergeInto(RemoteCommand<?> mergedCommand) {
ConsumeAsMuchAsPossibleCommand mergedConsume = (ConsumeAsMuchAsPossibleCommand) mergedCommand;
mergedConsume.setLimit(mergedConsume.getLimit() + 1);
}
public static TryConsumeCommand create(long tokensToConsume) {
if (tokensToConsume == 1) {
return TRY_CONSUME_ONE;
} else {
return new TryConsumeCommand(tokensToConsume);
}
}
@Override
public CommandResult<Boolean> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {<FILL_FUNCTION_BODY>}
public long getTokensToConsume() {
return tokensToConsume;
}
@Override
public SerializationHandle getSerializationHandle() {
return SERIALIZATION_HANDLE;
}
@Override
public boolean equalsByContent(TryConsumeCommand other) {
return tokensToConsume == other.tokensToConsume;
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return false;
}
@Override
public long estimateTokensToConsume() {
return tokensToConsume;
}
@Override
public long getConsumedTokens(Boolean result) {
return result ? tokensToConsume : 0;
}
@Override
public Version getRequiredVersion() {
return v_7_0_0;
}
}
|
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
RemoteBucketState state = mutableEntry.get();
state.refillAllBandwidth(currentTimeNanos);
long availableToConsume = state.getAvailableTokens();
if (tokensToConsume <= availableToConsume) {
state.consume(tokensToConsume);
mutableEntry.set(state);
return CommandResult.TRUE;
} else {
return CommandResult.FALSE;
}
| 1,158
| 136
| 1,294
|
<no_super_class>
|
bucket4j_bucket4j
|
bucket4j/bucket4j-core/src/main/java/io/github/bucket4j/distributed/remote/commands/VerboseCommand.java
|
VerboseCommand
|
toJsonCompatibleSnapshot
|
class VerboseCommand<T> implements RemoteCommand<RemoteVerboseResult<T>>, ComparableByContent<VerboseCommand<?>> {
public static final VerboseCommand<Boolean> TRY_CONSUME_ONE_VERBOSE = new VerboseCommand<>(TRY_CONSUME_ONE);
private final RemoteCommand<T> targetCommand;
private VerboseCommand(RemoteCommand<T> targetCommand) {
this.targetCommand = targetCommand;
}
public static <T> VerboseCommand<T> from(RemoteCommand<T> targetCommand) {
if (targetCommand == TryConsumeCommand.TRY_CONSUME_ONE) {
return (VerboseCommand<T>) TRY_CONSUME_ONE_VERBOSE;
} else {
return new VerboseCommand<>(targetCommand);
}
}
public RemoteCommand<T> getTargetCommand() {
return targetCommand;
}
@Override
public boolean canBeMerged(RemoteCommand<?> another) {
return this == TRY_CONSUME_ONE_VERBOSE && another == TRY_CONSUME_ONE_VERBOSE;
}
@Override
public RemoteCommand<?> toMergedCommand() {
return new VerboseCommand<>(targetCommand.toMergedCommand());
}
@Override
public void mergeInto(RemoteCommand<?> mergedCommand) {
targetCommand.mergeInto(((VerboseCommand<?>) mergedCommand).targetCommand);
}
@Override
public int getMergedCommandsCount() {
return targetCommand.getMergedCommandsCount();
}
@Override
public CommandResult<?> unwrapOneResult(RemoteVerboseResult<T> mergedVerboseResult, int indice) {
CommandResult<?> unwrappedTargetResult = targetCommand.unwrapOneResult(mergedVerboseResult.getValue(), indice);
RemoteVerboseResult<?> unwrappedVerboseResult = new RemoteVerboseResult<>(
mergedVerboseResult.getOperationTimeNanos(),
unwrappedTargetResult.getResultTypeId(),
unwrappedTargetResult.getData(),
mergedVerboseResult.getState()
);
return CommandResult.success(unwrappedVerboseResult, RemoteVerboseResult.SERIALIZATION_HANDLE);
}
@Override
public boolean isMerged() {
return targetCommand.isMerged();
}
@Override
public CommandResult<RemoteVerboseResult<T>> execute(MutableBucketEntry mutableEntry, long currentTimeNanos) {
if (!mutableEntry.exists()) {
return CommandResult.bucketNotFound();
}
CommandResult<T> result = targetCommand.execute(mutableEntry, currentTimeNanos);
RemoteVerboseResult<T> verboseResult = new RemoteVerboseResult<>(currentTimeNanos, result.getResultTypeId(), result.getData(), mutableEntry.get());
return CommandResult.success(verboseResult, RemoteVerboseResult.SERIALIZATION_HANDLE);
}
@Override
public SerializationHandle<RemoteCommand<?>> getSerializationHandle() {
return (SerializationHandle) SERIALIZATION_HANDLE;
}
public static final SerializationHandle<VerboseCommand<?>> SERIALIZATION_HANDLE = new SerializationHandle<VerboseCommand<?>>() {
@Override
public <I> VerboseCommand<?> deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
RemoteCommand<?> targetCommand = RemoteCommand.deserialize(adapter, input);
return VerboseCommand.from(targetCommand);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, VerboseCommand<?> command, Version backwardCompatibilityVersion, Scope scope) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
RemoteCommand.serialize(adapter, output, command.targetCommand, backwardCompatibilityVersion, scope);
}
@Override
public int getTypeId() {
return 35;
}
@Override
public Class<VerboseCommand<?>> getSerializedType() {
return (Class) VerboseCommand.class;
}
@Override
public VerboseCommand<?> fromJsonCompatibleSnapshot(Map<String, Object> snapshot) throws IOException {
int formatNumber = readIntValue(snapshot, "version");
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
RemoteCommand<?> targetCommand = RemoteCommand.fromJsonCompatibleSnapshot((Map<String, Object>) snapshot.get("targetCommand"));
return VerboseCommand.from(targetCommand);
}
@Override
public Map<String, Object> toJsonCompatibleSnapshot(VerboseCommand<?> command, Version backwardCompatibilityVersion, Scope scope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getTypeName() {
return "VerboseCommand";
}
};
@Override
public boolean equalsByContent(VerboseCommand<?> other) {
return ComparableByContent.equals(targetCommand, other.targetCommand);
}
@Override
public boolean isImmediateSyncRequired(long unsynchronizedTokens, long nanosSinceLastSync) {
return targetCommand.isImmediateSyncRequired(unsynchronizedTokens, nanosSinceLastSync);
}
@Override
public long estimateTokensToConsume() {
return targetCommand.estimateTokensToConsume();
}
@Override
public long getConsumedTokens(RemoteVerboseResult<T> result) {
return targetCommand.getConsumedTokens(result.getValue());
}
@Override
public Version getRequiredVersion() {
return Versions.max(v_7_0_0, targetCommand.getRequiredVersion());
}
}
|
Map<String, Object> result = new HashMap<>();
result.put("version", v_7_0_0.getNumber());
result.put("targetCommand", RemoteCommand.toJsonCompatibleSnapshot(command.targetCommand, backwardCompatibilityVersion, scope));
return result;
| 1,569
| 72
| 1,641
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.