-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathGenerate.java
More file actions
313 lines (284 loc) · 11.4 KB
/
Copy pathGenerate.java
File metadata and controls
313 lines (284 loc) · 11.4 KB
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
/**
* Copyright 2022 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.linkeddatahub.resource;
import com.atomgraph.core.MediaTypes;
import com.atomgraph.linkeddatahub.apps.model.Application;
import com.atomgraph.linkeddatahub.server.model.impl.DocumentHierarchyGraphStoreImpl;
import com.atomgraph.linkeddatahub.server.security.AgentContext;
import com.atomgraph.linkeddatahub.server.util.Skolemizer;
import com.atomgraph.linkeddatahub.vocabulary.LDH;
import com.atomgraph.linkeddatahub.vocabulary.VoID;
import com.atomgraph.linkeddatahub.vocabulary.DH;
import com.atomgraph.linkeddatahub.vocabulary.SIOC;
import com.atomgraph.spinrdf.vocabulary.SP;
import com.atomgraph.spinrdf.vocabulary.SPIN;
import java.net.URI;
import java.util.Calendar;
import java.util.Optional;
import java.util.UUID;
import jakarta.inject.Inject;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.container.ResourceContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriInfo;
import org.apache.jena.ontapi.model.OntModel;
import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.Syntax;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResIterator;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.DCTerms;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JAX-RS resource that generates containers for given classes.
*
* @author {@literal Martynas Jusevičius <martynas@atomgraph.com>}
*/
public class Generate
{
private static final Logger log = LoggerFactory.getLogger(Generate.class);
private final UriInfo uriInfo;
private final MediaTypes mediaTypes;
private final Application application;
private final OntModel ontology;
private final Optional<AgentContext> agentContext;
private final com.atomgraph.linkeddatahub.Application system;
private final ResourceContext resourceContext;
/**
* Constructs endpoint for container generation.
*
* @param request current request
* @param uriInfo current URI info
* @param mediaTypes supported media types
* @param application matched application
* @param ontology ontology of the current application
* @param system system application
* @param agentContext authenticated agent's context
* @param resourceContext resource context for creating resources
*/
@Inject
public Generate(@Context Request request, @Context UriInfo uriInfo, MediaTypes mediaTypes,
com.atomgraph.linkeddatahub.apps.model.Application application, Optional<OntModel> ontology, Optional<AgentContext> agentContext,
com.atomgraph.linkeddatahub.Application system, @Context ResourceContext resourceContext)
{
if (ontology.isEmpty()) throw new InternalServerErrorException("Ontology is not specified");
this.uriInfo = uriInfo;
this.mediaTypes = mediaTypes;
this.application = application;
this.ontology = ontology.get();
this.agentContext = agentContext;
this.system = system;
this.resourceContext = resourceContext;
}
/**
* Generates containers for given classes.
* Expects a model containing a parent container (<samp>sioc:has_parent</samp>) and one or more class specifications
* with <samp>void:class</samp> and <samp>spin:query</samp> properties. Creates a new container for each class with a view based
* on the provided SPARQL <samp>SELECT</samp> query.
*
* @param model the RDF model containing the generation parameters
* @return JAX-RS response indicating success or failure
*/
@POST
public Response post(Model model)
{
ResIterator it = model.listSubjectsWithProperty(SIOC.HAS_PARENT);
try
{
if (!it.hasNext()) throw new BadRequestException("Argument resource not provided");
Resource arg = it.next();
Resource service = arg.getPropertyResourceValue(LDH.service);
Resource parent = arg.getPropertyResourceValue(SIOC.HAS_PARENT);
if (parent == null) throw new BadRequestException("Parent container (sioc:has_parent) not provided");
ResIterator partIt = model.listSubjectsWithProperty(VoID._class);
try
{
while (partIt.hasNext())
{
Resource part = partIt.next();
Resource cls = part.getPropertyResourceValue(VoID._class);
Resource queryRes = part.getPropertyResourceValue(SPIN.query);
if (queryRes == null) throw new BadRequestException("Container query string (spin:query) not provided");
// Lookup query in ontology
Resource queryResource = getOntology().getResource(queryRes.getURI());
if (queryResource == null || !queryResource.hasProperty(SP.text))
throw new BadRequestException("Query resource not found in ontology: " + queryRes.getURI());
String queryString = queryResource.getProperty(SP.text).getString();
Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
if (!query.isSelectType()) throw new BadRequestException("Container query is not of SELECT type");
ParameterizedSparqlString pss = new ParameterizedSparqlString(query.toString());
pss.setIri(RDF.type.getLocalName(), cls.getURI()); // inject $type value
URI containerGraphURI = UriBuilder.fromUri(parent.getURI()).path("{slug}/").build(UUID.randomUUID().toString());
Model containerModel = ModelFactory.createDefaultModel();
createContainer(containerModel,
containerGraphURI, parent,
cls.getLocalName() + "s",
createView(containerModel, createContainerSelect(containerModel,
"Select " + cls.getLocalName(),
pss.asQuery(),
service)));
new Skolemizer(containerGraphURI.toString()).apply(containerModel);
// append triples directly to the graph store without doing an HTTP request (and thus no ACL check)
try (Response containerResponse = getResourceContext().getResource(DocumentHierarchyGraphStoreImpl.class).post(containerModel, false, containerGraphURI))
{
if (!containerResponse.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL))
{
if (log.isErrorEnabled()) log.error("Cannot create container");
throw new InternalServerErrorException("Cannot create container");
}
}
}
}
finally
{
partIt.close();
}
// ban the parent container URI from proxy cache to make sure the next query using it will be fresh (e.g. SELECT that loads children)
getSystem().ban(getSystem().getServiceContext(getApplication().getService()).getBackendProxy(), parent.getURI(), true);
return Response.ok().build();
}
finally
{
it.close();
}
}
/**
* Creates <code>SELECT</code> SPARQL query.
*
* @param model RDF model
* @param title query title
* @param query query object
* @param service optional SPARQL service resource
* @return query resource
*/
public Resource createContainerSelect(Model model, String title, Query query, Resource service)
{
Resource resource = model.createResource().
addProperty(RDF.type, SP.Select).
addLiteral(DCTerms.title, title).
addProperty(SP.text, query.toString());
if (service != null) resource.addProperty(LDH.service, service);
return resource;
}
/**
* Creates a container document.
*
* @param model RDF model
* @param graphURI named graph URI
* @param parent parent document resource
* @param title document title
* @param content document content
* @return container resource
*/
public Resource createContainer(Model model, URI graphURI, Resource parent, String title, Resource content)
{
return model.createResource(graphURI.toString()).
addProperty(RDF.type, DH.Container).
addProperty(SIOC.HAS_PARENT, parent).
addLiteral(DCTerms.title, title).
addLiteral(DH.slug, UUID.randomUUID().toString()).
addLiteral(DCTerms.created, Calendar.getInstance()).
addProperty(model.createProperty(RDF.getURI(), "_1"), content); // TO-DO: make sure we're creating sequence value larger than the existing ones?
}
/**
* Creates content resource.
*
* @param model RDF model
* @param query query resource
* @return content resource
*/
public Resource createView(Model model, Resource query)
{
return model.createResource().
addProperty(RDF.type, LDH.View).
addProperty(SPIN.query, query);
}
/**
* Returns the supported media types.
*
* @return media types
*/
public MediaTypes getMediaTypes()
{
return mediaTypes;
}
/**
* Returns the current application.
*
* @return the application
*/
public Application getApplication()
{
return application;
}
/**
* Returns the ontology.
*
* @return the ontology
*/
public OntModel getOntology()
{
return ontology;
}
/**
* Returns the current URI info.
*
* @return URI info
*/
public UriInfo getUriInfo()
{
return uriInfo;
}
/**
* Returns the authenticated agent's context.
*
* @return optional agent context
*/
public Optional<AgentContext> getAgentContext()
{
return agentContext;
}
/**
* Returns the system application.
*
* @return system application
*/
public com.atomgraph.linkeddatahub.Application getSystem()
{
return system;
}
/**
* Returns the resource context.
*
* @return resource context
*/
public ResourceContext getResourceContext()
{
return resourceContext;
}
}