Project

General

Profile

1
package eu.dnetlib.parthenos.virtuoso;
2

    
3
import java.io.IOException;
4
import java.io.OutputStream;
5
import java.io.StringWriter;
6
import java.util.HashMap;
7
import java.util.Iterator;
8
import java.util.List;
9
import java.util.Map;
10

    
11
import com.google.common.collect.Iterators;
12
import com.google.common.collect.Lists;
13
import eu.dnetlib.parthenos.CRM;
14
import eu.dnetlib.parthenos.publisher.ParthenosPublisherException;
15
import freemarker.template.Configuration;
16
import freemarker.template.Template;
17
import freemarker.template.TemplateException;
18
import org.apache.commons.io.IOUtils;
19
import org.apache.commons.lang3.StringUtils;
20
import org.apache.commons.logging.Log;
21
import org.apache.commons.logging.LogFactory;
22
import org.apache.http.HttpEntity;
23
import org.apache.http.HttpHeaders;
24
import org.apache.http.NameValuePair;
25
import org.apache.http.client.entity.UrlEncodedFormEntity;
26
import org.apache.http.client.methods.CloseableHttpResponse;
27
import org.apache.http.client.methods.HttpPost;
28
import org.apache.http.impl.client.CloseableHttpClient;
29
import org.apache.http.impl.client.HttpClients;
30
import org.apache.http.message.BasicNameValuePair;
31
import org.apache.http.util.EntityUtils;
32
import org.apache.jena.query.ResultSet;
33
import org.apache.jena.sparql.engine.http.QueryEngineHTTP;
34
import org.springframework.beans.factory.annotation.Autowired;
35
import org.springframework.beans.factory.annotation.Value;
36
import org.springframework.http.HttpStatus;
37
import org.springframework.web.bind.annotation.*;
38

    
39
/**
40
 * Created by Alessia Bardi on 31/01/2018.
41
 * Read-only API for virtuoso.
42
 *
43
 * //TODO: error handling (http://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services)
44
 * //TODO: pagination
45
 * //TODO swagger documentation?
46
 *
47
 * @author Alessia Bardi
48
 */
