001/*-
002 * #%L
003 * HAPI FHIR - Core Library
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.util;
021
022import org.apache.commons.lang3.Validate;
023
024import java.lang.reflect.InvocationHandler;
025import java.lang.reflect.Method;
026import java.lang.reflect.Proxy;
027
028public class ProxyUtil {
029        private ProxyUtil() {}
030
031        /**
032         * Wrap theInstance in a Proxy that synchronizes every method.
033         *
034         * @param theClass the target interface
035         * @param theInstance the instance to wrap
036         * @return a Proxy implementing theClass interface that syncronizes every call on theInstance
037         * @param <T> the interface type
038         */
039        public static <T> T synchronizedProxy(Class<T> theClass, T theInstance) {
040                Validate.isTrue(theClass.isInterface(), "%s is not an interface", theClass);
041                InvocationHandler handler = new SynchronizedHandler(theInstance);
042                Object object = Proxy.newProxyInstance(theClass.getClassLoader(), new Class<?>[] {theClass}, handler);
043                return theClass.cast(object);
044        }
045
046        /**
047         * Simple handler that first synchronizes on the delegate
048         */
049        static class SynchronizedHandler implements InvocationHandler {
050                private final Object theDelegate;
051
052                SynchronizedHandler(Object theDelegate) {
053                        this.theDelegate = theDelegate;
054                }
055
056                @Override
057                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
058                        synchronized (theDelegate) {
059                                return method.invoke(theDelegate, args);
060                        }
061                }
062        }
063}