Project

General

Profile

1
package eu.dnetlib.openaire.directindex.objects;
2

    
3
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
4
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
5
import eu.dnetlib.miscutils.datetime.DateUtils;
6
import eu.dnetlib.miscutils.functional.hash.Hashing;
7
import eu.dnetlib.miscutils.functional.string.EscapeXml;
8
import eu.dnetlib.openaire.directindex.api.DirecIndexApiException;
9
import eu.dnetlib.openaire.directindex.api.OpenAIRESubmitterUtils;
10
import org.apache.commons.lang.StringUtils;
11
import org.apache.commons.logging.Log;
12
import org.apache.commons.logging.LogFactory;
13
import org.apache.velocity.app.VelocityEngine;
14
import org.springframework.ui.velocity.VelocityEngineUtils;
15

    
16
import java.text.SimpleDateFormat;
17
import java.util.Date;
18
import java.util.HashMap;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.concurrent.TimeUnit;
22

    
23
public class ResultEntryToOaf {
24

    
25
    private static final Log log = LogFactory.getLog(ResultEntryToOaf.class);
26

    
27
    private static long last_cache_update = 0;
28
    private static final Map<String, Map<String, String>> cached_vocabularies = new HashMap<>();
29
    private static final Map<String, DatasourceEntry> cached_datasources = new HashMap<>();
30
    private static final Map<String, String> cached_contexts = new HashMap<>();
31

    
32
    private OpenAIRESubmitterUtils utils;
33

    
34
    public ResultEntryToOaf(final String community_api){
35
        utils = new OpenAIRESubmitterUtils(community_api);
36
    }
37

    
38
    public String asOafRecord(final ResultEntry entry, final VelocityEngine ve,
39
                              final ISLookUpService lookupService,
40
                              final String oafSchemaLocation) throws Exception {
41

    
42
        if (StringUtils.isBlank(entry.getOriginalId())
43
                && StringUtils
44
                .isBlank(entry.getOpenaireId())) { throw new DirecIndexApiException("One of the following fields is required: originalId or openaireId"); }
45
        if (StringUtils.isBlank(entry.getTitle())) { throw new DirecIndexApiException("A required field is missing: title"); }
46
        if (StringUtils.isBlank(entry.getUrl())) { throw new DirecIndexApiException("A required field is missing: url"); }
47
        if (StringUtils.isBlank(entry.getLicenseCode()) && StringUtils.isBlank(entry.getAccessRightCode())) { throw new DirecIndexApiException("A required field is missing: accessRightCode"); }
48
        if (StringUtils.isBlank(entry.getResourceType())) { throw new DirecIndexApiException("A required field is missing: resourceType"); }
49
        if (StringUtils.isBlank(entry.getCollectedFromId())) { throw new DirecIndexApiException("A required field is missing: collectedFromId"); }
50
        if (StringUtils.isBlank(entry.getType())) { throw new DirecIndexApiException("A required field is missing: type"); }
51

    
52
        final DatasourceEntry collectedFromEntry = getDatasourceInfo(entry.getCollectedFromId(), lookupService);
53
        final DatasourceEntry hostedByEntry = getDatasourceInfo(entry.getHostedById(), lookupService);
54

    
55
        if (StringUtils.isBlank(entry.getOpenaireId())) {
56
            entry.setOpenaireId(calculateOpenaireId(entry.getOriginalId(), collectedFromEntry));
57
        }
58

    
59
        if (!entry.getOpenaireId()
60
                .matches("^\\w{12}::\\w{32}$")) { throw new DirecIndexApiException(
61
                "Invalid openaireId: " + entry.getOpenaireId() + " - regex ^\\w{12}::\\w{32}$ not matched"); }
62

    
63

    
64
        final List<OpenAIRESubmitterUtils.ContextInfo> contextInfos = utils.processContexts(entry.getContexts(), getContexts(lookupService));
65

    
66
        final Map<String, Object> model = new HashMap<>();
67
        model.put("esc", new EscapeXml());
68
        model.put("util",utils);
69
        model.put("pub", this);
70
        model.put("objIdentifier", entry.getOpenaireId());
71
        model.put("oafSchemaLocation", oafSchemaLocation);
72
        model.put("resultTypes", getVocabulary("dnet:result_typologies", lookupService));
73
        model.put("rights", getVocabulary("dnet:access_modes", lookupService));
74
        model.put("resourceTypes", getVocabulary("dnet:publication_resource", lookupService));
75
        model.put("pidTypes", getVocabulary("dnet:pid_types", lookupService));
76
        model.put("languages", getVocabulary("dnet:languages", lookupService));
77
        model.put("contexts", getContexts(lookupService));
78
        model.put("contextInfo",contextInfos);
79
        model.put("dateOfCollection", new SimpleDateFormat("yyyy-MM-dd\'T\'hh:mm:ss\'Z\'").format(new Date()));
80
        model.put("collectedFrom", collectedFromEntry);
81
        model.put("hostedBy", hostedByEntry);
82

    
83
        return VelocityEngineUtils.mergeTemplateIntoString(ve, "/eu/dnetlib/openaire/directindex/indexRecord.xml.vm", "UTF-8", model);
84
    }
85

    
86
    private synchronized static DatasourceEntry getDatasourceInfo(final String dsId, final ISLookUpService lookupService) throws ISLookUpException {
87
        if (StringUtils
88
                .isBlank(dsId)) { return new DatasourceEntry("openaire____::1256f046-bf1f-4afc-8b47-d0b147148b18", "Unknown Repository", "unknown_____"); }
89

    
90
        if (!cached_datasources.containsKey(dsId)) {
91
            final String query =
92
                    "collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')//CONFIGURATION[./DATASOURCE_ORIGINAL_ID='" + dsId
93
                            + "']/concat(./OFFICIAL_NAME, ' @@@ ', .//FIELD/value[../key='NamespacePrefix'])";
94
            final String s = lookupService.getResourceProfileByQuery(query);
95
            final String[] arr = s.split("@@@");
96

    
97
            final DatasourceEntry ds = new DatasourceEntry(dsId, arr[0].trim(), arr[1].trim());
98

    
99
            if (StringUtils.isBlank(ds.getName()) || StringUtils.isBlank(ds.getPrefix())) {
100
                log.error("Invalid datasource id: " + dsId);
101
                throw new ISLookUpException("Invalid datasource id: " + dsId);
102
            } else {
103
                cached_datasources.put(dsId, ds);
104
            }
105
        }
106

    
107
        return cached_datasources.get(dsId);
108

    
109
    }
110

    
111
    private synchronized static Map<String, String> getVocabulary(final String voc, final ISLookUpService lookupService) throws ISLookUpException {
112

    
113
        if (DateUtils.now() - last_cache_update < TimeUnit.MINUTES.toMillis(15) && cached_vocabularies.containsKey(voc)) {
114
            return cached_vocabularies.get(voc);
115
        } else {
116
            final String query = "collection('/db/DRIVER/VocabularyDSResources/VocabularyDSResourceType')[.//VOCABULARY_NAME/@code='" + voc
117
                    + "']//TERM/concat(@code, ' @@@ ', @english_name)";
118

    
119
            final Map<String, String> map = new HashMap<>();
120
            for (final String s : lookupService.quickSearchProfile(query)) {
121
                final String[] arr = s.split("@@@");
122
                map.put(arr[0].trim(), arr[1].trim());
123
            }
124

    
125
            cached_vocabularies.put(voc, map);
126

    
127
            last_cache_update = DateUtils.now();
128

    
129
            return map;
130
        }
131
    }
132

    
133
    private synchronized static Map<String, String> getContexts(final ISLookUpService lookupService) throws ISLookUpException {
134
        if (DateUtils.now() - last_cache_update > TimeUnit.MINUTES.toMillis(15) || cached_contexts.isEmpty()) {
135
            final String query =
136
                    "collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')[.//context/@type='community' or .//context/@type='ri']//*[name()='context' or name()='category' or name()='concept']/concat(@id, ' @@@ ', @label)";
137

    
138
            cached_contexts.clear();
139
            for (final String s : lookupService.quickSearchProfile(query)) {
140
                final String[] arr = s.split("@@@");
141
                cached_contexts.put(arr[0].trim(), arr[1].trim());
142
            }
143
            last_cache_update = DateUtils.now();
144
        }
145
        return cached_contexts;
146
    }
147

    
148
    private static String calculateOpenaireId(final String originalId, final DatasourceEntry collectedFromEntry) {
149
        return collectedFromEntry.getPrefix() + "::" + Hashing.md5(originalId);
150
    }
151

    
152
    public static String calculateOpenaireId(final String originalId, final String collectedFromId, final ISLookUpService lookupService)
153
            throws ISLookUpException {
154
        return calculateOpenaireId(originalId, getDatasourceInfo(collectedFromId, lookupService));
155
    }
156
    public OpenAIRESubmitterUtils getUtils() {
157
        return utils;
158
    }
159

    
160
    public void setUtils(OpenAIRESubmitterUtils utils) {
161
        this.utils = utils;
162
    }
163
}
(4-4/5)