Project

General

Profile

Download (9.55 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.FileInputStream;
13
import java.io.InputStream;
14
import java.lang.reflect.Field;
15
import java.net.URL;
16
import java.util.Map;
17
import java.util.Properties;
18

    
19
import net.sf.ehcache.CacheManager;
20

    
21
import org.apache.log4j.Logger;
22
import org.eclipse.core.runtime.FileLocator;
23
import org.eclipse.core.runtime.Platform;
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.database.DatabaseUnitils;
34
import org.unitils.database.annotations.Transactional;
35
import org.unitils.database.util.TransactionMode;
36
import org.unitils.spring.annotation.SpringApplicationContext;
37

    
38
import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteController;
39
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
40
import eu.etaxonomy.cdm.api.application.CdmDataChangeService;
41
import eu.etaxonomy.cdm.api.cache.CdmServiceCacher;
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 ThreadedTest {
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
    private static ICdmRemoteSource cdmRemoteSource;
71
    private static CdmPersistentRemoteSource remotePersistentSource;
72

    
73
    public static boolean useManagedServer = true;
74

    
75

    
76
    protected static ICdmEntitySessionManager cdmEntitySessionManager;
77

    
78
    private final static String DEFAULT_USER = "admin";
79
    private final static String DEFAULT_PASSWORD = "00000";
80

    
81
    private static String userHomeKey = "user.home";
82

    
83
    private static String user = DEFAULT_USER;
84
    private static String password = DEFAULT_PASSWORD;
85

    
86

    
87
    protected static CDMServer cdmServer;
88

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

    
92
        DatabaseUnitils.disableConstraints();
93

    
94
        try {
95
            String userHomeDirPath;
96
            Bundle bundle = Platform.getBundle("eu.etaxonomy.taxeditor.test");
97

    
98
            URL userHomeDirURL = bundle.getEntry("src/test/resources");
99
            File userHomeDir = new File(FileLocator.resolve(userHomeDirURL).toURI());
100
            userHomeDirPath = userHomeDir.getAbsolutePath();
101

    
102
            URL serverPropertiesURL = bundle.getEntry("src/test/resources/server.properties");
103
            File serverPropertiesFile = new File(FileLocator.resolve(serverPropertiesURL).toURI());
104
            InputStream inputStream = new FileInputStream(serverPropertiesFile);
105

    
106
            Properties prop = new Properties();
107
            if (inputStream != null) {
108
                prop.load(inputStream);
109
                inputStream.close();
110
            }
111

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

    
115

    
116
            cdmServer = new CDMServer("cdmTest", serverPropertiesURL);
117

    
118

    
119
            if(prop.getProperty("user") != null) {
120
                user = prop.getProperty("user");
121
            }
122

    
123
            if(prop.getProperty("password") != null) {
124
                password = prop.getProperty("password");
125
            }
126

    
127
            initializeController(cdmServer.getName(),
128
                    cdmServer.getHost(),
129
                    cdmServer.getPort(),
130
                    cdmServer.getContextPath(),
131
                    NomenclaturalCode.ICNAFP,
132
                    user,
133
                    password);
134
        } catch (Exception e) {
135
            e.printStackTrace();
136
           // Assert.fail("Server failed to start. Reason : " + e.getMessage());
137
        }
138

    
139

    
140
    }
141

    
142
    public static void emptyAllCachesExceptModelCache() {
143
        CacheManager cm = CacheManager.create();
144
        String[] cacheNames = CacheManager.create().getCacheNames();
145
        for(String cacheName : cacheNames) {
146
            if(!cacheName.equals(CdmRemoteCacheManager.CDM_MODEL_CACHE_NAME)) {
147
                cm.removeCache(cacheName);
148
            }
149
        }
150
    }
151

    
152

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

    
155
        if(CdmApplicationState.getCurrentAppConfig() != null) {
156
            return;
157
        }
158
        cdmRemoteSource = CdmRemoteSource.NewInstance(sourceName, host, port, contextPath, ncode);
159
        CdmApplicationRemoteController remoteApplicationController =
160
                CdmApplicationRemoteController.NewInstance(cdmRemoteSource,
161
                        null,
162
                        null);
163
        CdmApplicationState.setCurrentAppConfig(remoteApplicationController);
164
        CdmApplicationState.setCdmServiceCacher(new CdmServiceCacher());
165
        try {
166
            remotePersistentSource = CdmPersistentRemoteSource.NewInstance(sourceName);
167
        } catch (CdmRemoteSourceException e) {
168
            Assert.fail("Default Remote Persistent Source failed to load. Reason : " + e.getMessage());
169
        }
170
        cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
171

    
172
        CdmApplicationState.setCurrentDataChangeService(new CdmDataChangeService());
173

    
174
        authenticate(username, password);
175

    
176
    }
177

    
178
    protected static void authenticate(String username, String password) {
179

    
180
        //FIXME:Remoting the authentication code should be replaced by a method call which actually
181
        // does the authentication in the editor code so that the 'real' authentication can be tested
182
        SecurityContextHolder.clearContext();
183
        SecurityContextImpl sc = new SecurityContextImpl();
184
        Authentication token = new UsernamePasswordAuthenticationToken(username,password);
185
        Authentication authentication = getRemoteApplicationController().getAuthenticationManager().authenticate(token);
186
        authentication = new UsernamePasswordAuthenticationToken(username,password, authentication.getAuthorities());
187
        sc.setAuthentication(authentication);
188

    
189
        SecurityContextHolder.setContext(sc);
190
        CdmApplicationState.setCurrentSecurityContext(SecurityContextHolder.getContext());
191

    
192
    }
193

    
194

    
195
    protected static CdmApplicationRemoteController getRemoteApplicationController() {
196
        return (CdmApplicationRemoteController) CdmApplicationState.getCurrentAppConfig();
197
    }
198

    
199
    protected static ICdmRemoteSource getCdmRemoteSource() {
200
        return cdmRemoteSource;
201
    }
202

    
203
    protected static CdmPersistentRemoteSource getCdmPersistentRemoteSource() {
204
        return remotePersistentSource;
205
    }
206

    
207
    protected static ICdmEntitySessionManager getCdmEntitySessionManager() {
208
        return cdmEntitySessionManager;
209
    }
210

    
211

    
212
    protected static CdmEntitySession getSession(ICdmEntitySessionEnabled sessionOwner) {
213
        Map<ICdmEntitySessionEnabled, CdmEntitySession> ownerSessionMap =
214
                (Map<ICdmEntitySessionEnabled, CdmEntitySession>) getFieldValueViaReflection(cdmEntitySessionManager, "ownerSessionMap");
215
        return ownerSessionMap.get(sessionOwner);
216
    }
217

    
218
    protected static CdmEntitySession getActiveSession() {
219
        return ((InheritableThreadLocal<CdmEntitySession>) getFieldValueViaReflection(cdmEntitySessionManager, "tlActiveSession")).get();
220
    }
221

    
222
    protected static CdmTransientEntityCacher getCacher(ICdmEntitySessionEnabled sessionOwner) {
223
        return (CdmTransientEntityCacher) getFieldValueViaReflection(getSession(sessionOwner), "cdmTransientEntityCacher");
224
    }
225

    
226

    
227
    protected static Object getFieldValueViaReflection(Object object, String fieldName) {
228
        Class<?> clazz = object.getClass();
229
        try {
230
            Field field = clazz.getDeclaredField(fieldName);
231
            field.setAccessible(true);
232
            return field.get(object);
233
        } catch (NoSuchFieldException e) {
234
            e.printStackTrace();
235
        } catch (SecurityException e) {
236
            e.printStackTrace();
237
        } catch (IllegalArgumentException e) {
238
            e.printStackTrace();
239
        } catch (IllegalAccessException e) {
240
            e.printStackTrace();
241
        }
242
        return null;
243
    }
244

    
245

    
246
    protected static void authenticateDefaultUser() {
247
        authenticate(user, password);
248
    }
249

    
250

    
251
}
(1-1/9)