001    // Copyright 2008, 2009 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry5.internal.spring;
016    
017    import org.apache.tapestry5.ioc.internal.util.InternalUtils;
018    import org.apache.tapestry5.spring.ApplicationContextCustomizer;
019    import org.apache.tapestry5.spring.TapestryApplicationContext;
020    import org.springframework.context.ApplicationContextException;
021    import org.springframework.web.context.ConfigurableWebApplicationContext;
022    import org.springframework.web.context.ContextLoader;
023    
024    import javax.servlet.ServletContext;
025    
026    public class CustomizingContextLoader extends ContextLoader
027    {
028        private final ApplicationContextCustomizer customizer;
029    
030        public CustomizingContextLoader(ApplicationContextCustomizer customizer)
031        {
032            this.customizer = customizer;
033        }
034    
035        @Override
036        protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext)
037        {
038            customizer.customizeApplicationContext(servletContext, applicationContext);
039        }
040    
041        @Override
042        protected Class determineContextClass(ServletContext servletContext) throws ApplicationContextException
043        {
044            String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
045    
046            if (InternalUtils.isNonBlank(contextClassName))
047            {
048                Class result = super.determineContextClass(servletContext);
049    
050                if (!TapestryApplicationContext.class.isAssignableFrom(result))
051                    throw new IllegalArgumentException(String.format(
052                            "When using the Tapestry/Spring integration library, you must specifiy a context class that extends from %s. Class %s does not. Update the '%s' servlet context init parameter.",
053                            TapestryApplicationContext.class.getName(),
054                            result.getName(),
055                            CONTEXT_CLASS_PARAM));
056    
057                return result;
058            }
059    
060            return TapestryApplicationContext.class;
061        }
062    }