Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.impl / src / main / java / org / gvsig / fmap / dal / impl / DefaultTransaction.java @ 47779

History | View | Annotate | Download (15.2 KB)

1
/*
2
 * gvSIG. Desktop Geographic Information System.
3
 * 
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 * 
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 * 
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 * 
16
 * You should have received a copy of the GNU General Public License 
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>. 
18
 * 
19
 * For any additional information, do not hesitate to contact us
20
 * at info AT gvsig.com, or visit our website www.gvsig.com.
21
 */
22

    
23
package org.gvsig.fmap.dal.impl;
24

    
25
import java.util.ArrayList;
26
import java.util.Collection;
27
import java.util.HashMap;
28
import java.util.HashSet;
29
import java.util.List;
30
import java.util.Map;
31
import java.util.Set;
32
import java.util.UUID;
33
import org.apache.commons.lang3.StringUtils;
34
import org.apache.commons.lang3.tuple.MutablePair;
35
import org.apache.commons.lang3.tuple.Pair;
36
import org.gvsig.fmap.dal.DataServerExplorer;
37
import org.gvsig.fmap.dal.DataStore;
38
import org.gvsig.fmap.dal.SupportTransactions;
39
import org.gvsig.fmap.dal.exception.DataException;
40
import org.gvsig.fmap.dal.feature.FeatureStore;
41
import static org.gvsig.fmap.dal.feature.FeatureStore.MODE_QUERY;
42
import org.gvsig.fmap.dal.spi.DataTransactionServices;
43
import org.gvsig.tools.dispose.Disposable;
44
import org.gvsig.tools.dispose.DisposeUtils;
45
import org.gvsig.tools.dispose.impl.AbstractDisposable;
46
import org.gvsig.tools.observer.BaseNotification;
47
import org.gvsig.tools.observer.ObservableHelper;
48
import org.gvsig.tools.observer.Observer;
49
import org.slf4j.Logger;
50
import org.slf4j.LoggerFactory;
51

    
52
/**
53
 *
54
 * @author gvSIG Team
55
 */
56
@SuppressWarnings("UseSpecificCatch")
57
public class DefaultTransaction extends AbstractDisposable implements DataTransactionServices {
58

    
59
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTransaction.class);
60
    
61
    private final String code;
62
    private final Map<String,DataServerExplorer> explorers;
63
    private final Map<String,ConnectionService> connections;
64
    private Map<String,Pair<DataStore,Boolean>> stores;
65
    private boolean inProgress;
66
    private List<Disposable> disposables;
67
    private ObservableHelper observableHelper;
68
    private Set<SupportTransactions> supportTransactions;
69

    
70
    public DefaultTransaction() {
71
        this.code = UUID.randomUUID().toString().replace("-", "");
72
        this.stores = new HashMap<>();
73
        this.explorers = new HashMap<>();
74
        this.disposables = new ArrayList<>();
75
        this.supportTransactions = new HashSet<>();
76
        this.inProgress = false;
77
        this.connections = new HashMap<>();
78
        this.observableHelper = new ObservableHelper();
79
    }
80

    
81
    @Override
82
    public String getCode() {
83
        return this.code;
84
    }
85

    
86
    @Override
87
    public void begin() throws DataException {
88
        if( this.inProgress ) {
89
            throw new IllegalStateException("Transaction already started.");
90
        }
91
        this.observableHelper.notifyObservers(this, new BaseNotification("BEGIN", null));
92
        this.inProgress = true;
93
    }
94

    
95
    @Override
