All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.bucket4j.grid.jcache.JCacheProxyManager Maven / Gradle / Ivy

There is a newer version: 8.0.1
Show newest version
/*-
 * ========================LICENSE_START=================================
 * Bucket4j
 * %%
 * Copyright (C) 2015 - 2020 Vladimir Bukhtoyarov
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =========================LICENSE_END==================================
 */
/*
 *
 * Copyright 2015-2018 Vladimir Bukhtoyarov
 *
 *       Licensed under the Apache License, Version 2.0 (the "License");
 *       you may not use this file except in compliance with the License.
 *       You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package io.github.bucket4j.grid.jcache;

import io.github.bucket4j.distributed.proxy.AbstractProxyManager;
import io.github.bucket4j.distributed.proxy.ClientSideConfig;
import io.github.bucket4j.distributed.remote.*;
import io.github.bucket4j.distributed.serialization.InternalSerializationHelper;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.MutableEntry;
import javax.cache.spi.CachingProvider;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * The extension of Bucket4j library addressed to support JCache API (JSR 107) specification.
 */
public class JCacheProxyManager extends AbstractProxyManager {

    private static final Map incompatibleProviders = Collections.emptyMap();
    static {
        // incompatibleProviders.put("org.infinispan", " use module bucket4j-infinispan directly");
    }

    private static final Set preferLambdaStyleProviders = Collections.singleton("org.infinispan");

    private final Cache cache;
    private final boolean preferLambdaStyle;

    public JCacheProxyManager(Cache cache) {
        this(cache, ClientSideConfig.getDefault());
    }

    public JCacheProxyManager(Cache cache, ClientSideConfig clientSideConfig) {
        super(clientSideConfig);
        checkCompatibilityWithProvider(cache);
        this.cache = Objects.requireNonNull(cache);
        this.preferLambdaStyle = preferLambdaStyle(cache);
    }

    @Override
    public  CommandResult execute(K key, Request request) {
        EntryProcessor entryProcessor = preferLambdaStyle? createLambdaProcessor(request) : new BucketProcessor<>(request);
        byte[] resultBytes = cache.invoke(key, entryProcessor);
        return InternalSerializationHelper.deserializeResult(resultBytes, request.getBackwardCompatibilityVersion());
    }

    @Override
    public void removeProxy(K key) {
        cache.remove(key);
    }

    @Override
    public boolean isAsyncModeSupported() {
        return false;
    }

    @Override
    public  CompletableFuture> executeAsync(K key, Request request) {
        // because JCache does not specify async API
        throw new UnsupportedOperationException();
    }

    @Override
    protected CompletableFuture removeAsync(K key) {
        // because JCache does not specify async API
        throw new UnsupportedOperationException();
    }

    private void checkCompatibilityWithProvider(Cache cache) {
        CacheManager cacheManager = cache.getCacheManager();
        if (cacheManager == null) {
            return;
        }

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

        String providerClassName = cachingProvider.getClass().getName();
        incompatibleProviders.forEach((providerPrefix, recommendation) -> {
            if (providerClassName.startsWith(providerPrefix)) {
                String message = "The Cache provider " + providerClassName + " is incompatible with Bucket4j, " + recommendation;
                throw new UnsupportedOperationException(message);
            }
        });
    }

    private boolean preferLambdaStyle(Cache cache) {
        CacheManager cacheManager = cache.getCacheManager();
        if (cacheManager == null) {
            return false;
        }

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

        String providerClassName = cachingProvider.getClass().getName();
        for (String providerPrefix : preferLambdaStyleProviders) {
            if (providerClassName.startsWith(providerPrefix)) {
                return true;
            }
        }

        return false;
    }

    public  EntryProcessor createLambdaProcessor(Request request) {
        byte[] serializedRequest = InternalSerializationHelper.serializeRequest(request);
        return  (Serializable & EntryProcessor) (mutableEntry, objects)
                -> new JCacheTransaction(mutableEntry, serializedRequest).execute();
    }

    private static class BucketProcessor implements Serializable, EntryProcessor {

        private static final long serialVersionUID = 911;

        private final byte[] serializedRequest;

        public BucketProcessor(Request request) {
            this.serializedRequest = InternalSerializationHelper.serializeRequest(request);
        }

        @Override
        public byte[] process(MutableEntry mutableEntry, Object... arguments) {
            return new JCacheTransaction(mutableEntry, serializedRequest).execute();
        }

    }

    private static class JCacheTransaction extends AbstractBinaryTransaction {

        private final MutableEntry targetEntry;

        private JCacheTransaction(MutableEntry targetEntry, byte[] requestBustes) {
            super(requestBustes);
            this.targetEntry = targetEntry;
        }

        @Override
        public boolean exists() {
            return targetEntry.exists();
        }

        @Override
        protected byte[] getRawState() {
            return targetEntry.getValue();
        }

        @Override
        protected void setRawState(byte[] stateBytes) {
            targetEntry.setValue(stateBytes);
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy