TransactionHelper.java

/*
 * Copyright 2020 Global Crop Diversity Trust
 *
 * 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 org.gringlobal.spring;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.extern.slf4j.Slf4j;
import org.genesys.blocks.util.CurrentApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * The TransactionHelper.
 */
@Slf4j
public class TransactionHelper {

	public static <T> T asUser(Authentication authentication, Callable<T> callable) throws Exception {
		Authentication prevAuth = SecurityContextHolder.getContext().getAuthentication();
		SecurityContextHolder.getContext().setAuthentication(authentication);
		try {
			return callable.call();
		} finally {
			SecurityContextHolder.getContext().setAuthentication(prevAuth);
		}
	}

	public static <T> T asCurrentUser(Callable<T> callable) throws Exception {
		Authentication prevAuth = SecurityContextHolder.getContext().getAuthentication();
		try {
			log.warn("Executing as {}", prevAuth);
			return asUser(prevAuth, callable);
		} finally {
			SecurityContextHolder.getContext().setAuthentication(prevAuth);
		}
	}

	public static <T> T executeInCurrentTransaction(boolean readonly, Callable<T> callable) {
		final ThrowableHolder throwableHolder = new ThrowableHolder();
		AtomicInteger retries = new AtomicInteger(0);
		// do {
		if (retries.get() > 0) {
			log.warn("Transaction retry #{}", retries.get());
		}
		T result = transactionTemplate(readonly, TransactionDefinition.PROPAGATION_REQUIRED, "TransactionHelper-REQUIRED").execute((TransactionStatus status) -> {
			throwableHolder.throwable = null;
			try {
				return callable.call();
			} catch (Throwable e) {
				log.debug("Transaction failed with error: {}", e.getMessage(), e);
				throwableHolder.throwable = e;
				status.setRollbackOnly();
				return null;
			}
		});
		if (throwableHolder.throwable == null) {
			return result;
		}
		// } while (throwableHolder.throwable != null && retries.incrementAndGet() < 3);

		throw new RuntimeException("Could not execute transaction", throwableHolder.throwable);
	}

	public static <T> T executeInTransaction(boolean readonly, Callable<T> callable) {
		final ThrowableHolder throwableHolder = new ThrowableHolder();
		AtomicInteger retries = new AtomicInteger(0);
		// do {
		if (retries.get() > 0) {
			log.warn("Transaction retry #{}", retries.get());
		}
		T result = transactionTemplate(readonly, TransactionDefinition.PROPAGATION_REQUIRES_NEW, "TransactionHelper-REQUIRES-NEW").execute((TransactionStatus status) -> {
			throwableHolder.throwable = null;
			try {
				return callable.call();
			} catch (Throwable e) {
				log.debug("Transaction failed with error: {}", e.getMessage());
				throwableHolder.throwable = e;
				status.setRollbackOnly();
				return null;
			}
		});
		if (throwableHolder.throwable == null) {
			return result;
		}
		// } while (throwableHolder.throwable != null && retries.incrementAndGet() < 3);

		throw new RuntimeException("Could not execute transaction", throwableHolder.throwable);
	}

	private static TransactionTemplate transactionTemplate(boolean readonly, int propagationBehavior, String transactionName) {
		if (CurrentApplicationContext.getContext() == null) {
			throw new RuntimeException("CurrentApplicationContext is not available.");
		}
		PlatformTransactionManager transactionManager = CurrentApplicationContext.getContext().getBean(PlatformTransactionManager.class);
		if (transactionManager == null) {
			throw new RuntimeException("PlatformTransactionManager is not available");
		}
		TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
		transactionTemplate.setName(transactionName);
		transactionTemplate.setReadOnly(readonly);
		transactionTemplate.setPropagationBehavior(propagationBehavior);
		transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
		return transactionTemplate;
	}

	/**
	 * Internal holder class for a Throwable in a callback transaction model.
	 */
	private static class ThrowableHolder {
		public Throwable throwable;
	}

}