Project

General

Profile

Download (12.4 KB) Statistics
| Branch: | Revision:
1
/**
2
* Copyright (C) 2016 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.cdm.io.greece;
10

    
11
import java.io.File;
12
import java.io.IOException;
13
import java.net.URI;
14
import java.util.ArrayList;
15
import java.util.List;
16

    
17
import org.apache.log4j.Logger;
18
import org.apache.sanselan.ImageReadException;
19
import org.apache.sanselan.Sanselan;
20
import org.apache.sanselan.common.IImageMetadata;
21
import org.apache.sanselan.common.ImageMetadata.Item;
22
import org.joda.time.DateTime;
23
import org.joda.time.DateTimeZone;
24
import org.joda.time.format.DateTimeFormat;
25
import org.joda.time.format.DateTimeFormatter;
26
import org.springframework.stereotype.Component;
27
import org.springframework.transaction.TransactionStatus;
28

    
29
import eu.etaxonomy.cdm.api.service.config.MatchingTaxonConfigurator;
30
import eu.etaxonomy.cdm.io.common.CdmImportBase;
31
import eu.etaxonomy.cdm.io.common.utils.ImportDeduplicationHelper;
32
import eu.etaxonomy.cdm.io.mexico.SimpleExcelTaxonImportState;
33
import eu.etaxonomy.cdm.model.agent.Person;
34
import eu.etaxonomy.cdm.model.common.CdmBase;
35
import eu.etaxonomy.cdm.model.common.Language;
36
import eu.etaxonomy.cdm.model.common.TimePeriod;
37
import eu.etaxonomy.cdm.model.description.Feature;
38
import eu.etaxonomy.cdm.model.description.TaxonDescription;
39
import eu.etaxonomy.cdm.model.description.TextData;
40
import eu.etaxonomy.cdm.model.media.Media;
41
import eu.etaxonomy.cdm.model.media.Rights;
42
import eu.etaxonomy.cdm.model.media.RightsType;
43
import eu.etaxonomy.cdm.model.reference.Reference;
44
import eu.etaxonomy.cdm.model.taxon.Synonym;
45
import eu.etaxonomy.cdm.model.taxon.Taxon;
46
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
47
/**
48
 * Import for the Flora Hellenica images.
49
 *
50
 * @author a.mueller
51
 * @since 03.04.2017
52
 */
53

    
54
@Component
55
public class FloraHellenicaImageImport<CONFIG extends FloraHellenicaImportConfigurator>
56
        extends CdmImportBase<CONFIG,SimpleExcelTaxonImportState<CONFIG>>{
57

    
58
    private static final long serialVersionUID = 7118028793298922703L;
59
    private static final Logger logger = Logger.getLogger(FloraHellenicaImageImport.class);
60

    
61
    private static final String BASE_URL = "https://media.e-taxonomy.eu/flora-greece/";
62
    private static final String IMAGE_FOLDER = "////BGBM-PESIHPC/Greece/thumbs/";
63

    
64
    @SuppressWarnings("unchecked")
65
    private ImportDeduplicationHelper<SimpleExcelTaxonImportState<?>> deduplicationHelper = (ImportDeduplicationHelper<SimpleExcelTaxonImportState<?>>)ImportDeduplicationHelper.NewInstance(this);
66

    
67
    /**
68
     * {@inheritDoc}
69
     */
70
    @Override
71
    protected void doInvoke(SimpleExcelTaxonImportState<CONFIG> state) {
72
        TransactionStatus tx = this.startTransaction();
73
        for (int plate = 1; plate < 22 ; plate++){
74
            try {
75
                handleSinglePlate(state, plate);
76
            } catch (Exception e) {
77
                logger.error("Error when handling plate " + plate);
78
                e.printStackTrace();
79
            }
80
        }
81
        this.commitTransaction(tx);
82
    }
83

    
84
    /**
85
     * @param state
86
     * @param plate
87
     */
88
    private void handleSinglePlate(SimpleExcelTaxonImportState<CONFIG> state, int plate) {
89
        String fill = plate < 10 ? "0" : "";
90
        String plateStr = "Plate_" + fill + plate + "/";
91
        String fullFolderUrl = BASE_URL + plateStr;
92
        String fullThumbUrl = BASE_URL + "thumbs/" + plateStr;
93
        String folderStr = IMAGE_FOLDER + plateStr;
94
        File file = new File(folderStr);
95
        String[] list = file.list();
96
        for (String fileStr : list){
97
            try {
98
                handleSingleFile(state, fullFolderUrl, fullThumbUrl, fileStr, plate);
99
            } catch (Exception e) {
100
                logger.error("Error when handling file: " + fileStr + " in plate " + plate);
101
                e.printStackTrace();
102
            }
103
        }
104
    }
105

    
106
    /**
107
     * @param state
108
     * @param fullFolderUrl
109
     * @param fullThumbUrl
110
     * @param fileStr
111
     * @param plate
112
     */
113
    private void handleSingleFile(SimpleExcelTaxonImportState<CONFIG> state,
114
            String fullFolderUrl, String fullThumbUrl, String fileStr, int plate) {
115
        String[] taxonNameAndArtist = getTaxonName(fileStr);
116
        String taxonNameStr = taxonNameAndArtist[0];
117
        String taxonNameStr2 = null;
118
        String artistStr = taxonNameAndArtist[1];
119
        if (fileStr.equals("RamondaSerbica(L)+Nathaliae(R)1.jpg")){
120
            taxonNameStr = "Ramonda serbica";
121
            taxonNameStr2 = "Ramonda nathaliae";
122
        }else if (fileStr.contains("HypericumCerastioides")){
123
            taxonNameStr = taxonNameStr.replace("HypericumCerastoides", "HypericumCerastioides");
124
        }else if (fileStr.contains("StachysScardica")){
125
            taxonNameStr = taxonNameStr.replace("StachysScardica", "BetonicaScardica");
126
        }else if (fileStr.contains("OleaEuropaeaOleaster ")){
127
            taxonNameStr = taxonNameStr.replace("OleaEuropaeaOleaster", "OleaEuropaeaEuropaea");
128
        }
129

    
130
        try {
131

    
132
            Media media = getImageMedia(fullFolderUrl + fileStr, fullThumbUrl + fileStr, true);
133

    
134
            //image metadata
135
            URI uri = URI.create(fullThumbUrl + fileStr);
136
            try{
137
                IImageMetadata metadata = Sanselan.getMetadata(uri.toURL().openStream(), null);
138
                ArrayList<?> items = metadata.getItems();
139
                for (Object object : items){
140
                    Item item = (Item) object;
141
//                    System.out.println(item.getKeyword() +  ":    " + item.getText());
142
                    String keyword = item.getKeyword().toLowerCase();
143
                    String value = removeQuots(item.getText());
144
                    if("image description".equals(keyword)){
145
                        media.putDescription(Language.DEFAULT(), value);
146
                    }else if ("artist".equals(keyword)){
147
                        if (isNotBlank(artistStr) && ! value.contains(artistStr)){
148
                            logger.warn("Artist and artistStr are different: " +  artistStr  + "; " + value);
149
                        }
150
                        artistStr = value;
151
                    }else if ("date time original".equalsIgnoreCase(item.getKeyword())){
152
                        DateTimeFormatter f = DateTimeFormat.forPattern("yyyy:MM:dd HH:mm:ss");
153
                        DateTime created = f.withZone(DateTimeZone.forID("Europe/Athens")).parseDateTime(value);
154
                        media.setMediaCreated(TimePeriod.NewInstance(created));
155
                    }
156
                }
157
            } catch (ImageReadException | IOException e1) {
158
                e1.printStackTrace();
159
            }
160
            if (isNotBlank(artistStr)){
161
                Person person = Person.NewInstance();
162
                String[] split = artistStr.split("\\+");
163
                if (split.length == 1){
164
                    person.setFamilyName(artistStr);
165
                }else if (split.length == 2){
166
                    person.setGivenName(split[0]);
167
                    person.setFamilyName(split[1]);
168
                }else{
169
                    person.setTitleCache("artistStr", true);
170
                }
171
                person = (Person)deduplicationHelper.getExistingAuthor(state, person);
172

    
173
                media.setArtist(person);
174
                //copyright
175
                Rights right = Rights.NewInstance();
176
                right.setType(RightsType.COPYRIGHT());
177
                right.setAgent(person);
178
                right = deduplicationHelper.getExistingCopyright(state, right);
179
                media.addRights(right);
180
            }
181

    
182
            String detail = "p. " + FloraHellenicaImageCaptionImport.startPage + 1 + plate *2;
183
            media.addPrimaryMediaSource(getSecReference(state), detail);
184

    
185

    
186
            Taxon taxon = getAcceptedTaxon(taxonNameStr);
187
            makeTextData(fileStr, media, taxon);
188
            if (taxonNameStr2 != null){
189
                Taxon taxon2 = getAcceptedTaxon(taxonNameStr);
190
                makeTextData(fileStr, media, taxon2);
191
            }
192

    
193

    
194
            if (taxonNameStr2 == null){
195
                media.putTitle(Language.LATIN(), taxon == null ? taxonNameStr :
196
                    taxon.getName().getTitleCache());
197
            }else{
198
                media.putTitle(Language.LATIN(), "Ramonda serbica(L) + R. nathaliae(R)");
199
            }
200

    
201

    
202
        } catch (Exception e) {
203
            e.printStackTrace();
204
            return;
205
        }
206
    }
207

    
208
    private String removeQuots(String text) {
209
        if (text.startsWith("'") && text.endsWith("'")){
210
            return text.substring(1, text.length() -1);
211
        }else{
212
            return text;
213
        }
214
    }
215

    
216
    private Reference secReference;
217
    private Reference getSecReference(SimpleExcelTaxonImportState<CONFIG> state) {
218
        if (secReference != null){
219
            secReference = getReferenceService().find(state.getConfig().getSecReference().getUuid());
220
        }
221
        return secReference;
222
    }
223

    
224

    
225
    /**
226
     * Gets the image gallery, creates
227
     */
228
    private void makeTextData(String fileStr, Media media, Taxon taxon) {
229
        if (taxon == null){
230
            logger.warn("Taxon not found for image " + fileStr + "."
231
                    + "Media could not be attached to taxon.");
232
            getMediaService().saveOrUpdate(media);
233
            return;
234
        }
235
        TaxonDescription imageGallery = taxon.getImageGallery(true);
236
        TextData textData;
237
        if (imageGallery.getElements().isEmpty()){
238
            textData = TextData.NewInstance();
239
            textData.setFeature(Feature.IMAGE());
240
        }else{
241
            textData = CdmBase.deproxy(imageGallery.getElements().iterator().next(), TextData.class);
242
        }
243
        imageGallery.addElement(textData);
244
        textData.addMedia(media);
245
    }
246

    
247
    /**
248
     * @param taxonNameStr
249
     * @return
250
     */
251
    private Taxon getAcceptedTaxon(String taxonNameStr) {
252

    
253
        MatchingTaxonConfigurator config = new MatchingTaxonConfigurator();
254
        taxonNameStr = adaptName(taxonNameStr);
255
        config.setTaxonNameTitle(taxonNameStr);
256
        config.setIncludeSynonyms(true);
257
        List<TaxonBase> list = getTaxonService().findTaxaByName(config);
258
        if (list.isEmpty()){
259
            logger.warn("Taxon not found for media: " + taxonNameStr);
260
            return null;
261
        }else{
262
            if (list.size()>1){
263
                logger.warn("More than 1 taxon found for media: " + taxonNameStr);
264
            }
265
            TaxonBase<?> taxonBase = list.get(0);
266
            Taxon result;
267
            if (taxonBase.isInstanceOf(Synonym.class)){
268
                result = CdmBase.deproxy(taxonBase, Synonym.class).getAcceptedTaxon();
269
            }else{
270
                result = CdmBase.deproxy(taxonBase, Taxon.class);
271
            }
272
            return result;
273
        }
274
    }
275

    
276
    /**
277
     * @param taxonNameStr
278
     * @return
279
     */
280
    private String adaptName(String taxonNameStr) {
281
        if (taxonNameStr.equals("Hypericum cerastoides")){
282
            taxonNameStr = "Hypericum cerastioides";
283
        }
284
        return taxonNameStr;
285
    }
286

    
287
    /**
288
     * @param fileStr
289
     * @return
290
     */
291
    private String[] getTaxonName(String fileStr) {
292
        String[] result = new String[2];
293
        fileStr = fileStr.split("\\.")[0];
294
        fileStr = fileStr.replaceAll("[0-9]", "");
295
        String[] x = fileStr.split("_");
296
        if (x.length == 2){
297
            result[1] = x[1];
298
        }
299

    
300
        fileStr = splitCamelCase(x[0]);
301
        String[] split = fileStr.split(" ");
302
        String name = split[0] + " " + split[1].toLowerCase() +
303
                (split.length > 2 ? " subsp. " + split[2].toLowerCase() : "");
304
        result[0] = name;
305
        System.out.println(result[0] + (result[1] != null ?  "   Artist: " + result[1]: ""));
306
        return result;
307
    }
308

    
309
    //from http://stackoverflow.com/questions/2559759/how-do-i-convert-camelcase-into-human-readable-names-in-java
310
    static String splitCamelCase(String s) {
311
        return s.replaceAll(
312
           String.format("%s",
313
//              "(?<=[A-Z])(?=[A-Z][a-z])",
314
              "(?<=[^A-Z])(?=[A-Z])"
315
//              "(?<=[A-Za-z])(?=[^A-Za-z])"
316
           ),
317
           " "
318
        );
319
     }
320

    
321
    /**
322
     * {@inheritDoc}
323
     */
324
    @Override
325
    protected boolean doCheck(SimpleExcelTaxonImportState<CONFIG> state) {
326
        return false;
327
    }
328

    
329
    /**
330
     * {@inheritDoc}
331
     */
332
    @Override
333
    protected boolean isIgnore(SimpleExcelTaxonImportState<CONFIG> state) {
334
        return ! state.getConfig().isDoImages();
335
    }
336

    
337

    
338

    
339
}
(5-5/16)