49
@RestController
50
public class VirtuosoReadAPI {
51

    
52
	private static final Log log = LogFactory.getLog(VirtuosoReadAPI.class);
53

    
54
	@Value("${virtuoso.sparqlurl}")
55
	private String sparqlUrl;
56
	@Value("${virtuoso.pwd}")
57
	private String username;
58
	@Value("${virtuoso.pwd}")
59
	private String password;
60
	@Value("${virtuoso.uri.base.default}")
61
	private String defaultBaseURI;
62
	@Value("${virtuoso.connectionstring")
63
	private String virtuosoConnectionString;
64

    
65
	@Autowired
66
	private Configuration freemarkerConfig;
67

    
68
	@RequestMapping(value = "/virtuoso/apiSubjectsWithType", produces = { "application/json" }, method = RequestMethod.GET)
69
	public List<String> getSubjectsForApiWithType(@RequestParam final String api, @RequestParam final String typeNamespace, @RequestParam final String typeName, @RequestParam final int limit, @RequestParam final int offset){
70
		String fullTypeName = typeNamespace + typeName;
71
		log.debug(String.format("Getting subjects of type %s for API %s limit %d offset %d", fullTypeName, api, limit, offset));
72
		//if I add the ORDER BY the query is too slow: let's hope we are not getting the same subjects over and over again
73
		String queryForSubjectsTemplate = "DEFINE input:inference 'parthenos_rules' SELECT DISTINCT ?s WHERE { GRAPH ?g {?s a <%s> .} . GRAPH <provenance> {?g <dnetcollectedFrom> <%s> .}} LIMIT %d OFFSET %d";
74
		String q = String.format(queryForSubjectsTemplate, fullTypeName, defaultBaseURI+api, limit, offset);
75
		final QueryEngineHTTP serviceRequest = new QueryEngineHTTP(sparqlUrl, q);
76
		ResultSet subjects = serviceRequest.execSelect();
77
		Iterator<String> s = Iterators.transform(subjects, qs -> qs.getResource("s").getURI());
78
		List<String> res = Lists.newArrayList(s);
79
		serviceRequest.close();
80
		return res;
81
	}
82

    
83
	/**
84
	 * Returns the paginated list of resource URI used as subjects in the context of a given api. All subject URIs are returned, except from CRM.E55_Type and CRM.E41_Appellation.
85
	 * TODO: probably we can remove this, as it is used only for testing.
86
	 * @param api
87
	 * @param limit
88
	 * @param offset
89
	 * @return a page of URIs that are subjects in the context of a given api
90
	 *
91
	 */
92
	@Deprecated
93
	@RequestMapping(value = "/virtuoso/apiSubjects", produces = { "application/json" }, method = RequestMethod.GET)
94
	public List<String> getSubjectsForApi(@RequestParam final String api, @RequestParam final int limit, @RequestParam final int offset){
95
		log.debug(String.format("Getting subjects for API %s, limit %d offset %d", api, limit, offset));
96
		//if I add the ORDER BY the query is too slow: let's hope we are not getting the same subjects over and over again
97
		String queryForSubjectsTemplate = "DEFINE input:inference 'parthenos_rules' SELECT DISTINCT ?s WHERE { GRAPH ?g {?s a ?t . FILTER (?t != <%s> && ?t != <%s>)} . GRAPH <provenance> {?g <dnetcollectedFrom> <%s> .}} LIMIT %d OFFSET %d ";
98
		String q = String.format(queryForSubjectsTemplate, CRM.E55_Type.getURI(), CRM.E41_Appellation.getURI(), defaultBaseURI+api, limit, offset);
99
		final QueryEngineHTTP serviceRequest = new QueryEngineHTTP(sparqlUrl, q);
100
		ResultSet subjects = serviceRequest.execSelect();
101
		Iterator<String> s = Iterators.transform(subjects, qs -> qs.getResource("s").getURI());
102
		List<String> res = Lists.newArrayList(s);
103
		serviceRequest.close();
104
		return res;
105
	}
106

    
107

    
108
	@RequestMapping(value = "/virtuoso/subject", produces = { "application/rdf+xml", "application/xml" }, method = RequestMethod.GET)
109
	@ResponseStatus(value = HttpStatus.OK)
110
	public void getSubject(@RequestParam final String subjectURL, @RequestParam final String typeName, @RequestParam final String timeoutMs, final OutputStream responseStream)
111
			throws IOException, TemplateException, ParthenosPublisherException {
112
		String templateName = typeName+".sparql";
113
		Template temp = freemarkerConfig.getTemplate(templateName);
114
		Map<String, String> values = new HashMap<>();
115
		values.put("subjectURL", subjectURL);
116

    
117
		StringWriter sw = new StringWriter();
118
		temp.process(values, sw);
119
		String q = sw.toString();
120
		log.debug("Querying for "+subjectURL+" with query "+templateName);
121
		sendConstructResponse(q, timeoutMs, responseStream);
122
	}
123

    
124

    
125
	protected void sendConstructResponse(final String query, final String timeoutMs, final OutputStream responseStream) throws IOException, ParthenosPublisherException {
126
		String res = executeSparqlPost(query, timeoutMs);
127
		IOUtils.write(res, responseStream);
128
	}
129

    
130
	protected String executeSparqlPost(final String query, final String timeoutMs) throws IOException, ParthenosPublisherException {
131
		try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
132
			HttpPost httpPost = new HttpPost(sparqlUrl);
133
			httpPost.setHeader(HttpHeaders.ACCEPT, "application/rdf+xml");
134
			List<NameValuePair> nvps = Lists.newArrayList();
135
			nvps.add(new BasicNameValuePair("query", query));
136
			if (StringUtils.isNotBlank(timeoutMs)) {
137
				nvps.add(new BasicNameValuePair("timeout", timeoutMs));
138
			}
139
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
140

    
141

    
142
			try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
143
				HttpEntity entity2 = response2.getEntity();
144
				String res = IOUtils.toString(entity2.getContent());
145
				EntityUtils.consume(entity2);
146
				int statusCode = response2.getStatusLine().getStatusCode();
147
				switch(statusCode){
148
				case 200:
149
					return res;
150
				case 504:
151
					String msg = String.format("ERROR 504 on query %s", query);
152
					throw new ParthenosPublisherException(msg);
153
				default:
154
					String errorMessage = String.format("ERROR HTTP STATUS CODE %d, REASON PHRASE: %s\n ERROR BODY: %s", statusCode, response2.getStatusLine(), res);
155
					log.error(errorMessage);
156
					throw new ParthenosPublisherException(errorMessage);
157
				}
158
			}
159
		}
160

    
161

    
162
	}
163
	
164

    
165

    
166

    
167

    
168
}
(3-3/3)