Project

General

Profile

Download (11 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2007 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

    
10
package eu.etaxonomy.cdm.io.common;
11

    
12
import java.lang.reflect.Constructor;
13
import java.lang.reflect.InvocationTargetException;
14
import java.util.HashMap;
15
import java.util.Map;
16

    
17
import org.apache.log4j.Logger;
18
import org.springframework.beans.BeansException;
19
import org.springframework.context.ApplicationContext;
20
import org.springframework.context.ApplicationContextAware;
21
import org.springframework.security.authentication.AuthenticationManager;
22
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
23
import org.springframework.security.core.Authentication;
24
import org.springframework.security.core.context.SecurityContext;
25
import org.springframework.security.core.context.SecurityContextHolder;
26
import org.springframework.stereotype.Component;
27

    
28
import eu.etaxonomy.cdm.api.application.CdmRepository;
29
import eu.etaxonomy.cdm.api.service.IService;
30
import eu.etaxonomy.cdm.io.common.events.IIoObserver;
31
import eu.etaxonomy.cdm.io.fact.altitude.in.analyze.ExcelFormatAnalyzeResult;
32
import eu.etaxonomy.cdm.io.fact.altitude.in.analyze.ExcelFormatAnalyzer;
33
import eu.etaxonomy.cdm.io.fact.in.FactExcelImportConfiguratorBase;
34
import eu.etaxonomy.cdm.model.common.CdmBase;
35

    
36
/**
37
 * @author a.mueller
38
 * @since 20.06.2008
39
 */
40

    
41
@Component("defaultImport")
42
public class CdmApplicationAwareDefaultImport<T extends IImportConfigurator> implements ICdmImporter<T>, ApplicationContextAware {
43
    private static final Logger logger = Logger.getLogger(CdmApplicationAwareDefaultImport.class);
44

    
45
    protected ApplicationContext applicationContext;
46

    
47

    
48
    @Override
49
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
50
        this.applicationContext = applicationContext;
51
    }
52

    
53

    
54
    //Constants
55
    final boolean OBLIGATORY = true;
56
    final boolean FACULTATIVE = false;
57
    final int modCount = 1000;
58

    
59
    IService<CdmBase> service = null;
60

    
61
    //different type of stores that are used by the known imports
62
    Map<String, MapWrapper<? extends CdmBase>> stores = new HashMap<>();
63

    
64
    public CdmApplicationAwareDefaultImport(){
65

    
66
    	stores.put(ICdmIO.TEAM_STORE, new MapWrapper<>(service));
67
        stores.put(ICdmIO.REFERENCE_STORE, new MapWrapper<>(service));
68
        stores.put(ICdmIO.NOMREF_STORE, new MapWrapper<>(service));
69
        stores.put(ICdmIO.TAXONNAME_STORE, new MapWrapper<>(service));
70
        stores.put(ICdmIO.TAXON_STORE, new MapWrapper<>(service));
71
        stores.put(ICdmIO.SPECIMEN_STORE, new MapWrapper<>(service));
72
    }
73

    
74

    
75
    @Override
76
    public ImportResult invoke(IImportConfigurator config){
77
        ImportResult result = new ImportResult();
78
        if (config.getCheck().equals(IImportConfigurator.CHECK.CHECK_ONLY)){
79
            boolean success = doCheck(config);
80
            if (! success){
81
                result.setAborted();
82
            }
83
        }else if (config.getCheck().equals(IImportConfigurator.CHECK.CHECK_AND_IMPORT)){
84
            boolean success = doCheck(config);
85
            if (success){
86
                result = doImport(config);
87
            }else{
88
                result.setAborted();
89
            }
90
        }else if (config.getCheck().equals(IImportConfigurator.CHECK.IMPORT_WITHOUT_CHECK)){
91
            result = doImport(config);
92
        }else{
93
            String message = "Unknown CHECK type";
94
            logger.error(message);
95
            result.addError(message);
96
        }
97
        return result;
98
    }
99

    
100
    @SuppressWarnings("unchecked")
101
    protected <S extends IImportConfigurator> boolean doCheck(S  config){
102
        boolean result = true;
103

    
104
        //check
105
        if (config == null){
106
            logger.warn("CdmImportConfiguration is null");
107
            return false;
108
        }
109
        System.out.println("Start checking Source ("+ config.getSourceNameString() + ") ...");
110
        if (! config.isValid()){
111
            logger.warn("CdmImportConfiguration is not valid");
112
            return false;
113
        }
114

    
115
        ImportStateBase state = config.getNewState();
116
        state.initialize(config);
117
        state.setCheck(true);
118

    
119
        if (config instanceof FactExcelImportConfiguratorBase<?>){
120
            ExcelFormatAnalyzer<?> analyzer = ((FactExcelImportConfiguratorBase<?>)config).getAnalyzer();
121
            ExcelFormatAnalyzeResult analyzeResult = analyzer.invoke();
122
            //TODO very preliminary for development only
123
            System.out.println(analyzeResult.toString());
124
            try {
125
                for (Class<ICdmImport> ioClass: config.getIoClassList()){
126
                    Constructor<ICdmImport> constructor = ioClass.getConstructor();
127
                    constructor.setAccessible(true);
128
                    ICdmImport ioInstance = constructor.newInstance();
129
                    CdmRepository repository = (CdmRepository)applicationContext.getBean("CdmRepository");
130
                    ioInstance.setRepository(repository);
131
//                    ioInstance.analyze();
132
                }
133
            } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
134
                analyzeResult.addFatalError("Problem accessing the constructor of the import class. Please contact your system developers");
135
            }
136
            if (analyzeResult.hasErrors()){
137
                result = false;
138
            }
139
        }else{
140
            //do check for each class
141
            for (Class<ICdmImport> ioClass: config.getIoClassList()){
142
                try {
143
                    String ioBeanName = getComponentBeanName(ioClass);
144
                    ICdmIO cdmIo = applicationContext.getBean(ioBeanName, ICdmIO.class);
145
                    if (cdmIo != null){
146
                        registerObservers(config, cdmIo);
147
                        state.setCurrentIO(cdmIo);
148
                        result &= cdmIo.check(state);
149
                        unRegisterObservers(config, cdmIo);
150
                    }else{
151
                        logger.error("cdmIO was null");
152
                        result &= false;
153
                    }
154
                } catch (Exception e) {
155
                    logger.error(e);
156
                    e.printStackTrace();
157
                    result &= false;
158
                }
159
            }
160
        }
161

    
162

    
163
        //return
164
        System.out.println("End checking Source ("+ config.getSourceNameString() + ") for import to Cdm");
165
        state.setCheck(false);
166
        return result;
167

    
168
    }
