forked from JabRef/jabref
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DBMSSynchronizer.java
429 lines (389 loc) · 16.9 KB
/
DBMSSynchronizer.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
package org.jabref.logic.shared;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern;
import org.jabref.logic.exporter.BibDatabaseWriter;
import org.jabref.logic.exporter.MetaDataSerializer;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.util.MetaDataParser;
import org.jabref.logic.shared.event.ConnectionLostEvent;
import org.jabref.logic.shared.event.SharedEntriesNotPresentEvent;
import org.jabref.logic.shared.event.UpdateRefusedEvent;
import org.jabref.logic.shared.exception.OfflineLockException;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.event.EntriesAddedEvent;
import org.jabref.model.database.event.EntriesRemovedEvent;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.event.EntriesEvent;
import org.jabref.model.entry.event.EntriesEventSource;
import org.jabref.model.entry.event.FieldChangedEvent;
import org.jabref.model.metadata.MetaData;
import org.jabref.model.metadata.event.MetaDataChangedEvent;
import org.jabref.model.util.FileUpdateMonitor;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Synchronizes the shared or local databases with their opposite side. Local changes are pushed by {@link EntriesEvent}
* using Google's Guava EventBus.
*/
public class DBMSSynchronizer implements DatabaseSynchronizer {
private static final Logger LOGGER = LoggerFactory.getLogger(DBMSSynchronizer.class);
private DBMSProcessor dbmsProcessor;
private String dbName;
private final BibDatabaseContext bibDatabaseContext;
private MetaData metaData;
private final BibDatabase bibDatabase;
private final EventBus eventBus;
private Connection currentConnection;
private final Character keywordSeparator;
private final GlobalCitationKeyPattern globalCiteKeyPattern;
private final FileUpdateMonitor fileMonitor;
private Optional<BibEntry> lastEntryChanged;
public DBMSSynchronizer(BibDatabaseContext bibDatabaseContext, Character keywordSeparator,
GlobalCitationKeyPattern globalCiteKeyPattern, FileUpdateMonitor fileMonitor) {
this.bibDatabaseContext = Objects.requireNonNull(bibDatabaseContext);
this.bibDatabase = bibDatabaseContext.getDatabase();
this.metaData = bibDatabaseContext.getMetaData();
this.fileMonitor = fileMonitor;
this.eventBus = new EventBus();
this.keywordSeparator = keywordSeparator;
this.globalCiteKeyPattern = Objects.requireNonNull(globalCiteKeyPattern);
this.lastEntryChanged = Optional.empty();
}
/**
* Listening method. Inserts a new {@link BibEntry} into shared database.
*
* @param event {@link EntriesAddedEvent} object
*/
@Subscribe
public void listen(EntriesAddedEvent event) {
// While synchronizing the local database (see synchronizeLocalDatabase() below), some EntriesEvents may be posted.
// In this case DBSynchronizer should not try to insert the bibEntry entry again (but it would not harm).
if (isEventSourceAccepted(event) && checkCurrentConnection()) {
synchronizeLocalMetaData();
pullWithLastEntry();
synchronizeLocalDatabase();
dbmsProcessor.insertEntries(event.getBibEntries());
// Reset last changed entry because it just has already been synchronized -> Why necessary?
lastEntryChanged = Optional.empty();
}
}
/**
* Listening method. Updates an existing shared {@link BibEntry}.
*
* @param event {@link FieldChangedEvent} object
*/
@Subscribe
public void listen(FieldChangedEvent event) {
BibEntry bibEntry = event.getBibEntry();
// While synchronizing the local database (see synchronizeLocalDatabase() below), some EntriesEvents may be posted.
// In this case DBSynchronizer should not try to update the bibEntry entry again (but it would not harm).
if (isPresentLocalBibEntry(bibEntry) && isEventSourceAccepted(event) && checkCurrentConnection() && !event.isFilteredOut()) {
synchronizeLocalMetaData();
pullWithLastEntry();
synchronizeSharedEntry(bibEntry);
synchronizeLocalDatabase(); // Pull changes for the case that there were some
} else {
// Set new BibEntry that has been changed last
lastEntryChanged = Optional.of(bibEntry);
}
}
/**
* Listening method. Deletes the given list of {@link BibEntry} from shared database.
*
* @param event {@link EntriesRemovedEvent} object
*/
@Subscribe
public void listen(EntriesRemovedEvent event) {
// While synchronizing the local database (see synchronizeLocalDatabase() below), some EntriesEvents may be posted.
// In this case DBSynchronizer should not try to delete the bibEntry entry again (but it would not harm).
if (isEventSourceAccepted(event) && checkCurrentConnection()) {
synchronizeLocalMetaData();
pullWithLastEntry();
dbmsProcessor.removeEntries(event.getBibEntries());
synchronizeLocalDatabase();
}
}
/**
* Listening method. Synchronizes the shared {@link MetaData} and applies them locally.
*
* @param event
*/
@Subscribe
public void listen(MetaDataChangedEvent event) {
if (checkCurrentConnection()) {
synchronizeSharedMetaData(event.getMetaData(), globalCiteKeyPattern);
synchronizeLocalDatabase();
applyMetaData();
dbmsProcessor.notifyClients();
}
}
/**
* Sets the table structure of shared database if needed and pulls all shared entries to the new local database.
*
* @throws DatabaseNotSupportedException if the version of shared database does not match the version of current
* shared database support ({@link DBMSProcessor}).
*/
public void initializeDatabases() throws DatabaseNotSupportedException {
try {
if (!dbmsProcessor.checkBaseIntegrity()) {
LOGGER.info("Integrity check failed. Fixing...");
// This check should only be performed once on initial database setup.
if (dbmsProcessor.databaseIsAtMostJabRef35()) {
throw new DatabaseNotSupportedException();
}
// Calling dbmsProcessor.setupSharedDatabase() lets dbmsProcessor.checkBaseIntegrity() be true.
dbmsProcessor.setupSharedDatabase();
}
} catch (SQLException e) {
LOGGER.error("Could not check intergrity", e);
throw new IllegalStateException(e);
}
dbmsProcessor.startNotificationListener(this);
synchronizeLocalMetaData();
synchronizeLocalDatabase();
}
/**
* Synchronizes the local database with shared one. Possible update types are: removal, update, or insert of a
* {@link BibEntry}.
*/
@Override
public void synchronizeLocalDatabase() {
if (!checkCurrentConnection()) {
return;
}
List<BibEntry> localEntries = bibDatabase.getEntries();
Map<Integer, Integer> idVersionMap = dbmsProcessor.getSharedIDVersionMapping();
// remove old entries locally
removeNotSharedEntries(localEntries, idVersionMap.keySet());
List<Integer> entriesToInsertIntoLocalDatabase = new ArrayList<>();
// compare versions and update local entry if needed
for (Map.Entry<Integer, Integer> idVersionEntry : idVersionMap.entrySet()) {
boolean remoteEntryMatchingOneLocalEntryFound = false;
for (BibEntry localEntry : localEntries) {
if (idVersionEntry.getKey().equals(localEntry.getSharedBibEntryData().getSharedID())) {
remoteEntryMatchingOneLocalEntryFound = true;
if (idVersionEntry.getValue() > localEntry.getSharedBibEntryData().getVersion()) {
Optional<BibEntry> sharedEntry = dbmsProcessor.getSharedEntry(idVersionEntry.getKey());
if (sharedEntry.isPresent()) {
// update fields
localEntry.setType(sharedEntry.get().getType(), EntriesEventSource.SHARED);
localEntry.getSharedBibEntryData()
.setVersion(sharedEntry.get().getSharedBibEntryData().getVersion());
sharedEntry.get().getFieldMap().forEach(
// copy remote values to local entry
(field, value) -> localEntry.setField(field, value, EntriesEventSource.SHARED)
);
// locally remove not existing fields
localEntry.getFields().stream()
.filter(field -> !sharedEntry.get().hasField(field))
.forEach(
field -> localEntry.clearField(field, EntriesEventSource.SHARED)
);
}
}
}
}
if (!remoteEntryMatchingOneLocalEntryFound) {
entriesToInsertIntoLocalDatabase.add(idVersionEntry.getKey());
}
}
if (!entriesToInsertIntoLocalDatabase.isEmpty()) {
// in case entries should be added into the local database, insert them
bibDatabase.insertEntries(dbmsProcessor.partitionAndGetSharedEntries(entriesToInsertIntoLocalDatabase), EntriesEventSource.SHARED);
}
}
/**
* Removes all local entries which are not present on shared database.
*
* @param localEntries List of {@link BibEntry} the entries should be removed from
* @param sharedIDs Set of all IDs which are present on shared database
*/
private void removeNotSharedEntries(List<BibEntry> localEntries, Set<Integer> sharedIDs) {
List<BibEntry> entriesToRemove =
localEntries.stream()
.filter(localEntry -> !sharedIDs.contains(localEntry.getSharedBibEntryData().getSharedID()))
.collect(Collectors.toList());
if (!entriesToRemove.isEmpty()) {
eventBus.post(new SharedEntriesNotPresentEvent(entriesToRemove));
// remove all non-shared entries without triggering listeners
bibDatabase.removeEntries(entriesToRemove, EntriesEventSource.SHARED);
}
}
/**
* Synchronizes the shared {@link BibEntry} with the local one.
*/
@Override
public void synchronizeSharedEntry(BibEntry bibEntry) {
if (!checkCurrentConnection()) {
return;
}
try {
BibDatabaseWriter.applySaveActions(bibEntry, metaData); // perform possibly existing save actions
dbmsProcessor.updateEntry(bibEntry);
} catch (OfflineLockException exception) {
eventBus.post(new UpdateRefusedEvent(bibDatabaseContext, exception.getLocalBibEntry(), exception.getSharedBibEntry()));
} catch (SQLException e) {
LOGGER.error("SQL Error", e);
}
}
/**
* Synchronizes all meta data locally.
*/
public void synchronizeLocalMetaData() {
if (!checkCurrentConnection()) {
return;
}
try {
metaData.setEventPropagation(false);
MetaDataParser parser = new MetaDataParser(fileMonitor);
parser.parse(metaData, dbmsProcessor.getSharedMetaData(), keywordSeparator);
metaData.setEventPropagation(true);
} catch (ParseException e) {
LOGGER.error("Parse error", e);
}
}
/**
* Synchronizes all shared meta data.
*/
private void synchronizeSharedMetaData(MetaData data, GlobalCitationKeyPattern globalCiteKeyPattern) {
if (!checkCurrentConnection()) {
return;
}
try {
dbmsProcessor.setSharedMetaData(MetaDataSerializer.getSerializedStringMap(data, globalCiteKeyPattern));
} catch (SQLException e) {
LOGGER.error("SQL Error: ", e);
}
}
/**
* Applies the {@link MetaData} on all local and shared BibEntries.
*/
public void applyMetaData() {
if (!checkCurrentConnection()) {
return;
}
for (BibEntry bibEntry : bibDatabase.getEntries()) {
try {
// synchronize only if changes were present
if (!BibDatabaseWriter.applySaveActions(bibEntry, metaData).isEmpty()) {
dbmsProcessor.updateEntry(bibEntry);
}
} catch (OfflineLockException exception) {
eventBus.post(new UpdateRefusedEvent(bibDatabaseContext, exception.getLocalBibEntry(), exception.getSharedBibEntry()));
} catch (SQLException e) {
LOGGER.error("SQL Error: ", e);
}
}
}
/**
* Synchronizes the local BibEntries and applies the fetched MetaData on them.
*/
@Override
public void pullChanges() {
if (!checkCurrentConnection()) {
return;
}
// First synchronize entry, then synchronize database
pullWithLastEntry();
synchronizeLocalDatabase();
synchronizeLocalMetaData();
}
// Synchronizes local BibEntries only if last entry changes still remain
public void pullLastEntryChanges() {
if (!lastEntryChanged.isEmpty()) {
if (!checkCurrentConnection()) {
return;
}
synchronizeLocalMetaData();
pullWithLastEntry();
synchronizeLocalDatabase(); // Pull changes for the case that there were some
}
}
// Synchronizes local BibEntries and pulls remaining last entry changes
private void pullWithLastEntry() {
if (!lastEntryChanged.isEmpty() && isPresentLocalBibEntry(lastEntryChanged.get())) {
synchronizeSharedEntry(lastEntryChanged.get());
}
lastEntryChanged = Optional.empty();
}
/**
* Checks whether the current SQL connection is valid. In case that the connection is not valid a new {@link
* ConnectionLostEvent} is going to be sent.
*
* @return <code>true</code> if the connection is valid, else <code>false</code>.
*/
public boolean checkCurrentConnection() {
try {
boolean isValid = currentConnection.isValid(0);
if (!isValid) {
LOGGER.warn("Lost SQL connection.");
eventBus.post(new ConnectionLostEvent(bibDatabaseContext));
}
return isValid;
} catch (SQLException e) {
LOGGER.error("SQL Error:", e);
return false;
}
}
/**
* Checks whether the {@link EntriesEventSource} of an {@link EntriesEvent} is crucial for this class.
*
* @param event An {@link EntriesEvent}
* @return <code>true</code> if the event is able to trigger operations in {@link DBMSSynchronizer}, else
* <code>false</code>
*/
public boolean isEventSourceAccepted(EntriesEvent event) {
EntriesEventSource eventSource = event.getEntriesEventSource();
return ((eventSource == EntriesEventSource.LOCAL) || (eventSource == EntriesEventSource.UNDO));
}
@Override
public void openSharedDatabase(DatabaseConnection connection) throws DatabaseNotSupportedException {
this.dbName = connection.getProperties().getDatabase();
this.currentConnection = connection.getConnection();
this.dbmsProcessor = DBMSProcessor.getProcessorInstance(connection);
initializeDatabases();
}
@Override
public void closeSharedDatabase() {
// Submit remaining entry changes
pullLastEntryChanges();
try {
dbmsProcessor.stopNotificationListener();
currentConnection.close();
} catch (SQLException e) {
LOGGER.error("SQL Error:", e);
}
}
private boolean isPresentLocalBibEntry(BibEntry bibEntry) {
return bibDatabase.getEntries().contains(bibEntry);
}
@Override
public String getDBName() {
return dbName;
}
public DBMSProcessor getDBProcessor() {
return dbmsProcessor;
}
@Override
public DatabaseConnectionProperties getConnectionProperties() {
return dbmsProcessor.getDBMSConnectionProperties();
}
public void setMetaData(MetaData metaData) {
this.metaData = metaData;
}
@Override
public void registerListener(Object listener) {
eventBus.register(listener);
}
}