Project

General

Profile

« Previous | Next » 

Revision 62685

Added by Alessia Bardi over 1 year ago

[maven-release-plugin] copy for tag dnet-directindex-api-3.0.1

View differences:

modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/api/IndexClientManager.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import eu.dnetlib.functionality.index.utils.ZkServers;
4
import org.apache.commons.logging.Log;
5
import org.apache.commons.logging.LogFactory;
6
import org.apache.solr.client.solrj.impl.CloudSolrClient;
7

  
8
public class IndexClientManager {
9

  
10
    private static final Log log = LogFactory.getLog(IndexClientManager.class);
11

  
12
    private CloudSolrClient client = null;
13

  
14
    public CloudSolrClient getClient(IndexDsInfo info) {
15

  
16
        if (client == null) {
17
            log.info(String.format("Initializing solr client (%s) with collection %s", info.getIndexBaseUrl(), info.getColl()));
18
            ZkServers zk = ZkServers.newInstance(info.getIndexBaseUrl());
19
            CloudSolrClient.Builder builder = new CloudSolrClient.Builder(zk.getHosts(), zk.getChroot()).withParallelUpdates(true);
20
            client = builder.build();
21
        }
22
        client.setDefaultCollection(info.getColl());
23
        return client;
24
    }
25

  
26
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/api/ResultSubmitterService.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import org.apache.commons.logging.Log;
4
import org.apache.commons.logging.LogFactory;
5
import org.apache.solr.client.solrj.impl.CloudSolrClient;
6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.beans.factory.annotation.Value;
8

  
9
import javax.annotation.Resource;
10
import java.util.concurrent.Executors;
11
import java.util.concurrent.ScheduledExecutorService;
12
import java.util.concurrent.TimeUnit;
13

  
14
public class ResultSubmitterService {
15

  
16
    private static final Log log = LogFactory.getLog(ResultSubmitterService.class);
17

  
18
    @Autowired
19
    private IndexDSRetriever indexDSRetriever;
20

  
21
    @Resource(name = "indexClientManager")
22
    private IndexClientManager clientManager;
23

  
24
    /**
25
     * Autocommit feature activation flag
26
     */
27
    @Value(value = "${openaire.api.directindex.autocommit.active}")
28
    private boolean autocommitactive;
29

  
30
    /**
31
     * Autocommit frequency (Seconds)
32
     */
33
    @Value(value = "${openaire.api.directindex.autocommit.frequency}")
34
    private long commitfrquency = 60;
35

  
36
    private ScheduledExecutorService executor;
37

  
38
    public ResultSubmitterService() {
39
        executor = Executors.newSingleThreadScheduledExecutor();
40
        updateCommitSchedule();
41
    }
42

  
43
    private void updateCommitSchedule() {
44
        log.info("updating commit schedule");
45

  
46
        executor.scheduleAtFixedRate(() -> {
47
            if (isAutocommitactive()) {
48
                try {
49
                    IndexDsInfo info = indexDSRetriever.calculateCurrentIndexDsInfo();
50
                    CloudSolrClient client = clientManager.getClient(info);
51
                    log.info("performing commit on " + info.getColl());
52
                    client.commit();
53
                } catch (Throwable e) {
54
                    log.error("unable to perform commit", e);
55
                }
56
            }
57
        }, 0, getCommitfrquency(), TimeUnit.SECONDS);
58
    }
59

  
60
    public boolean isAutocommitactive() {
61
        return autocommitactive;
62
    }
63

  
64
    public synchronized void setAutocommitactive(boolean autocommitactive) {
65
        this.autocommitactive = autocommitactive;
66
    }
67

  
68
    public long getCommitfrquency() {
69
        return commitfrquency;
70
    }
71

  
72
    public synchronized void setCommitfrquency(long commitfrquency) {
73
        this.commitfrquency = commitfrquency;
74
    }
75

  
76
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/api/DirecIndexApiException.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import eu.dnetlib.common.rmi.RMIException;
4

  
5
public class DirecIndexApiException extends RMIException {
6

  
7
	/**
8
	 *
9
	 */
10
	private static final long serialVersionUID = -3888037031334809448L;
11

  
12
	public DirecIndexApiException(final String string) {
13
		super(string);
14
	}
15

  
16
	public DirecIndexApiException(final String string, final Throwable exception) {
17
		super(string, exception);
18
	}
19

  
20
	public DirecIndexApiException(final Throwable exception) {
21
		super(exception);
22
	}
23

  
24
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/objects/DsmSearchRequest.java
1
package eu.dnetlib.openaire.directindex.objects;
2

  
3
import java.io.Serializable;
4

  
5
public class DsmSearchRequest implements Serializable {
6

  
7
	private static final long serialVersionUID = -2532361140043817319L;
8

  
9
	private String id;
10

  
11
	public DsmSearchRequest() {}
12

  
13
	public DsmSearchRequest(final String id) {
14
		this.id = id;
15
	}
16

  
17
	public String getId() {
18
		return id;
19
	}
20

  
21
	public void setId(final String id) {
22
		this.id = id;
23
	}
24
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/objects/ResultEntry.java
1
package eu.dnetlib.openaire.directindex.objects;
2

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

  
18
import java.text.SimpleDateFormat;
19
import java.util.*;
20
import java.util.concurrent.TimeUnit;
21

  
22
/**
23
 * Created by michele on 02/12/15.
24
 */
25
public class ResultEntry {
26

  
27

  
28
	private String openaireId;
29
	private String originalId;
30
	private String title;
31
	private List<String> authors = new ArrayList<>();
32
	private String publisher;
33
	private String description;
34
	private String language;
35
	private List<PidEntry> pids = new ArrayList<>();
36
	/**
37
	 * @Deprecated: use accessRightCode
38
	 */
39
	@Deprecated
40
	private String licenseCode;
41
	private String accessRightCode;
42
	private String embargoEndDate;
43
	/**
44
	 * One of publication, dataset, software, other. Default value is publication.
45
	 */
46
	private String type = "publication";
47
	private String resourceType;
48
	private String url;
49
	private String collectedFromId;
50
	private String hostedById;
51

  
52
	// String according to the EGI context profile, example: egi::classification::natsc::math
53
	private List<String> contexts = new ArrayList<>();
54

  
55
	// String according to openaire guidelines:
56
	// info:eu-repo/grantAgreement/Funder/FundingProgram/ProjectID/[Jurisdiction]/[ProjectName]/[ProjectAcronym]
57
	private List<String> linksToProjects = new ArrayList<>();
58

  
59
	private static final Log log = LogFactory.getLog(ResultEntry.class);
60

  
61
	public ResultEntry() {}
62

  
63
	public String getOpenaireId() {
64
		return openaireId;
65
	}
66

  
67
	public void setOpenaireId(final String openaireId) {
68
		this.openaireId = openaireId;
69
	}
70

  
71
	public String getOriginalId() {
72
		return originalId;
73
	}
74

  
75
	public void setOriginalId(final String originalId) {
76
		this.originalId = originalId;
77
	}
78

  
79
	@ApiModelProperty(required = true)
80
	public String getTitle() {
81
		return title;
82
	}
83

  
84
	public void setTitle(final String title) {
85
		this.title = title;
86
	}
87

  
88
	public List<String> getAuthors() {
89
		return authors;
90
	}
91

  
92
	public void setAuthors(final List<String> authors) {
93
		this.authors = authors;
94
	}
95

  
96
	public String getPublisher() {
97
		return publisher;
98
	}
99

  
100
	public void setPublisher(final String publisher) {
101
		this.publisher = publisher;
102
	}
103

  
104
	public String getDescription() {
105
		return description;
106
	}
107

  
108
	public void setDescription(final String description) {
109
		this.description = description;
110
	}
111

  
112
	@ApiModelProperty(value = "ISO Alpha-3 code. E.g. 'eng', 'ita'")
113
	public String getLanguage() {
114
		return language;
115
	}
116

  
117
	public void setLanguage(final String language) {
118
		this.language = language;
119
	}
120

  
121
	public List<PidEntry> getPids() {
122
		return pids;
123
	}
124

  
125
	public void setPids(final List<PidEntry> pids) {
126
		this.pids = pids;
127
	}
128

  
129
	@Deprecated
130
	@ApiModelProperty(required = false, allowableValues = "OPEN, CLOSED, RESTRICTED, EMBARGO, UNKNOWN, OTHER, OPEN SOURCE")
131
	public String getLicenseCode() {
132
		return licenseCode;
133
	}
134
	@Deprecated
135
	public void setLicenseCode(final String licenseCode) {
136
		this.licenseCode = licenseCode;
137
	}
138

  
139
	/**
140
	 * Set required = true when the deprecated licenseCode is not used anymore by our client and it is removed
141
	 * @return access rights code
142
	 */
143
	@ApiModelProperty(required = false, allowableValues = "OPEN, CLOSED, RESTRICTED, EMBARGO, UNKNOWN, OTHER, OPEN SOURCE")
144
	public String getAccessRightCode() {
145
		return accessRightCode;
146
	}
147

  
148
	public void setAccessRightCode(final String accessRightCode) {
149
		this.accessRightCode = accessRightCode;
150
	}
151

  
152
	@ApiModelProperty(required = true, value = "Use 001 for articles, 021 for datasets, 0029 for software. See: http://api.openaire.eu/vocabularies/dnet:publication_resource for all the available resource types.")
153
	public String getResourceType() {
154
		return resourceType;
155
	}
156

  
157
	public void setResourceType(final String resourceType) {
158
		this.resourceType = resourceType;
159
	}
160

  
161
	@ApiModelProperty(required = true)
162
	public String getUrl() {
163
		return url;
164
	}
165

  
166
	public void setUrl(final String url) {
167
		this.url = url;
168
	}
169

  
170
	@ApiModelProperty(required = true, value = "Use opendoar___::2659 for Zenodo Publications; re3data_____::r3d100010468 for Zenodo datasets; infrastruct::openaire for OpenAIRE portal.")
171
	public String getCollectedFromId() {
172
		return collectedFromId;
173
	}
174

  
175
	public void setCollectedFromId(final String collectedFromId) {
176
		this.collectedFromId = collectedFromId;
177
	}
178

  
179
	public String getHostedById() {
180
		return hostedById;
181
	}
182

  
183
	public void setHostedById(final String hostedById) {
184
		this.hostedById = hostedById;
185
	}
186

  
187
	@ApiModelProperty(value = "E.g. fet, egi::classification::natsc::math::pure, egi::projects::EMI")
188
	public List<String> getContexts() {
189
		return contexts;
190
	}
191

  
192
	public void setContexts(final List<String> contexts) {
193
		this.contexts = contexts;
194
	}
195

  
196
	@ApiModelProperty(value = "E.g. info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus")
197
	public List<String> getLinksToProjects() {
198
		return linksToProjects;
199
	}
200

  
201
	public void setLinksToProjects(final List<String> linksToProjects) {
202
		this.linksToProjects = linksToProjects;
203
	}
204

  
205
	@ApiModelProperty(allowableValues = "publication, dataset, software, other")
206
	public String getType() {
207
		return type;
208
	}
209

  
210
	public void setType(final String type) {
211
		this.type = type;
212
	}
213

  
214
	public String getEmbargoEndDate() {
215
		return embargoEndDate;
216
	}
217

  
218
	public void setEmbargoEndDate(final String embargoEndDate) {
219
		this.embargoEndDate = embargoEndDate;
220
	}
221

  
222
	@Override
223
	public String toString() {
224
		return new Gson().toJson(this);
225
	}
226

  
227
	public String getAnyId() {
228
		return StringUtils.isNotBlank(openaireId) ? openaireId : originalId;
229
	}
230
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/objects/PidEntry.java
1
package eu.dnetlib.openaire.directindex.objects;
2

  
3
import io.swagger.annotations.ApiModelProperty;
4

  
5
/**
6
 * Created by michele on 02/12/15.
7
 */
8
public class PidEntry {
9

  
10
	private String type;
11
	private String value;
12

  
13
	public PidEntry() {
14
	}
15

  
16
	public PidEntry(final String type, final String value) {
17
		this.type = type;
18
		this.value = value;
19
	}
20

  
21
	@ApiModelProperty(required = true, value = "E.g. doi, pmc, urn. See http://api.openaire.eu/vocabularies/dnet:pid_types")
22
	public String getType() {
23
		return type;
24
	}
25

  
26
	public void setType(final String type) {
27
		this.type = type;
28
	}
29

  
30
	@ApiModelProperty(required = true)
31
	public String getValue() {
32
		return value;
33
	}
34

  
35
	public void setValue(final String value) {
36
		this.value = value;
37
	}
38
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/objects/ResultEntryToOaf.java
1
package eu.dnetlib.openaire.directindex.objects;
2

  
3
import java.text.SimpleDateFormat;
4
import java.util.Date;
5
import java.util.HashMap;
6
import java.util.List;
7
import java.util.Map;
8
import java.util.concurrent.TimeUnit;
9

  
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 eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
17
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
18
import eu.dnetlib.miscutils.datetime.DateUtils;
19
import eu.dnetlib.miscutils.functional.hash.Hashing;
20
import eu.dnetlib.miscutils.functional.string.EscapeXml;
21
import eu.dnetlib.openaire.directindex.api.DirecIndexApiException;
22
import eu.dnetlib.openaire.directindex.api.OpenAIRESubmitterUtils;
23

  
24
public class ResultEntryToOaf {
25

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

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

  
33
	private OpenAIRESubmitterUtils utils;
34

  
35
	public ResultEntryToOaf(final OpenAIRESubmitterUtils utils) {
36
		this.utils = utils;
37
	}
38

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

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

  
58
		final DatasourceEntry collectedFromEntry = getDatasourceInfo(entry.getCollectedFromId(), utils);
59
		final DatasourceEntry hostedByEntry = getDatasourceInfo(entry.getHostedById(), utils);
60

  
61
		if (StringUtils.isBlank(entry.getOpenaireId())) {
62
			entry.setOpenaireId(calculateOpenaireId(entry.getOriginalId(), collectedFromEntry));
63
		}
64

  
65
		if (!entry.getOpenaireId()
66
			.matches("^\\w{12}::\\w{32}$")) {
67
			throw new DirecIndexApiException(
68
				"Invalid openaireId: " + entry.getOpenaireId() + " - regex ^\\w{12}::\\w{32}$ not matched");
69
		}
70

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

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

  
90
		return VelocityEngineUtils.mergeTemplateIntoString(ve, "/eu/dnetlib/openaire/directindex/indexRecord.xml.vm", "UTF-8", model);
91
	}
92

  
93
	private synchronized static DatasourceEntry getDatasourceInfo(final String dsId, final OpenAIRESubmitterUtils utils) throws ISLookUpException {
94
		if (StringUtils
95
			.isBlank(dsId)) {
96
			return new DatasourceEntry("openaire____::1256f046-bf1f-4afc-8b47-d0b147148b18", "Unknown Repository", "unknown_____");
97
		}
98

  
99
		if (!cached_datasources.containsKey(dsId)) {
100

  
101
			final DatasourceEntry ds = utils.findDatasource(dsId);
102

  
103
			if (ds == null || StringUtils.isBlank(ds.getName()) || StringUtils.isBlank(ds.getPrefix())) {
104
				log.error("Invalid datasource id: " + dsId);
105
				throw new ISLookUpException("Invalid datasource id: " + dsId);
106
			} else {
107
				cached_datasources.put(dsId, ds);
108
			}
109
		}
110

  
111
		return cached_datasources.get(dsId);
112

  
113
	}
114

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

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

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

  
129
			cached_vocabularies.put(voc, map);
130

  
131
			last_cache_update = DateUtils.now();
132

  
133
			return map;
134
		}
135
	}
136

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

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

  
152
	private static String calculateOpenaireId(final String originalId, final DatasourceEntry collectedFromEntry) {
153
		return collectedFromEntry.getPrefix() + "::" + Hashing.md5(originalId);
154
	}
155

  
156
	public static String calculateOpenaireId(final String originalId, final String collectedFromId, final OpenAIRESubmitterUtils utils)
157
		throws ISLookUpException {
158
		return calculateOpenaireId(originalId, getDatasourceInfo(collectedFromId, utils));
159
	}
160

  
161
	public OpenAIRESubmitterUtils getUtils() {
162
		return utils;
163
	}
164

  
165
	public void setUtils(final OpenAIRESubmitterUtils utils) {
166
		this.utils = utils;
167
	}
168
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/pom.xml
1
<?xml version="1.0" ?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
	<parent>
4
		<groupId>eu.dnetlib</groupId>
5
		<artifactId>dnet45-parent</artifactId>
6
		<version>1.0.0</version>
7
		<relativePath />
8
	</parent>
9
	<modelVersion>4.0.0</modelVersion>
10
	<groupId>eu.dnetlib</groupId>
11
	<artifactId>dnet-directindex-api</artifactId>
12
	<packaging>jar</packaging>
13
	<version>3.0.1</version>
14

  
15
	<scm>
16
		<developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet45/modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1</developerConnection>
17
	</scm>
18
	<dependencies>
19
		<dependency>
20
			<groupId>eu.dnetlib</groupId>
21
			<artifactId>dnet-openaireplus-mapping-utils</artifactId>
22
			<version>[7.0.0,8.0.0)</version>
23
			<exclusions>
24
				<exclusion>
25
					<groupId>eu.dnetlib</groupId>
26
					<artifactId>dnet-hadoop-commons</artifactId>
27
				</exclusion>
28
			</exclusions>
29
		</dependency>
30
		<dependency>
31
			<groupId>eu.dnetlib</groupId>
32
			<artifactId>dnet-index-client</artifactId>
33
			<version>[3.0.0,4.0.0)</version>
34
		</dependency>
35
		<dependency>
36
			<groupId>junit</groupId>
37
			<artifactId>junit</artifactId>
38
			<version>${junit.version}</version>
39
			<scope>test</scope>
40
		</dependency>
41
		<dependency>
42
			<groupId>io.springfox</groupId>
43
			<artifactId>springfox-swagger2</artifactId>
44
			<version>${springfox-version}</version>
45
		</dependency>
46
		<dependency>
47
			<groupId>org.mockito</groupId>
48
			<artifactId>mockito-core</artifactId>
49
			<version>1.9.5</version>
50
		</dependency>
51
		<dependency>
52
			<groupId>org.apache.velocity</groupId>
53
			<artifactId>velocity</artifactId>
54
			<version>1.7</version>
55
			<exclusions>
56
				<exclusion>
57
					<artifactId>antlr</artifactId>
58
					<groupId>antlr</groupId>
59
				</exclusion>
60
			</exclusions>
61
		</dependency>
62
		<dependency>
63
			<groupId>org.apache.velocity</groupId>
64
			<artifactId>velocity-tools</artifactId>
65
			<version>2.0</version>
66
			<exclusions>
67
				<exclusion>
68
					<artifactId>antlr</artifactId>
69
					<groupId>antlr</groupId>
70
				</exclusion>
71
			</exclusions>
72
		</dependency>
73
		<dependency>
74
			<groupId>org.springframework</groupId>
75
			<artifactId>spring-context-support</artifactId>
76
			<version>${spring.version}</version>
77
		</dependency>
78
		<dependency>
79
			<groupId>com.fasterxml.jackson.core</groupId>
80
			<artifactId>jackson-annotations</artifactId>
81
			<version>2.9.4</version>
82
		</dependency>
83
    </dependencies>
84

  
85
	<properties>
86
		<springfox-version>2.5.0</springfox-version>
87
	</properties>
88
</project>
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/java/eu/dnetlib/openaire/directindex/objects/DatasourceEntry.java
1
package eu.dnetlib.openaire.directindex.objects;
2

  
3
import eu.dnetlib.miscutils.functional.hash.Hashing;
4
import org.apache.commons.lang.StringUtils;
5

  
6
/**
7
 * Created by michele on 02/12/15.
8
 */
9
public class DatasourceEntry {
10

  
11
	private String id;
12
	private String name;
13
	private String prefix;
14

  
15
	public DatasourceEntry() {
16
	}
17

  
18
	public DatasourceEntry(final String id, final String name, final String prefix) {
19
		this.id = id;
20
		this.name = name;
21
		this.prefix = prefix;
22
	}
23

  
24
	public String getId() {
25
		return id;
26
	}
27

  
28
	public void setId(final String id) {
29
		this.id = id;
30
	}
31

  
32
	public String getName() {
33
		return name;
34
	}
35

  
36
	public void setName(final String name) {
37
		this.name = name;
38
	}
39

  
40
	public String getPrefix() {
41
		return prefix;
42
	}
43

  
44
	public void setPrefix(final String prefix) {
45
		this.prefix = prefix;
46
	}
47

  
48
	public String calculateOpenaireId() {
49
		if (StringUtils.isNotBlank(id)) {
50
			final String[] arr = id.split("::");
51
			if (arr.length == 2) {
52
				return String.format("%s::%s", arr[0], Hashing.md5(arr[1]));
53
			}
54
		}
55
		return "";
56
	}
57
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/resources/eu/dnetlib/openaire/directindex/applicationContext-api.properties
1
openaire.api.directindex.mongo.host=localhost
2
openaire.api.directindex.mongo.port=27017
3
openaire.api.directindex.mongo.db=openaireplus_apis
4
openaire.api.directindex.mongo.collection=recent_publications
5
openaire.api.directindex.layoutToRecord.xslt=/eu/dnetlib/msro/openaireplus/workflows/index/openaireLayoutToRecordStylesheet.xsl
6
openaire.api.directindex.findSolrIndexUrl.xquery=/eu/dnetlib/openaire/directindex/findSolrIndexUrl.xquery
7
openaire.api.directindex.findIndexDsInfo.xquery=/eu/dnetlib/openaire/directindex/findIndexDsInfo.xquery
8
openaire.api.directindex.autocommit.active=true
9
openaire.api.directindex.autocommit.frequency=6
10
openaire.api.community=http://${container.hostname}/openaire/community/
11
openaire.api.dsm=http://${container.hostname}/openaire/ds/
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/resources/eu/dnetlib/openaire/directindex/api/ehcache.xml
1
<ehcache>
2

  
3
	<!-- Sets the path to the directory where cache .data files are created. 
4
		If the path is a Java System Property it is replaced by its value in the 
5
		running VM. The following properties are translated: user.home - User's home 
6
		directory user.dir - User's current working directory java.io.tmpdir - Default 
7
		temp file path -->
8
	<diskStore path="java.io.tmpdir" />
9

  
10

  
11
	<!--Default Cache configuration. These will applied to caches programmatically 
12
		created through the CacheManager. The following attributes are required for 
13
		defaultCache: maxInMemory - Sets the maximum number of objects that will 
14
		be created in memory eternal - Sets whether elements are eternal. If eternal, 
15
		timeouts are ignored and the element is never expired. timeToIdleSeconds 
16
		- Sets the time to idle for an element before it expires. i.e. The maximum 
17
		amount of time between accesses before an element expires Is only used if 
18
		the element is not eternal. Optional attribute. A value of 0 means that an 
19
		Element can idle for infinity timeToLiveSeconds - Sets the time to live for 
20
		an element before it expires. i.e. The maximum time between creation time 
21
		and when an element expires. Is only used if the element is not eternal. 
22
		overflowToDisk - Sets whether elements can overflow to disk when the in-memory 
23
		cache has reached the maxInMemory limit. -->
24

  
25
	<!-- <defaultCache maxElementsInMemory="1000" overflowToDisk="true" -->
26
	<!-- eternal="true" diskPersistent="false" timeToIdleSeconds="0" -->
27
	<!-- timeToLiveSeconds="0" memoryStoreEvictionPolicy="LRU" -->
28
	<!-- diskExpiryThreadIntervalSeconds="120" diskSpoolBufferSizeMB="5" /> -->
29

  
30
<!-- Expires once in a day -->
31
	<cache name="indexDsInfo" maxElementsInMemory="5" eternal="false"
32
		timeToIdleSeconds="86400" timeToLiveSeconds="86400" overflowToDisk="false" />
33

  
34
<!-- 	<cache name="publisherfields" maxElementsInMemory="30" eternal="false" -->
35
<!-- 		timeToIdleSeconds="1800" timeToLiveSeconds="1800" overflowToDisk="false" /> -->
36
		
37
<!-- 	<cache name="publisheridscheme" maxElementsInMemory="1" eternal="false" -->
38
<!-- 		timeToIdleSeconds="1800" timeToLiveSeconds="1800" overflowToDisk="false" /> -->
39
		
40
<!-- 	<cache name="publisheridnamespace" maxElementsInMemory="1" -->
41
<!-- 		eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800" -->
42
<!-- 		overflowToDisk="false" /> -->
43

  
44

  
45

  
46

  
47

  
48
</ehcache>
49

  
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/test/java/eu/dnetlib/openaire/directindex/utils/OpenaireLayoutToRecordStylesheetTest.java
1
package eu.dnetlib.openaire.directindex.utils;
2

  
3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import com.fasterxml.jackson.databind.ObjectWriter;
5
import com.google.common.collect.Maps;
6
import eu.dnetlib.functionality.index.solr.feed.StreamingInputDocumentFactory;
7
import eu.dnetlib.miscutils.datetime.DateUtils;
8
import eu.dnetlib.miscutils.functional.xml.ApplyXslt;
9
import org.apache.commons.io.IOUtils;
10
import org.apache.solr.common.SolrInputDocument;
11
import org.junit.Test;
12
import org.springframework.core.io.ClassPathResource;
13

  
14
import javax.xml.stream.XMLStreamException;
15
import javax.xml.transform.Transformer;
16
import javax.xml.transform.TransformerException;
17
import javax.xml.transform.TransformerFactory;
18
import javax.xml.transform.stream.StreamResult;
19
import javax.xml.transform.stream.StreamSource;
20
import java.io.IOException;
21
import java.io.InputStream;
22
import java.io.StringReader;
23
import java.io.StringWriter;
24
import java.text.SimpleDateFormat;
25
import java.util.Map;
26

  
27
import static org.junit.Assert.assertFalse;
28
import static org.junit.Assert.assertNotNull;
29

  
30

  
31
public class OpenaireLayoutToRecordStylesheetTest {
32

  
33
	private static final String OPENAIRE_LAYOUT_TO_RECORD_STYLESHEET_XSL = "eu/dnetlib/openaire/directindex/utils/openaireLayoutToRecordStylesheet.xsl";
34

  
35
	private static final String MDFORMAT_FIELDS_PROFILE = "eu/dnetlib/openaire/directindex/utils/2-8b9503d9-8a86-4330-93ef-7e0cd9bc87c2.xml";
36

  
37
	private static final String OAF_RECORD = "eu/dnetlib/openaire/directindex/utils/oafRecord.xml";
38

  
39
	@Test
40
	public void directIndexOafToIndexTest() throws IOException, TransformerException, XMLStreamException {
41
		final Transformer layoutTransformer = TransformerFactory.newInstance().newTransformer(streamSource(OPENAIRE_LAYOUT_TO_RECORD_STYLESHEET_XSL));
42
		final StreamResult layoutToXsltXslt = new StreamResult(new StringWriter());
43
		layoutTransformer.setParameter("format", "DMF");
44
		layoutTransformer.transform(new StreamSource(new StringReader(getLayoutSource("DMF"))), layoutToXsltXslt);
45
		String xslt2xslt = layoutToXsltXslt.getWriter().toString();
46
		//System.out.println(xslt2xslt);
47
		ApplyXslt applyXslt = new ApplyXslt(xslt2xslt);
48
		String indexRecord = applyXslt.evaluate(readFromClasspath(OAF_RECORD));
49
		//System.out.println(indexRecord);
50
		StreamingInputDocumentFactory factory = new StreamingInputDocumentFactory();
51
		SolrInputDocument doc = factory.parseDocument(DateUtils.now_ISO8601(), indexRecord, "dsId", "dnetResult");
52

  
53
		assertNotNull(doc);
54
		assertFalse(doc.isEmpty());
55
		assertFalse(doc.containsKey("__dsid"));
56
		assertFalse(doc.containsKey("__dsversion"));
57
		assertFalse(doc.containsKey("__deleted"));
58

  
59
		System.out.println("SolrDocument");
60

  
61
		System.out.println(doc.values());
62

  
63
		System.out.println("SolrDocument fields");
64

  
65
		Map<String, Object> fields = Maps.newHashMap();
66

  
67
		doc.entrySet().stream()
68
				.forEach(e -> {
69
					Object value = e.getValue().getValueCount() == 1 ? e.getValue().getFirstValue() : e.getValue().getValues();
70
					fields.put(e.getKey(), value);
71
				});
72

  
73
		final ObjectWriter objectWriter = new ObjectMapper()
74
				.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
75
				.writerWithDefaultPrettyPrinter();
76

  
77
		System.out.println(objectWriter.writeValueAsString(fields));
78
	}
79

  
80
	private String getLayoutSource(final String format) throws IOException {
81
		return readFromClasspath(MDFORMAT_FIELDS_PROFILE);
82
	}
83

  
84
	private StreamSource streamSource(final String s) throws IOException {
85
		return new StreamSource(new StringReader(readFromClasspath(s)));
86
	}
87

  
88
	private String readFromClasspath(final String s) throws IOException {
89
		ClassPathResource resource = new ClassPathResource(s);
90
		InputStream inputStream = resource.getInputStream();
91
		return IOUtils.toString(inputStream);
92
	}
93

  
94

  
95

  
96
}
97

  
98

  
99

  
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/resources/eu/dnetlib/openaire/directindex/findIndexDsInfo.xquery
1
distinct-values(for $s in collection('/db/DRIVER/ServiceResources/SearchServiceResourceType')//SERVICE_PROPERTIES[./PROPERTY[@key = 'infrastructure' and @value = 'public'] ]
2
let $format := $s/PROPERTY[@key = "mdformat"]/@value/string()
3
return(
4
for $x in collection('/db/DRIVER/IndexDSResources/IndexDSResourceType')
5
where
6
    $x//METADATA_FORMAT =$format and
7
            $x//METADATA_FORMAT_INTERPRETATION = 'openaire' and
8
            $x//METADATA_FORMAT_LAYOUT = 'index'
9
return
10
    concat($x//RESOURCE_IDENTIFIER/@value/string(), ' @@@ ', $format , ' @@@ ', $format , '-index-openaire')
11
))
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/test/java/eu/dnetlib/openaire/directindex/api/OpenAIRESubmitterUtilsTest.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import static org.mockito.Mockito.CALLS_REAL_METHODS;
4
import static org.mockito.Mockito.doReturn;
5
import static org.mockito.Mockito.mock;
6
import static org.mockito.Mockito.withSettings;
7

  
8
import java.util.ArrayList;
9
import java.util.List;
10
import java.util.Map;
11
import java.util.Map.Entry;
12

  
13
import org.junit.Assert;
14
import org.junit.Before;
15
import org.junit.Test;
16
import org.junit.runner.RunWith;
17
import org.mockito.runners.MockitoJUnitRunner;
18

  
19
import com.google.common.collect.Lists;
20
import com.google.common.collect.Maps;
21
import com.google.gson.Gson;
22

  
23
import eu.dnetlib.openaire.directindex.objects.DatasourceEntry;
24

  
25
/**
26
 * Created by Alessia Bardi on 26/05/2017.
27
 *
28
 * @author Alessia Bardi
29
 */
30
@RunWith(MockitoJUnitRunner.class)
31
public class OpenAIRESubmitterUtilsTest {
32

  
33
	private OpenAIRESubmitterUtils utils;
34

  
35
	final String fullProject = "info:eu-repo/grantAgreement/EC/FP7/244909/EU/Making Capabilities Work/WorkAble";
36
	final String minimalProject = "info:eu-repo/grantAgreement/EC/FP7/244909///WorkAble";
37
	final String onlyId = "info:eu-repo/grantAgreement/EC/FP7/244909/";
38
	final String onlyTitle = "info:eu-repo/grantAgreement/EC/FP7/244909/EU/Making Capabilities Work";
39
	final String escapedId = "info:eu-repo/grantAgreement/RCUK//NE%2FL003066%2F1/";
40
	final String heProjectFromZenodo =
41
		"info:eu-repo/grantAgreement/EC/Horizon Europe Framework Programme - HORIZON-CSA\\HORIZON Action Grant Budget-Based/101058527/";
42
	final String chistera = "info:eu-repo/grantAgreement/CHIST-ERA//CHIST-ERA-19-XAI-002/";
43

  
44
	@Before
45
	public void setup() {
46
		utils = mock(OpenAIRESubmitterUtils.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
47
		doReturn(Lists.newArrayList("dh-ch", "dariah", "bar", "x")).when(utils).translateZenodoCommunity("https://zenodo.org/communities/dimpo");
48
		doReturn(Lists.newArrayList()).when(utils).translateZenodoCommunity("https://zenodo.org/communities/dumbo");
49

  
50
	}
51

  
52
	@Test
53
	public void testCalculateProjectInfoCHISTERA() {
54
		final Map<String, String> project = utils.calculateProjectInfo(chistera);
55
		print(project);
56
		Assert.assertEquals("CHIST-ERA-19-XAI-002", project.get("code"));
57
		Assert.assertEquals("chistera____::289ec73ce0e9ece89a0cbdf74c445cd8", project.get("id"));
58

  
59
	}
60

  
61
	@Test
62
	public void testCalculateProjectInfoZenodo() {
63
		final Map<String, String> project = utils.calculateProjectInfo(onlyId);
64
		print(project);
65
		Assert.assertEquals("244909", project.get("code"));
66

  
67
	}
68

  
69
	@Test
70
	public void testCalculateProjectInfoZenodoHE() {
71
		final Map<String, String> project = utils.calculateProjectInfo(heProjectFromZenodo);
72
		print(project);
73
		Assert.assertEquals("101058527", project.get("code"));
74
		Assert.assertEquals("corda_____he::eab43774d3762e87f5e66030c6e01d2b", project.get("id"));
75

  
76
	}
77

  
78
	@Test
79
	public void testCalculateProjectInfoEscaped() {
80
		final Map<String, String> project = utils.calculateProjectInfo(escapedId);
81
		print(project);
82
		Assert.assertEquals("NE/L003066/1", project.get("code"));
83
	}
84

  
85
	@Test
86
	public void testCalculateProjectInfoFull() {
87
		final Map<String, String> project = utils.calculateProjectInfo(fullProject);
88
		print(project);
89
		Assert.assertEquals(10, project.size());
90
		for (final String k : project.keySet()) {
91
			Assert.assertNotNull(project.get(k));
92
			Assert.assertNotSame("", project.get(k));
93
		}
94
	}
95

  
96
	@Test
97
	public void testCalculateProjectInfoOnlyId() {
98
		final Map<String, String> project = utils.calculateProjectInfo(onlyId);
99
		print(project);
100
		Assert.assertEquals("244909", project.get("code"));
101
	}
102

  
103
	@Test
104
	public void testCalculateProjectInfoMinimalAcro() {
105
		final Map<String, String> project = utils.calculateProjectInfo(minimalProject);
106
		print(project);
107
		Assert.assertEquals("244909", project.get("code"));
108
		Assert.assertEquals("WorkAble", project.get("acronym"));
109
	}
110

  
111
	@Test
112
	public void testCalculateProjectInfoOnlyTitle() {
113
		final Map<String, String> project = utils.calculateProjectInfo(onlyTitle);
114
		print(project);
115
		Assert.assertEquals("244909", project.get("code"));
116
		Assert.assertEquals("Making Capabilities Work", project.get("title"));
117
	}
118

  
119
	@Test
120
	public void testJerusalem() {
121
		final String s =
122
			"info:eu-repo/grantAgreement/EC/FP7/337895/EU/Opening Jerusalem Archives: For a connected History of ‘Citadinité’ in the Holy City (1840-1940)/OPEN-JERUSALEM";
123
		final Map<String, String> project = utils.calculateProjectInfo(s);
124
		print(project);
125
		Assert.assertEquals("337895", project.get("code"));
126
		Assert.assertEquals("Opening Jerusalem Archives: For a connected History of ‘Citadinité’ in the Holy City (1840-1940)", project.get("title"));
127
		Assert.assertEquals("OPEN-JERUSALEM", project.get("acronym"));
128
	}
129

  
130
	private void print(final Map<String, String> map) {
131
		for (final Entry e : map.entrySet()) {
132
			System.out.println(e.getKey() + " = " + e.getValue());
133
		}
134
	}
135

  
136
	@Test
137
	public void testContext() {
138
		final List<String> zenodoCommunities = new ArrayList<>();
139
		zenodoCommunities.add("https://zenodo.org/communities/dimpo");
140
		zenodoCommunities.add("https://zenodo.org/communities/dumbo");
141
		final Map<String, String> labelMap = Maps.newHashMap();
142
		labelMap.put("dariah", "DARIAH");
143
		labelMap.put("dh-ch", "DH-CH");
144
		labelMap.put("foo", "FOO");
145
		labelMap.put("bar", "");
146

  
147
		final List<OpenAIRESubmitterUtils.ContextInfo> tmp = utils.processContexts(zenodoCommunities, labelMap);
148
		Assert.assertEquals(2, tmp.size());
149

  
150
		Assert.assertTrue(tmp.get(0).getId().equals("dh-ch") || tmp.get(1).getId().equalsIgnoreCase("dh-ch"));
151
		Assert.assertTrue(tmp.get(0).getId().equals("dariah") || tmp.get(1).getId().equalsIgnoreCase("dariah"));
152
	}
153

  
154
	@Test
155
	public void testWrongH2020() {
156
		final String link = "info:eu-repo/grantAgreement/EC/Horizon 2020 Framework Programme - Research and Innovation action/881825/";
157
		final Map<String, String> info = utils.calculateProjectInfo(link);
158
		System.out.println(info);
159
		Assert.assertEquals("H2020", info.get("fundingName"));
160
	}
161

  
162
	@Test
163
	public void testFindDatasource_01() {
164
		final OpenAIRESubmitterUtils utils = new OpenAIRESubmitterUtils("", "https://services.openaire.eu/openaire/ds/");
165
		final DatasourceEntry res = utils.findDatasource("opendoar____::1112");
166
		System.err.println(new Gson().toJson(res));
167
	}
168

  
169
}
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/main/resources/eu/dnetlib/openaire/directindex/indexRecord.xml.vm
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3

  
4
#macro(context $ctx)
5
        <$!ctx.elem id="$!esc.evaluate($!ctx.id)" label="$!esc.evaluate($!ctx.label)" #if($!ctx.isRoot()) type="community"#end>
6
	#foreach($child in $!ctx.children)#context($child)#end
7
        </$!ctx.elem>
8
#end
9

  
10
<record xmlns:dri="http://www.driver-repository.eu/namespace/dri" xmlns:oaf="http://namespace.openaire.eu/oaf">
11
	<result>
12
		<header>
13
			<dri:objIdentifier>$!esc.evaluate($!objIdentifier)</dri:objIdentifier>
14
			<dri:dateOfCollection>$!esc.evaluate($!dateOfCollection)</dri:dateOfCollection>
15
			<dri:status>under curation</dri:status>
16
			<counters/>
17
		</header>
18
		<metadata>
19
			<oaf:entity schemaLocation="http://namespace.openaire.eu/oaf $!oafSchemaLocation">
20
				<oaf:result>
21
					<title classid="main title" classname="main title" schemeid="dnet:dataCite_title" schemename="dnet:dataCite_title">
22
						$!esc.evaluate($!pub.title)
23
					</title>
24
					#foreach($author in $!pub.authors)
25
                    	<creator rank="$velocityCount" name="" surname="">$!esc.evaluate($!author)</creator>
26
                    #end
27
					<dateofacceptance/>
28
					<resulttype classid="$!esc.evaluate($!pub.type)" classname="$!esc.evaluate($!resultTypes.get($!pub.type))" schemeid="dnet:result_typologies" schemename="dnet:result_typologies"/>
29
					<language classid="$!esc.evaluate($!pub.language)" classname="$!esc.evaluate($!languages.get($!pub.language))" schemeid="dnet:languages"
30
					          schemename="dnet:languages"/>
31
					<description>
32
						$!esc.evaluate($!pub.description)
33
					</description>
34
					<country classid="" classname="" schemeid="" schemename=""/>
35
					<subject classid="" classname="" schemeid="" schemename=""/>
36
					<relevantdate classid="" classname="" schemeid="" schemename=""/>
37
					<publisher>$!esc.evaluate($!pub.publisher)</publisher>
38
					<embargoenddate>$!esc.evaluate($!pub.embargoEndDate)</embargoenddate>
39
					<journal issn="" eissn="" lissn="" ep="" iss="" sp="" vol=""/>
40
					<source/>
41
					<fulltext/>
42
					<format/>
43
					<storagedate/>
44
					<resourcetype classid="" classname="" schemeid="" schemename=""/>
45
					<device/>
46
					<size/>
47
					<version/>
48
					<lastmetadataupdate/>
49
					<metadataversionnumber/>
50
					<documentationUrl/>
51
					<codeRepositoryUrl/>
52
					<programmingLanguage classid="" classname="" schemeid="" schemename="" />
53
					<contactperson />
54
					<contactgroup />
55
					<tool />
56
					<originalId>$!esc.evaluate($!pub.originalId)</originalId>
57
					<collectedfrom name="$!esc.evaluate($!collectedFrom.name)" id="$!esc.evaluate($!collectedFrom.calculateOpenaireId())"/>
58

  
59
					#foreach($pid in $!pub.pids)
60
						<pid classid="$!esc.evaluate($!pid.type)" classname="$!esc.evaluate($!pidTypes.get($!pid.type))" schemeid="dnet:pid_types"
61
						     schemename="dnet:pid_types">$!esc.evaluate($pid.value)</pid>
62
					#end
63
					#if($!pub.accessRightCode)
64
						<bestaccessright classid="$!esc.evaluate($!pub.accessRightCode)" classname="$!esc.evaluate($!rights.get($!pub.accessRightCode))"
65
						                 schemeid="dnet:access_modes" schemename="dnet:access_modes"/>
66
					#elseif($!pub.licenseCode)
67
							<bestaccessright classid="$!esc.evaluate($!pub.licenseCode)" classname="$!esc.evaluate($!rights.get($!pub.licenseCode))"
68
							                 schemeid="dnet:access_modes" schemename="dnet:access_modes"/>
69
					#else
70
						<bestaccessright classid="UNKNOWN" classname="not available" schemeid="dnet:access_modes" schemename="dnet:access_modes" />
71
					#end
72

  
73
					#foreach($ctx in $contextInfo)
74
                        #context($ctx)
75
                    #end
76

  
77
					<datainfo>
78
						<inferred>false</inferred>
79
						<deletedbyinference>false</deletedbyinference>
80
						<trust>0.9</trust>
81
						<inferenceprovenance/>
82
						<provenanceaction classid="user:insert" classname="user:insert" schemeid="dnet:provenanceActions" schemename="dnet:provenanceActions"/>
83
					</datainfo>
84

  
85
					<rels>
86
						#foreach($link in $!pub.linksToProjects)
87

  
88
							#set( $info = $!util.calculateProjectInfo($!link) )
89
							<rel inferred="false" trust="0.9" inferenceprovenance="" provenanceaction="user:claim">
90
								<to class="isProducedBy" scheme="dnet:result_project_relations" type="project">$!esc.evaluate($!info.id)</to>
91
								<code>$!esc.evaluate($!info.code)</code>
92
								<acronym>$!esc.evaluate($!info.acronym)</acronym>
93
								<title>$!esc.evaluate($!info.title)</title>
94
								<contracttype classid="" classname="" schemeid="" schemename=""/>
95

  
96
								<funding>
97
									<funder id="$!esc.evaluate($!info.funderId)"
98
									        shortname="$!esc.evaluate($!info.funderShortName)"
99
									        name="$!esc.evaluate($!info.funderName)"
100
									        jurisdiction="$!esc.evaluate($!info.jurisdiction)"/>
101
									#if($!info.fundingId)
102
									<funding_level_0 name="$!esc.evaluate($!info.fundingName)">$!esc.evaluate($!info.fundingId)</funding_level_0>
103
									#end
104
								</funding>
105
								<websiteurl/>
106
							</rel>
107
						#end
108
					</rels>
109
					<children>
110
						<instance id="$!esc.evaluate($!objIdentifier)">
111
							<instancetype classid="$!esc.evaluate($!pub.resourceType)" classname="$!esc.evaluate($resourceTypes.get($!pub.resourceType))"
112
							              schemeid="dnet:publication_resource" schemename="dnet:publication_resource"/>
113
							<collectedfrom name="$!esc.evaluate($!collectedFrom.name)" id="$!esc.evaluate($!collectedFrom.calculateOpenaireId())"/>
114
							<hostedby name="$!esc.evaluate($!hostedBy.name)" id="$!esc.evaluate($!hostedBy.calculateOpenaireId())"/>
115
							#if($!pub.accessRightCode)
116
								<accessright classid="$!esc.evaluate($!pub.accessRightCode)" classname="$!esc.evaluate($!rights.get($!pub.accessRightCode))"
117
								                 schemeid="dnet:access_modes" schemename="dnet:access_modes"/>
118
							#elseif($!pub.licenseCode)
119
								<accessright classid="$!esc.evaluate($!pub.licenseCode)" classname="$!esc.evaluate($!rights.get($!pub.licenseCode))"
120
								                 schemeid="dnet:access_modes" schemename="dnet:access_modes"/>
121
							#else
122
								<accessright classid="UNKNOWN" classname="not available" schemeid="dnet:access_modes" schemename="dnet:access_modes" />
123
							#end
124
							<dateofacceptance/>
125
							<webresource>
126
								<url>$!esc.evaluate($!pub.url)</url>
127
							</webresource>
128
						</instance>
129
					</children>
130
				</oaf:result>
131
			</oaf:entity>
132
		</metadata>
133
	</result>
134
</record>
modules/dnet-directindex-api/tags/dnet-directindex-api-3.0.1/src/test/java/eu/dnetlib/openaire/directindex/objects/ResultEntryToOafTest.java
1
package eu.dnetlib.openaire.directindex.objects;
2

  
3
import static org.mockito.Matchers.anyString;
4
import static org.mockito.Mockito.CALLS_REAL_METHODS;
5
import static org.mockito.Mockito.doReturn;
6
import static org.mockito.Mockito.mock;
7
import static org.mockito.Mockito.when;
8
import static org.mockito.Mockito.withSettings;
9

  
10
import java.io.InputStreamReader;
11
import java.io.StringReader;
12
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.List;
15
import java.util.Properties;
16

  
17
import org.apache.commons.lang3.StringEscapeUtils;
18
import org.apache.velocity.app.VelocityEngine;
19
import org.dom4j.Document;
20
import org.dom4j.Node;
21
import org.dom4j.io.OutputFormat;
22
import org.dom4j.io.SAXReader;
23
import org.dom4j.io.XMLWriter;
24
import org.junit.Assert;
25
import org.junit.Before;
26
import org.junit.Test;
27
import org.junit.runner.RunWith;
28
import org.mockito.Mock;
29
import org.mockito.runners.MockitoJUnitRunner;
30

  
31
import com.google.common.collect.Lists;
32
import com.google.gson.Gson;
33

  
34
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
35
import eu.dnetlib.openaire.directindex.api.DirecIndexApiException;
36
import eu.dnetlib.openaire.directindex.api.OpenAIRESubmitterUtils;
37

  
38
/**
39
 * Created by michele on 14/12/15.
40
 */
41
@RunWith(MockitoJUnitRunner.class)
42
public class ResultEntryToOafTest {
43

  
44
	private VelocityEngine ve;
45

  
46
	private final String community_api = "https://dev-openaire.d4science.org/openaire/community/";
47
	private final String dsm_api = "https://dev-openaire.d4science.org/openaire/ds/";
48

  
49
	@Mock
50
	private ISLookUpService lookUpService;
51

  
52
	private ResultEntryToOaf toOaf;
53
	private OpenAIRESubmitterUtils utils;
54

  
55
	@Before
56
	public void setUp() throws Exception {
57

  
58
		utils = mock(OpenAIRESubmitterUtils.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
59
		doReturn(Lists.newArrayList("dh-ch", "dariah", "bar", "x")).when(utils).translateZenodoCommunity("https://zenodo.org/communities/dimpo");
60
		doReturn(Lists.newArrayList()).when(utils).translateZenodoCommunity("https://zenodo.org/communities/dumbo");
61
		doReturn(Lists.newArrayList("noLabel", "enermaps")).when(utils).translateZenodoCommunity("https://sandbox.zenodo.org/communities/oac-ni");
62
		doReturn(Lists.newArrayList("noLabel", "enermaps")).when(utils).translateZenodoCommunity("https://zenodo.org/communities/oac-ni");
63
		doReturn(new DatasourceEntry("test________::XXX", "XXX", "xxxx________")).when(utils).findDatasource(anyString());
64
		toOaf = new ResultEntryToOaf(utils);
65

  
66
		final Properties props = new Properties();
67
		props.setProperty("resource.loader", "class");
68
		props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
69
		props.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.Log4JLogChute");
70
		ve = new VelocityEngine();
71
		ve.init(props);
72

  
73
		when(lookUpService.quickSearchProfile(anyString())).thenAnswer(invocation -> {
74
			final String query = invocation.getArguments()[0].toString();
75
			if (query.contains("dnet:result_typologies")) {
76
				return Arrays.asList("publication @@@ publication", "dataset @@@ dataset", "software @@@ software", "other @@@ other");
77
			} else if (query.contains("dnet:access_modes")) {
78
				return Arrays.asList("OPEN @@@ Open Access");
79
			} else if (query.contains("dnet:publication_resource")) {
80
				return Arrays.asList("0001 @@@ Journal Article");
81
			} else if (query.contains("dnet:pid_types")) {
82
				return Arrays.asList("oai @@@ Open Archive Initiative", "doi @@@ Digital object identifier");
83
			} else if (query.contains("dnet:languages")) {
84
				return Arrays.asList("ita @@@ Italian");
85
			} else if (query.contains("ContextDSResourceType")) {
86
				return Arrays
87
					.asList("egi::classification::natsc::math::stats @@@ Statistics and Probability", "egi::classification::natsc::math::pure @@@ Pure Mathematics", "egi::classification::natsc::math @@@ Mathematics", "egi::classification::natsc @@@ Natural Sciences", "egi::classification @@@ EGI classification scheme", "egi @@@ EGI", "enermaps @@@ Energy Research", "enermaps::selection @@@ Selected by the H2020 EnerMaps project");
88
			} else {
89
				return new ArrayList<String>();
90
			}
91
		});
92

  
93
	}
94

  
95
	@Test
96
	public void testAsIndexRecord() throws Exception {
97
		final ResultEntry pub = new ResultEntry();
98
		pub.setOriginalId("ORIG_ID_1234");
99
		pub.setTitle("TEST TITLE <test>");
100
		pub.getAuthors().add("Michele Artini");
101
		pub.getAuthors().add("Claudio Atzori");
102
		pub.getAuthors().add("Alessia Bardi");
103
		pub.setPublisher("Test publisher");
104
		pub.setDescription("DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION ");
105
		pub.setLanguage("ita");
106
		pub.setLicenseCode("OPEN");
107
		pub.setResourceType("0001");
108
		pub.setUrl("http://test.it/a=1&b=2");
109
		pub.getPids().add(new PidEntry("doi", "10.000/xyz-123"));
110
		pub.getPids().add(new PidEntry("oai", "oai:1234"));
111
		pub.setCollectedFromId("test________::zenodo");
112
		pub.setHostedById("test________::UNKNOWN");
113
		pub.getLinksToProjects().add("info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus");
114
		pub.getLinksToProjects().add("info:eu-repo/grantAgreement/RCUK//244%2F909/EU/Making Capabilities Work/WorkAble");
115
		pub.getContexts().add("egi::classification::natsc::math::pure");
116
		pub.getContexts().add("egi::classification::natsc::math::stats");
117
		pub.getContexts().add("enermaps");
118
		pub.getContexts().add("enermaps::selection");
119
		final String xml = toOaf.asOafRecord(pub, ve, lookUpService, "http://oaf/oaf.xsd");
120

  
121
		final Document doc = new SAXReader().read(new StringReader(xml));
122

  
123
		final Node resultNode = doc.selectSingleNode("//oaf:result");
124
		Assert.assertNotNull(resultNode);
125
		final Node origIdNode = resultNode.selectSingleNode("./originalId");
126
		Assert.assertNotNull(origIdNode);
127
		Assert.assertEquals("ORIG_ID_1234", origIdNode.getText());
128
		final Node titleNode = resultNode.selectSingleNode("./title");
129
		Assert.assertNotNull(titleNode);
130
		Assert.assertNotNull(titleNode.getText());
131
		final List<Node> accessRightsNodes = resultNode.selectNodes(".//accessright/@classid");
132
		for (final Node aNode : accessRightsNodes) {
133
			Assert.assertEquals("OPEN", aNode.getStringValue());
134
		}
135
		final Node bestARNode = resultNode.selectSingleNode("./bestaccessright/@classid");
136
		Assert.assertEquals("OPEN", bestARNode.getStringValue());
137

  
138
		// final OutputFormat format = OutputFormat.createPrettyPrint();
139
		// final XMLWriter writer = new XMLWriter(System.out, format);
140
		// writer.write(doc);
141

  
142
	}
143

  
144
	@Test
145
	public void testAsIndexRecordAccessRight() throws Exception {
146
		final ResultEntry pub = new ResultEntry();
147
		pub.setOriginalId("ORIG_ID_1234");
148
		pub.setTitle("TEST TITLE <test>");
149
		pub.getAuthors().add("Michele Artini");
150
		pub.getAuthors().add("Claudio Atzori");
151
		pub.getAuthors().add("Alessia Bardi");
152
		pub.setPublisher("Test publisher");
153
		pub.setDescription("DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION ");
154
		pub.setLanguage("ita");
155
		pub.setLicenseCode("CLOSED");
156
		pub.setAccessRightCode("OPEN");
157
		pub.setResourceType("0001");
158
		pub.setUrl("http://test.it/a=1&b=2");
159
		pub.getPids().add(new PidEntry("doi", "10.000/xyz-123"));
160
		pub.getPids().add(new PidEntry("oai", "oai:1234"));
161
		pub.setCollectedFromId("test________::zenodo");
162
		pub.setHostedById("test________::UNKNOWN");
163
		pub.getLinksToProjects().add("info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus");
164
		pub.getLinksToProjects().add("info:eu-repo/grantAgreement/EC/FP7/244909/EU/Making Capabilities Work/WorkAble");
165
		pub.getContexts().add("egi::classification::natsc::math::pure");
166
		pub.getContexts().add("egi::classification::natsc::math::stats");
167
		final String xml = toOaf.asOafRecord(pub, ve, lookUpService, "http://oaf/oaf.xsd");
168

  
169
		final Document doc = new SAXReader().read(new StringReader(xml));
170

  
171
		final Node resultNode = doc.selectSingleNode("//oaf:result");
172
		Assert.assertNotNull(resultNode);
173
		final Node origIdNode = resultNode.selectSingleNode("./originalId");
174
		Assert.assertNotNull(origIdNode);
175
		Assert.assertEquals("ORIG_ID_1234", origIdNode.getText());
176
		final Node titleNode = resultNode.selectSingleNode("./title");
177
		Assert.assertNotNull(titleNode);
178
		Assert.assertNotNull(titleNode.getText());
179
		final List<Node> accessRightsNodes = resultNode.selectNodes(".//accessright/@classid");
180
		for (final Node aNode : accessRightsNodes) {
181
			Assert.assertEquals("OPEN", aNode.getStringValue());
182
		}
183
		final Node bestARNode = resultNode.selectSingleNode("./bestaccessright/@classid");
184
		Assert.assertEquals("OPEN", bestARNode.getStringValue());
185

  
186
		// final OutputFormat format = OutputFormat.createPrettyPrint();
187
		// final XMLWriter writer = new XMLWriter(System.out, format);
188
		// writer.write(doc);
189

  
190
	}
191

  
192
	@Test
193
	public void testAsORP() throws Exception {
194
		final ResultEntry pub = new ResultEntry();
195
		pub.setOriginalId("ORIG_ID_1234");
196
		pub.setTitle("TEST TITLE <test>");
197
		pub.getAuthors().add("Michele Artini");
198
		pub.getAuthors().add("Claudio Atzori");
199
		pub.getAuthors().add("Alessia Bardi");
200
		pub.setPublisher("Test publisher");
201
		pub.setDescription("DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION & DESCRIPTION ");
202
		pub.setLanguage("ita");
203
		pub.setLicenseCode("CLOSED");
204
		pub.setAccessRightCode("OPEN");
205
		pub.setResourceType("0020");
206
		pub.setType("other");
207
		pub.setUrl("http://test.it/a=1&b=2");
208
		pub.getPids().add(new PidEntry("doi", "10.000/xyz-123"));
209
		pub.getPids().add(new PidEntry("oai", "oai:1234"));
210
		pub.setCollectedFromId("test________::zenodo");
211
		pub.setHostedById("test________::UNKNOWN");
212
		pub.getLinksToProjects().add("info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus");
213
		pub.getLinksToProjects().add("info:eu-repo/grantAgreement/EC/FP7/244909/EU/Making Capabilities Work/WorkAble");
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff