Project

General

Profile

Download (10.5 KB) Statistics
| Branch: | Tag: | Revision:
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.api.application.CdmApplicationState;
41
import eu.etaxonomy.cdm.api.application.CdmDataChangeService;
42
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
43
import eu.etaxonomy.taxeditor.remoting.cache.CdmRemoteCacheManager;
44
import eu.etaxonomy.taxeditor.remoting.cache.CdmTransientEntityCacher;
45
import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
46
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
47
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
48
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
49
import eu.etaxonomy.taxeditor.session.CdmEntitySession;
50
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
51
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
52

    
53

    
54
/**
55
 * Base class for remoting tests, responsible for
56
 * - starting / stop the cdm server
57
 * - running some basic connection tests
58
 * - setting up the remote configuration.
59
 *
60
 */
61
@Transactional(TransactionMode.DISABLED)
62
@SpringApplicationContext("file:./target/classes/eu/etaxonomy/cdm/testRemotingApplicationContext.xml")
63
public abstract class BaseRemotingTest extends UnitilsJUnit4 {
64
    private static final Logger logger = Logger.getLogger(BaseRemotingTest.class);
65

    
66

    
67
    public static final Resource SERVER_PROPERTIES_FILE =
68
            new ClassPathResource("server.properties");
69

    
70
    public static final Resource EDITOR_DATASOURCES_FILE =
71
            new ClassPathResource(".cdmLibrary/writableResources/cdm.datasources.xml");
72

    
73
    //private static CdmApplicationRemoteController remoteApplicationController;
74
    private static ICdmRemoteSource cdmRemoteSource;
75
    private static CdmPersistentRemoteSource remotePersistentSource;
76

    
77
    public static boolean useManagedServer = true;
78

    
79

    
80
    protected static ICdmEntitySessionManager cdmEntitySessionManager;
81

    
82
    private final static String DEFAULT_USER = "admin";
83
    private final static String DEFAULT_PASSWORD = "00000";
84

    
85
    private static String userHomeKey = "user.home";
86

    
87
    private static String user = DEFAULT_USER;
88
    private static String password = DEFAULT_PASSWORD;
89

    
90
    @BeforeClass
91
    public static void initializeBaseRemotingTest() {
92

    
93
        //NOTE: Run this the cdmTest H2 DB whenever it needs to be
94
        //      recreated e.g. after a model change
95
        DatabaseUnitils.disableConstraints();
96

    
97
        try {
98
            String userHomeDirPath;
99
            Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.test");
100
            // if bundle is null then we are running as junit test in eclipse
101
            if(bundle == null) {
102
                userHomeDirPath = EDITOR_DATASOURCES_FILE.getFile().getParentFile().getParentFile().getParent();
103
            } else {
104
                // ... else we are running in maven which requires loading the dir via the
105
                // classpath bundle
106
                URL userHomeDirURL = bundle.getEntry("src/test/resources");
107
                File userHomeDir = new File(FileLocator.resolve(userHomeDirURL).toURI());
108
                userHomeDirPath = userHomeDir.getAbsolutePath();
109
            }
110

    
111

    
112
            logger.info("Setting user.home to " + userHomeDirPath);
113
            System.setProperty(userHomeKey, userHomeDirPath);
114

    
115
            CDMServer cdmServer = CDMServer.getInstance();
116

    
117

    
118
            Properties prop = new Properties();
119
            InputStream inputStream = SERVER_PROPERTIES_FILE.getInputStream();
120

    
121
            if (inputStream != null) {
122
                prop.load(inputStream);
123
                inputStream.close();
124
            }
125

    
126
            if(prop.getProperty("httpPort") != null) {
127
                cdmServer.setHttpPort(Integer.valueOf(prop.getProperty("httpPort")));
128
            }
129

    
130
            if(prop.getProperty("stopPort") != null) {
131
                cdmServer.setStopPort(Integer.valueOf(prop.getProperty("stopPort")));
132
            }
133

    
134
            if(prop.getProperty("stopKey") != null) {
135
                cdmServer.setStopKey(prop.getProperty("stopKey"));
136
            }
137

    
138
            if(prop.getProperty("user") != null) {
139
                user = prop.getProperty("user");
140
            }
141

    
142
            if(prop.getProperty("password") != null) {
143
                password = prop.getProperty("password");
144
            }
145

    
146
            cdmServer.start();
147
            initializeController(CDMServer.getInstance().getName(),
148
                    CDMServer.getInstance().getHost(),
149
                    CDMServer.getInstance().getPort(),
150
                    CDMServer.getInstance().getContextPath(),
151
                    NomenclaturalCode.ICNAFP,
152
                    user,
153
                    password);
154
        } catch (Exception e) {
155
            e.printStackTrace();
156
           // Assert.fail("Server failed to start. Reason : " + e.getMessage());
157
        }
158

    
159
        logger.info("Emptying all caches (except model cache) ");
160
        emptyAllCachesExceptModelCache();
161
    }
162

    
163
    public static void emptyAllCachesExceptModelCache() {
164
        CacheManager cm = CacheManager.create();
165
        String[] cacheNames = CacheManager.create().getCacheNames();
166
        for(String cacheName : cacheNames) {
167
            if(!cacheName.equals(CdmRemoteCacheManager.CDM_MODEL_CACHE_NAME)) {
168
                cm.getCache(cacheName).removeAll();
169
            }
170
        }
171
    }
172

    
173

    
174
    public static void initializeController(String sourceName, String host, int port, String contextPath, NomenclaturalCode ncode, String username, String password) {
175

    
176
        if(CdmApplicationState.getCurrentAppConfig() != null) {
177
            return;
178
        }
179
        cdmRemoteSource = CdmRemoteSource.NewInstance(sourceName, host, port, contextPath, ncode);
180
        CdmApplicationRemoteController remoteApplicationController =
181
                CdmApplicationRemoteController.NewInstance(cdmRemoteSource,
182
                        null,
183
                        null);
184
        CdmApplicationState.setCurrentAppConfig(remoteApplicationController);
185
        try {
186
            remotePersistentSource = CdmPersistentRemoteSource.NewInstance(sourceName);
187
        } catch (CdmRemoteSourceException e) {
188
            Assert.fail("Default Remote Persistent Source failed to load. Reason : " + e.getMessage());
189
        }
190
        cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
191

    
192
        CdmApplicationState.setCurrentDataChangeService(new CdmDataChangeService());
193

    
194
        //FIXME:Remoting the authentication code should be replaced by a method call which actually
195
        // does the authentication in the editor code so that the 'real' authentication can be tested
196
        SecurityContextHolder.clearContext();
197
        SecurityContextImpl sc = new SecurityContextImpl();
198
        Authentication token = new UsernamePasswordAuthenticationToken(username,password);
199
        Authentication authentication = getRemoteApplicationController().getAuthenticationManager().authenticate(token);
200
        authentication = new UsernamePasswordAuthenticationToken(username,password, authentication.getAuthorities());
201
        sc.setAuthentication(authentication);
202

    
203
        SecurityContextHolder.setContext(sc);
204
    }
205

    
206

    
207

    
208
    protected static CdmApplicationRemoteController getRemoteApplicationController() {
209
        return (CdmApplicationRemoteController) CdmApplicationState.getCurrentAppConfig();
210
    }
211

    
212
    protected static ICdmRemoteSource getCdmRemoteSource() {
213
        return cdmRemoteSource;
214
    }
215

    
216
    protected static CdmPersistentRemoteSource getCdmPersistentRemoteSource() {
217
        return remotePersistentSource;
218
    }
219

    
220
    protected static ICdmEntitySessionManager getCdmEntitySessionManager() {
221
        return cdmEntitySessionManager;
222
    }
223

    
224

    
225
    protected static CdmEntitySession getSession(ICdmEntitySessionEnabled sessionOwner) {
226
        Map<ICdmEntitySessionEnabled, CdmEntitySession> ownerSessionMap =
227
                (Map<ICdmEntitySessionEnabled, CdmEntitySession>) getFieldValueViaReflection(cdmEntitySessionManager, "ownerSessionMap");
228
        return ownerSessionMap.get(sessionOwner);
229
    }
230

    
231
    protected static CdmEntitySession getActiveSession() {
232
        return (CdmEntitySession) getFieldValueViaReflection(cdmEntitySessionManager, "activeSession");
233
    }
234

    
235
    protected static CdmTransientEntityCacher getCacher(ICdmEntitySessionEnabled sessionOwner) {
236
        return (CdmTransientEntityCacher) getFieldValueViaReflection(getSession(sessionOwner), "cdmTransientEntityCacher");
237
    }
238

    
239
    @AfterClass
240
    public static void cleanup() {
241
        try {
242
            CDMServer.getInstance().stop();
243
        } catch (Exception e) {
244
            Assert.fail("Server could not be stopped. Reason : " + e.getMessage());
245
        }
246
    }
247

    
248

    
249
    protected static Object getFieldValueViaReflection(Object object, String fieldName) {
250
        Class<?> clazz = object.getClass();
251
        try {
252
            Field field = clazz.getDeclaredField(fieldName);
253
            field.setAccessible(true);
254
            return field.get(object);
255
        } catch (NoSuchFieldException e) {
256
            e.printStackTrace();
257
        } catch (SecurityException e) {
258
            e.printStackTrace();
259
        } catch (IllegalArgumentException e) {
260
            e.printStackTrace();
261
        } catch (IllegalAccessException e) {
262
            e.printStackTrace();
263
        }
264
        return null;
265
    }
266

    
267

    
268

    
269

    
270
}
(1-1/7)