Project

General

Profile

Download (13.4 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.taxonx2013;
11

    
12
import java.awt.Dimension;
13
import java.io.File;
14
import java.io.FileWriter;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import eu.etaxonomy.cdm.common.URI;
18
import java.net.URL;
19
import java.util.ArrayList;
20
import java.util.HashMap;
21
import java.util.List;
22
import java.util.Map;
23

    
24
import javax.swing.JOptionPane;
25
import javax.swing.JScrollPane;
26
import javax.swing.JTextArea;
27
import javax.xml.parsers.DocumentBuilder;
28
import javax.xml.parsers.DocumentBuilderFactory;
29

    
30
import org.apache.commons.lang.StringUtils;
31
import org.apache.log4j.Logger;
32
import org.springframework.stereotype.Component;
33
import org.springframework.transaction.TransactionStatus;
34
import org.w3c.dom.Document;
35

    
36
import eu.etaxonomy.cdm.io.common.CdmImportBase;
37
import eu.etaxonomy.cdm.model.common.CdmBase;
38
import eu.etaxonomy.cdm.model.common.Language;
39
import eu.etaxonomy.cdm.model.description.Feature;
40
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
41
import eu.etaxonomy.cdm.model.name.Rank;
42
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
43
import eu.etaxonomy.cdm.model.reference.Reference;
44
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
45
import eu.etaxonomy.cdm.model.taxon.Classification;
46
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
47
import eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException;
48

    
49
/**
50
 * @author p.kelbert 2013
51
 */
52
@Component
53
public class TaxonXImport
54
        extends CdmImportBase<TaxonXImportConfigurator, TaxonXImportState>{
55

    
56
    private static final long serialVersionUID = 8166758191513137605L;
57
    private static final Logger logger = Logger.getLogger(TaxonXImport.class);
58

    
59
    private static String prefix = "";
60
    public static String LOG_FOLDER = "C:\\Users\\pesiimport\\.cdmLibrary\\log\\taxonX\\";
61

    
62
    private Classification classification = null;
63
    private Reference ref = null;
64

    
65
    private TaxonXImportState taxonXstate;
66
    private TaxonXDataHolder dataHolder;
67
    private DerivedUnit derivedUnitBase;
68

    
69
    private TransactionStatus tx;
70

    
71
    private TaxonXXMLFieldGetter taxonXFieldGetter;
72

    
73
    public TaxonXImport() {
74
        super();
75
    }
76

    
77
    private Map<String,Feature> featuresMap = new HashMap<String, Feature>();
78

    
79
    @Override
80
    protected boolean doCheck(TaxonXImportState state) {
81
        logger.warn("Checking not yet implemented for "	+ this.getClass().getSimpleName());
82
        this.taxonXstate = state;
83
        return true;
84
    }
85

    
86
    /**
87
     * getClassification
88
     * asks for user interaction for decision
89
     * @param classificationName : the name of the classification we are looking for
90
     * @set the global classification object
91
     */
92
    private void setClassification() {
93
        logger.info("SET CLASSIFICATION "+classification);
94
        String classificationName = taxonXstate.getConfig().getClassificationName();
95
        String defaultClassificatioName = taxonXstate.getConfig().getImportClassificationName();
96

    
97
        List<Classification> classifList = getClassificationService().list(Classification.class, null, null, null, null);
98
        Map<String,Classification> classificationMap = new HashMap<String,Classification>();
99
        ArrayList<String> nodeList = new ArrayList<String>();
100
        String citation ="";
101
        String title ="";
102
        for (Classification cla:classifList){
103
            try{
104
//                citation = cla.getCitation().toString();
105
            }catch(Exception e){
106
                citation="";
107
            }
108
            title=StringUtils.isBlank(cla.getTitleCache()) ? "no name" : cla.getTitleCache();
109
            if (citation.length()>title.length()){
110
                nodeList.add(citation);
111
                classificationMap.put(citation, cla);
112
            }
113
            else{
114
                nodeList.add(title);
115
                classificationMap.put(title, cla);
116
            }
117
        }
118
        boolean defaultClassificationExists = nodeList.indexOf(defaultClassificatioName)>-1;
119
        if (! defaultClassificationExists ) {
120
            nodeList.add(defaultClassificatioName);
121
        }
122
        if (nodeList.indexOf(classificationName)<0) {
123
            nodeList.add(classificationName);
124
        }
125
        final String other = "Other classification - add a new one";
126
        nodeList.add(other);
127

    
128
        String s;
129
        if (defaultClassificatioName != null && defaultClassificationExists  && taxonXstate.getConfig().isAlwaysUseDefaultClassification()) {
130
            s=defaultClassificatioName;
131
        } else{
132
            JTextArea textArea = new JTextArea("Which classification do you want to use ? \nThe current reference is " + classificationName);
133
            JScrollPane scrollPane = new JScrollPane(textArea);
134
            textArea.setLineWrap(true);
135
            textArea.setWrapStyleWord(true);
136
            scrollPane.setPreferredSize( new Dimension( 600, 100 ) );
137

    
138
            s = (String)JOptionPane.showInputDialog(
139
                    null,
140
                    scrollPane,
141
                    "Classification",
142
                    JOptionPane.PLAIN_MESSAGE,
143
                    null,
144
                    nodeList.toArray(),
145
                    defaultClassificatioName);
146
        }
147
        ref=getReferenceService().find(ref.getUuid());
148
        if (!classificationMap.containsKey(s)){
149
            //System.out.println("Classif inconnue ?? "+s+", "+classifDic);
150
        	Reference classificationReference = null;
151

    
152
        	if (s.equalsIgnoreCase(other)){
153
                classificationName = askForValue("classification name ?", classificationName);
154
            	classificationReference = ReferenceFactory.newDatabase();
155
            	classificationReference.setTitle(classificationName);
156
            }else if (s.equalsIgnoreCase(defaultClassificatioName)){
157
            	classificationName = defaultClassificatioName;
158
            	classificationReference = ReferenceFactory.newDatabase();
159
            	classificationReference.setTitle(classificationName);
160
            }
161
            //new classification
162
            classification = Classification.NewInstance(classificationName, classificationReference,   Language.DEFAULT());
163
            getClassificationService().saveOrUpdate(classification);
164
            refreshTransaction();
165
        }
166
        else{
167
            classification = classificationMap.get(s);
168
        }
169
        if (classification == null) {
170
            String name = taxonXstate.getConfig().getClassificationName();
171
            classification = Classification.NewInstance(name, ref,  Language.DEFAULT());
172
            if (taxonXstate.getConfig().getClassificationUuid() != null) {
173
                classification.setUuid(taxonXstate.getConfig().getClassificationUuid());
174
            }
175
            getClassificationService().saveOrUpdate(classification);
176
            refreshTransaction();
177
        }
178
    }
179

    
180
    /**
181
     * asks users for decision
182
     * @param string : the parameter name we are looking at
183
     * @param defaultValue : the default value
184
     * @return
185
     */
186
    private String askForValue(String string, String defaultValue) {
187
        JTextArea textArea = new JTextArea(string);
188
        JScrollPane scrollPane = new JScrollPane(textArea);
189
        textArea.setLineWrap(true);
190
        textArea.setWrapStyleWord(true);
191
        scrollPane.setPreferredSize( new Dimension( 600, 100 ) );
192

    
193
        String s = (String)JOptionPane.showInputDialog(
194
                null,
195
                scrollPane,
196
                "What should be the "+string,
197
                JOptionPane.PLAIN_MESSAGE,
198
                null,
199
                null,
200
                defaultValue);
201

    
202
        return s;
203

    
204
    }
205

    
206
    @Override
207
    public void doInvoke(TaxonXImportState state) {
208
        taxonXstate = state;
209
        tx = startTransaction();
210

    
211
        logger.info("INVOKE TaxonXImport ");
212
        URI sourceName = this.taxonXstate.getConfig().getSource();
213

    
214
        //        this.taxonXstate.getConfig().getClassificationName();
215
        //        this.taxonXstate.getConfig().getClassificationUuid();
216

    
217
        ref = taxonXstate.getConfig().getSourceReference();
218

    
219

    
220

    
221
        Reference secundum = taxonXstate.getConfig().getSecundum();
222
        List<Reference> references = this.getReferenceService().list(Reference.class, null, null, null, null);
223
        boolean refFound = false;
224
        for (Reference re:references){
225
            if (re.getCitation().equalsIgnoreCase(secundum.getCitation())){
226
                refFound = true;
227
                secundum = re;
228
            }
229
        }
230
        if (refFound) {
231
            secundum = CdmBase.deproxy(secundum, Reference.class);
232
            taxonXstate.getConfig().setSecundum(secundum);
233
        } else {
234
            this.getReferenceService().saveOrUpdate(secundum);
235
            taxonXstate.getConfig().setSecundum(secundum);
236
        }
237

    
238

    
239
        Reference urlRef = taxonXstate.getConfig().getOriginalSourceURL();
240
        for (Reference re:references){
241
            if (re.getCitation().equalsIgnoreCase(urlRef.getCitation())){
242
                urlRef=re;
243
            }
244
        }
245
        this.getReferenceService().saveOrUpdate(urlRef);
246
        urlRef=getReferenceService().find(urlRef.getUuid());
247

    
248
        if(!taxonXstate.getConfig().hasAskedForHigherRank()){
249
            Rank maxRank = askForHigherRank(taxonXstate.getConfig().getNomenclaturalCode());
250
            taxonXstate.getConfig().setMaxRank(maxRank);
251
            taxonXstate.getConfig().setHasAskedForHigherRank(true);
252
        }
253

    
254

    
255
        String message = "go taxonx!";
256
        logger.info(message);
257
        updateProgress(this.taxonXstate, message);
258
        dataHolder = new TaxonXDataHolder();
259

    
260
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
261
        DocumentBuilder builder;
262
        URL url;
263

    
264
        try {
265
            builder = factory.newDocumentBuilder();
266
            url = sourceName.toURL();
267
            Object o = url.getContent();
268
            InputStream is = (InputStream) o;
269
            Document document = builder.parse(is);
270

    
271
            taxonXFieldGetter = new TaxonXXMLFieldGetter(dataHolder, prefix, document, this, taxonXstate, classification, featuresMap);
272
            /*parse the Mods from the TaxonX file
273
             *create the appropriate Reference object
274
             */
275
            ref = taxonXFieldGetter.parseMods();
276
            //            logger.info("CLASSNAME :" +taxonXstate.getConfig().getClassificationName());
277
            setClassification();
278
            taxonXFieldGetter.updateClassification(classification);
279
            //            logger.info("classif :"+classification);
280
            taxonXFieldGetter.parseTreatment(ref,sourceName);
281
            featuresMap = taxonXFieldGetter.getFeaturesUsed();
282

    
283
        }catch(Exception e){
284
            e.printStackTrace();
285
            logger.warn(e);
286

    
287
            File file = new File(LOG_FOLDER + "urlTaxonX.txt");
288
            FileWriter writer;
289
            try {
290
                writer = new FileWriter(file ,true);
291
                writer.write(sourceName+"\n");
292
                writer.flush();
293
                writer.close();
294
            } catch (IOException e1) {
295
                logger.error(e1.getMessage());
296
            }
297

    
298
            logger.warn(sourceName);
299
        }
300

    
301
        //TODO:check how deduplicate work (and if it works..)
302
//        if(taxonXstate.getConfig().getLastImport()) {
303
//            deduplicate();
304
//        }
305
        commitTransaction(tx);
306
    }
307

    
308
    public void deduplicate(){
309
        //System.out.println("DEDUPLICATE REFERENCE");
310
        getReferenceService().deduplicate(Reference.class, null,null);
311
        //System.out.println("DEDUPLICATE TAXONBASE");
312
        getTaxonService().deduplicate(TaxonBase.class, null, null);
313
        //System.out.println("DEDUP END");
314
    }
315

    
316

    
317
    private void refreshTransaction(){
318
        commitTransaction(tx);
319
        tx = startTransaction();
320
        ref = getReferenceService().find(ref.getUuid());
321
        classification = getClassificationService().find(classification.getUuid());
322
        try{
323
            derivedUnitBase = (DerivedUnit) getOccurrenceService().find(derivedUnitBase.getUuid());
324
        }catch(Exception e){
325
            //logger.warn("derivedunit up to date or not created yet");
326
        }
327
    }
328

    
329
    /**
330
     * @return
331
     */
332
    private Rank askForHigherRank(NomenclaturalCode nomenclaturalCode) {
333
        JTextArea textArea = new JTextArea("Everything below that rank should be imported:");
334
        JScrollPane scrollPane = new JScrollPane(textArea);
335
        textArea.setLineWrap(true);
336
        textArea.setWrapStyleWord(true);
337
        scrollPane.setPreferredSize( new Dimension( 600, 50 ) );
338

    
339
        List<Rank> rankList = new ArrayList<Rank>();
340
        rankList = getTermService().list(Rank.class, null, null, null, null);
341

    
342
        List<String> rankListStr = new ArrayList<String>();
343
        for (Rank r:rankList) {
344
            rankListStr.add(r.toString());
345
        }
346
        String s = (String)JOptionPane.showInputDialog(
347
                null,
348
                scrollPane,
349
                null,
350
                JOptionPane.PLAIN_MESSAGE,
351
                null,
352
                rankListStr.toArray(),
353
                "Suprageneric Taxon");
354

    
355
        Rank cR = null;
356
        try {
357
            cR = Rank.getRankByEnglishName(s,nomenclaturalCode,true);
358
        } catch (UnknownCdmTypeException e) {
359
            logger.warn("Unknown rank ?!"+s);
360
            logger.warn(e);
361
        }
362
        return cR;
363
    }
364

    
365
    @Override
366
    protected boolean isIgnore(TaxonXImportState state) {
367
    	return false;
368
    }
369
}
(4-4/9)