TransactionHelper.java

/*
 * Copyright 2019 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.genesys.spring;

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

import org.genesys.blocks.util.CurrentApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * The TransactionHelper.
 * 
 * @author Matija Obreza
 */
public class TransactionHelper {
	public static final Logger LOG = LoggerFactory.getLogger(TransactionHelper.class);

	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.trace("Executing as {}", prevAuth.getName());
			return asUser(prevAuth, callable);
		} finally {
			SecurityContextHolder.getContext().setAuthentication(prevAuth);
		}
	}

	/**
	 * Update as current user.
	 * 
	 * Shorthand for asCurrentUser(() -> executeInTransaction(false, () -> ...
	 *
	 * @param <T> the generic type
	 * @param callable the callable
	 * @return the t
	 * @throws Exception the exception
	 */
	public static <T> T updateAsCurrentUser(Callable<T> callable) throws Exception {
		return asCurrentUser(() -> executeInTransaction(false, callable));
	}

	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).execute(new TransactionCallback<T>() {
			@Override
			public T doInTransaction(TransactionStatus status) {
				throwableHolder.throwable = null;
				try {
					return callable.call();
				} catch (Throwable e) {
					LOG.error("Transaction failed with {}", 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) {
		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.setReadOnly(readonly);
		transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
		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;
	}

}