/
ModelXSLTWriter.java
472 lines (401 loc) · 18.5 KB
/
ModelXSLTWriter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/**
* Copyright 2012 Martynas Jusevičius <martynas@atomgraph.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.atomgraph.client.writer;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.reasoner.Reasoner;
import org.apache.jena.reasoner.rulesys.GenericRuleReasoner;
import org.apache.jena.reasoner.rulesys.Rule;
import org.apache.jena.vocabulary.RDF;
import com.sun.jersey.spi.resource.Singleton;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.Providers;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.jena.iri.IRI;
import org.apache.jena.iri.IRIFactory;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.RDFWriter;
import org.apache.jena.rdfxml.xmloutput.impl.Basic;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.checker.CheckerIRI;
import org.apache.jena.riot.system.ErrorHandlerFactory;
import com.atomgraph.client.exception.OntClassNotFoundException;
import com.atomgraph.client.filter.response.ConstructorBase;
import com.atomgraph.client.util.DataManager;
import com.atomgraph.client.util.OntologyProvider;
import com.atomgraph.client.util.XSLTBuilder;
import com.atomgraph.client.vocabulary.AC;
import com.atomgraph.client.vocabulary.LDT;
import com.atomgraph.core.util.Link;
import com.atomgraph.core.vocabulary.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Transforms RDF with XSLT stylesheet and writes (X)HTML result to response.
* Needs to be registered in the application.
*
* @author Martynas Jusevičius <martynas@atomgraph.com>
* @see <a href="http://jena.apache.org/documentation/javadoc/jena/com/hp/hpl/jena/rdf/model/Model.html">Model</a>
* @see <a href="http://jsr311.java.net/nonav/javadoc/javax/ws/rs/ext/MessageBodyWriter.html">MessageBodyWriter</a>
*/
@Provider
@Singleton
@Produces({MediaType.APPLICATION_XHTML_XML,MediaType.TEXT_HTML}) // MediaType.APPLICATION_XML ?
public class ModelXSLTWriter implements MessageBodyWriter<Model> // WriterGraphRIOT?
{
private static final Logger log = LoggerFactory.getLogger(ModelXSLTWriter.class);
private final Templates templates;
private final Map<Resource, MediaType> modeMediaTypeMap = new HashMap<>();
{
modeMediaTypeMap.put(AC.EditMode, MediaType.TEXT_HTML_TYPE);
modeMediaTypeMap.put(AC.MapMode, MediaType.TEXT_HTML_TYPE);
}
@Context private UriInfo uriInfo;
@Context private Request request;
@Context private HttpHeaders httpHeaders;
@Context private ServletConfig servletConfig;
@Context private Providers providers;
@Context private HttpServletRequest httpServletRequest;
/**
* Constructs from XSLT builder.
*
* @param templates
* @see com.atomgraph.client.util.XSLTBuilder
*/
public ModelXSLTWriter(Templates templates)
{
if (templates == null) throw new IllegalArgumentException("Templates cannot be null");
this.templates = templates;
}
public Providers getProviders()
{
return providers;
}
public DataManager getDataManager()
{
ContextResolver<DataManager> cr = getProviders().getContextResolver(DataManager.class, null);
return cr.getContext(DataManager.class);
}
public ModelXSLTWriter()
{
this.templates = null;
}
@Override
public void writeTo(Model model, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headerMap, OutputStream entityStream) throws IOException
{
if (log.isTraceEnabled()) log.trace("Writing Model with HTTP headers: {} MediaType: {}", headerMap, mediaType);
try
{
Templates stylesheet = getTemplates();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//RDFWriter writer = model.getWriter(RDFLanguages.RDFXML.getName());
RDFWriter writer = new Basic(); // workaround for Jena 3.0.1 bug: https://issues.apache.org/jira/browse/JENA-1168
writer.setProperty("allowBadURIs", true); // round-tripping RDF/POST with user input may contain invalid URIs
writer.write(model, baos, null);
synchronized (this)
{
getXSLTBuilder(XSLTBuilder.fromStylesheet(stylesheet).document(new ByteArrayInputStream(baos.toByteArray())),
headerMap).
resolver(getDataManager()).
result(new StreamResult(entityStream)).
transform();
}
}
catch (TransformerException ex)
{
if (log.isErrorEnabled()) log.error("XSLT transformation failed", ex);
throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); // TO-DO: make Mapper
}
}
public void write(Model model, OutputStream entityStream) throws TransformerException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
model.write(baos, RDFLanguages.RDFXML.getName(), null);
XSLTBuilder.fromStylesheet(getTemplates()).
document(new ByteArrayInputStream(baos.toByteArray())).
resolver(getDataManager()).
result(new StreamResult(entityStream)).
transform();
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
{
return Model.class.isAssignableFrom(type);
}
@Override
public long getSize(Model model, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
{
return -1;
}
public Source getSource(Model model)
{
if (model == null) throw new IllegalArgumentException("Model cannot be null");
if (log.isDebugEnabled()) log.debug("Number of Model stmts read: {}", model.size());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
model.write(stream, RDFLanguages.RDFXML.getName(), null);
if (log.isDebugEnabled()) log.debug("RDF/XML bytes written: {}", stream.toByteArray().length);
return new StreamSource(new ByteArrayInputStream(stream.toByteArray()));
}
public Source getSource(OntModel ontModel, boolean writeAll)
{
if (!writeAll) return getSource(ontModel);
if (ontModel == null) throw new IllegalArgumentException("OntModel cannot be null");
if (log.isDebugEnabled()) log.debug("Number of OntModel stmts read: {}", ontModel.size());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ontModel.writeAll(stream, Lang.RDFXML.getName(), null);
if (log.isDebugEnabled()) log.debug("RDF/XML bytes written: {}", stream.toByteArray().length);
return new StreamSource(new ByteArrayInputStream(stream.toByteArray()));
}
public UriInfo getUriInfo()
{
return uriInfo;
}
public Request getRequest()
{
return request;
}
public HttpHeaders getHttpHeaders()
{
return httpHeaders;
}
public ServletConfig getServletConfig()
{
return servletConfig;
}
public HttpServletRequest getHttpServletRequest()
{
return httpServletRequest;
}
public Map<Resource, MediaType> getModeMediaTypeMap()
{
return modeMediaTypeMap;
}
public URI getMode()
{
if (getUriInfo().getQueryParameters().getFirst(AC.mode.getLocalName()) != null)
return URI.create(getUriInfo().getQueryParameters().getFirst(AC.mode.getLocalName()));
return null;
}
public URI getContextURI()
{
return URI.create(getHttpServletRequest().getRequestURL().toString()).
resolve(getHttpServletRequest().getContextPath() + "/");
}
public Templates getTemplates()
{
if (templates != null) return templates;
else
{
ContextResolver<Templates> cr = getProviders().getContextResolver(Templates.class, null);
return cr.getContext(Templates.class);
}
}
public XSLTBuilder getXSLTBuilder(XSLTBuilder bld, MultivaluedMap<String, Object> headerMap) throws TransformerConfigurationException
{
bld.parameter("{" + A.absolutePath.getNameSpace() + "}" + A.absolutePath.getLocalName(), getUriInfo().getAbsolutePath()).
parameter("{" + A.requestUri.getNameSpace() + "}" + A.requestUri.getLocalName(), getUriInfo().getRequestUri()).
parameter("{" + A.method.getNameSpace() + "}" + A.method.getLocalName(), getRequest().getMethod()).
parameter("{" + A.httpHeaders.getNameSpace() + "}" + A.httpHeaders.getLocalName(), headerMap.toString()).
parameter("{" + AC.contextUri.getNameSpace() + "}" + AC.contextUri.getLocalName(), getContextURI());
try
{
URI typeHref = getLinkHref(headerMap, "Link", RDF.type.getLocalName());
if (typeHref != null)
bld.parameter("{" + RDF.type.getNameSpace() + "}" + RDF.type.getLocalName(), typeHref);
URI baseHref = getLinkHref(headerMap, "Link", LDT.baseUri.getURI()); // LDT.baseUri?
if (baseHref != null)
bld.parameter("{" + LDT.baseUri.getNameSpace() + "}" + LDT.baseUri.getLocalName(), baseHref);
URI ontologyHref = getLinkHref(headerMap, "Link", LDT.ontology.getURI());
if (ontologyHref != null)
{
bld.parameter("{" + LDT.ontology.getNameSpace() + "}" + LDT.ontology.getLocalName(), ontologyHref);
OntModelSpec ontModelSpec = getOntModelSpec(getRules(headerMap, "Rules"));
OntModel sitemap = getOntModel(ontologyHref.toString(), ontModelSpec);
bld.parameter("{" + AC.sitemap.getNameSpace() + "}" + AC.sitemap.getLocalName(), getSource(sitemap, true));
}
}
catch (URISyntaxException ex)
{
if (log.isErrorEnabled()) log.error("'Link' response header contains invalid URI: {}", headerMap.getFirst("Link"));
}
Object query = headerMap.getFirst("Query");
if (query != null) bld.parameter("{http://spinrdf.org/spin#}query", query.toString());
// workaround for Google Maps and Saxon-CE
// They currently seem to work only in HTML mode and not in XHTML, because of document.write() usage
// https://saxonica.plan.io/issues/1447
// https://code.google.com/p/gmaps-api-issues/issues/detail?id=2820
MediaType customMediaType = getCustomMediaType(getUriInfo());
if (customMediaType != null)
{
if (log.isDebugEnabled()) log.debug("Overriding response media type with '{}'", customMediaType);
List<Object> contentTypes = new ArrayList();
contentTypes.add(customMediaType);
headerMap.put(HttpHeaders.CONTENT_TYPE, contentTypes);
}
Object contentType = headerMap.getFirst(HttpHeaders.CONTENT_TYPE);
if (contentType != null)
{
if (log.isDebugEnabled()) log.debug("Writing Model using XSLT media type: {}", contentType);
bld.outputProperty(OutputKeys.MEDIA_TYPE, contentType.toString());
}
Object contentLanguage = headerMap.getFirst(HttpHeaders.CONTENT_LANGUAGE);
if (contentLanguage != null)
{
if (log.isDebugEnabled()) log.debug("Writing Model using language: {}", contentLanguage.toString());
bld.parameter("{" + LDT.lang.getNameSpace() + "}" + LDT.lang.getLocalName(), contentLanguage.toString());
}
// pass HTTP query parameters into XSLT
Iterator<Entry<String, List<String>>> paramIt = getUriInfo().getQueryParameters().entrySet().iterator();
while (paramIt.hasNext())
{
Entry<String, List<String>> entry = paramIt.next();
bld.parameter(entry.getKey(), entry.getValue().get(0)); // set string value
if (log.isDebugEnabled()) log.debug("Setting XSLT param \"{}\" from HTTP query string with value: {}", entry.getKey(), entry.getValue().get(0));
}
// override the reserved parameters that need special types
return setQueryParameters(bld, getUriInfo());
}
public XSLTBuilder setQueryParameters(XSLTBuilder bld, UriInfo uriInfo)
{
if (bld == null) throw new IllegalArgumentException("XSLTBuilder cannot be null");
if (uriInfo == null) throw new IllegalArgumentException("UriInfo name cannot be null");
/*
// map uri query param values to g:requestUri XSLT param values
if (uriInfo.getQueryParameters().getFirst(AC.uri.getLocalName()) != null)
bld.parameter("{" + A.requestUri.getNameSpace() + "}" + A.requestUri.getLocalName(),
URI.create(uriInfo.getQueryParameters().getFirst(AC.uri.getLocalName())));
*/
if (uriInfo.getQueryParameters().getFirst(LDT.lang.getLocalName()) != null)
bld.parameter("{" + LDT.lang.getNameSpace() + "}" + LDT.lang.getLocalName(),
uriInfo.getQueryParameters().getFirst(LDT.lang.getLocalName()));
if (uriInfo.getQueryParameters().getFirst(AC.endpointUri.getLocalName()) != null)
bld.parameter("{" + AC.endpointUri.getNameSpace() + "}" + AC.endpointUri.getLocalName(),
URI.create(uriInfo.getQueryParameters().getFirst(AC.endpointUri.getLocalName())));
return bld;
}
public OntModel getSitemap(MultivaluedMap<String, Object> headerMap, String ontologyURI)
{
return getOntModel(ontologyURI, getOntModelSpec(getRules(headerMap, "Rules")));
}
public URI getLinkHref(MultivaluedMap<String, Object> headerMap, String headerName, String rel) throws URISyntaxException
{
if (headerMap == null) throw new IllegalArgumentException("Header Map cannot be null");
if (headerName == null) throw new IllegalArgumentException("String header name cannot be null");
if (rel == null) throw new IllegalArgumentException("Property Map cannot be null");
List<Object> links = headerMap.get(headerName);
if (links != null)
{
Iterator<Object> it = links.iterator();
while (it.hasNext())
{
String linkHeader = it.next().toString();
Link link = Link.valueOf(linkHeader);
if (link.getRel().equals(rel)) return link.getHref();
}
}
return null;
}
public OntModelSpec getOntModelSpec(List<Rule> rules)
{
OntModelSpec ontModelSpec = new OntModelSpec(OntModelSpec.OWL_MEM);
if (rules != null)
{
Reasoner reasoner = new GenericRuleReasoner(rules);
//reasoner.setDerivationLogging(true);
//reasoner.setParameter(ReasonerVocabulary.PROPtraceOn, Boolean.TRUE);
ontModelSpec.setReasoner(reasoner);
}
return ontModelSpec;
}
public final List<Rule> getRules(MultivaluedMap<String, Object> headerMap, String headerName)
{
String rules = getRulesString(headerMap, headerName);
if (rules == null) return null;
return Rule.parseRules(rules);
}
public String getRulesString(MultivaluedMap<String, Object> headerMap, String headerName)
{
if (headerMap == null) throw new IllegalArgumentException("Header Map cannot be null");
if (headerName == null) throw new IllegalArgumentException("String header name cannot be null");
Object rules = headerMap.getFirst(headerName);
if (rules != null) return rules.toString();
return null;
}
public OntModel getOntModel(String ontologyURI, OntModelSpec ontModelSpec)
{
return new OntologyProvider().getOntModel(ontologyURI, ontModelSpec);
}
public MediaType getCustomMediaType(UriInfo uriInfo)
{
Resource mode = null;
if (uriInfo.getQueryParameters().getFirst(AC.forClass.getLocalName()) != null)
mode = AC.EditMode; // this could be solved using a dummy ac:ConstructMode instead
else
{
if (uriInfo.getQueryParameters().getFirst(AC.mode.getLocalName()) != null)
mode = ResourceFactory.createResource(uriInfo.getQueryParameters().getFirst(AC.mode.getLocalName()));
}
if (mode != null && getModeMediaTypeMap().containsKey(mode))
return getModeMediaTypeMap().get(mode);
return null;
}
public IRI checkURI(String classIRIStr)
{
if (classIRIStr == null) throw new IllegalArgumentException("URI String cannot be null");
IRI classIRI = IRIFactory.iriImplementation().create(classIRIStr);
// throws Exceptions on bad URIs:
CheckerIRI.iriViolations(classIRI, ErrorHandlerFactory.getDefaultErrorHandler());
return classIRI;
}
public Source getConstructedSource(URI ontologyURI, URI forClassURI) throws URISyntaxException
{
if (ontologyURI == null) throw new IllegalArgumentException("Ontology URI cannot be null");
if (forClassURI == null) throw new IllegalArgumentException("Class URI cannot be null");
Model model = ModelFactory.createDefaultModel();
OntModelSpec ontModelSpec = getOntModelSpec(null);
OntModel ontModel = getOntModel(ontologyURI.toString(), ontModelSpec);
OntClass forClass = ontModel.getOntClass(checkURI(forClassURI.toString()).toURI().toString());
if (forClass == null) throw new OntClassNotFoundException("OntClass '" + forClassURI + "' not found in sitemap");
new ConstructorBase().construct(forClass, model);
return getSource(model);
}
}