Project

General

Profile

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

    
3
import java.text.SimpleDateFormat;
4
import java.util.Date;
5
import javax.annotation.Resource;
6

    
7
import com.google.gson.Gson;
8
import eu.dnetlib.common.rmi.DNetRestDocumentation;
9
import eu.dnetlib.data.index.CloudIndexClientException;
10
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
11
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
12
import eu.dnetlib.functionality.index.solr.feed.StreamingInputDocumentFactory;
13
import eu.dnetlib.miscutils.functional.UnaryFunction;
14
import eu.dnetlib.openaire.directindex.objects.ResultEntry;
15
import eu.dnetlib.openaire.directindex.objects.ResultEntryToOaf;
16
import eu.dnetlib.openaire.directindex.utils.OafToIndexRecordFactory;
17
import org.apache.commons.lang.exception.ExceptionUtils;
18
import org.apache.commons.logging.Log;
19
import org.apache.commons.logging.LogFactory;
20
import org.apache.solr.client.solrj.impl.CloudSolrClient;
21
import org.apache.solr.common.SolrInputDocument;
22
import org.apache.velocity.app.VelocityEngine;
23
import org.springframework.beans.factory.annotation.Autowired;
24
import org.springframework.beans.factory.annotation.Value;
25
import org.springframework.http.HttpStatus;
26
import org.springframework.stereotype.Controller;
27
import org.springframework.web.bind.annotation.*;
28

    
29
/**
30
 * Created by michele on 11/11/15.
31
 */
