Project

General

Profile

« Previous | Next » 

Revision 54314

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

View differences:

modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/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>2.1.7-solr75</version>
14

  
15
	<scm>
16
		<developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet45/modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75</developerConnection>
17
	</scm>
18
	<dependencies>
19
		<dependency>
20
			<groupId>eu.dnetlib</groupId>
21
			<artifactId>dnet-openaireplus-mapping-utils</artifactId>
22
			<version>[6.2.21-solr75]</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>[2.3.2-solr75]</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
	</dependencies>
79

  
80
	<properties>
81
		<springfox-version>2.5.0</springfox-version>
82
	</properties>
83
</project>
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/test/resources/eu/dnetlib/msro/openaireplus/api/objects/test_zenodo.json
1
{
2
  "authors":[
3
	"Alouges, Fran\u00e7ois",
4
	"Di Fratta, Giovanni"
5
  ],
6
  "collectedFromId":"opendoar____::2659",
7
  "description":"The paper is about the parking 3-sphere swimmer ($\\text{sPr}_3$). This is a low-Reynolds number model swimmer composed of three balls of equal radii. The three balls can move along three horizontal axes (supported in the same plane) that mutually meet at the center of $\\text{sPr}_3$ with angles of $120^{\u2218}$ . The governing dynamical system is introduced and the implications of its geometric symmetries revealed. It is then shown that, in the first order range of small strokes, optimal periodic strokes are ellipses embedded in 3d space, i.e. closed curves of the form $t\ud835\udfc4 [0,2\u03c0] \u21a6 (\\cos t)u + (\\sin t)v$ for suitable orthogonal vectors $u$ and $v$ of $\u211d^3$. A simple analytic expression for the vectors $u$ and $v$ is derived. The results of the paper are used in a second article where the real physical dynamics of $\\text{sPr}_3$ is analyzed in the asymptotic range of very long arms. ; Comment: 17 pages, 4 figures",
8
  "hostedById":"opendoar____::2659",
9
  "licenseCode":"OPEN",
10
  "originalId":"oai:zenodo.org:996201",
11
  "pids":[
12
	{
13
	  "type":"oai",
14
	  "value":"oai:zenodo.org:996201"
15
	},
16
	{
17
	  "type":"doi",
18
	  "value":"10.5281/zenodo.996201"
19
	}
20
  ],
21
  "publisher":"Zenodo",
22
  "resourceType":"0020",
23
  "title":"Parking 3-sphere swimmer. I. Energy minimizing strokes",
24
  "type":"publication",
25
  "url":"https://zenodo.org/record/996201"
26
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/test/resources/eu/dnetlib/msro/openaireplus/api/objects/test_record_wrong_openaireId.json
1
{
2
  "openaireId":"dedup_wf_001::ab42e811",
3
  "originalId": "ORIG_ID_TEST",
4
  "type": "publication",
5
  "title": "TEST TITLE",
6
  "authors": [
7
	"Michele Artini",
8
	"Claudio Atzori",
9
	"Alessia Bardi"
10
  ],
11
  "publisher": "Test publisher",
12
  "description": "DESCRIPTION DESCRIPTION DESCRIPTION DESCRIPTION DESCRIPTION DESCRIPTION",
13
  "language": "ita",
14
  "pids": [
15
	{
16
	  "type": "doi",
17
	  "value": "10.000/xyz-123"
18
	},
19
	{
20
	  "type": "oai",
21
	  "value": "oai:1234"
22
	}
23
  ],
24
  "licenseCode": "EMBARGO",
25
  "embargoEndDate": "2018-02-02",
26
  "resourceType": "0001",
27
  "url": "http://test.it/xyz",
28
  "collectedFromId": "opendoar____::2659",
29
  "hostedById": "opendoar____::2659",
30
  "linksToProjects": [
31
	"info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus",
32
	"info:eu-repo/grantAgreement/EC/FP7/244909/EU/Making Capabilities Work/WorkAble"
33
  ],
34
  "contexts": [
35
	"egi::classification::natsc::math::pure",
36
	"egi::classification::natsc::math::stats"
37
  ]
38
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/test/resources/eu/dnetlib/msro/openaireplus/api/objects/test_record_with_greek_chars.json
1
{
2
  "originalId": "ORIG_ID_12345",
3
  "title": "TEST TITLE WITH Greek Characters",
4
  "authors": [
5
	"αβγδεζηθικλμ νξοπρσςτυφχψω",
6
	"ΑΒΓΔΕΖΗΘΙΚΛ ΜΝΞΟΠΡΣΤΥΦΧΨΩ"
7
  ],
8
  "publisher": "âââââââ",
9
  "description": "Αν περιμένατε να βρίσκεται εδώ μια σελίδα και δεν υπάρχει, η σελίδα μπορεί να μην εμφανίζεται λόγω καθυστέρησης στην ανανέωση της βάσης δεδομένων, ή μπορεί να έχει διαγραφεί. (Δείτε την γρήγορη διαγραφή σελίδων για πιθανούς λόγους). Μπορείτε να δοκιμάστε την λειτουργία εκκαθάρισης, και να ελέγξετε το αρχείο διαγραφών.",
10
  "language": "ell",
11
  "pids": [
12
	{
13
	  "type": "doi",
14
	  "value": "10.000/xyz-123-gr"
15
	}
16
  ],
17
  "licenseCode": "EMBARGO",
18
  "embargoEndDate": "2018-02-02",
19
  "resourceType": "0001",
20
  "url": "http://test.it/xyz",
21
  "collectedFromId": "opendoar____::2659",
22
  "hostedById": "opendoar____::2367",
23
  "linksToProjects": [
24
	"info:eu-repo/grantAgreement/EC/FP7/123456/EU//Test"
25
  ],
26
  "contexts": [
27
	"egi::classification::natsc::math::stats"
28
  ]
29
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/api/OpenaireResultSubmitter.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import com.google.gson.Gson;
4
import eu.dnetlib.common.rmi.DNetRestDocumentation;
5
import eu.dnetlib.data.index.CloudIndexClient;
6
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
7
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
8
import eu.dnetlib.openaire.directindex.objects.ResultEntry;
9
import eu.dnetlib.openaire.directindex.utils.OafToIndexRecordFactory;
10
import org.apache.commons.lang.exception.ExceptionUtils;
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.beans.factory.annotation.Value;
15
import org.springframework.http.HttpStatus;
16
import org.springframework.stereotype.Controller;
17
import org.springframework.web.bind.annotation.*;
18

  
19
import javax.annotation.Resource;
20
import java.util.Map;
21

  
22
/**
23
 * Created by michele on 11/11/15.
24
 */
25
@Controller
26
@DNetRestDocumentation
27
public class OpenaireResultSubmitter {
28

  
29
	private static final Log log = LogFactory.getLog(OpenaireResultSubmitter.class);
30

  
31
	@Value(value = "oaf.schema.location")
32
	private String oafSchemaLocation;
33

  
34
	@Resource
35
	private UniqueServiceLocator serviceLocator;
36

  
37
	@Resource
38
	private OafToIndexRecordFactory oafToIndexRecordFactory;
39

  
40
	@Resource
41
	private RecentResultsQueue recentResultsQueue;
42

  
43
	@Resource(name = "openaireplusApisVelocityEngine")
44
	private VelocityEngine velocityEngine;
45

  
46
	@Resource(name = "indexClientMap")
47
	private IndexClientMap clientMap;
48

  
49
	@Resource(name = "resultSubmitterService")
50
	private ResultSubmitterService submitterService;
51

  
52
	@RequestMapping(value = { "/api/admin/autocommit/active" }, method = RequestMethod.GET)
53
	public @ResponseBody Boolean getAutocommit() throws DirecIndexApiException {
54
		return submitterService.isAutocommitactive();
55
	}
56

  
57
	@RequestMapping(value = { "/api/admin/autocommit/active" }, method = RequestMethod.POST)
58
	public @ResponseBody Boolean setAutocommit(@RequestParam(value = "active", required = true) final Boolean active) throws DirecIndexApiException {
59
		submitterService.setAutocommitactive(active);
60
		log.info(String.format("automatic commit, active '%s', frequency '%s'", submitterService.isAutocommitactive(), submitterService.getCommitfrquency()));
61
		return submitterService.isAutocommitactive();
62
	}
63

  
64
	@Deprecated
65
	@RequestMapping(value = { "/api/publications/feedJson", "/api/results/feedJson" }, method = RequestMethod.POST)
66
	public @ResponseBody String feedObjectJson(@RequestParam(value = "json", required = true) final String json,
67
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws DirecIndexApiException {
68
		final ResultEntry pub = new Gson().fromJson(json, ResultEntry.class);
69
		return feedObject(pub, commit);
70
	}
71

  
72
	@RequestMapping(value = { "/api/results/feedObject" }, method = RequestMethod.POST)
73
	public @ResponseBody String feedResult(@RequestBody final ResultEntry pub,
74
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit)
75
			throws DirecIndexApiException {
76
		return feed(pub, commit);
77
	}
78

  
79
	@Deprecated
80
	@RequestMapping(value = { "/api/publications/feedObject" }, method = RequestMethod.POST)
81
	public @ResponseBody String feedObject(@RequestBody final ResultEntry pub,
82
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit)
83
			throws DirecIndexApiException {
84
		return feed(pub, commit);
85
	}
86

  
87

  
88
	@RequestMapping(value = "/api/result/{openaireId}", method = RequestMethod.DELETE)
89
	public @ResponseBody boolean deleteResultWithOpenaireId(
90
			@PathVariable(value = "openaireId") final String openaireId,
91
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws DirecIndexApiException {
92

  
93
		return deleteResult(openaireId, commit);
94
	}
95

  
96
	@RequestMapping(value = "/api/results", method = RequestMethod.DELETE)
97
	public @ResponseBody boolean deleteResultWithOriginalId(
98
			@RequestParam(value = "originalId", required = true) final String originalId,
99
			@RequestParam(value = "collectedFromId", required = true) final String collectedFromId,
100
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws Exception {
101

  
102
		final String openaireId = ResultEntry.calculateOpenaireId(originalId, collectedFromId, serviceLocator.getService(ISLookUpService.class));
103
		return deleteResult(openaireId, commit);
104
	}
105

  
106
	@Deprecated
107
	@RequestMapping(value = { "/api/publications/deleteObject", "/api/results/delete" }, method = RequestMethod.POST)
108
	public @ResponseBody boolean deleteResultPost(
109
			@RequestParam(value = "originalId", required = true) final String originalId,
110
			@RequestParam(value = "collectedFromId", required = true) final String collectedFromId,
111
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws Exception {
112

  
113
		final String openaireId = ResultEntry.calculateOpenaireId(originalId, collectedFromId, serviceLocator.getService(ISLookUpService.class));
114
		return deleteResult(openaireId, commit);
115
	}
116

  
117
	@Deprecated
118
	private String feed(final ResultEntry pub, final boolean commit) throws DirecIndexApiException {
119
		return feed(pub);
120
	}
121

  
122
	private String feed(final ResultEntry pub) throws DirecIndexApiException {
123
		try {
124
			final String oafRecord = pub.asOafRecord(velocityEngine, serviceLocator.getService(ISLookUpService.class), oafSchemaLocation);
125

  
126
			for(Map.Entry<IndexDsInfo, CloudIndexClient> e : clientMap.getClients().entrySet()) {
127
				final IndexDsInfo idx = e.getKey();
128
				final CloudIndexClient client = e.getValue();
129
				client.feed(oafRecord, idx.getIndexDsId(), oafToIndexRecordFactory.newTransformer(idx.getFormat()), false);
130
			}
131

  
132
			recentResultsQueue.add(oafRecord);
133

  
134
			return pub.getOpenaireId();
135
		} catch (final Throwable e) {
136
			log.error("Error saving record", e);
137
			log.debug(pub.toString());
138
			throw new DirecIndexApiException("Error adding publication: " + e.getMessage(), e);
139
		}
140
	}
141

  
142
	private boolean deleteResult(final String openaireId, final boolean commit) throws DirecIndexApiException {
143
		try {
144
			for(Map.Entry<IndexDsInfo, CloudIndexClient> e : clientMap.getClients().entrySet()) {
145
				final IndexDsInfo idx = e.getKey();
146
				final CloudIndexClient client = e.getValue();
147
				client.remove(openaireId, false);
148
				log.info("Deleted result with id: " + openaireId + " from: " + idx.getIndexBaseUrl());
149
			}
150

  
151
			recentResultsQueue.remove(openaireId);
152
			return true;
153
		} catch (Throwable e) {
154
			throw new DirecIndexApiException("Error deleting publication: " + e.getMessage(), e);
155
		}
156
	}
157

  
158
	@ExceptionHandler(Exception.class)
159
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
160
	public @ResponseBody ErrorMessage handleException(final Exception e) {
161
		log.error("Error in direct index API", e);
162
		return new ErrorMessage(e);
163
	}
164

  
165
	public class ErrorMessage {
166

  
167
		private final String message;
168
		private final String stacktrace;
169

  
170
		public ErrorMessage(final Exception e) {
171
			this(e.getMessage(), ExceptionUtils.getStackTrace(e));
172
		}
173

  
174
		public ErrorMessage(final String message, final String stacktrace) {
175
			this.message = message;
176
			this.stacktrace = stacktrace;
177
		}
178

  
179
		public String getMessage() {
180
			return this.message;
181
		}
182

  
183
		public String getStacktrace() {
184
			return this.stacktrace;
185
		}
186

  
187
	}
188

  
189
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/deploy.info
1
{"type_source": "SVN", "goal": "package -U source:jar", "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet45/modules/dnet-directindex-api/branches/solr75", "deploy_repository": "dnet45-snapshots", "version": "4", "mail": "sandro.labruzzo@isti.cnr.it,michele.artini@isti.cnr.it, claudio.atzori@isti.cnr.it, alessia.bardi@isti.cnr.it", "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet45-snapshots", "name": "dnet-directindex-api_solr75"}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/api/ResultSubmitterService.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import eu.dnetlib.data.index.CloudIndexClient;
4
import eu.dnetlib.data.index.CloudIndexClientException;
5
import org.apache.commons.logging.Log;
6
import org.apache.commons.logging.LogFactory;
7
import org.springframework.beans.factory.annotation.Value;
8

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

  
15
public class ResultSubmitterService {
16

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

  
19
    @Resource(name = "indexClientMap")
20
    private IndexClientMap clientMap;
21

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

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

  
34
    private ScheduledExecutorService executor;
35

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

  
41
    private void updateCommitSchedule() {
42
        log.info("updating commit schedule");
43

  
44
        executor.scheduleAtFixedRate(() -> {
45
            if (isAutocommitactive()) {
46
                try {
47
                    for (Map.Entry<IndexDsInfo, CloudIndexClient> entry : clientMap.getClients().entrySet()) {
48
                        final IndexDsInfo i = entry.getKey();
49
                        final CloudIndexClient client = entry.getValue();
50

  
51
                        log.info("performing commit on " + i.getColl());
52
                        try {
53
                            client.commit();
54
                        } catch (CloudIndexClientException e) {
55
                            log.error("error performing commit on " + i.getColl(), e);
56
                        }
57
                    }
58
                } catch (DirecIndexApiException e) {
59
                    log.error(e);
60
                }
61
            }
62
        }, 0, getCommitfrquency(), TimeUnit.SECONDS);
63
    }
64

  
65
    public boolean isAutocommitactive() {
66
        return autocommitactive;
67
    }
68

  
69
    public synchronized void setAutocommitactive(boolean autocommitactive) {
70
        this.autocommitactive = autocommitactive;
71
    }
72

  
73
    public long getCommitfrquency() {
74
        return commitfrquency;
75
    }
76

  
77
    public synchronized void setCommitfrquency(long commitfrquency) {
78
        this.commitfrquency = commitfrquency;
79
    }
80

  
81
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/api/IndexDsInfo.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
public class IndexDsInfo {
4

  
5
    private final String indexBaseUrl;
6
    private final String indexDsId;
7
    private final String format;
8
    private final String coll;
9

  
10
    public IndexDsInfo(final String indexBaseUrl, final String indexDsId, final String format, final String coll) {
11
        this.indexBaseUrl = indexBaseUrl;
12
        this.indexDsId = indexDsId;
13
        this.format = format;
14
        this.coll = coll;
15
    }
16

  
17
    public String getIndexBaseUrl() {
18
        return indexBaseUrl;
19
    }
20

  
21
    public String getIndexDsId() {
22
        return indexDsId;
23
    }
24

  
25
    public String getFormat() {
26
        return format;
27
    }
28

  
29
    public String getColl() {
30
        return coll;
31
    }
32

  
33
    @Override
34
    public int hashCode() {
35
        return getColl().hashCode();
36
    }
37

  
38
    @Override
39
    public boolean equals(Object other) {
40
        if (!(other instanceof IndexDsInfo)) return false;
41

  
42
        return getColl().equals(((IndexDsInfo) other).getColl());
43
    }
44
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/api/IndexClientMap.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import com.google.common.collect.Lists;
4
import com.google.common.collect.Maps;
5
import eu.dnetlib.data.index.CloudIndexClient;
6
import eu.dnetlib.data.index.CloudIndexClientException;
7
import eu.dnetlib.data.index.CloudIndexClientFactory;
8
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
9
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
10
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
11
import org.apache.commons.io.IOUtils;
12
import org.apache.commons.logging.Log;
13
import org.apache.commons.logging.LogFactory;
14
import org.springframework.beans.factory.annotation.Value;
15
import org.springframework.core.io.ClassPathResource;
16

  
17
import javax.annotation.Resource;
18
import java.io.IOException;
19
import java.util.List;
20
import java.util.Map;
21

  
22
public class IndexClientMap {
23

  
24
    private static final Log log = LogFactory.getLog(IndexClientMap.class);
25

  
26
    @Value(value = "${openaire.api.directindex.findSolrIndexUrl.xquery}")
27
    private ClassPathResource findSolrIndexUrl;
28

  
29
    @Value(value = "${openaire.api.directindex.findIndexDsInfo.xquery}")
30
    private ClassPathResource findIndexDsInfo;
31

  
32
    @Resource
33
    private UniqueServiceLocator serviceLocator;
34

  
35
    private Map<IndexDsInfo, CloudIndexClient> clients = Maps.newHashMap();
36

  
37
    public Map<IndexDsInfo, CloudIndexClient> getClients() throws DirecIndexApiException {
38
        try {
39
            final List<IndexDsInfo> idxList = calculateCurrentIndexDsInfo();
40

  
41
            if (idxList == null || idxList.isEmpty()) {
42
                throw new DirecIndexApiException("cannot create index: no public Search Service found");
43
            }
44
            if (idxList.size() > 1) {
45
                log.warn("found more than 1 public search service");
46
            }
47

  
48
            for(IndexDsInfo i : idxList) {
49
                if (!clients.containsKey(i)) {
50
                    clients.put(i, CloudIndexClientFactory.newIndexClient(i.getIndexBaseUrl(), i.getColl(), false));
51
                }
52
            }
53
            return clients;
54

  
55
        } catch (IOException | ISLookUpException | CloudIndexClientException e) {
56
            throw new DirecIndexApiException(e);
57
        }
58
    }
59

  
60
    private List<IndexDsInfo> calculateCurrentIndexDsInfo() throws IOException, ISLookUpException {
61
        final List<IndexDsInfo> list = Lists.newArrayList();
62

  
63
        final String queryUrl = IOUtils.toString(findSolrIndexUrl.getInputStream());
64
        final String queryDs = IOUtils.toString(findIndexDsInfo.getInputStream());
65

  
66
        final ISLookUpService lu = serviceLocator.getService(ISLookUpService.class);
67
        final String indexBaseUrl = lu.getResourceProfileByQuery(queryUrl);
68

  
69
        final List<String> idxDs = lu.quickSearchProfile(queryDs);
70
        for (final String idx : idxDs) {
71
            final String[] arr = idx.split("@@@");
72
            list.add(new IndexDsInfo(indexBaseUrl, arr[0].trim(), arr[1].trim(), arr[2].trim()));
73
        }
74
        return list;
75
    }
76
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/api/OpenAIRESubmitterUtils.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import java.io.StringWriter;
4
import java.util.ArrayList;
5
import java.util.HashMap;
6
import java.util.List;
7
import java.util.Map;
8

  
9
import com.google.common.base.Function;
10
import com.google.common.collect.Lists;
11
import eu.dnetlib.miscutils.functional.hash.Hashing;
12
import org.apache.commons.lang.StringUtils;
13

  
14
/**
15
 * Created by michele on 15/01/16.
16
 */
17
public class OpenAIRESubmitterUtils {
18

  
19
	private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(OpenAIRESubmitterUtils.class);
20

  
21
	public Map<String, String> calculateProjectInfo(final String link) {
22
		final Map<String, String> info = new HashMap<String, String>();
23
		final String[] arr = link.split("/");
24
		// info:eu-repo/grantAgreement/EC/FP7/244909/EU/Making Capabilities Work/WorkAble
25

  
26
		if (arr.length > 4) {
27
			final String acronym = arr.length > 7 ? arr[7] : "";
28
			final String title = arr.length > 6 ? StringUtils.isNotBlank(arr[6]) ? arr[6] : acronym : "";
29
			final String jurisdiction = arr.length > 5 ? arr[5] : "";
30
			final String funderId = calculateFunderId(arr[2], arr[3]);
31
			info.put("id", calculateProjectId(arr[2], arr[3], arr[4]));
32
			info.put("funderShortName", arr[2]);
33
			info.put("fundingName", arr[3]);
34
			info.put("code", arr[4]);
35
			info.put("jurisdiction", jurisdiction);
36
			info.put("title", title);
37
			info.put("acronym", acronym);
38
			info.put("funderId", funderId);
39
			info.put("funderName", calculateFunderName(arr[2]));
40
			info.put("fundingId", funderId + "::" + arr[3]);
41
		}
42
		return info;
43
	}
44

  
45
	protected String calculateFunderPrefix(final String funderShortName, final String funding){
46
		switch(funderShortName.toLowerCase()){
47
		case "conicyt":
48
			return "conicytf____::";
49
		case "ec":
50
			if (funding.equalsIgnoreCase("fp7")) {
51
				return "corda_______::";
52
			} else {
53
				return "corda__h2020::";
54
			}
55
		case "hrzz":
56
		case "mzos":
57
			return "irb_hr______::";
58
		case "tara":
59
			return "taraexp_____::";
60
		case "tubitak":
61
			return "tubitakf____::";
62
		default:
63
			String prefix = funderShortName.toLowerCase();
64
			//ensure we have 12 chars
65
			while(prefix.length() < 12) prefix += "_";
66
			return prefix +"::";
67
		}
68
	}
69

  
70
	protected String calculateProjectId(final String funderShortName, final String funding, final String code) {
71
		final String suffix = Hashing.md5(code);
72
		final String funderPrefix = calculateFunderPrefix(funderShortName, funding);
73
		return funderPrefix + suffix;
74
	}
75

  
76
	protected String calculateFunderId(final String funderShortName, final String funding) {
77
		switch (funderShortName.toLowerCase()) {
78
		case "ec":
79
			return "ec__________::EC";
80
		default:
81
			String prefix = calculateFunderPrefix(funderShortName, funding);
82
			return prefix + funderShortName.toUpperCase();
83
		}
84
	}
85

  
86

  
87
	protected String calculateFunderName(final String funderShortName) {
88

  
89
		switch (funderShortName.toLowerCase()) {
90
		case "aff":
91
		case "aka":
92
			return "Academy of Finland";
93
		case "arc":
94
			return "Australian Research Council (ARC)";
95
		case "conicyt":
96
			return "Comisión Nacional de Investigación Científica y Tecnológica";
97
		case "ec":
98
			return "European Commission";
99
		case "fct":
100
			return "Fundação para a Ciência e a Tecnologia, I.P.";
101
		case "fwf":
102
			return "Austrian Science Fund (FWF)";
103
		case "hrzz":
104
			return "Croatian Science Foundation (CSF)";
105
		case "mestd":
106
			return "Ministry of Education, Science and Technological Development of Republic of Serbia";
107
		case "miur":
108
			return "Ministero dell'Istruzione dell'Università e della Ricerca";
109
		case "mzos":
110
			return "Ministry of Science, Education and Sports of the Republic of Croatia (MSES)";
111
		case "nhmrc":
112
			return "National Health and Medical Research Council (NHMRC)";
113
		case "nih":
114
			return "National Institutes of Health";
115
		case "nsf":
116
			return "National Science Foundation";
117
		case "nwo":
118
			return "Netherlands Organisation for Scientific Research (NWO)";
119
		case "rcuk":
120
			return "Research Council UK";
121
		case "sfi":
122
			return "Science Foundation Ireland";
123
		case "sgov":
124
			return "Gobierno de España";
125
		case "snsf":
126
			return "Swiss National Science Foundation";
127
		case "tara":
128
			return "Tara Expeditions Foundation";
129
		case "tubitak":
130
			return "Türkiye Bilimsel ve Teknolojik Araştırma Kurumu";
131
		case "wt":
132
			return "Wellcome Trust";
133
		default:
134
			log.error("Funder short name '"+funderShortName+"' not managed");
135
			return "";
136
		}
137
	}
138

  
139
	public List<ContextInfo> processContexts(final List<String> list) {
140
		return Lists.newArrayList(Lists.transform(list, new Function<String, ContextInfo>() {
141

  
142
			@Override
143
			public ContextInfo apply(final String s) {
144
				return createContextInfo(s.split("::"), 0);
145
			}
146

  
147
			private ContextInfo createContextInfo(final String[] arr, final int pos) {
148
				final StringWriter id = new StringWriter();
149
				id.write(arr[0]);
150
				for (int i = 0; i < pos; i++) {
151
					id.write("::");
152
					id.write(arr[i + 1]);
153
				}
154
				final String elem = (pos == 0) ? "context" : (pos == 1) ? "category" : "concept";
155
				final ContextInfo info = new ContextInfo(elem, id.toString());
156
				if ((pos + 1) < arr.length) {
157
					info.getChildren().add(createContextInfo(arr, pos + 1));
158
				}
159
				return info;
160
			}
161
		}));
162

  
163
	}
164

  
165
	public class ContextInfo {
166

  
167
		private String elem;
168
		private String id;
169
		private List<ContextInfo> children = new ArrayList<ContextInfo>();
170

  
171
		public ContextInfo(final String elem,
172
				final String id) {
173
			this.elem = elem;
174
			this.id = id;
175
		}
176

  
177
		public String getElem() {
178
			return elem;
179
		}
180

  
181
		public void setElem(final String elem) {
182
			this.elem = elem;
183
		}
184

  
185
		public String getId() {
186
			return id;
187
		}
188

  
189
		public void setId(final String id) {
190
			this.id = id;
191
		}
192

  
193
		public List<ContextInfo> getChildren() {
194
			return children;
195
		}
196

  
197
		public void setChildren(final List<ContextInfo> children) {
198
			this.children = children;
199
		}
200

  
201
		public boolean isRoot() {
202
			return elem.equals("context");
203
		}
204
	}
205
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/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-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/api/RecentResultsQueue.java
1
package eu.dnetlib.openaire.directindex.api;
2

  
3
import java.io.StringReader;
4
import java.util.Iterator;
5
import java.util.List;
6

  
7
import com.mongodb.*;
8
import eu.dnetlib.miscutils.datetime.DateUtils;
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11
import org.dom4j.io.SAXReader;
12
import org.springframework.beans.factory.annotation.Required;
13

  
14
/**
15
 * Created by michele on 11/11/15.
16
 */
17
public class RecentResultsQueue implements Iterable<String> {
18

  
19
	private static final Log log = LogFactory.getLog(RecentResultsQueue.class);
20

  
21
	private DB db;
22
	private String collection;
23

  
24
	public void init() {
25
		if (!db.collectionExists(collection)) {
26
			log.info(String.format("creating collection %s", collection));
27
			db.createCollection(collection, new BasicDBObject());
28
		}
29
	}
30

  
31
	@Override
32
	public Iterator<String> iterator() {
33

  
34
		final DBCursor cursor = db.getCollection(collection).find();
35

  
36
		return new Iterator<String>() {
37

  
38
			@Override
39
			public boolean hasNext() {
40
				return cursor.hasNext();
41
			}
42

  
43
			@Override
44
			public String next() {
45
				final DBObject obj = cursor.next();
46
				return ((obj != null) && obj.containsField("record")) ? obj.get("record").toString() : "";
47
			}
48

  
49
			@Override
50
			public void remove() {
51
				throw new RuntimeException("NOT IMPLEMENTED");
52
			}
53
		};
54
	}
55

  
56
	synchronized public void add(final String oaf) throws Exception {
57
		final String id = (new SAXReader()).read(new StringReader(oaf)).valueOf("//*[local-name() = 'objIdentifier']");
58

  
59
		log.info("Saving record " + id + " in db: " + db.getName() + ", coll: " + collection);
60

  
61
		final DBCollection coll = db.getCollection(collection);
62
		final DBObject obj = BasicDBObjectBuilder.start()
63
				.append("id", id)
64
				.append("record", oaf)
65
				.append("date", DateUtils.now())
66
				.get();
67
		coll.update(new BasicDBObject("id", id), obj, true, false);
68
	}
69

  
70
	public void remove(final List<String> list) {
71
		final DBCollection coll = db.getCollection(collection);
72
		for (final String id : list) {
73
			coll.remove(new BasicDBObject("id", id));
74
		}
75
	}
76

  
77
	public void remove(final String... ids) {
78
		final DBCollection coll = db.getCollection(collection);
79
		for (final String id : ids) {
80
			coll.remove(new BasicDBObject("id", id));
81
		}
82
	}
83

  
84
	public DB getDb() {
85
		return db;
86
	}
87

  
88
	@Required
89
	public void setDb(final DB db) {
90
		this.db = db;
91
	}
92

  
93
	public String getCollection() {
94
		return collection;
95
	}
96

  
97
	@Required
98
	public void setCollection(final String collection) {
99
		this.collection = collection;
100
	}
101
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/objects/ResultEntry.java
1
package eu.dnetlib.openaire.directindex.objects;
2

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

  
11
import org.apache.commons.lang.StringUtils;
12
import org.apache.commons.logging.Log;
13
import org.apache.commons.logging.LogFactory;
14
import org.apache.velocity.app.VelocityEngine;
15
import org.springframework.ui.velocity.VelocityEngineUtils;
16

  
17
import com.google.gson.Gson;
18

  
19
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
20
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
21
import eu.dnetlib.miscutils.datetime.DateUtils;
22
import eu.dnetlib.miscutils.functional.hash.Hashing;
23
import eu.dnetlib.miscutils.functional.string.EscapeXml;
24
import eu.dnetlib.openaire.directindex.api.DirecIndexApiException;
25
import eu.dnetlib.openaire.directindex.api.OpenAIRESubmitterUtils;
26
import io.swagger.annotations.ApiModelProperty;
27

  
28
/**
29
 * Created by michele on 02/12/15.
30
 */
31
public class ResultEntry {
32

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

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

  
60
	// String according to openaire guidelines:
61
	// info:eu-repo/grantAgreement/Funder/FundingProgram/ProjectID/[Jurisdiction]/[ProjectName]/[ProjectAcronym]
62
	private List<String> linksToProjects = new ArrayList<>();
63

  
64
	private static long last_cache_update = 0;
65
	private static final Map<String, Map<String, String>> cached_vocabularies = new HashMap<>();
66
	private static final Map<String, DatasourceEntry> cached_datasources = new HashMap<>();
67
	private static final Map<String, String> cached_contexts = new HashMap<>();
68

  
69
	private static final Log log = LogFactory.getLog(ResultEntry.class);
70

  
71
	public ResultEntry() {}
72

  
73
	public String getOpenaireId() {
74
		return openaireId;
75
	}
76

  
77
	public void setOpenaireId(final String openaireId) {
78
		this.openaireId = openaireId;
79
	}
80

  
81
	public String getOriginalId() {
82
		return originalId;
83
	}
84

  
85
	public void setOriginalId(final String originalId) {
86
		this.originalId = originalId;
87
	}
88

  
89
	@ApiModelProperty(required = true)
90
	public String getTitle() {
91
		return title;
92
	}
93

  
94
	public void setTitle(final String title) {
95
		this.title = title;
96
	}
97

  
98
	public List<String> getAuthors() {
99
		return authors;
100
	}
101

  
102
	public void setAuthors(final List<String> authors) {
103
		this.authors = authors;
104
	}
105

  
106
	public String getPublisher() {
107
		return publisher;
108
	}
109

  
110
	public void setPublisher(final String publisher) {
111
		this.publisher = publisher;
112
	}
113

  
114
	public String getDescription() {
115
		return description;
116
	}
117

  
118
	public void setDescription(final String description) {
119
		this.description = description;
120
	}
121

  
122
	@ApiModelProperty(value = "ISO Alpha-3 code. E.g. 'eng', 'ita'")
123
	public String getLanguage() {
124
		return language;
125
	}
126

  
127
	public void setLanguage(final String language) {
128
		this.language = language;
129
	}
130

  
131
	public List<PidEntry> getPids() {
132
		return pids;
133
	}
134

  
135
	public void setPids(final List<PidEntry> pids) {
136
		this.pids = pids;
137
	}
138

  
139
	@Deprecated
140
	@ApiModelProperty(required = false, allowableValues = "OPEN, CLOSED, RESTRICTED, EMBARGO, UNKNOWN, OTHER, OPEN SOURCE")
141
	public String getLicenseCode() {
142
		return licenseCode;
143
	}
144
	@Deprecated
145
	public void setLicenseCode(final String licenseCode) {
146
		this.licenseCode = licenseCode;
147
	}
148

  
149
	/**
150
	 * Set required = true when the deprecated licenseCode is not used anymore by our client and it is removed
151
	 * @return
152
	 */
153
	@ApiModelProperty(required = false, allowableValues = "OPEN, CLOSED, RESTRICTED, EMBARGO, UNKNOWN, OTHER, OPEN SOURCE")
154
	public String getAccessRightCode() {
155
		return accessRightCode;
156
	}
157

  
158
	public void setAccessRightCode(final String accessRightCode) {
159
		this.accessRightCode = accessRightCode;
160
	}
161

  
162
	@ApiModelProperty(required = true, value = "Use 001 for articles, 021 for datasets. See: http://api.openaire.eu/vocabularies/dnet:publication_resource.")
163
	public String getResourceType() {
164
		return resourceType;
165
	}
166

  
167
	public void setResourceType(final String resourceType) {
168
		this.resourceType = resourceType;
169
	}
170

  
171
	@ApiModelProperty(required = true)
172
	public String getUrl() {
173
		return url;
174
	}
175

  
176
	public void setUrl(final String url) {
177
		this.url = url;
178
	}
179

  
180
	@ApiModelProperty(required = true, value = "Use opendoar___::2659 for Zenodo Publications; re3data_____::r3d100010468 for Zenodo datasets; infrastruct::openaire for OpenAIRE portal.")
181
	public String getCollectedFromId() {
182
		return collectedFromId;
183
	}
184

  
185
	public void setCollectedFromId(final String collectedFromId) {
186
		this.collectedFromId = collectedFromId;
187
	}
188

  
189
	public String getHostedById() {
190
		return hostedById;
191
	}
192

  
193
	public void setHostedById(final String hostedById) {
194
		this.hostedById = hostedById;
195
	}
196

  
197
	@ApiModelProperty(value = "E.g. fet, egi::classification::natsc::math::pure, egi::projects::EMI")
198
	public List<String> getContexts() {
199
		return contexts;
200
	}
201

  
202
	public void setContexts(final List<String> contexts) {
203
		this.contexts = contexts;
204
	}
205

  
206
	@ApiModelProperty(value = "E.g. info:eu-repo/grantAgreement/EC/FP7/283595/EU//OpenAIREplus")
207
	public List<String> getLinksToProjects() {
208
		return linksToProjects;
209
	}
210

  
211
	public void setLinksToProjects(final List<String> linksToProjects) {
212
		this.linksToProjects = linksToProjects;
213
	}
214

  
215
	@ApiModelProperty(allowableValues = "publication, dataset")
216
	public String getType() {
217
		return type;
218
	}
219

  
220
	public void setType(final String type) {
221
		this.type = type;
222
	}
223

  
224
	public String getEmbargoEndDate() {
225
		return embargoEndDate;
226
	}
227

  
228
	public void setEmbargoEndDate(final String embargoEndDate) {
229
		this.embargoEndDate = embargoEndDate;
230
	}
231

  
232
	public String asOafRecord(final VelocityEngine ve,
233
			final ISLookUpService lookupService,
234
			final String oafSchemaLocation) throws Exception {
235

  
236
		if (StringUtils.isBlank(getOriginalId())
237
				&& StringUtils
238
						.isBlank(getOpenaireId())) { throw new DirecIndexApiException("One of the following fields is required: originalId or openaireId"); }
239
		if (StringUtils.isBlank(getTitle())) { throw new DirecIndexApiException("A required field is missing: title"); }
240
		if (StringUtils.isBlank(getUrl())) { throw new DirecIndexApiException("A required field is missing: url"); }
241
		if (StringUtils.isBlank(getLicenseCode()) && StringUtils.isBlank(getAccessRightCode())) { throw new DirecIndexApiException("A required field is missing: accessRightCode"); }
242
		if (StringUtils.isBlank(getResourceType())) { throw new DirecIndexApiException("A required field is missing: resourceType"); }
243
		if (StringUtils.isBlank(getCollectedFromId())) { throw new DirecIndexApiException("A required field is missing: collectedFromId"); }
244
		if (StringUtils.isBlank(getType())) { throw new DirecIndexApiException("A required field is missing: type"); }
245

  
246
		final DatasourceEntry collectedFromEntry = getDatasourceInfo(collectedFromId, lookupService);
247
		final DatasourceEntry hostedByEntry = getDatasourceInfo(hostedById, lookupService);
248

  
249
		if (StringUtils.isBlank(openaireId)) {
250
			setOpenaireId(calculateOpenaireId(originalId, collectedFromEntry));
251
		}
252

  
253
		if (!openaireId
254
				.matches("^\\w{12}::\\w{32}$")) { throw new DirecIndexApiException(
255
						"Invalid openaireId: " + openaireId + " - regex ^\\w{12}::\\w{32}$ not matched"); }
256

  
257
		final Map<String, Object> model = new HashMap<>();
258
		model.put("esc", new EscapeXml());
259
		model.put("util", new OpenAIRESubmitterUtils());
260
		model.put("pub", this);
261
		model.put("objIdentifier", getOpenaireId());
262
		model.put("oafSchemaLocation", oafSchemaLocation);
263
		model.put("resultTypes", getVocabulary("dnet:result_typologies", lookupService));
264
		model.put("rights", getVocabulary("dnet:access_modes", lookupService));
265
		model.put("resourceTypes", getVocabulary("dnet:publication_resource", lookupService));
266
		model.put("pidTypes", getVocabulary("dnet:pid_types", lookupService));
267
		model.put("languages", getVocabulary("dnet:languages", lookupService));
268
		model.put("contexts", getContexts(lookupService));
269
		model.put("dateOfCollection", new SimpleDateFormat("yyyy-MM-dd\'T\'hh:mm:ss\'Z\'").format(new Date()));
270
		model.put("collectedFrom", collectedFromEntry);
271
		model.put("hostedBy", hostedByEntry);
272

  
273
		return VelocityEngineUtils.mergeTemplateIntoString(ve, "/eu/dnetlib/openaire/directindex/indexRecord.xml.vm", "UTF-8", model);
274
	}
275

  
276
	private static String calculateOpenaireId(final String originalId, final DatasourceEntry collectedFromEntry) {
277
		return collectedFromEntry.getPrefix() + "::" + Hashing.md5(originalId);
278
	}
279

  
280
	public static String calculateOpenaireId(final String originalId, final String collectedFromId, final ISLookUpService lookupService)
281
			throws ISLookUpException {
282
		return calculateOpenaireId(originalId, getDatasourceInfo(collectedFromId, lookupService));
283
	}
284

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

  
289
		if (!cached_datasources.containsKey(dsId)) {
290
			final String query =
291
					"collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType')//CONFIGURATION[./DATASOURCE_ORIGINAL_ID='" + dsId
292
							+ "']/concat(./OFFICIAL_NAME, ' @@@ ', .//FIELD/value[../key='NamespacePrefix'])";
293
			final String s = lookupService.getResourceProfileByQuery(query);
294
			final String[] arr = s.split("@@@");
295

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

  
298
			if (StringUtils.isBlank(ds.getName()) || StringUtils.isBlank(ds.getPrefix())) {
299
				log.error("Invalid datasource id: " + dsId);
300
				throw new ISLookUpException("Invalid datasource id: " + dsId);
301
			} else {
302
				cached_datasources.put(dsId, ds);
303
			}
304
		}
305

  
306
		return cached_datasources.get(dsId);
307

  
308
	}
309

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

  
312
		if (DateUtils.now() - last_cache_update < TimeUnit.MINUTES.toMillis(15) && cached_vocabularies.containsKey(voc)) {
313
			return cached_vocabularies.get(voc);
314
		} else {
315
			final String query = "collection('/db/DRIVER/VocabularyDSResources/VocabularyDSResourceType')[.//VOCABULARY_NAME/@code='" + voc
316
					+ "']//TERM/concat(@code, ' @@@ ', @english_name)";
317

  
318
			final Map<String, String> map = new HashMap<>();
319
			for (final String s : lookupService.quickSearchProfile(query)) {
320
				final String[] arr = s.split("@@@");
321
				map.put(arr[0].trim(), arr[1].trim());
322
			}
323

  
324
			cached_vocabularies.put(voc, map);
325

  
326
			last_cache_update = DateUtils.now();
327

  
328
			return map;
329
		}
330
	}
331

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

  
337
			cached_contexts.clear();
338
			for (final String s : lookupService.quickSearchProfile(query)) {
339
				final String[] arr = s.split("@@@");
340
				cached_contexts.put(arr[0].trim(), arr[1].trim());
341
			}
342
			last_cache_update = DateUtils.now();
343
		}
344
		return cached_contexts;
345
	}
346

  
347
	@Override
348
	public String toString() {
349
		return new Gson().toJson(this);
350
	}
351

  
352
	public String getAnyId() {
353
		return StringUtils.isNotBlank(openaireId) ? openaireId : originalId;
354
	}
355
}
modules/dnet-directindex-api/tags/dnet-directindex-api-2.1.7-solr75/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-2.1.7-solr75/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-2.1.7-solr75/src/main/java/eu/dnetlib/openaire/directindex/utils/OafToIndexRecordFactory.java
1
package eu.dnetlib.openaire.directindex.utils;
2

  
3
import java.io.IOException;
4
import java.io.StringReader;
5
import java.io.StringWriter;
6
import javax.annotation.Resource;
7
import javax.xml.transform.Transformer;
8
import javax.xml.transform.TransformerException;
9
import javax.xml.transform.TransformerFactory;
10
import javax.xml.transform.stream.StreamResult;
11
import javax.xml.transform.stream.StreamSource;
12

  
13
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
14
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
15
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
16
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
17
import eu.dnetlib.miscutils.functional.xml.ApplyXslt;
18
import org.apache.commons.io.IOUtils;
19
import org.springframework.beans.factory.annotation.Required;
20
import org.springframework.core.io.ClassPathResource;
21

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

  
27
	private ClassPathResource layoutToRecord;
28

  
29
	@Resource
30
	private UniqueServiceLocator serviceLocator;
31

  
32
	public ApplyXslt newTransformer(final String format) throws ISLookUpException, IOException, TransformerException {
33
		final TransformerFactory factory = TransformerFactory.newInstance();
34
		final Transformer layoutTransformer = factory.newTransformer(readLayoutToRecord());
35

  
36
		final StreamResult layoutToXsltXslt = new StreamResult(new StringWriter());
37

  
38
		layoutTransformer.setParameter("format", format);
39
		layoutTransformer.transform(new StreamSource(new StringReader(getLayoutSource(format))), layoutToXsltXslt);
40

  
41
		return new ApplyXslt(layoutToXsltXslt.getWriter().toString());
42
	}
43

  
44
	private StreamSource readLayoutToRecord() throws IOException {
45
		return new StreamSource(new StringReader(IOUtils.toString(layoutToRecord.getInputStream())));
46
	}
47

  
48
	private String getLayoutSource(final String format) throws ISLookUpDocumentNotFoundException, ISLookUpException {
49
		return serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(
50
				"collection('/db/DRIVER/MDFormatDSResources/MDFormatDSResourceType')[.//NAME='" + format + "']//LAYOUT[@name='index']");
51
	}
52

  
53
	public ClassPathResource getLayoutToRecord() {
54
		return layoutToRecord;
55
	}
56

  
57
	@Required
58
	public void setLayoutToRecord(final ClassPathResource layoutToRecord) {
59
		this.layoutToRecord = layoutToRecord;
60
	}
61

  
62
}
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff