Project

General

Profile

Download (9.32 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.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
    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
    protected static CDMServer cdmServer;
87

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

    
91
        DatabaseUnitils.disableConstraints();
92

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

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

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

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

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

    
114

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

    
117

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

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

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

    
138
        logger.info("Emptying all caches (except model cache) ");
139
        //emptyAllCachesExceptModelCache();
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
        try {
165
            remotePersistentSource = CdmPersistentRemoteSource.NewInstance(sourceName);
166
        } catch (CdmRemoteSourceException e) {
167
            Assert.fail("Default Remote Persistent Source failed to load. Reason : " + e.getMessage());
168
        }
169
        cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
170

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

    
173
        //FIXME:Remoting the authentication code should be replaced by a method call which actually
174
        // does the authentication in the editor code so that the 'real' authentication can be tested
175
        SecurityContextHolder.clearContext();
176
        SecurityContextImpl sc = new SecurityContextImpl();
177
        Authentication token = new UsernamePasswordAuthenticationToken(username,password);
178
        Authentication authentication = getRemoteApplicationController().getAuthenticationManager().authenticate(token);
179
        authentication = new UsernamePasswordAuthenticationToken(username,password, authentication.getAuthorities());
180
        sc.setAuthentication(authentication);
181

    
182
        SecurityContextHolder.setContext(sc);
183
        CdmApplicationState.setCurrentSecurityContext(SecurityContextHolder.getContext());
184
    }
185

    
186

    
187

    
188
    protected static CdmApplicationRemoteController getRemoteApplicationController() {
189
        return (CdmApplicationRemoteController) CdmApplicationState.getCurrentAppConfig();
190
    }
191

    
192
    protected static ICdmRemoteSource getCdmRemoteSource() {
193
        return cdmRemoteSource;
194
    }
195

    
196
    protected static CdmPersistentRemoteSource getCdmPersistentRemoteSource() {
197
        return remotePersistentSource;
198
    }
199

    
200
    protected static ICdmEntitySessionManager getCdmEntitySessionManager() {
201
        return cdmEntitySessionManager;
202
    }
203

    
204

    
205
    protected static CdmEntitySession getSession(ICdmEntitySessionEnabled sessionOwner) {
206
        Map<ICdmEntitySessionEnabled, CdmEntitySession> ownerSessionMap =
207
                (Map<ICdmEntitySessionEnabled, CdmEntitySession>) getFieldValueViaReflection(cdmEntitySessionManager, "ownerSessionMap");
208
        return ownerSessionMap.get(sessionOwner);
209
    }
210

    
211
    protected static CdmEntitySession getActiveSession() {
212
        return (CdmEntitySession) getFieldValueViaReflection(cdmEntitySessionManager, "activeSession");
213
    }
214

    
215
    protected static CdmTransientEntityCacher getCacher(ICdmEntitySessionEnabled sessionOwner) {
216
        return (CdmTransientEntityCacher) getFieldValueViaReflection(getSession(sessionOwner), "cdmTransientEntityCacher");
217
    }
218

    
219

    
220
    protected static Object getFieldValueViaReflection(Object object, String fieldName) {
221
        Class<?> clazz = object.getClass();
222
        try {
223
            Field field = clazz.getDeclaredField(fieldName);
224
            field.setAccessible(true);
225
            return field.get(object);
226
        } catch (NoSuchFieldException e) {
227
            e.printStackTrace();
228
        } catch (SecurityException e) {
229
            e.printStackTrace();
230
        } catch (IllegalArgumentException e) {
231
            e.printStackTrace();
232
        } catch (IllegalAccessException e) {
233
            e.printStackTrace();
234
        }
235
        return null;
236
    }
237

    
238

    
239

    
240

    
241
}
(1-1/7)