Project

General

Profile

Download (10.3 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.model.name.NomenclaturalCode;
42
import eu.etaxonomy.taxeditor.remoting.cache.CdmRemoteCacheManager;
43
import eu.etaxonomy.taxeditor.remoting.cache.CdmTransientEntityCacher;
44
import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
45
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
46
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
47
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
48
import eu.etaxonomy.taxeditor.session.CdmEntitySession;
49
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
50
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
51

    
52

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

    
65

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

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

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

    
76
    public static boolean useManagedServer = true;
77

    
78

    
79
    protected static ICdmEntitySessionManager cdmEntitySessionManager;
80

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

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

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

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

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

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

    
110

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

    
114
            CDMServer cdmServer = CDMServer.getInstance();
115

    
116

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

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

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

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

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

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

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

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

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

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

    
172

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

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

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

    
200
        SecurityContextHolder.setContext(sc);
201
    }
202

    
203

    
204

    
205
    protected static CdmApplicationRemoteController getRemoteApplicationController() {
206
        return (CdmApplicationRemoteController) CdmApplicationState.getCurrentAppConfig();
207
    }
208

    
209
    protected static ICdmRemoteSource getCdmRemoteSource() {
210
        return cdmRemoteSource;
211
    }
212

    
213
    protected static CdmPersistentRemoteSource getCdmPersistentRemoteSource() {
214
        return remotePersistentSource;
215
    }
216

    
217
    protected static ICdmEntitySessionManager getCdmEntitySessionManager() {
218
        return cdmEntitySessionManager;
219
    }
220

    
221

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

    
228
    protected static CdmEntitySession getActiveSession() {
229
        return (CdmEntitySession) getFieldValueViaReflection(cdmEntitySessionManager, "activeSession");
230
    }
231

    
232
    protected static CdmTransientEntityCacher getCacher(ICdmEntitySessionEnabled sessionOwner) {
233
        return (CdmTransientEntityCacher) getFieldValueViaReflection(getSession(sessionOwner), "cdmTransientEntityCacher");
234
    }
235

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

    
245

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

    
264

    
265

    
266

    
267
}
(1-1/7)