96
    public void commit() throws DataException {
97
        if (!this.isInProgress()) {
98
            throw new IllegalStateException("Can't commit transaction without begin.");
99
        }
100
        try {
101
            LOGGER.debug("commit in "+this.getCode());
102
            int retries = 5;
103
            boolean needretry = false;
104
            while(retries > 0) {
105
                needretry = false;
106
                Collection<Pair<DataStore, Boolean>> theStores = new ArrayList(stores.values());
107
                for (Pair<DataStore, Boolean> item : theStores) {
108
                    DataStore store = getStore(item);
109
                    if (store instanceof FeatureStore) {
110
                        FeatureStore fstore = (FeatureStore) store;
111
                        if (fstore != null && fstore.getMode() != MODE_QUERY) {
112
                            LOGGER.debug("commit: finishEditing "+store.getFullName());
113
                            fstore.finishEditing();
114
                            needretry=true;
115
                        }
116
                    }
117
                }
118
                if( !needretry ) {
119
                    break;
120
                }
121
                LOGGER.debug("commit: retry store finish editing");
122
                retries--;
123
            }
124
            for (ConnectionService connection : this.connections.values()) {
125
                connection.finish();
126
            }
127
            this.observableHelper.notifyObservers(this, new BaseNotification("COMMIT", null));
128
            this.inProgress = false;
129
        } finally {
130
            LOGGER.debug("commit out "+this.getCode());
131
        }
132
    }
133

    
134
    @Override
135
    public void rollback() throws DataException {
136
        if( !this.isInProgress() ) {
137
            throw new IllegalStateException("Can't rollback transaction without begin.");
138
        }
139
//        LOGGER.info("rollback in");
140
        for (Pair<DataStore, Boolean> item : stores.values()) {
141
            DataStore store = getStore(item);
142
            if( store instanceof FeatureStore ) {
143
                FeatureStore fstore = (FeatureStore) store;
144
                if( fstore.getMode() != MODE_QUERY) {
145
                    fstore.cancelEditing();
146
                }
147
            }
148
        }
149
        for (ConnectionService connection : this.connections.values()) {
150
            connection.abort();
151
        }
152
        this.observableHelper.notifyObservers(this, new BaseNotification("ROLLBACK", null));
153
        this.inProgress = false;
154
//        LOGGER.info("rollback out");
155
    }
156

    
157
    @Override
158
    public void rollbackQuietly() {
159
        try {
160
            this.rollback();
161
        } catch(Exception ex) {
162
            // Do nothing
163
        }
164
    }
165

    
166
    @Override
167
    public void add(DataStore store) {
168
        add(store, null, true);
169
    }
170

    
171
    @Override
172
    public void add(DataStore store, String id) { 
173
        this.add(store, id, true);
174
    }
175
    
176
    @Override
177
    public void add(DataStore store, boolean local) {
178
        this.add(store, null, local);
179
    }
180
    
181
    @Override
182
    public void add(DataStore store, String id, boolean local) {
183
        if (store == null) {
184
            throw new IllegalArgumentException("The store is required.");
185
        }
186
//        try {
187
//            LOGGER.info("add in "+this.getCode()+" "+store.getFullName());
188
            String theId = id;
189
            if (StringUtils.isBlank(id)) {
190
                theId = store.hashCode() + "@" + store.getFullName();
191
            } else {
192
                DataStore theStore = getStore(this.stores.get(theId));
193
                if (theStore != null) {
194
                    if (theStore == store) {
195
                        return;
196
                    }
197
                    throw new IllegalArgumentException("The id '" + id + "' is already used.");
198
                }
199
            }
200
            if (store instanceof SupportTransactions) {
201
                ((SupportTransactions) store).setTransaction(this);
202
            }
203
            if (!local) {
204
                DisposeUtils.bind(store);
205
            }
206
            this.stores.put(theId, new MutablePair<>(store, local));
207
//        } finally {
208
//            LOGGER.info("add out");
209
//        }
210
    }
211

    
212
    @Override
213
    public FeatureStore getFeatureStore(String id) {
214
        FeatureStore store = (FeatureStore) this.getStore(this.stores.get(id));
215
        if(store == null){
216
            for (Pair<DataStore, Boolean> value : stores.values()) {
217
                DataStore currentStore = this.getStore(value);
218
                if(StringUtils.equalsIgnoreCase(id, currentStore.getName())){
219
                    if(store != null){
220
                        if(!StringUtils.equals(store.getFullName(), currentStore.getFullName())){
221
                            return null;
222
                        }
223
                    }
224
                    store = (FeatureStore) this.getStore(value);
225
                }
226
            }
227
        }
228
        return store;
229
    }
