View Javadoc

1   /**
2    * Copyright 2010 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   */
15  
16  package org.kuali.student.common.test.spring;
17  
18  import java.lang.reflect.Field;
19  import java.util.EventListener;
20  import java.util.HashMap;
21  import java.util.Map;
22  
23  import javax.jws.WebService;
24  import javax.servlet.Servlet;
25  import javax.xml.namespace.QName;
26  
27  import org.junit.internal.runners.InitializationError;
28  import org.junit.internal.runners.JUnit4ClassRunner;
29  import org.junit.runner.notification.RunNotifier;
30  import org.kuali.student.common.ws.beans.JaxWsClientFactory;
31  import org.mortbay.jetty.Server;
32  import org.mortbay.jetty.servlet.Context;
33  import org.mortbay.jetty.servlet.ServletHandler;
34  import org.mortbay.jetty.servlet.ServletHolder;
35  import org.mortbay.jetty.servlet.ServletMapping;
36  import org.springframework.web.context.ContextLoaderListener;
37  
38  @Deprecated
39  public class ServiceTestClassRunner extends JUnit4ClassRunner {
40  	private final Class<?> testImplClass;
41  	private Server server;
42  
43  	public ServiceTestClassRunner(Class<?> klass) throws InitializationError {
44  		super(klass);
45  		testImplClass = klass;
46  
47  	}
48  
49  	/**
50  	 * Creates a client and injects it into the test class based on the
51  	 * &#064;Client annotations
52  	 */
53  	/*
54  	 * (non-Javadoc)
55  	 * 
56  	 * @see org.junit.internal.runners.JUnit4ClassRunner#createTest()
57  	 */
58  	@Override
59  	protected Object createTest() throws Exception {
60  		Object instance = super.createTest();
61  		try {
62  			for (Field f : instance.getClass().getDeclaredFields()) {
63  				if (f.isAnnotationPresent(Client.class)) {
64  					Client a = f.getAnnotation(Client.class);
65  					String port = System.getProperty("ks.test.port");
66  					
67  					Class<?> serviceImplClass = Class.forName(a.value());
68  					String serviceName = "";
69  					String serviceNamespaceURI = "";
70  					String serviceWsdlLocation = "http://localhost:" + port
71  							+ "/Service/Service" + (a.secure() ? "Secure" : "")
72  							+ "?wsdl";
73  					String serviceAddress = "http://localhost:" + port
74  							+ "/Service/Service" + (a.secure() ? "Secure" : "");
75  
76  					if (serviceImplClass.isAnnotationPresent(WebService.class)) {
77  						WebService wsAnnotation = serviceImplClass
78  								.getAnnotation(WebService.class);
79  						serviceName = wsAnnotation.serviceName();
80  						serviceNamespaceURI = wsAnnotation.targetNamespace();
81  					}
82  
83  					Class<?> clientImplClass = Class
84  							.forName("org.kuali.student.common.ws.beans.JaxWsClientFactoryBean");
85  
86  					if (a.secure()) {
87  						try {
88  							clientImplClass = Class
89  									.forName("org.kuali.student.common.cxf.security.SecureJaxWsProxyFactoryBean");
90  						} catch (ClassNotFoundException cnfe) {
91  						}
92  					}
93  
94  					JaxWsClientFactory clientFactory = (JaxWsClientFactory) clientImplClass
95  							.newInstance();
96  
97  					clientFactory.setServiceEndpointInterface(f.getType());
98  					clientFactory.setServiceName(new QName(serviceNamespaceURI,
99  							serviceName));
100 					clientFactory.setWsdlLocation(serviceWsdlLocation);
101 					clientFactory.setAddress(serviceAddress);
102 
103 					f.setAccessible(true);
104 					f.set(instance, clientFactory.getObject());
105 				}
106 			}
107 		} catch (Exception e) {
108 			throw new RuntimeException(e);
109 		}
110 		return instance;
111 	}
112 
113 	/**
114 	 * Start a server based on the service Impl &#064;WebService annotaions and
115 	 * the test class &#064;
116 	 */
117 	private void startServer() {
118 		try {
119 			// Set the default Port
120 			if (System.getProperty("ks.test.default.port")==null||System.getProperty("ks.test.default.port").isEmpty()){
121 				System.setProperty("ks.test.port", "9191");
122 			} else {
123 				System.setProperty("ks.test.port", System.getProperty("ks.test.default.port"));
124 			}
125 
126 			// Grab the client annotation and set the service implementation and
127 			// port as system properties
128 			for (Field f : testImplClass.getDeclaredFields()) {
129 				if (f.isAnnotationPresent(Client.class)) {
130 					Client a = f.getAnnotation(Client.class);
131 					if (a.secure()) {
132 						System.setProperty("ks.test.serviceImplSecure", a
133 								.value());
134 					} else {
135 						System.setProperty("ks.test.serviceImplClass", a
136 								.value());
137 					}
138 					if(a.port()!=null&&!a.port().isEmpty()){
139 						System.setProperty("ks.test.port", a.port());
140 					}
141 					if(!"".equals(a.additionalContextFile())){
142 						System.setProperty("ks.test.additionalContextFile", a.additionalContextFile());
143 					}else{
144 						System.setProperty("ks.test.additionalContextFile", "classpath:*noSuchContextFile.xml");
145 					}
146 				}
147 			}
148 
149 			// If no secure client defined, set secure service endpoint impl
150 			// to be same as non-secure endpoint impl
151 			if (System.getProperty("ks.test.serviceImplSecure") == null) {
152 				System.setProperty("ks.test.serviceImplSecure", System
153 						.getProperty("ks.test.serviceImplClass"));
154 			}
155 
156 			// Grab the persistence context loacation or set a default value
157 			if (testImplClass
158 					.isAnnotationPresent(PersistenceFileLocation.class)) {
159 				PersistenceFileLocation a = testImplClass
160 						.getAnnotation(PersistenceFileLocation.class);
161 				System.setProperty("ks.test.persistenceLocation", a.value());
162 			} else {
163 				System.setProperty("ks.test.persistenceLocation",
164 						"classpath:META-INF/persistence.xml");
165 			}
166 
167 			// Grab the Dao information and pass it to a System variable
168 			Daos daos = testImplClass.getAnnotation(Daos.class);
169 
170 			StringBuilder daoImpls = new StringBuilder("");
171             boolean foundDAOs = false;
172 			if (daos != null) {
173 				int i = 1;
174 				for (Dao dao : daos.value()) {
175                     foundDAOs = true;
176 					daoImpls.append(dao.value()).append("|").append(dao.testDataFile()).append("|").append(dao.testSqlFile());
177 					if (i < daos.value().length) {
178                         daoImpls.append(",");
179 					}
180 					i++;
181 				}
182 			}
183             System.setProperty("ks.test.daoImplClasses", daoImpls.toString());
184 			
185 			server = new Server(Integer.valueOf(System
186 					.getProperty("ks.test.port")));
187 
188 			Context context = new Context();
189 			ServletHandler servletHandler = new ServletHandler();
190 			ServletHolder servletHolder = new ServletHolder();
191 			ServletMapping servletMapping = new ServletMapping();
192 			ContextLoaderListener contextLoaderListener = new ContextLoaderListener();
193 
194 			
195             Class<?> servletClass;
196 			String wsEngine;
197 			try{
198 			    servletClass = Class.forName("org.apache.cxf.transport.servlet.CXFServlet");		    
199 			    wsEngine = "cxf";
200 			} catch (ClassNotFoundException e) {
201 	            servletClass = Class.forName("com.sun.xml.ws.transport.http.servlet.WSSpringServlet");
202 				wsEngine = "jaxws";
203 			}
204 
205 			Servlet servlet = (Servlet) servletClass.newInstance();
206 
207 			servletHolder.setName("Service");
208 			servletHolder.setServlet(servlet);
209 			servletHandler.setServlets(new ServletHolder[] { servletHolder });
210 
211 			servletMapping.setPathSpec("/*");
212 			servletMapping.setServletName("Service");
213 			servletHandler
214 					.setServletMappings(new ServletMapping[] { servletMapping });
215 
216 			context.setContextPath("/Service");
217 			context.setResourceBase("src/test/resources");
218 
219 			Map<String, String> initParams = new HashMap<String, String>();
220 			
221 			//Set the context config location
222 			String contextConfigLocation = "classpath:META-INF/" + wsEngine + "-context.xml";
223 			if(foundDAOs){
224 				//If there are Daos defined, add the dao context file
225 				contextConfigLocation +="\nclasspath:META-INF/default-dao-context-test.xml";
226 			}
227 			
228 			initParams.put("contextConfigLocation", contextConfigLocation);
229 			initParams.put("log4jConfigLocation", "log4j.properties");
230 			context.setInitParams(initParams);
231 			context
232 					.setEventListeners(new EventListener[] { contextLoaderListener });
233 			context.setServletHandler(servletHandler);
234 
235 			server.setHandler(context);
236 
237 			server.start();
238 		} catch (Exception e) {
239 			throw new RuntimeException(e);
240 		}
241 
242 	}
243 
244 	/*
245 	 * (non-Javadoc)
246 	 * 
247 	 * @see org.junit.internal.runners.JUnit4ClassRunner#run(org.junit.runner.notification.RunNotifier)
248 	 */
249 	@Override
250 	public void run(RunNotifier notifier) {
251 		startServer();
252 		super.run(notifier);
253 		stopServer();
254 	}
255 
256 	private void stopServer() {
257 		try {
258 			server.stop();
259 		} catch (Exception e) {
260 			throw new RuntimeException(e);
261 		}
262 	}
263 
264 }