io.github.bucket4j.grid.GridBucketState Java Examples

The following examples show how to use io.github.bucket4j.grid.GridBucketState. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CoherenceProxy.java    From bucket4j with Apache License 2.0 6 votes vote down vote up
private <T extends Serializable> CompletableFuture<CommandResult<T>> invokeAsync(K key, JCacheEntryProcessor<K, T> entryProcessor) {
    CompletableFuture<CommandResult<T>> future = new CompletableFuture<>();
    SingleEntryAsynchronousProcessor<K, GridBucketState, CommandResult<T>> asyncProcessor =
            new SingleEntryAsynchronousProcessor<K, GridBucketState, CommandResult<T>>(adoptEntryProcessor(entryProcessor)) {
        @Override
        public void onResult(Map.Entry<K, CommandResult<T>> entry) {
            super.onResult(entry);
            future.complete(entry.getValue());
        }
        @Override
        public void onException(Throwable error) {
            super.onException(error);
            future.completeExceptionally(error);
        }
    };
    cache.invoke(key, asyncProcessor);
    return future;
}
 
Example #2
Source File: JCacheProxy.java    From bucket4j with Apache License 2.0 6 votes vote down vote up
private void checkProviders(Cache<K, GridBucketState> cache) {
    CacheManager cacheManager = cache.getCacheManager();
    if (cacheManager == null) {
        return;
    }

    CachingProvider cachingProvider = cacheManager.getCachingProvider();
    if (cachingProvider == null) {
        return;
    }

    String providerClassName = cachingProvider.getClass().getName();
    incompatibleProviders.forEach((providerPrefix, recommendation) -> {
        if (providerClassName.startsWith(providerPrefix)) {
            String message = "The Cache provider " + providerClassName + " is incompatible with Bucket4j, " + recommendation;
            throw new UnsupportedOperationException(message);
        }
    });
}
 
Example #3
Source File: InfinispanProxy.java    From bucket4j with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<BucketConfiguration> getConfiguration(K key) {
    try {
        SerializableFunction<EntryView.ReadWriteEntryView<K, GridBucketState>, GridBucketState> findFunction =
                (SerializableFunction<EntryView.ReadWriteEntryView<K, GridBucketState>, GridBucketState>)
                entry -> entry.find().orElse(null);
        GridBucketState state = readWriteMap.eval(key, findFunction).get();
        if (state == null) {
            return Optional.empty();
        } else {
            return Optional.of(state.getConfiguration());
        }
    } catch (InterruptedException | ExecutionException e) {
        throw new CacheException(e);
    }
}
 
Example #4
Source File: GridProxyMock.java    From bucket4j with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResult execute(Serializable key, GridCommand command) {
    if (exception != null) {
        throw new RuntimeException();
    }
    if (state == null) {
        return CommandResult.bucketNotFound();
    }
    emulateSerialization(key);
    command = emulateSerialization(command);
    GridBucketState newState = emulateSerialization(state);
    Serializable resultData = command.execute(newState, timeMeter.currentTimeNanos());
    if (command.isBucketStateModified()) {
        state = newState;
    }
    resultData = emulateSerialization(resultData);
    return CommandResult.success(resultData);
}
 
Example #5
Source File: HazelcastProxy.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<BucketConfiguration> getConfiguration(K key) {
    GridBucketState state = cache.get(key);
    if (state == null) {
        return Optional.empty();
    } else {
        return Optional.of(state.getConfiguration());
    }
}
 
Example #6
Source File: Bucket4jInfinispanApplication.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 5 votes vote down vote up
@Bean
@Qualifier("RateLimit")
public ReadWriteMap<String, GridBucketState> map() {
    DefaultCacheManager cacheManager = new DefaultCacheManager();
    cacheManager.defineConfiguration("rateLimit", new ConfigurationBuilder().build());
    AdvancedCache<String, GridBucketState> cache = cacheManager.<String, GridBucketState>getCache("rateLimit").getAdvancedCache();
    FunctionalMapImpl<String, GridBucketState> functionalMap = FunctionalMapImpl.create(cache);
    return ReadWriteMapImpl.create(functionalMap);
}
 