230
    
231
    @Override
232
    public void add(DataServerExplorer explorer) {
233
        this.add(explorer, null, true);
234
    }
235

    
236
    @Override
237
    public void add(DataServerExplorer explorer, String id) {
238
        this.add(explorer, id, true);
239
    }
240
    
241
    @Override
242
    public void add(DataServerExplorer explorer, boolean local) {
243
        this.add(explorer, null, local);
244
    }
245
    
246
    @Override
247
    public void add(DataServerExplorer explorer, String id, boolean local) {
248
        if(explorer == null){
249
            throw new IllegalArgumentException("The explorer is required.");
250
        }
251
        String theId = id;
252
        if( StringUtils.isBlank(id) ) {
253
            theId = String.valueOf(explorer.hashCode());
254
        } else {
255
            DataServerExplorer theExplorer = this.explorers.get(theId);
256
            if(theExplorer!=null ){
257
                if( theExplorer==explorer ) {
258
                    return;
259
                }
260
                throw new IllegalArgumentException("The id '"+id+"' is already used.");
261
            }
262
        }
263
        
264
        if( explorer instanceof SupportTransactions ) {
265
            ((SupportTransactions) explorer).setTransaction(this);
266
        }
267
        if(!local){
268
            DisposeUtils.bind(explorer);
269
        }
270
        this.explorers.put(theId,explorer);
271
    }
272
    
273
    @Override
274
    public DataServerExplorer getServerExplorer(String id) {
275
        return this.explorers.get(id);
276
    }
277

    
278
    @Override
279
    public void add(Disposable resource) throws DataException {
280
        this.disposables.add(resource);
281
    }
282

    
283
    @Override
284
    public void add(SupportTransactions obj, boolean local) throws DataException {
285
        if(obj == null){
286
            throw new IllegalArgumentException("The transaction supplier is required.");
287
        }
288
        if(obj instanceof DataStore){
289
          this.add((DataStore)obj, local);
290
          return;
291
        } 
292
        if(obj instanceof DataServerExplorer){
293
          this.add((DataServerExplorer)obj, local);
294
          return;
295
        } 
296
        obj.setTransaction(this);
297
        if(!local){
298
            DisposeUtils.bind(obj);
299
        }
300
        this.supportTransactions.add(obj);
301
    }
302

    
303
    @Override
304
    public void remove(DataStore store) {
305
        if( this.inProgress && !DisposeUtils.isNullOrDisposed(store)){
306
            throw new IllegalStateException("Can't remove store from a in progress transaction.");
307
        }
308
//        try {
309
//            LOGGER.info("remove in");        
310
            String id = null;
311
            for (Map.Entry<String, Pair<DataStore,Boolean>> entry : this.stores.entrySet()) {
312
                if( store == getStore(entry.getValue()) ) {
313
                    id = entry.getKey();
314
                    break;
315
                }
316
            }
317
            if( id==null ) {
318
                return;
319
            }
320
            if( store instanceof SupportTransactions ) {
321
                ((SupportTransactions) store).setTransaction(null);
322
            }
323
            this.stores.remove(id);
324
            DisposeUtils.dispose(store);
325
//        } finally {
326
//            LOGGER.info("remove in");        
327
//        }
328
    }
329

    
330
    @Override