32
@Controller
33
@DNetRestDocumentation
34
public class OpenaireResultSubmitter {
35

    
36
	private static final Log log = LogFactory.getLog(OpenaireResultSubmitter.class);
37

    
38
	@Value(value = "${openaire.api.community}")
39
	private String community_api;
40

    
41
	@Value(value = "oaf.schema.location")
42
	private String oafSchemaLocation;
43

    
44
	@Resource
45
	private UniqueServiceLocator serviceLocator;
46

    
47
	@Resource
48
	private OafToIndexRecordFactory oafToIndexRecordFactory;
49

    
50
	@Resource
51
	private RecentResultsQueue recentResultsQueue;
52

    
53
	@Resource(name = "openaireplusApisVelocityEngine")
54
	private VelocityEngine velocityEngine;
55

    
56
	@Resource(name = "indexClientManager")
57
	private IndexClientManager clientManager;
58

    
59
	@Resource(name = "resultSubmitterService")
60
	private ResultSubmitterService submitterService;
61

    
62
	@Autowired
63
	private IndexDSRetriever indexDSRetriever;
64

    
65
	@RequestMapping(value = { "/api/admin/autocommit/active" }, method = RequestMethod.GET)
66
	public @ResponseBody Boolean getAutocommit() throws DirecIndexApiException {
67
		return submitterService.isAutocommitactive();
68
	}
69

    
70
	@RequestMapping(value = { "/api/admin/autocommit/active" }, method = RequestMethod.POST)
71
	public @ResponseBody Boolean setAutocommit(@RequestParam(value = "active", required = true) final Boolean active) throws DirecIndexApiException {
72
		submitterService.setAutocommitactive(active);
73
		log.info(String.format("automatic commit, active '%s', frequency '%s'", submitterService.isAutocommitactive(), submitterService.getCommitfrquency()));
74
		return submitterService.isAutocommitactive();
75
	}
76

    
77
	@RequestMapping(value="/api/admin/evictCache", method=RequestMethod.GET)
78
	@ResponseStatus(value = HttpStatus.OK)
79
	public void evictCache(){
80
		indexDSRetriever.evictCache();
81
	}
82

    
83
	@Deprecated
84
	@RequestMapping(value = { "/api/publications/feedJson", "/api/results/feedJson" }, method = RequestMethod.POST)
85
	public @ResponseBody String feedObjectJson(@RequestParam(value = "json", required = true) final String json,
86
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws DirecIndexApiException {
87
		log.debug(json);
88
		final ResultEntry pub = new Gson().fromJson(json, ResultEntry.class);
89
		return feedObject(pub, commit);
90
	}
91

    
92

    
93
	@RequestMapping(value = { "/api/results/feedObject" }, method = RequestMethod.POST)
94
	public @ResponseBody String feedResult(@RequestBody final ResultEntry pub,
95
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit)
96
			throws DirecIndexApiException {
97
		return feed(pub,commit);
98

    
99
	}
100

    
101
	@Deprecated
102
	@RequestMapping(value = { "/api/publications/feedObject" }, method = RequestMethod.POST)
103
	public @ResponseBody String feedObject(@RequestBody final ResultEntry pub,
104
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit)
105
			throws DirecIndexApiException {
106
		return feed(pub, commit);
107
	}
108

    
109

    
110
	@RequestMapping(value = "/api/result/{openaireId}", method = RequestMethod.DELETE)
111
	public @ResponseBody boolean deleteResultWithOpenaireId(
112
			@PathVariable(value = "openaireId") final String openaireId,
113
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws DirecIndexApiException {
114

    
115
		return deleteResult(openaireId);
116
	}
117

    
118
	@RequestMapping(value = "/api/results", method = RequestMethod.DELETE)
119
	public @ResponseBody boolean deleteResultWithOriginalId(
120
			@RequestParam(value = "originalId", required = true) final String originalId,
121
			@RequestParam(value = "collectedFromId", required = true) final String collectedFromId,
122
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws Exception {
123

    
124
		final String openaireId = ResultEntryToOaf.calculateOpenaireId(originalId, collectedFromId, serviceLocator.getService(ISLookUpService.class));
125
		return deleteResult(openaireId);
126
	}
127

    
128
	@Deprecated
129
	@RequestMapping(value = { "/api/publications/deleteObject", "/api/results/delete" }, method = RequestMethod.POST)
130
	public @ResponseBody boolean deleteResultPost(
131
			@RequestParam(value = "originalId", required = true) final String originalId,
132
			@RequestParam(value = "collectedFromId", required = true) final String collectedFromId,
133
			@RequestParam(value = "commit", required = false, defaultValue = "true") final boolean commit) throws Exception {
134

    
135
		final String openaireId = ResultEntryToOaf.calculateOpenaireId(originalId, collectedFromId, serviceLocator.getService(ISLookUpService.class));
136
		return deleteResult(openaireId);
137
	}
138

    
139
	@Deprecated
140
	private String feed(final ResultEntry pub, final boolean commit) throws DirecIndexApiException {
141
		return feed(pub);
142
	}
143

    
144
	private String feed(final ResultEntry pub) throws DirecIndexApiException {
145
		log.debug(pub);
146
		try {
147
			ResultEntryToOaf toOaf = new ResultEntryToOaf(community_api);
148
			final IndexDsInfo info = indexDSRetriever.calculateCurrentIndexDsInfo();
149
			final String oafRecord = toOaf.asOafRecord(pub, velocityEngine, serviceLocator.getService(ISLookUpService.class), oafSchemaLocation);
150
			final SolrInputDocument solrDocument = prepareSolrDocument(oafRecord, info.getIndexDsId(), oafToIndexRecordFactory.newTransformer(info.getFormat()));
151

    
152
			clientManager.getClient(info).add(solrDocument);
153
			recentResultsQueue.add(oafRecord);
154

    
155
			return pub.getOpenaireId();
156
		} catch (final Throwable e) {
157
			log.error("Error saving record", e);
158
			log.debug(pub.toString());
159
			throw new DirecIndexApiException("Error adding publication: " + e.getMessage(), e);
160
		}
161
	}
162

    
163
	private SolrInputDocument prepareSolrDocument(String record, String indexDsId, UnaryFunction<String, String> toIndexRecord) throws CloudIndexClientException {
164
		try {
165
			StreamingInputDocumentFactory documentFactory = new StreamingInputDocumentFactory();
166
			String version = (new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'")).format(new Date());
167
			String indexRecord = toIndexRecord.evaluate(record);
168
			if (log.isDebugEnabled()) {
169
				log.debug("***************************************\nSubmitting index record:\n" + indexRecord + "\n***************************************\n");
170
			}
171

    
172
			return documentFactory.parseDocument(version, indexRecord, indexDsId, "dnetResult");
173
		} catch (Throwable e) {
174
			throw new CloudIndexClientException("Error creating solr document", e);
175
		}
176
	}
177

    
178
	private boolean deleteResult(final String openaireId) throws DirecIndexApiException {
179
		try {
180
			IndexDsInfo info = indexDSRetriever.calculateCurrentIndexDsInfo();
181
			String query = String.format("objidentifier:\"%s\" OR resultdupid:\"%s\"", openaireId, openaireId);
182
			final CloudSolrClient client = clientManager.getClient(info);
183
			client.deleteByQuery(info.getColl(), query);
184
			log.info("Deleted result with id: " + openaireId + " from: " + info.getIndexBaseUrl());
185

    
186
			recentResultsQueue.remove(openaireId);
187
			return true;
188
		} catch (Throwable e) {
189
			throw new DirecIndexApiException("Error deleting publication: " + e.getMessage(), e);
190
		}
191
	}
192

    
193
	@ExceptionHandler(Exception.class)
194
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
195
	public @ResponseBody ErrorMessage handleException(final Exception e) {
196
		log.error("Error in direct index API", e);
197
		return new ErrorMessage(e);
198
	}
199

    
200
	public class ErrorMessage {
201

    
202
		private final String message;
203
		private final String stacktrace;
204

    
205
		public ErrorMessage(final Exception e) {
206
			this(e.getMessage(), ExceptionUtils.getStackTrace(e));
207
		}
208

    
209
		public ErrorMessage(final String message, final String stacktrace) {
210
			this.message = message;
211
			this.stacktrace = stacktrace;
212
		}
213

    
214
		public String getMessage() {
215
			return this.message;
216
		}
217

    
218
		public String getStacktrace() {
219
			return this.stacktrace;
220
		}
221

    
222
	}
223

    
224
}
(6-6/8)