DelegatingEndpointInterceptorProxy.java

/*
 * Copyright 2022 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 javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.context.ServletContextAware;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.EndpointInterceptor;

/**
 * In unit testing all hell breaks loose because of {@code @EnableWs}.
 * <p>This {@code DelegatingEndpointInterceptorProxy} is modeled on {@code DelegatingFilterProxy}.
 *
 * @author Matija Obreza
 */
public class DelegatingEndpointInterceptorProxy implements EndpointInterceptor, ServletContextAware {

	@Nullable
	private ApplicationContext applicationContext;

	@Nullable
	private String targetBeanName;

	@Nullable
	private ServletContext servletContext;

	@Nullable
	private volatile EndpointInterceptor delegate;

	private final Object delegateMonitor = new Object();

	/**
	 * Create a new {@code DelegatingEndpointInterceptorProxy} with the given {@link EndpointInterceptor} delegate.
	 * Bypasses entirely the need for interacting with a Spring application context,
	 * specifying the {@linkplain #setTargetBeanName target bean name}, etc.
	 * <p>For use with instance-based registration of interceptors.
	 * @param delegate the {@code EndpointInterceptor} instance that this proxy will delegate to (must not be {@code null}).
	 */
	public DelegatingEndpointInterceptorProxy(EndpointInterceptor delegate) {
		Assert.notNull(delegate, "Delegate EndpointInterceptor must not be null");
		this.delegate = delegate;
	}

	/**
	 * Create a new {@code DelegatingEndpointInterceptorProxy} that will retrieve the named target
	 * bean from the Spring {@code ApplicationContext}.
	 * <p>For use with instance-based registration of interceptors.
	 * <p>The target bean must implement the standard EndpointInterceptor interface.
	 * @param targetBeanName name of the target interceptor bean to look up in the Spring
	 * application context (must not be {@code null}).
	 */
	public DelegatingEndpointInterceptorProxy(String targetBeanName) {
		this(targetBeanName, null);
	}

	/**
	 * Create a new {@code DelegatingEndpointInterceptorProxy} that will retrieve the named target
	 * bean from the given Spring {@code WebApplicationContext}.
	 * <p>For use with instance-based registration of filters.
	 * <p>The target bean must implement the standard Servlet EndpointInterceptor interface.
	 * <p>The given {@code WebApplicationContext} may or may not be refreshed when passed
	 * in. If it has not, and if the context implements {@link ConfigurableApplicationContext},
	 * a {@link ConfigurableApplicationContext#refresh() refresh()} will be attempted before
	 * retrieving the named target bean.
	 * <p>This proxy's {@code Environment} will be inherited from the given
	 * {@code WebApplicationContext}.
	 * @param targetBeanName name of the target filter bean in the Spring application
	 * context (must not be {@code null}).
	 * @param context the application context from which the target filter will be retrieved;
	 * if {@code null}, an application context will be looked up from {@code ServletContext}
	 * as a fallback.
	 * @see #findApplicationContext()
	 * @see #setEnvironment(org.springframework.core.env.Environment)
	 */
	public DelegatingEndpointInterceptorProxy(String targetBeanName, @Nullable ApplicationContext context) {
		Assert.hasText(targetBeanName, "Target EndpointInterceptor bean name must not be null or empty");
		this.setTargetBeanName(targetBeanName);
		this.applicationContext = context;
	}

	/**
	 * Set the name of the target bean in the Spring application context.
	 * The target bean must implement the standard Servlet EndpointInterceptor interface.
	 * <p>By default, the {@code filter-name} as specified for the
	 * DelegatingEndpointInterceptorProxy in {@code web.xml} will be used.
	 */
	public void setTargetBeanName(@Nullable String targetBeanName) {
		this.targetBeanName = targetBeanName;
	}

	/**
	 * Return the name of the target bean in the Spring application context.
	 */
	@Nullable
	protected String getTargetBeanName() {
		return this.targetBeanName;
	}

	// Lazily initialize the delegate if necessary.
	private EndpointInterceptor getDelegateToUse() throws ServletException {
		EndpointInterceptor delegateToUse = this.delegate;
		if (delegateToUse == null) {
			synchronized (this.delegateMonitor) {
				delegateToUse = this.delegate;
				if (delegateToUse == null) {
					ApplicationContext context = findApplicationContext();
					if (context == null) {
						throw new IllegalStateException("No ApplicationContext found");
					}
					delegateToUse = initDelegate(context);
				}
				this.delegate = delegateToUse;
			}
		}
		return delegateToUse;
	}

	@Override
	public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
		EndpointInterceptor delegateToUse = this.delegate;
		if (delegateToUse == null) {
			delegateToUse = getDelegateToUse();
		}
		return delegateToUse.handleRequest(messageContext, endpoint);
	}

	@Override
	public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
		EndpointInterceptor delegateToUse = this.delegate;
		if (delegateToUse == null) {
			delegateToUse = getDelegateToUse();
		}
		return delegateToUse.handleResponse(messageContext, endpoint);
	}

	@Override
	public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
		EndpointInterceptor delegateToUse = this.delegate;
		if (delegateToUse == null) {
			delegateToUse = getDelegateToUse();
		}
		return delegateToUse.handleFault(messageContext, endpoint);
	}

	@Override
	public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
		EndpointInterceptor delegateToUse = this.delegate;
		if (delegateToUse == null) {
			delegateToUse = getDelegateToUse();
		}
		delegateToUse.afterCompletion(messageContext, endpoint, ex);
	}


	/**
	 * Return the {@code ApplicationContext} passed in at construction time, if available.
	 * Otherwise, attempt to retrieve a {@code WebApplicationContext} from the
	 * {@code ServletContext} attribute with the {@linkplain #setContextAttribute
	 * configured name} if set. Otherwise look up a {@code WebApplicationContext} under
	 * the well-known "root" application context attribute. The
	 * {@code WebApplicationContext} must have already been loaded and stored in the
	 * {@code ServletContext} before this filter gets initialized (or invoked).
	 * <p>Subclasses may override this method to provide a different
	 * {@code WebApplicationContext} retrieval strategy.
	 * @return the {@code WebApplicationContext} for this proxy, or {@code null} if not found
	 * @see #DelegatingEndpointInterceptorProxy(String, ApplicationContext)
	 */
	@Nullable
	protected ApplicationContext findApplicationContext() {
		assert(this.applicationContext != null);

		// The user has injected a context at construction time -> use it...
		if (this.applicationContext instanceof ConfigurableApplicationContext) {
			ConfigurableApplicationContext cac = (ConfigurableApplicationContext) this.applicationContext;
			if (!cac.isActive()) {
				// The context has not yet been refreshed -> do so before returning it...
				cac.refresh();
			}
		}
		return this.applicationContext;
	}

	/**
	 * Initialize the EndpointInterceptor delegate, defined as bean the given Spring
	 * application context.
	 * <p>The default implementation fetches the bean from the application context
	 * @param context the root application context
	 * @return the initialized delegate EndpointInterceptor
	 * @see #getTargetBeanName()
	 */
	protected EndpointInterceptor initDelegate(ApplicationContext context) {
		String targetBeanName = getTargetBeanName();
		Assert.state(targetBeanName != null, "No target bean name set");
		EndpointInterceptor delegate = context.getBean(targetBeanName, EndpointInterceptor.class);
		return delegate;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}