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

com.palantir.common.proxy.ReplaceIfExceptionMatchingProxy Maven / Gradle / Ivy

There is a newer version: 0.1152.0
Show newest version
/*
 * (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
 *
 * 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 com.palantir.common.proxy;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import com.google.common.reflect.AbstractInvocationHandler;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.function.Supplier;

@SuppressWarnings("ProxyNonConstantType")
public final class ReplaceIfExceptionMatchingProxy extends AbstractInvocationHandler {
    private static final SafeLogger log = SafeLoggerFactory.get(ReplaceIfExceptionMatchingProxy.class);

    private final Supplier delegateFactory;
    private final Predicate shouldReplace;
    private volatile T delegate;

    private ReplaceIfExceptionMatchingProxy(Supplier delegateFactory, Predicate shouldReplace) {
        this.delegateFactory = delegateFactory;
        this.shouldReplace = shouldReplace;
    }

    @Override
    protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(getAndPossiblyInitializeDelegate(), args);
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            replaceIfNecessary(cause);
            throw cause;
        }
    }

    private T getAndPossiblyInitializeDelegate() {
        T perceivedDelegate = delegate;
        if (perceivedDelegate == null) {
            synchronized (this) {
                perceivedDelegate = delegate;
                if (perceivedDelegate == null) {
                    perceivedDelegate = delegate = delegateFactory.get();
                }
            }
        }
        return perceivedDelegate;
    }

    private void replaceIfNecessary(Throwable thrown) {
        if (shouldReplace.test(thrown)) {
            synchronized (this) {
                T replacement = delegateFactory.get();
                if (delegate != replacement) {
                    log.info("Replacing underlying proxy due to thrown exception", thrown);
                    delegate = replacement;
                }
            }
        }
    }

    public static  T create(
            Class interfaceClass,
            Supplier delegate,
            Duration minCreationInterval,
            Predicate shouldReplace) {
        return newProxyInstance(
                interfaceClass,
                Suppliers.memoizeWithExpiration(delegate::get, minCreationInterval.toMillis(), TimeUnit.MILLISECONDS),
                shouldReplace);
    }

    @SuppressWarnings("unchecked")
    @VisibleForTesting
    static  T newProxyInstance(Class interfaceClass, Supplier delegate, Predicate shouldReplace) {
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class[] {interfaceClass},
                new ReplaceIfExceptionMatchingProxy<>(delegate, shouldReplace));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy