View Javadoc

1   /**
2    * Copyright 2005-2012 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.ksb.messaging.servlet;
17  
18  import org.apache.cxf.Bus;
19  import org.apache.cxf.interceptor.Interceptor;
20  import org.apache.cxf.message.Message;
21  import org.apache.cxf.transport.servlet.ServletController;
22  import org.apache.cxf.transport.servlet.ServletTransportFactory;
23  import org.apache.log4j.Logger;
24  import org.kuali.rice.core.api.config.property.ConfigContext;
25  import org.kuali.rice.core.api.exception.RiceRuntimeException;
26  import org.kuali.rice.core.api.util.ClassLoaderUtils;
27  import org.kuali.rice.ksb.api.KsbApiServiceLocator;
28  import org.kuali.rice.ksb.api.bus.Endpoint;
29  import org.kuali.rice.ksb.api.bus.ServiceConfiguration;
30  import org.kuali.rice.ksb.api.bus.support.SoapServiceConfiguration;
31  import org.kuali.rice.ksb.security.SignatureSigningResponseWrapper;
32  import org.kuali.rice.ksb.security.SignatureVerifyingRequestWrapper;
33  import org.kuali.rice.ksb.service.KSBServiceLocator;
34  import org.springframework.beans.BeansException;
35  import org.springframework.context.i18n.LocaleContext;
36  import org.springframework.web.HttpRequestHandler;
37  import org.springframework.web.servlet.DispatcherServlet;
38  import org.springframework.web.servlet.HandlerAdapter;
39  import org.springframework.web.servlet.HandlerExecutionChain;
40  import org.springframework.web.servlet.ModelAndView;
41  import org.springframework.web.servlet.mvc.Controller;
42  import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter;
43  import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
44  
45  import javax.servlet.ServletException;
46  import javax.servlet.http.HttpServletRequest;
47  import javax.servlet.http.HttpServletResponse;
48  import javax.xml.namespace.QName;
49  import java.io.IOException;
50  import java.util.List;
51  import java.util.Locale;
52  
53  
54  /**
55   * A {@link DispatcherServlet} which dispatches incoming requests to the appropriate
56   * service endpoint.
57   *
58   * @author Kuali Rice Team (rice.collab@kuali.org)
59   */
60  public class KSBDispatcherServlet extends DispatcherServlet {
61  
62  	private static final Logger LOG = Logger.getLogger(KSBDispatcherServlet.class);
63  
64  	private static final long serialVersionUID = 6790121225857950019L;
65  	private KSBHttpInvokerHandler httpInvokerHandler;
66  	private ServletController cxfServletController;
67  	
68  	protected void initFrameworkServlet() throws ServletException, BeansException {
69  		this.httpInvokerHandler = new KSBHttpInvokerHandler();
70  		
71          Bus bus = KSBServiceLocator.getCXFBus();
72  
73          List<Interceptor<? extends Message>> inInterceptors = KSBServiceLocator.getInInterceptors();
74          if(inInterceptors != null) {
75          	List<Interceptor<? extends Message>> busInInterceptors = bus.getInInterceptors();
76          	busInInterceptors.addAll(inInterceptors);
77          }
78         
79          List<Interceptor<? extends Message>> outInterceptors = KSBServiceLocator.getOutInterceptors();
80          if(outInterceptors != null) {
81          	List<Interceptor<? extends Message>> busOutInterceptors = bus.getOutInterceptors();
82          	busOutInterceptors.addAll(outInterceptors);
83          }
84          
85  		ServletTransportFactory servletTransportFactory = KSBServiceLocator.getCXFServletTransportFactory();
86  				
87  		this.cxfServletController = new ServletController(servletTransportFactory, this.getServletConfig(), this.getServletContext(), bus);
88  		
89  		if (!ConfigContext.getCurrentContextConfig().getDevMode()) {
90  		    // disable handling of URLs ending in /services which display CXF generated service lists
91  		    this.cxfServletController.setHideServiceList(true);
92  		}
93  		
94  		this.setPublishEvents(false);
95  	}
96  
97  	protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
98  		if (handler instanceof HttpRequestHandler) {
99  			return new HttpRequestHandlerAdapter();
100 		} else if (handler instanceof Controller) {
101 			Object unwrappedHandler = ClassLoaderUtils.unwrapFromProxy(handler);
102 			if (unwrappedHandler instanceof CXFServletControllerAdapter) {
103 				// TODO this just seems weird as this controller is initially null when it's created, does there need to be some synchronization here?
104 				((CXFServletControllerAdapter)unwrappedHandler).setController(cxfServletController);
105 			}			
106 			return new SimpleControllerHandlerAdapter();
107 		}
108 		throw new RiceRuntimeException("handler of type " + handler.getClass().getName() + " is not known and can't be used by " + KSBDispatcherServlet.class.getName());
109 	}
110 
111 	/**
112 	 * Return the HandlerExecutionChain for this request.
113 	 * Try all handler mappings in order.
114 	 * @param request current HTTP request
115 	 * @param cache whether to cache the HandlerExecutionChain in a request attribute
116 	 * @return the HandlerExceutionChain, or <code>null</code> if no handler could be found
117 	 */
118 	protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception {
119 		return this.httpInvokerHandler.getHandler(request);
120 	}
121 
122 	@Override
123 	protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
124 		try {
125 			QName serviceName = this.httpInvokerHandler.getServiceNameFromRequest(request);
126 			LOG.info("Caught Exception from service " + serviceName, ex);
127 		} catch (Throwable throwable) {
128 			LOG.warn("Caught exception attempting to log exception thrown from remotely accessed service", throwable);
129 		}
130 		return null;
131 	}
132 
133 	/**
134 	 * Overrides the service method to replace the request and responses with one which will provide input and output streams for
135 	 * verifying and signing the data.
136 	 */
137 	@Override
138 	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
139 		if (isSecure(request)) {
140 			super.service(new SignatureVerifyingRequestWrapper(request), new SignatureSigningResponseWrapper(response));
141 		} else {
142 			super.service(request, response);
143 		}
144 	}
145 
146 	protected boolean isSecure(HttpServletRequest request) {
147 		QName serviceName = this.httpInvokerHandler.getServiceNameFromRequest(request);
148 		if (LOG.isDebugEnabled()) {
149 		    LOG.debug("Checking service " + serviceName + " for security enabled");
150 		}
151 		Endpoint endpoint = KsbApiServiceLocator.getServiceBus().getEndpoint(serviceName);
152 		if (endpoint == null) {
153 			LOG.error("Attempting to acquire non-existent service " + request.getRequestURI());
154 		    throw new RiceRuntimeException("Attempting to acquire non-existent service.");
155 		}
156 		ServiceConfiguration serviceConfiguration = endpoint.getServiceConfiguration();
157 		if (serviceConfiguration instanceof SoapServiceConfiguration) {
158 		    return false;
159 		}
160 		return serviceConfiguration.getBusSecurity();
161 	}
162 	
163 	/**
164 	 * Overriding this method to correct a NullPointerException when the
165 	 * getLocale() method is called on the LocaleContext returned here.  This
166 	 * tries to use the LocaleContext from the parent class, but if a NPE is
167 	 * thrown when getLocale() is invoked on the context it will return a new
168 	 * LocaleContext which defaults to English.
169 	 */
170 	@Override
171     protected LocaleContext buildLocaleContext(HttpServletRequest request) {
172         try {
173             // Get the context from the parent class
174             LocaleContext localeContext = super.buildLocaleContext(request);
175             // Check to see if the localeResolver is null
176             localeContext.getLocale();
177             return localeContext;
178         } catch (NullPointerException npe) {
179             // If a NPE is thrown catch it and return a LocaleContext which
180             // always returns English
181             return new LocaleContext() {
182                 public Locale getLocale() {
183                     return Locale.ENGLISH;
184                 }
185             };
186         }
187     }
188 }