-
Notifications
You must be signed in to change notification settings - Fork 14
/
StorageConnector.java
411 lines (370 loc) · 16.1 KB
/
StorageConnector.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
/**
* Copyright (C) 2016 Czech Technical University in Prague
* <p>
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.ontodriver.sesame.connector;
import cz.cvut.kbss.ontodriver.config.DriverConfiguration;
import cz.cvut.kbss.ontodriver.exception.OntoDriverException;
import cz.cvut.kbss.ontodriver.sesame.config.SesameConfigParam;
import cz.cvut.kbss.ontodriver.sesame.exceptions.RepositoryCreationException;
import cz.cvut.kbss.ontodriver.sesame.exceptions.RepositoryNotFoundException;
import cz.cvut.kbss.ontodriver.sesame.exceptions.SesameDriverException;
import org.eclipse.rdf4j.common.iteration.Iterations;
import org.eclipse.rdf4j.model.*;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.RepositoryResult;
import org.eclipse.rdf4j.repository.config.RepositoryConfig;
import org.eclipse.rdf4j.repository.config.RepositoryConfigException;
import org.eclipse.rdf4j.repository.manager.RemoteRepositoryManager;
import org.eclipse.rdf4j.repository.manager.RepositoryManager;
import org.eclipse.rdf4j.repository.manager.RepositoryProvider;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.repository.sail.config.SailRepositoryConfig;
import org.eclipse.rdf4j.sail.Sail;
import org.eclipse.rdf4j.sail.config.SailImplConfig;
import org.eclipse.rdf4j.sail.helpers.SailWrapper;
import org.eclipse.rdf4j.sail.inferencer.fc.ForwardChainingRDFSInferencer;
import org.eclipse.rdf4j.sail.inferencer.fc.config.ForwardChainingRDFSInferencerConfig;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.eclipse.rdf4j.sail.nativerdf.config.NativeStoreConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
class StorageConnector extends AbstractConnector {
private static final String[] KNOWN_REMOTE_SCHEMES = {"http", "https", "ftp"};
private static final String LOCAL_NATIVE_REPO = "repositories/";
private static final String FILE_SCHEME = "file";
private static final Logger LOG = LoggerFactory.getLogger(StorageConnector.class);
private final DriverConfiguration configuration;
private Repository repository;
private RepositoryManager manager;
private RepositoryConnection connection;
StorageConnector(DriverConfiguration configuration) throws SesameDriverException {
assert configuration != null;
this.configuration = configuration;
initialize();
this.open = true;
}
private void initialize() throws SesameDriverException {
final URI serverUri = configuration.getStorageProperties().getPhysicalURI();
LOG.debug("Initializing connector to repository at {}", serverUri);
try {
final boolean isRemote = isRemoteRepository(serverUri);
if (isRemote) {
this.repository = connectToRemoteRepository(serverUri.toString());
} else {
this.repository = createLocalRepository();
}
verifyRepositoryCreated(serverUri, isRemote);
repository.initialize();
} catch (RepositoryException | RepositoryConfigException e) {
throw new SesameDriverException("Failed to acquire sesame repository connection.", e);
}
}
private static boolean isRemoteRepository(URI uri) {
final String scheme = uri.getScheme();
for (String s : KNOWN_REMOTE_SCHEMES) {
if (s.equals(scheme)) {
return true;
}
}
return false;
}
private Repository connectToRemoteRepository(String repoUri) {
this.manager = RepositoryProvider.getRepositoryManagerOfRepository(repoUri);
final RemoteRepositoryManager remoteManager = (RemoteRepositoryManager) manager;
final String username = configuration.getProperty(SesameConfigParam.USERNAME, "");
if (!username.isEmpty()) {
final String password = configuration.getProperty(SesameConfigParam.PASSWORD, "");
remoteManager.setUsernameAndPassword(username, password);
}
return manager.getRepository(RepositoryProvider.getRepositoryIdOfRepository(repoUri));
}
private Repository createLocalRepository() {
final URI localUri = configuration.getStorageProperties().getPhysicalURI();
if (!isFileUri(localUri) && configuration.is(SesameConfigParam.USE_VOLATILE_STORAGE)) {
return createInMemoryRepository();
} else {
return createNativeRepository(configuration, localUri);
}
}
private static boolean isFileUri(URI uri) {
return uri.getScheme() != null && uri.getScheme().equals(FILE_SCHEME);
}
/**
* Creates a local in-memory Sesame repository which is disposed when the VM shuts down.
*/
private Repository createInMemoryRepository() {
LOG.trace("Creating local in-memory repository.");
final MemoryStore ms = new MemoryStore();
if (configuration.is(SesameConfigParam.USE_INFERENCE)) {
return new SailRepository(new ForwardChainingRDFSInferencer(ms));
} else {
return new SailRepository(ms);
}
}
/**
* Creates native repository.
* <p>
* This kind of repository stores data in files and is persistent after the VM shuts down.
*/
private Repository createNativeRepository(DriverConfiguration configuration, final URI localUri) {
LOG.trace("Creating local native repository at " + localUri);
final String[] tmp = localUri.toString().split(LOCAL_NATIVE_REPO);
if (tmp.length != 2) {
throw new RepositoryCreationException(
"Unsupported local Sesame repository path. Expected file://path/repositories/id but got "
+ localUri);
}
String repoId = tmp[1];
if (repoId.charAt(repoId.length() - 1) == '/') {
repoId = repoId.substring(0, repoId.length() - 1);
}
try {
this.manager = RepositoryProvider.getRepositoryManagerOfRepository(localUri.toASCIIString());
final RepositoryConfig cfg = createLocalNativeRepositoryConfig(repoId, configuration);
manager.addRepositoryConfig(cfg);
return manager.getRepository(repoId);
} catch (RepositoryConfigException | RepositoryException e) {
throw new RepositoryCreationException("Unable to create local repository at " + localUri, e);
}
}
private static RepositoryConfig createLocalNativeRepositoryConfig(String repoId,
DriverConfiguration configuration) {
SailImplConfig backend = new NativeStoreConfig();
if (configuration.is(SesameConfigParam.USE_INFERENCE)) {
backend = new ForwardChainingRDFSInferencerConfig(backend);
}
final SailRepositoryConfig repoType = new SailRepositoryConfig(backend);
return new RepositoryConfig(repoId, repoType);
}
private void verifyRepositoryCreated(URI serverUri, boolean isRemote) {
if (repository == null) {
if (isRemote) {
throw new RepositoryNotFoundException("Unable to reach repository at " + serverUri);
} else {
throw new RepositoryCreationException("Unable to create local repository at " + serverUri);
}
}
}
@Override
public void close() throws SesameDriverException {
if (!open) {
return;
}
LOG.debug("Closing connector to repository {}.", configuration.getStorageProperties().getPhysicalURI());
try {
repository.shutDown();
if (manager != null) {
manager.shutDown();
}
} catch (RepositoryException e) {
throw new SesameDriverException("Exception caught when closing Sesame repository connection.", e);
} finally {
this.open = false;
}
}
@Override
public TupleQueryResult executeSelectQuery(String query) throws SesameDriverException {
final RepositoryConnection connection = acquireConnection();
return new ConnectionStatementExecutor(connection).executeSelectQuery(query);
// The connection is released by the result set once it is closed
}
RepositoryConnection acquireConnection() throws SesameDriverException {
// Workaround for local native storage being reset when multiple drivers access it
if (!repository.isInitialized()) {
initialize();
}
try {
LOG.trace("Acquiring repository connection.");
return repository.getConnection();
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
void releaseConnection(RepositoryConnection connection) throws SesameDriverException {
try {
if (connection != null) {
LOG.trace("Releasing repository connection.");
connection.close();
}
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
@Override
public boolean executeBooleanQuery(String query) throws SesameDriverException {
try (final RepositoryConnection connection = acquireConnection()) {
return new ConnectionStatementExecutor(connection).executeBooleanQuery(query);
}
}
@Override
public void executeUpdate(String query) throws SesameDriverException {
try (final RepositoryConnection connection = acquireConnection()) {
new ConnectionStatementExecutor(connection).executeUpdate(query);
}
}
@Override
public List<Resource> getContexts() throws SesameDriverException {
try (final RepositoryConnection connection = acquireConnection()) {
final RepositoryResult<Resource> res = connection.getContextIDs();
return Iterations.asList(res);
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
@Override
public ValueFactory getValueFactory() {
return repository.getValueFactory();
}
@Override
public void begin() throws SesameDriverException {
super.begin();
this.connection = acquireConnection();
try {
connection.begin();
} catch (RepositoryException e) {
transaction.rollback();
throw new SesameDriverException(e);
}
}
@Override
public void commit() throws SesameDriverException {
assert connection != null;
transaction.commit();
try {
connection.commit();
connection.close();
this.connection = null;
transaction.afterCommit();
} catch (RepositoryException e) {
transaction.rollback();
throw new SesameDriverException(e);
}
}
@Override
public void rollback() throws SesameDriverException {
assert connection != null;
transaction.rollback();
try {
connection.rollback();
connection.close();
this.connection = null;
} catch (RepositoryException e) {
throw new SesameDriverException(e);
} finally {
transaction.afterRollback();
}
}
@Override
public void addStatements(Collection<Statement> statements) throws SesameDriverException {
verifyTransactionActive();
assert connection != null;
try {
connection.add(statements);
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
@Override
public void removeStatements(Collection<Statement> statements) throws SesameDriverException {
verifyTransactionActive();
assert connection != null;
try {
connection.remove(statements);
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
@Override
public Collection<Statement> findStatements(Resource subject, IRI property, Value value, boolean includeInferred)
throws SesameDriverException {
return findStatements(subject, property, value, includeInferred, null);
}
@Override
public Collection<Statement> findStatements(Resource subject, org.eclipse.rdf4j.model.IRI property,
Value value, boolean includeInferred, IRI context)
throws SesameDriverException {
try (final RepositoryConnection connection = acquireConnection()) {
final RepositoryResult<Statement> m;
if (context != null) {
m = connection.getStatements(subject, property, null, includeInferred, context);
} else {
m = connection.getStatements(subject, property, null, includeInferred);
}
return Iterations.asList(m);
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
@Override
public boolean containsStatement(Resource subject, IRI property, Value value, boolean includeInferred)
throws SesameDriverException {
return containsStatement(subject, property, value, includeInferred, null);
}
@Override
public boolean containsStatement(Resource subject, IRI property, Value value, boolean includeInferred, IRI context)
throws SesameDriverException {
try (final RepositoryConnection connection = acquireConnection()) {
if (context != null) {
return connection.hasStatement(subject, property, null, includeInferred, context);
} else {
return connection.hasStatement(subject, property, null, includeInferred);
}
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
@Override
public <T> T unwrap(Class<T> cls) throws OntoDriverException {
if (cls.isAssignableFrom(getClass())) {
return cls.cast(this);
}
if (cls.isAssignableFrom(repository.getClass())) {
return cls.cast(repository);
}
throw new SesameDriverException("No instance of class " + cls + " found.");
}
/**
* Replaces the currently open repository with the specified one.
* <p>
* Note that this functionality is only supported for in-memory stores.
*
* @param newRepository The new repository to set
*/
public void setRepository(Repository newRepository) {
Objects.requireNonNull(newRepository);
if (!isInMemoryRepository(repository)) {
throw new UnsupportedOperationException("Cannot replace repository which is not in-memory.");
}
if (transaction.isActive()) {
throw new IllegalStateException("Cannot replace repository in transaction.");
}
repository.shutDown();
assert newRepository.isInitialized();
this.repository = newRepository;
// Since in-memory repositories are not registered in RepositoryManager, we shouldn't need to deal with it
}
private static boolean isInMemoryRepository(Repository repo) {
if (!(repo instanceof SailRepository)) {
return false;
}
final Sail sail = ((SailRepository) repo).getSail();
return sail instanceof SailWrapper ? ((SailWrapper) sail).getBaseSail() instanceof MemoryStore :
sail instanceof MemoryStore;
}
}