Example #7
Source File: RateLimitingFilter.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
public RateLimitingFilter(JHipsterProperties jHipsterProperties) {
    this.jHipsterProperties = jHipsterProperties;

    CachingProvider cachingProvider = Caching.getCachingProvider();
    CacheManager cacheManager = cachingProvider.getCacheManager();
    CompleteConfiguration<String, GridBucketState> config =
        new MutableConfiguration<String, GridBucketState>()
            .setTypes(String.class, GridBucketState.class);

    this.cache = cacheManager.createCache(GATEWAY_RATE_LIMITING_CACHE_NAME, config);
    this.buckets = Bucket4j.extension(JCache.class).proxyManagerForCache(cache);
}
 
Example #8
Source File: RateLimitingFilter.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
public RateLimitingFilter(JHipsterProperties jHipsterProperties) {
    this.jHipsterProperties = jHipsterProperties;

    CachingProvider cachingProvider = Caching.getCachingProvider();
    CacheManager cacheManager = cachingProvider.getCacheManager();
    CompleteConfiguration<String, GridBucketState> config =
        new MutableConfiguration<String, GridBucketState>()
            .setTypes(String.class, GridBucketState.class);

    this.cache = cacheManager.createCache(GATEWAY_RATE_LIMITING_CACHE_NAME, config);
    this.buckets = Bucket4j.extension(JCache.class).proxyManagerForCache(cache);
}
 
Example #9
Source File: ExecuteProcessor.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public CommandResult<T> process(MutableEntry<K, GridBucketState> mutableEntry, Object... arguments) {
    if (!mutableEntry.exists()) {
        return CommandResult.bucketNotFound();
    }
    long currentTimeNanos = currentTimeNanos();
    GridBucketState gridBucketState = mutableEntry.getValue();

    T result = targetCommand.execute(gridBucketState, currentTimeNanos);
    if (targetCommand.isBucketStateModified()) {
        mutableEntry.setValue(gridBucketState);
    }
    return CommandResult.success(result);
}
 
Example #10
Source File: JCacheProxy.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<BucketConfiguration> getConfiguration(K key) {
    GridBucketState state = cache.get(key);
    if (state == null) {
        return Optional.empty();
    } else {
        return Optional.of(state.getConfiguration());
    }
}
 
Example #11
Source File: IgniteProxy.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<BucketConfiguration> getConfiguration(K key) {
    GridBucketState state = cache.get(key);
    if (state == null) {
        return Optional.empty();
    } else {
        return Optional.of(state.getConfiguration());
    }
}
 
Example #12
Source File: PackageAcessor.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
public static BucketState getState(Bucket bucket) {
    if (bucket instanceof LockFreeBucket) {
        AtomicReference stateRef = getFieldValue(bucket, "stateRef");
        return getFieldValue(stateRef.get(), "state");
    } else if (bucket instanceof SynchronizedBucket) {
        return getFieldValue(bucket, "state");
    } else if (bucket instanceof GridBucket) {
        GridProxyMock proxy = getFieldValue(bucket, "gridProxy");
        GridBucketState gridState = getFieldValue(proxy, "state");
        return gridState.getState();
    } else {
        throw new IllegalStateException("Unknown bucket type " + bucket.getClass());
    }
}
 
Example #13
Source File: RateLimitingFilter.java    From tutorials with MIT License 5 votes vote down vote up
public RateLimitingFilter(JHipsterProperties jHipsterProperties) {
    this.jHipsterProperties = jHipsterProperties;

    CachingProvider cachingProvider = Caching.getCachingProvider();
    CacheManager cacheManager = cachingProvider.getCacheManager();
    CompleteConfiguration<String, GridBucketState> config =
        new MutableConfiguration<String, GridBucketState>()
            .setTypes(String.class, GridBucketState.class);

    this.cache = cacheManager.createCache(GATEWAY_RATE_LIMITING_CACHE_NAME, config);
    this.buckets = Bucket4j.extension(JCache.class).proxyManagerForCache(cache);
}
 
Example #14
Source File: CoherenceProxy.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<BucketConfiguration> getConfiguration(K key) {
    GridBucketState state = cache.get(key);
    if (state == null) {
        return Optional.empty();
    } else {
        return Optional.of(state.getConfiguration());
    }
}
 
Example #15
Source File: HazelcastProxy.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<BucketConfiguration> getConfiguration(K key) {
    GridBucketState state = cache.get(key);
    if (state == null) {
        return Optional.empty();
    } else {
        return Optional.of(state.getConfiguration());
    }
}
 
