-
Notifications
You must be signed in to change notification settings - Fork 14
/
StorageConnector.java
326 lines (290 loc) · 12.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
/**
* Copyright (C) 2020 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.Constants;
import cz.cvut.kbss.ontodriver.sesame.config.SesameConfigParam;
import cz.cvut.kbss.ontodriver.sesame.config.SesameOntoDriverProperties;
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.manager.RepositoryManager;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.sail.Sail;
import org.eclipse.rdf4j.sail.helpers.SailWrapper;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
class StorageConnector extends AbstractConnector {
private static final Logger LOG = LoggerFactory.getLogger(StorageConnector.class);
private final DriverConfiguration configuration;
private final int maxReconnectAttempts;
private Repository repository;
private RepositoryManager manager;
private RepositoryConnection connection;
StorageConnector(DriverConfiguration configuration) throws SesameDriverException {
assert configuration != null;
this.configuration = configuration;
this.maxReconnectAttempts = resolveMaxReconnectAttempts();
initialize();
this.open = true;
}
private int resolveMaxReconnectAttempts() throws SesameDriverException {
try {
final int attempts = configuration.isSet(SesameConfigParam.RECONNECT_ATTEMPTS) ? Integer.parseInt(
configuration.getProperty(SesameConfigParam.RECONNECT_ATTEMPTS)) :
Constants.DEFAULT_RECONNECT_ATTEMPTS_COUNT;
if (attempts < 0) {
throw invalidReconnectAttemptsConfig();
}
return attempts;
} catch (NumberFormatException e) {
throw invalidReconnectAttemptsConfig();
}
}
private static SesameDriverException invalidReconnectAttemptsConfig() {
return new SesameDriverException(
"Invalid value of configuration parameter " + SesameOntoDriverProperties.SESAME_RECONNECT_ATTEMPTS +
". Must be a non-negative integer.");
}
private void initialize() throws SesameDriverException {
final RepositoryConnectorInitializer initializer = new RepositoryConnectorInitializer(configuration,
maxReconnectAttempts);
initializer.initializeRepository();
this.manager = initializer.getManager();
this.repository = initializer.getRepository();
}
@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 conn = acquireConnection();
return new ConnectionStatementExecutor(conn).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();
}
LOG.trace("Acquiring repository connection.");
return acquire(1);
}
private RepositoryConnection acquire(int attempts) throws SesameDriverException {
try {
return repository.getConnection();
} catch (RepositoryException e) {
if (attempts < maxReconnectAttempts) {
LOG.warn("Unable to acquire repository connection. Error is: {}. Retrying...", e.getMessage());
return acquire(attempts + 1);
}
LOG.error("Threshold of failed connection acquisition attempts reached, throwing exception.");
throw new SesameDriverException(e);
}
}
void releaseConnection(RepositoryConnection conn) throws SesameDriverException {
try {
if (conn != null) {
LOG.trace("Releasing repository connection.");
conn.close();
}
} catch (RepositoryException e) {
throw new SesameDriverException(e);
}
}
@Override
public boolean executeBooleanQuery(String query) throws SesameDriverException {
try (final RepositoryConnection conn = acquireConnection()) {
return new ConnectionStatementExecutor(conn).executeBooleanQuery(query);
}
}
@Override
public void executeUpdate(String query) throws SesameDriverException {
try (final RepositoryConnection conn = acquireConnection()) {
new ConnectionStatementExecutor(conn).executeUpdate(query);
}
}
@Override
public List<Resource> getContexts() throws SesameDriverException {
try (final RepositoryConnection conn = acquireConnection()) {
final RepositoryResult<Resource> res = conn.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 conn = acquireConnection()) {
final RepositoryResult<Statement> m;
if (context != null) {
m = conn.getStatements(subject, property, null, includeInferred, context);
} else {
m = conn.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 conn = acquireConnection()) {
if (context != null) {
return conn.hasStatement(subject, property, null, includeInferred, context);
} else {
return conn.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;
}
}