331
    public void remove(DataServerExplorer serverExplorer) {
332
        if( this.inProgress ) {
333
            throw new IllegalStateException("Can't remove server explorer from a in progress transaction.");
334
        }
335
        String id = null;
336
        for (Map.Entry<String, DataServerExplorer> entry : this.explorers.entrySet()) {
337
            if( serverExplorer == entry.getValue() ) {
338
                id = entry.getKey();
339
                break;
340
            }
341
        }
342
        if( id==null ) {
343
            return;
344
        }
345
        if( serverExplorer instanceof SupportTransactions ) {
346
            ((SupportTransactions) serverExplorer).setTransaction(null);
347
        }
348
        this.explorers.remove(id);
349
        DisposeUtils.dispose(serverExplorer);
350
    }
351

    
352
    @Override
353
    public boolean isInProgress() {
354
        return inProgress;
355
    }
356

    
357
    @Override
358
    public void doDispose() {
359
//        LOGGER.info("doDispose in "+this.getCode());        
360
        
361
        if( this.inProgress ) {
362
            this.rollbackQuietly();
363
        }
364
        for (Pair<DataStore, Boolean> item : stores.values()) {
365
            DataStore store = getStore(item);
366
            if( store instanceof SupportTransactions ) {
367
                ((SupportTransactions) store).setTransaction(null);
368
            }
369
            DisposeUtils.disposeQuietly(store);
370
            
371
        }
372
        for (DataServerExplorer explorer : explorers.values()) {
373
            if( explorer instanceof SupportTransactions ) {
374
                ((SupportTransactions) explorer).setTransaction(null);
375
            }
376
            DisposeUtils.disposeQuietly(explorer);
377
            
378
        }
379
        for (Disposable resource : disposables) {
380
            if( resource instanceof SupportTransactions ) {
381
                ((SupportTransactions) resource).setTransaction(null);
382
            }
383
            DisposeUtils.disposeQuietly(resource);            
384
        }
385
        for (SupportTransactions obj : supportTransactions) {
386
            obj.setTransaction(null);
387
            DisposeUtils.disposeQuietly(obj);            
388
        }
389
        for (ConnectionService connection : this.connections.values()) {
390
            connection.dispose();
391
        }
392
        this.supportTransactions = null;
393
        this.disposables = null;
394
        this.stores = null;
395
//        LOGGER.info("doDispose out");        
396
   }
397

    
398
    @Override
399
    public void close() throws Exception {
400
        this.dispose();
401
    }
402

    
403
    @Override
404
    public void addConnection(ConnectionService connection) {
405
        if( this.connections.containsKey(connection.getId()) ) {
406
            return;
407
        }
408
        this.connections.put(connection.getId(), connection);
409
    }
410

    
411
    @Override
412
    public ConnectionService getConnection(String id) {
413
        return this.connections.get(id);
414
    }
415

    
416
    @Override
417
    public void removeConnection(String id) {
418
        this.connections.remove(id);
419
    }
420

    
421
    @Override
422
    public boolean existsConnection(String id) {
423
        return this.connections.containsKey(id);
424
    }
425

    
426
    @Override
427
    public void addObserver(Observer obsrvr) {
428
        this.observableHelper.addObserver(obsrvr);
429
    }
430

    
431
    @Override
432
    public void deleteObserver(Observer obsrvr) {
433
        this.observableHelper.deleteObserver(obsrvr);
434
    }
435

    
436
    @Override
437
    public void deleteObservers() {
438
        this.observableHelper.deleteObservers();
439
    }
440

    
441
    @Override
442
    public boolean contains(DataServerExplorer explorer) {
443
        for (DataServerExplorer value : this.explorers.values()) {
444
            if(explorer == value){
445
                return true;
446
            }
447
        }
448
        return false;
449
    }
450

    
451
    @Override
452
    public boolean contains(DataStore store) {
453
        for (Pair<DataStore, Boolean> item : stores.values()) {
454
            DataStore value = getStore(item);
455
            if(store == value){
456
                return true;
457
            }
458
        }
459
        return false;
460
    }
461
    
462
    private DataStore getStore(Pair<DataStore, Boolean> item) {
463
        if( item == null ) {
464
            return null;
465
        }
466
        return item.getLeft();
467
    }
468
        
469
}