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

io.mongock.driver.api.lock.guard.proxy.LockGuardProxy Maven / Gradle / Ivy

package io.mongock.driver.api.lock.guard.proxy;

import io.changock.migration.api.annotations.NonLockGuarded;
import io.changock.migration.api.annotations.NonLockGuardedType;
import io.mongock.driver.api.lock.LockManager;
import sun.reflect.generics.reflectiveObjects.TypeVariableImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

//TODO add tests
public class LockGuardProxy implements InvocationHandler {

  private final LockManager lockManager;
  private final T implementation;
  private final LockGuardProxyFactory proxyFactory;

  public LockGuardProxy(T implementation, LockManager lockManager, LockGuardProxyFactory proxyFactory) {
    this.implementation = implementation;
    this.lockManager = lockManager;
    this.proxyFactory = proxyFactory;
  }

  private static boolean shouldTryProxyReturn(List methodNoGuardedLockTypes, Type type) {
    return
        !(type instanceof TypeVariableImpl && ((TypeVariableImpl) type).getGenericDeclaration() != null )
        && !methodNoGuardedLockTypes.contains(NonLockGuardedType.RETURN)
        && !methodNoGuardedLockTypes.contains(NonLockGuardedType.NONE);
  }

  private static boolean shouldMethodBeLockGuarded(List noGuardedLockTypes) {
    return !noGuardedLockTypes.contains(NonLockGuardedType.METHOD) && !noGuardedLockTypes.contains(NonLockGuardedType.NONE);
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    NonLockGuarded nonLockGuarded = method.getAnnotation(NonLockGuarded.class);
    List noGuardedLockTypes = nonLockGuarded != null ? Arrays.asList(nonLockGuarded.value()) : Collections.emptyList();
    if (shouldMethodBeLockGuarded(noGuardedLockTypes)) {
      lockManager.ensureLockDefault();
    }

    return shouldTryProxyReturn(noGuardedLockTypes, method.getGenericReturnType())
        ? proxyFactory.getRawProxy(method.invoke(implementation, args), method.getReturnType())
        : method.invoke(implementation, args);
  }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy