533f08f3fc6691d5e682c97f37a2fbc80900f9c6
[taxeditor.git] / eu.etaxonomy.taxeditor.test / src / test / java / eu / etaxonomy / taxeditor / httpinvoker / BaseRemotingTest.java
1 /**
2 * Copyright (C) 2014 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9 package eu.etaxonomy.taxeditor.httpinvoker;
10
11 import java.io.File;
12 import java.io.InputStream;
13 import java.lang.reflect.Field;
14 import java.net.URL;
15 import java.util.Map;
16 import java.util.Properties;
17
18 import net.sf.ehcache.CacheManager;
19
20 import org.apache.log4j.Logger;
21 import org.eclipse.core.runtime.FileLocator;
22 import org.eclipse.core.runtime.Platform;
23 import org.junit.AfterClass;
24 import org.junit.Assert;
25 import org.junit.BeforeClass;
26 import org.osgi.framework.Bundle;
27 import org.springframework.core.io.ClassPathResource;
28 import org.springframework.core.io.Resource;
29 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
30 import org.springframework.security.core.Authentication;
31 import org.springframework.security.core.context.SecurityContextHolder;
32 import org.springframework.security.core.context.SecurityContextImpl;
33 import org.unitils.UnitilsJUnit4;
34 import org.unitils.database.DatabaseUnitils;
35 import org.unitils.database.annotations.Transactional;
36 import org.unitils.database.util.TransactionMode;
37 import org.unitils.spring.annotation.SpringApplicationContext;
38
39 import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteController;
40 import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
41 import eu.etaxonomy.taxeditor.remoting.cache.CdmRemoteCacheManager;
42 import eu.etaxonomy.taxeditor.remoting.cache.CdmTransientEntityCacher;
43 import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
44 import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
45 import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
46 import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
47 import eu.etaxonomy.taxeditor.session.CdmEntitySession;
48 import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
49 import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
50
51
52 /**
53 * Base class for remoting tests, responsible for
54 * - starting / stop the cdm server
55 * - running some basic connection tests
56 * - setting up the remote configuration.
57 *
58 */
59 @Transactional(TransactionMode.DISABLED)
60 @SpringApplicationContext("file:./target/classes/eu/etaxonomy/cdm/testRemotingApplicationContext.xml")
61 public class BaseRemotingTest extends UnitilsJUnit4 {
62 private static final Logger logger = Logger.getLogger(BaseRemotingTest.class);
63
64
65 public static final Resource SERVER_PROPERTIES_FILE =
66 new ClassPathResource("server.properties");
67
68 public static final Resource EDITOR_DATASOURCES_FILE =
69 new ClassPathResource(".cdmLibrary/writableResources/cdm.datasources.xml");
70
71 private static CdmApplicationRemoteController remoteApplicationController;
72 private static ICdmRemoteSource cdmRemoteSource;
73 private static CdmPersistentRemoteSource remotePersistentSource;
74
75 public static boolean useManagedServer = true;
76
77
78 protected static ICdmEntitySessionManager cdmEntitySessionManager;
79
80 private final static String DEFAULT_USER = "admin";
81 private final static String DEFAULT_PASSWORD = "00000";
82
83 private static String userHomeKey = "user.home";
84
85 private static String user = DEFAULT_USER;
86 private static String password = DEFAULT_PASSWORD;
87
88 @BeforeClass
89 public static void initializeBaseRemotingTest() {
90
91 //NOTE: Run this the cdmTest H2 DB whenever it needs to be
92 // recreated e.g. after a model change
93 DatabaseUnitils.disableConstraints();
94
95 try {
96 String userHomeDirPath;
97 Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.test");
98 // if bundle is null then we are running as junit test in eclipse
99 if(bundle == null) {
100 userHomeDirPath = EDITOR_DATASOURCES_FILE.getFile().getParentFile().getParentFile().getParent();
101 } else {
102 // ... else we are running in maven which requires loading the dir via the
103 // classpath bundle
104 URL userHomeDirURL = bundle.getEntry("src/test/resources");
105 File userHomeDir = new File(FileLocator.resolve(userHomeDirURL).toURI());
106 userHomeDirPath = userHomeDir.getAbsolutePath();
107 }
108
109
110 logger.info("Setting user.home to " + userHomeDirPath);
111 System.setProperty(userHomeKey, userHomeDirPath);
112
113 CDMServer cdmServer = CDMServer.getInstance();
114
115
116 Properties prop = new Properties();
117 InputStream inputStream = SERVER_PROPERTIES_FILE.getInputStream();
118
119 if (inputStream != null) {
120 prop.load(inputStream);
121 inputStream.close();
122 }
123
124 if(prop.getProperty("httpPort") != null) {
125 cdmServer.setHttpPort(Integer.valueOf(prop.getProperty("httpPort")));
126 }
127
128 if(prop.getProperty("stopPort") != null) {
129 cdmServer.setStopPort(Integer.valueOf(prop.getProperty("stopPort")));
130 }
131
132 if(prop.getProperty("stopKey") != null) {
133 cdmServer.setStopKey(prop.getProperty("stopKey"));
134 }
135
136 if(prop.getProperty("user") != null) {
137 user = prop.getProperty("user");
138 }
139
140 if(prop.getProperty("password") != null) {
141 password = prop.getProperty("password");
142 }
143
144 cdmServer.start();
145 initializeController(CDMServer.getInstance().getName(),
146 CDMServer.getInstance().getHost(),
147 CDMServer.getInstance().getPort(),
148 CDMServer.getInstance().getContextPath(),
149 NomenclaturalCode.ICNAFP,
150 user,
151 password);
152 } catch (Exception e) {
153 e.printStackTrace();
154 // Assert.fail("Server failed to start. Reason : " + e.getMessage());
155 }
156
157 logger.info("Emptying all caches (except model cache) ");
158 emptyAllCachesExceptModelCache();
159 }
160
161 public static void emptyAllCachesExceptModelCache() {
162 CacheManager cm = CacheManager.create();
163 String[] cacheNames = CacheManager.create().getCacheNames();
164 for(String cacheName : cacheNames) {
165 if(!cacheName.equals(CdmRemoteCacheManager.CDM_MODEL_CACHE_NAME)) {
166 cm.getCache(cacheName).removeAll();
167 }
168 }
169 }
170
171
172 public static void initializeController(String sourceName, String host, int port, String contextPath, NomenclaturalCode ncode, String username, String password) {
173
174 if(remoteApplicationController != null) {
175 return;
176 }
177 cdmRemoteSource = CdmRemoteSource.NewInstance(sourceName, host, port, contextPath, ncode);
178 remoteApplicationController =
179 CdmApplicationRemoteController.NewInstance(cdmRemoteSource,
180 null,
181 null);
182
183 try {
184 remotePersistentSource = CdmPersistentRemoteSource.NewInstance(sourceName);
185 } catch (CdmRemoteSourceException e) {
186 Assert.fail("Default Remote Persistent Source failed to load. Reason : " + e.getMessage());
187 }
188 cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
189
190 SecurityContextHolder.clearContext();
191 SecurityContextImpl sc = new SecurityContextImpl();
192 Authentication token = new UsernamePasswordAuthenticationToken(username,password);
193 Authentication authentication = getRemoteApplicationController().getAuthenticationManager().authenticate(token);
194 authentication = new UsernamePasswordAuthenticationToken(username,password, authentication.getAuthorities());
195 sc.setAuthentication(authentication);
196
197 SecurityContextHolder.setContext(sc);
198 }
199
200
201
202 protected static CdmApplicationRemoteController getRemoteApplicationController() {
203 return remoteApplicationController;
204 }
205
206 protected static ICdmRemoteSource getCdmRemoteSource() {
207 return cdmRemoteSource;
208 }
209
210 protected static CdmPersistentRemoteSource getCdmPersistentRemoteSource() {
211 return remotePersistentSource;
212 }
213
214 protected static ICdmEntitySessionManager getCdmEntitySessionManager() {
215 return cdmEntitySessionManager;
216 }
217
218
219 protected static CdmEntitySession getSession(ICdmEntitySessionEnabled sessionOwner) {
220 Map<ICdmEntitySessionEnabled, CdmEntitySession> ownerSessionMap =
221 (Map<ICdmEntitySessionEnabled, CdmEntitySession>) getFieldValueViaReflection(cdmEntitySessionManager, "ownerSessionMap");
222 return ownerSessionMap.get(sessionOwner);
223 }
224
225 protected static CdmEntitySession getActiveSession() {
226 return (CdmEntitySession) getFieldValueViaReflection(cdmEntitySessionManager, "activeSession");
227 }
228
229 protected static CdmTransientEntityCacher getCacher(ICdmEntitySessionEnabled sessionOwner) {
230 return (CdmTransientEntityCacher) getFieldValueViaReflection(getSession(sessionOwner), "cdmTransientEntityCacher");
231 }
232
233 @AfterClass
234 public static void cleanup() {
235 try {
236 CDMServer.getInstance().stop();
237 } catch (Exception e) {
238 Assert.fail("Server could not be stopped. Reason : " + e.getMessage());
239 }
240 }
241
242
243 protected static Object getFieldValueViaReflection(Object object, String fieldName) {
244 Class<?> clazz = object.getClass();
245 try {
246 Field field = clazz.getDeclaredField(fieldName);
247 field.setAccessible(true);
248 return field.get(object);
249 } catch (NoSuchFieldException e) {
250 e.printStackTrace();
251 } catch (SecurityException e) {
252 e.printStackTrace();
253 } catch (IllegalArgumentException e) {
254 e.printStackTrace();
255 } catch (IllegalAccessException e) {
256 e.printStackTrace();
257 }
258 return null;
259 }
260
261
262
263
264 }