169

    
170
    private void registerObservers(IImportConfigurator config, ICdmIO io){
171
        for (IIoObserver observer : config.getObservers()){
172
            io.addObserver(observer);
173
        }
174
    }
175

    
176
    private void unRegisterObservers(IImportConfigurator config, ICdmIO io){
177
        for (IIoObserver observer : config.getObservers()){
178
            io.removeObserver(observer);
179
        }
180
    }
181

    
182
    /**
183
     * Executes the whole
184
     */
185
    protected <S extends IImportConfigurator>  ImportResult doImport(S config){
186
        ImportResult result = new ImportResult();
187
        //validate
188
        if (config == null){
189
            String message = "Configuration is null";
190
            logger.error(message);
191
            result.addError(message);
192
            result.setAborted();
193
            return result;
194
        }
195

    
196
        if (! config.isValid()){
197
            String message = "Configuration is not valid";
198
            logger.error(message);
199
            result.addError(message);
200
            result.setAborted();
201
            return result;
202
        }
203

    
204
        config.getSourceReference();
205
        logger.info("Start import from Source '"+ config.getSourceNameString() + "' to destination '" + config.getDestinationNameString() + "'");
206

    
207
        ImportStateBase state = config.getNewState();
208
        state.initialize(config);
209
        state.setResult(result);
210

    
211
//        CdmPermissionEvaluator permissionEval = applicationContext.getBean("cdmPermissionEvaluator", CdmPermissionEvaluator.class);
212

    
213
        state.setSuccess(true);
214
        //do invoke for each class
215
        for (Class<ICdmImport> ioClass: config.getIoClassList()){
216
            try {
217
                String ioBeanName = getComponentBeanName(ioClass);
218
                ICdmImport cdmIo = applicationContext.getBean(ioBeanName, ICdmImport.class);
219
                if (cdmIo != null){
220
                    registerObservers(config, cdmIo);
221
                    state.setCurrentIO(cdmIo);
222
                    cdmIo.invoke(state);
223
                    result.addReport(state.getReportAsByteArray());
224
                    unRegisterObservers(config, cdmIo);
225
                }else{
226
                    String message = "cdmIO was null";
227
                    logger.error(message);
228
                    result.addError(message);
229
                }
230
            } catch (Exception e) {
231
                logger.error(e);
232
                e.printStackTrace();
233
                result.addException(e);
234
            }
235
        }
236

    
237
        logger.info("End import from source '" + config.getSourceNameString()
238
                + "' to destination '" + config.getDestinationNameString() + "'"
239
                + "("+ result.toString() + ")"
240
                ) ;
241
        return result;
242
    }
243

    
244
    /**
245
     * Returns the name of a component bean. If the name is defined in the Component annotation this name is returned.
246
     * Otherwise the class name is returned with starting lower case.
247
     * @param ioClass
248
     * @return
249
     * @throws IllegalArgumentException if the class does not have a "Component" annotation
250
     */
251
    public static String getComponentBeanName(Class<ICdmImport> ioClass) throws IllegalArgumentException {
252
        Component component = ioClass.getAnnotation(Component.class);
253
        if (component == null){
254
            throw new IllegalArgumentException("Class " + ioClass.getName() + " is missing a @Component annotation." );
255
        }
256
        String ioBean = component.value();
257
        if ("".equals(ioBean)){
258
            ioBean = ioClass.getSimpleName();
259
            ioBean = ioBean.substring(0, 1).toLowerCase() + ioBean.substring(1); //make camelcase
260
        }
261
        return ioBean;
262
    }
263

    
264
    public void authenticate(IImportConfigurator config) {
265
        UsernamePasswordAuthenticationToken token = config.getAuthenticationToken();
266
        if (token != null){
267
            SecurityContext context = SecurityContextHolder.getContext();
268

    
269
            AuthenticationManager authenticationManager = applicationContext.getBean("authenticationManager", AuthenticationManager.class);;
270
            Authentication authentication = authenticationManager.authenticate(token);
271
            context.setAuthentication(authentication);
272
        }else{
273
        	logger.warn("No authentication token available");
274
        }
275

    
276
    }
277

    
278
}
(2-2/65)