Example #16
Source File: CoherencePofSerializerTest.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializationOfBucketState() throws IOException {
    Bandwidth[] bandwidths = new Bandwidth[] {
            simple(10, ofSeconds(42)),
            classic(20, greedy(300, ofHours(2))),
            classic(400, intervallyAligned(1000, ofDays(2), Instant.now(), false))
    };
    BucketConfiguration bucketConfiguration = new BucketConfiguration(Arrays.asList(bandwidths));
    BucketState bucketState = new BucketState(bucketConfiguration, System.nanoTime());

    bucketState.addTokens(bandwidths, 42);
    GridBucketState gridBucketState = new GridBucketState(bucketConfiguration, bucketState);

    testSerialization(gridBucketState);
}
 
Example #17
Source File: HazelcastEntryProcessorAdapter.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public Object process(Map.Entry<K, GridBucketState> entry) {
    HazelcastMutableEntryAdapter<K> entryAdapter = new HazelcastMutableEntryAdapter<>(entry);
    CommandResult<T> result = entryProcessor.process(entryAdapter);
    if (entryAdapter.isModified()) {
        GridBucketState state = entry.getValue();
        backupProcessor = new SimpleBackupProcessor<>(state);
    }
    return result;
}
 
Example #18
Source File: Bucket4jInfinispanRateLimiterTest.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
    DefaultCacheManager cacheManager = new DefaultCacheManager();
    cacheManager.defineConfiguration("rateLimit", new ConfigurationBuilder().build());
    AdvancedCache<String, GridBucketState> cache = cacheManager.<String, GridBucketState>getCache("rateLimit").getAdvancedCache();
    FunctionalMapImpl<String, GridBucketState> functionalMap = FunctionalMapImpl.create(cache);
    FunctionalMap.ReadWriteMap<String, GridBucketState> readWriteMap = ReadWriteMapImpl.create(functionalMap);
    target = new Bucket4jInfinispanRateLimiter(readWriteMap);
}
 
Example #19
Source File: GridProxyMock.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public void createInitialState(Serializable key, BucketConfiguration configuration) {
    if (exception != null) {
        throw new RuntimeException();
    }
    BucketState bucketState = BucketState.createInitialState(configuration, timeMeter.currentTimeNanos());
    this.state = new GridBucketState(configuration, bucketState);
}
 
Example #20
Source File: SerializableFunctionAdapter.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
public MutableEntryAdapter(EntryView.ReadWriteEntryView<K, GridBucketState> entryView) {
    this.entryView = entryView;
}
 
Example #21
Source File: InfinispanTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
private static ReadWriteMap<String, GridBucketState> toMap(Cache<String, GridBucketState> cache) {
    FunctionalMapImpl<String, GridBucketState> functionalMap = FunctionalMapImpl.create(cache.getAdvancedCache());
    return ReadWriteMapImpl.create(functionalMap);
}
 
Example #22
Source File: SerializableFunctionAdapter.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
public void setValue(GridBucketState value) {
    entryView.set(value);
}
 
Example #23
Source File: JCacheProxy.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
public JCacheProxy(Cache<K, GridBucketState> cache) {
    this.cache = Objects.requireNonNull(cache);
    checkProviders(cache);
}
 
Example #24
Source File: SerializableFunctionAdapter.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
public void setValue(GridBucketState value) {
    entryView.set(value);
}
 
Example #25
Source File: SimpleBackupProcessor.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
public Object process(Map.Entry<K, GridBucketState> entry) {
    entry.setValue(state);
    return null; // return value from backup processor is ignored, see https://github.com/hazelcast/hazelcast/pull/14995
}
 
Example #26
Source File: SimpleBackupProcessor.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
public <I> SimpleBackupProcessor<?> deserialize(DeserializationAdapter<I> adapter, I input) throws IOException {
    GridBucketState state = adapter.readObject(input, GridBucketState.class);
    return new SimpleBackupProcessor<>(state);
}
 
Example #27
Source File: HazelcastProxyManager.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
HazelcastProxyManager(IMap<K, GridBucketState> map) {
    if (map == null) {
        throw new IllegalArgumentException("map must not be null");
    }
    this.gridProxy = new HazelcastProxy<>(map);
}
 
Example #28
Source File: HazelcastEntryProcessorAdapter.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
public EntryBackupProcessor<K, GridBucketState> getBackupProcessor() {
    return backupProcessor;
}
 
Example #29
Source File: HazelcastProxy.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
public HazelcastProxy(IMap<K, GridBucketState> cache) {
    this.cache = cache;
}
 
Example #30
Source File: SimpleBackupProcessor.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
public SimpleBackupProcessor(GridBucketState state) {
    this.state = state;
}