/
CSVGraphStoreRowProcessor.java
272 lines (245 loc) · 9.08 KB
/
CSVGraphStoreRowProcessor.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
/**
* Copyright 2021 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.imports.stream.csv;
import static com.atomgraph.core.MediaType.APPLICATION_NTRIPLES_TYPE;
import com.atomgraph.core.client.LinkedDataClient;
import com.atomgraph.linkeddatahub.model.Service;
import com.univocity.parsers.common.ParsingContext;
import com.univocity.parsers.common.processor.RowProcessor;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.net.URI;
import org.apache.jena.atlas.lib.IRILib;
import org.apache.jena.query.Dataset;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.glassfish.jersey.uri.UriComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author {@literal Martynas Jusevičius <martynas@atomgraph.com>}
*/
public class CSVGraphStoreRowProcessor implements RowProcessor // extends com.atomgraph.etl.csv.stream.CSVStreamRDFProcessor
{
private static final Logger log = LoggerFactory.getLogger(CSVGraphStoreRowProcessor.class);
private final Service service, adminService;
private final LinkedDataClient ldc;
private final String base;
private final Query query;
private int subjectCount, tripleCount;
/**
* Constructs row processor.
*
* @param service SPARQL service of the application
* @param adminService SPARQL service of the admin application
* @param ldc Linked Data client
* @param base base URI
* @param query transformation query
*/
public CSVGraphStoreRowProcessor(Service service, Service adminService, LinkedDataClient ldc, String base, Query query)
{
this.service = service;
this.adminService = adminService;
this.ldc = ldc;
this.base = base;
this.query = query;
}
@Override
public void processStarted(ParsingContext context)
{
subjectCount = tripleCount = 0;
}
@Override
public void rowProcessed(String[] row, ParsingContext context)
{
Dataset rowDataset = transformRow(row, context);
// the default graph is ignored!
rowDataset.listNames().forEachRemaining(graphUri ->
{
// exceptions get swallowed by the client? TO-DO: wait for completion
Model namedModel = rowDataset.getNamedModel(graphUri);
if (!namedModel.isEmpty()) add(Entity.entity(namedModel, APPLICATION_NTRIPLES_TYPE), graphUri);
// purge cache entries that include the graph URI
if (getService().getBackendProxy() != null) ban(getService().getClient(), getService().getBackendProxy(), graphUri).close();
if (getAdminService() != null && getAdminService().getBackendProxy() != null) ban(getAdminService().getClient(), getAdminService().getBackendProxy(), graphUri).close();
}
);
}
/**
* Creates a graph using <code>PUT</code> if it doesn't exist, otherwise appends data using <code>POST</code>.
*
* @param entity request entity
* @param graphURI the graph URI
* @return JAX-RS response
*/
protected Response add(Entity entity, String graphURI)
{
try (Response headResponse = getLinkedDataClient().head(URI.create(graphURI)))
{
if (headResponse.getStatus() == Response.Status.OK.getStatusCode()) // POST if graph already exists
{
try (Response cr = getLinkedDataClient().post(URI.create(graphURI), getLinkedDataClient().getReadableMediaTypes(Model.class), entity))
{
if (!cr.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL))
{
if (log.isErrorEnabled()) log.error("RDF document with URI <{}> could not be successfully created using PUT. Status code: {}", graphURI, cr.getStatus());
throw new RuntimeException(new IOException("RDF document with URI <" + graphURI + "> could not be successfully created using PUT. Status code: " + cr.getStatus()));
}
return Response.status(cr.getStatus()).
entity(cr.readEntity(Model.class)).
build();
}
}
else // PUT to create graph
{
try (Response cr = getLinkedDataClient().put(URI.create(graphURI), getLinkedDataClient().getReadableMediaTypes(Model.class), entity))
{
if (!cr.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL))
{
if (log.isErrorEnabled()) log.error("RDF document with URI <{}> could not be successfully created using PUT. Status code: {}", graphURI, cr.getStatus());
throw new RuntimeException(new IOException("RDF document with URI <" + graphURI + "> could not be successfully created using PUT. Status code: " + cr.getStatus()));
}
return Response.status(cr.getStatus()).
entity(cr.readEntity(Model.class)).
build();
}
}
}
}
/**
* Transforms CSV row into an an RDF graph.
* First a generic CSV/RDF graph is constructed. Then the transformation query is applied on it.
* Extended SPARQL syntax is used to allow the <code>CONSTRUCT GRAPH</code> query form.
*
* @param row CSV row
* @param context parsing context
* @return RDF result
*/
public Dataset transformRow(String[] row, ParsingContext context)
{
Model rowModel = ModelFactory.createDefaultModel();
Resource subject = rowModel.createResource();
subjectCount++;
int cellNo = 0;
for (String cell : row)
{
if (cell != null && context.headers()[cellNo] != null)
{
String fragmentId = IRILib.encodeUriComponent(context.headers()[cellNo]);
Property property = rowModel.createProperty(getBase(), "#" + fragmentId);
subject.addProperty(property, cell);
tripleCount++;
}
cellNo++;
}
try (QueryExecution qex = QueryExecution.create(getQuery(), rowModel))
{
return qex.execConstructDataset();
}
}
@Override
public void processEnded(ParsingContext context)
{
}
/**
* Bans a URL from proxy cache.
*
* @param client HTTP client
* @param proxy proxy cache endpoint
* @param url request URL
* @return response from cache
*/
public Response ban(Client client, Resource proxy, String url)
{
if (url == null) throw new IllegalArgumentException("Resource cannot be null");
// create new Client instance, otherwise ApacheHttpClient reuses connection and Varnish ignores BAN request
return client.
target(proxy.getURI()).
request().
header("X-Escaped-Request-URI", UriComponent.encode(url, UriComponent.Type.UNRESERVED)).
method("BAN", Response.class);
}
/**
* Return application's SPARQL service.
*
* @return SPARQL service
*/
public Service getService()
{
return service;
}
/**
* Return admin application's SPARQL service.
*
* @return SPARQL service
*/
public Service getAdminService()
{
return adminService;
}
/**
* Returns base URI.
* @return base URI string
*/
public String getBase()
{
return base;
}
/**
* Returns the transformation query.
*
* @return SPARQL query
*/
public Query getQuery()
{
return query;
}
/**
* Returns the cumulative count of RDF subject resources.
*
* @return subject count
*/
public int getSubjectCount()
{
return subjectCount;
}
/**
* Returns the cumulative count of RDF triples.
*
* @return triple count
*/
public int getTripleCount()
{
return tripleCount;
}
/**
* Returns the HTTP client.
*
* @return client object
*/
public LinkedDataClient getLinkedDataClient()
{
return ldc;
}
}