Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc2 / spi / JDBCStoreProviderBase.java @ 44185

History | View | Annotate | Download (19.7 KB)

1
package org.gvsig.fmap.dal.store.jdbc2.spi;
2

    
3
import java.text.MessageFormat;
4
import org.gvsig.fmap.dal.store.jdbc2.JDBCStoreProvider;
5
import java.util.Arrays;
6
import java.util.Collections;
7
import java.util.Iterator;
8
import java.util.List;
9
import org.apache.commons.lang3.BooleanUtils;
10
import org.apache.commons.lang3.StringUtils;
11
import org.cresques.cts.IProjection;
12
import org.gvsig.fmap.dal.DALLocator;
13
import org.gvsig.fmap.dal.DataManager;
14
import org.gvsig.fmap.dal.DataServerExplorer;
15
import org.gvsig.fmap.dal.DataStore;
16
import org.gvsig.fmap.dal.DataStoreNotification;
17
import org.gvsig.fmap.dal.DataTypes;
18
import org.gvsig.fmap.dal.exception.CloseException;
19
import org.gvsig.fmap.dal.exception.DataException;
20
import org.gvsig.fmap.dal.exception.InitializeException;
21
import org.gvsig.fmap.dal.exception.OpenException;
22
import org.gvsig.fmap.dal.exception.ReadException;
23
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
24
import org.gvsig.fmap.dal.feature.EditableFeatureType;
25
import org.gvsig.fmap.dal.feature.FeatureQuery;
26
import org.gvsig.fmap.dal.feature.FeatureRule;
27
import org.gvsig.fmap.dal.feature.FeatureRules;
28
import org.gvsig.fmap.dal.feature.FeatureType;
29
import org.gvsig.fmap.dal.feature.spi.AbstractFeatureStoreProvider;
30
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
31
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
32
import org.gvsig.fmap.dal.feature.spi.FeatureSetProvider;
33
import org.gvsig.fmap.dal.resource.ResourceParameters;
34
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
35
import org.gvsig.fmap.dal.resource.exception.ResourceException;
36
import org.gvsig.fmap.dal.resource.spi.AbstractResource;
37
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
38
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
39
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
40
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
41
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
42
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
43
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
44
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
45
import org.gvsig.fmap.dal.store.jdbc2.ResulSetControler;
46
import org.gvsig.fmap.dal.store.jdbc2.impl.JDBCSetProvider;
47
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.AppendOperation;
48
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.CalculateEnvelopeOfColumnOperation;
49
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.CanModifyTableOperation;
50
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.CountOperation;
51
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureProviderByReferenceOperation;
52
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
53
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.PerformChangesOperation;
54
import org.gvsig.fmap.geom.Geometry;
55
import org.gvsig.fmap.geom.primitive.Envelope;
56
import org.gvsig.tools.dynobject.DynField;
57
import org.gvsig.tools.dynobject.DynObject;
58
import org.gvsig.tools.dynobject.exception.DynFieldNotFoundException;
59
import org.gvsig.tools.exception.BaseException;
60
import org.slf4j.Logger;
61
import org.slf4j.LoggerFactory;
62

    
63
@SuppressWarnings("UseSpecificCatch")
64
public class JDBCStoreProviderBase
65
        extends AbstractFeatureStoreProvider
66
        implements ResourceConsumer, JDBCStoreProvider {
67

    
68
    final static private Logger LOGGER = LoggerFactory.getLogger(JDBCStoreProviderBase.class);
69

    
70
    public class CountValue implements CalculatedValue<Long> {
71
        
72
        private Long value = null;
73

    
74
        @Override
75
        public void calculate() {
76
            JDBCStoreParameters params = getParameters();
77
            CountOperation count = getOperations().createCount(
78
                    getOperations().createTableReference(params),
79
                    params.getBaseFilter(), 
80
                    null
81
            );
82
            this.value = (Long) count.perform();            
83
        }
84
        
85
        @Override
86
        public void reset() {
87
            this.value = null;
88
        }
89
        
90
        @Override
91
        public Long get() {
92
            if( this.value == null ) {
93
                this.calculate();
94
            }
95
            return this.value;
96
        }
97
    } 
98
    
99
    public class EnvelopeValue implements CalculatedValue<Envelope> {
100
        
101
        private Envelope value = null;
102
        private boolean needCalculate = true;
103

    
104
        @Override
105
        public void calculate() {
106
            try {
107
                value = null;
108
                String columnName = getFeatureStore()
109
                        .getDefaultFeatureType()
110
                        .getDefaultGeometryAttributeName();
111
                if( columnName==null ) {
112
                    return;
113
                }
114
                IProjection crs = getFeatureStore()
115
                        .getDefaultFeatureType()
116
                        .getDefaultSRS();
117
                JDBCStoreParameters params = getParameters();
118
                CalculateEnvelopeOfColumnOperation calculateEnvelopeOfColumn = 
119
                    getOperations().createCalculateEnvelopeOfColumn(
120
                        getOperations().createTableReference(params),
121
                        columnName, 
122
                        params.getBaseFilter(), 
123
                        params.getWorkingArea(), 
124
                        crs
125
                    );
126
                value = (Envelope) calculateEnvelopeOfColumn.perform();
127
                
128
            } catch(Exception ex) {
129
                throw new RuntimeException("Can't calculate envelope.", ex);
130
            } finally {
131
               needCalculate = false;
132
            }
133
        }
134
        
135
        @Override
136
        public void reset() {
137
            this.value = null;
138
            this.needCalculate = true;
139
        }
140
        
141
        @Override
142
        public synchronized Envelope get() {
143
            if( needCalculate ) {
144
                this.calculate();
145
            }
146
            return this.value;
147
        }
148
    } 
149
        
150
    public class AllowWriteValue implements CalculatedValue<Boolean> {
151
        
152
        private Boolean value = null;
153

    
154
        @Override
155
        public void calculate() {
156
            try {
157
                JDBCStoreParameters params = getParameters();
158
                CanModifyTableOperation canModifyTable = 
159
                    getOperations().createCanModifyTableOperation(
160
                        getOperations().createTableReference(params)
161
                    );
162
                this.value = (boolean) canModifyTable.perform();
163
            } catch(Exception ex) {
164
                throw new RuntimeException("Can't determine if allow write.", ex);
165
            }
166
        }
167
        
168
        @Override
169
        public void reset() {
170
            this.value = null;
171
        }
172
        
173
        @Override
174
        public Boolean get() {
175
            if( this.value == null ) {
176
                this.calculate();
177
            }
178
            return this.value;
179
        }
180
    } 
181
    
182
    protected final JDBCHelper helper;
183

    
184
    protected CalculatedValue<Long> count = null;
185
    
186
    protected CalculatedValue<Envelope> envelope = null;
187

    
188
    protected CalculatedValue<Boolean> allowWrite = null;
189

    
190
    protected AppendOperation appendOperation = null;
191
    
192
    @SuppressWarnings({"OverridableMethodCallInConstructor", "CallToThreadStartDuringObjectConstruction"})
193
    protected JDBCStoreProviderBase(
194
            JDBCStoreParameters params,
195
            DataStoreProviderServices storeServices,
196
            DynObject metadata,
197
            JDBCHelper helper
198
    ) throws InitializeException {
199
        super(params, storeServices, metadata);
200
        this.helper = helper;
201
        this.initializeFeatureType();
202
        try {
203
            if( BooleanUtils.isTrue((Boolean) params.getDynValue("precalculateEnvelope"))  ) {
204
                FeatureType featureType = this.getStoreServices().getDefaultFeatureType();
205
                if( !StringUtils.isEmpty(featureType.getDefaultGeometryAttributeName()) ) {
206
                    Thread thread = new Thread(new Runnable() {
207
                        @Override
208
                        public void run() {
209
                            LOGGER.debug("Precalculating envelope of '"+getSourceId()+"'.");
210
                            getEnvelopeValue().get();
211
                        }
212
                    }, "PrecalculateEnvelopeOfDBTable");
213
                    thread.start();
214
                    Thread.sleep(1);
215
                }
216
           }
217
        } catch(Exception ex) {
218
            LOGGER.warn("Probems precalculating the envelope of table '"+this.getSourceId()+"'.", ex);
219
        }
220
    }
221

    
222
    
223
    @Override
224
    public JDBCSQLBuilderBase createExpression() {
225
        return this.getHelper().createSQLBuilder();
226
    }
227

    
228
    @Override
229
    public JDBCStoreParameters getParameters() {
230
        return (JDBCStoreParameters) super.getParameters();
231
    }  
232

    
233
    @Override
234
    public JDBCHelper getHelper() {
235
        return helper;
236
    }
237
    
238
    public OperationsFactory getOperations() {
239
        return this.getHelper().getOperations();
240
    }
241
    
242
    @Override
243
    public String getProviderName() {
244
        return this.getHelper().getProviderName();
245
    }
246
    
247
    @Override
248
    public int getOIDType() {
249
        return DataTypes.UNKNOWN;
250
    }
251

    
252
    @Override
253
    public Object createNewOID() {
254
        return null;
255
    }
256
    
257
    @Override
258
    public boolean allowAutomaticValues() {
259
        return this.getHelper().allowAutomaticValues();
260
    }
261

    
262
    @Override
263
    public boolean allowWrite() {
264
        return this.getAllowWriteValue().get();
265
    }
266
    
267
    @Override
268
    public Object getDynValue(String name) throws DynFieldNotFoundException {
269
        try {
270
            if (DataStore.METADATA_ENVELOPE.equalsIgnoreCase(name)) {
271
                Envelope env = this.getEnvelope();
272
                if (env != null) {
273
                    return env;
274
                }
275
            } else if (DataStore.METADATA_CRS.equalsIgnoreCase(name)) {
276
                IProjection proj;
277
                proj = this.getFeatureStore().getDefaultFeatureType().getDefaultSRS();
278
                if (proj != null) {
279
                    return proj;
280
                }
281
            }
282
        } catch (DataException e) {
283
            throw new RuntimeException(e);
284
        }
285
        return super.getDynValue(name);
286
    }
287

    
288
    @Override
289
    public CalculatedValue<Long> getCountValue() {
290
        if( this.count == null ) {
291
            this.count = new CountValue();
292
        }
293
        return this.count;
294
    }
295

    
296
    @Override
297
    public CalculatedValue<Envelope> getEnvelopeValue() {
298
        if( this.envelope == null ) {
299
            this.envelope = new EnvelopeValue();
300
        }
301
        return this.envelope;
302
    }
303
    
304
    @Override
305
    public CalculatedValue<Boolean> getAllowWriteValue() {
306
        if( this.allowWrite == null ) {
307
            this.allowWrite = new AllowWriteValue();
308
        }
309
        return this.allowWrite;
310
    }
311
    
312
    @Override
313
    public long getFeatureCount() throws DataException {
314
        return this.getCountValue().get();
315
    }
316
    
317
    @Override
318
    public boolean closeResourceRequested(ResourceProvider resource) {
319
        ResulSetControler resulSetControler = this.getHelper().getResulSetControler();
320
        resulSetControler.pack();
321
        return resulSetControler.getOpenCount() == 0;
322
    }
323

    
324
    @Override
325
    public void close() throws CloseException {
326
        JDBCUtils.closeQuietly(this.getHelper());
327
    }
328

    
329
    @Override
330
    public void resourceChanged(ResourceProvider resource) {
331
        this.getStoreServices().notifyChange(
332
                DataStoreNotification.RESOURCE_CHANGED,
333
                resource
334
        );
335
    }
336

    
337
    @Override
338
    public DataServerExplorer getExplorer() throws ReadException {
339
        DataManager manager = DALLocator.getDataManager();
340
        JDBCServerExplorerParameters exParams;
341
        JDBCStoreParameters params = getParameters();
342
        try {
343
            exParams = this.getHelper().createServerExplorerParameters();
344
            DynField[] fields = exParams.getDynClass().getDynFields();
345
            for (DynField field : fields) {
346
                try {
347
                    exParams.setDynValue(field.getName(), params.getDynValue(field.getName()));
348
                } catch(Exception ex) {
349
                    // Ignore
350
                }
351
            }
352
            exParams.setHost(params.getHost());
353
            exParams.setPort(params.getPort());
354
            exParams.setDBName(params.getDBName());
355
            exParams.setUser(params.getUser());
356
            exParams.setPassword(params.getPassword());
357
            exParams.setUrl(params.getUrl());
358
            exParams.setCatalog(params.getCatalog());
359
            exParams.setSchema(params.getSchema());
360
            exParams.setJDBCDriverClassName(params.getJDBCDriverClassName());
361

    
362
            return manager.openServerExplorer(exParams.getExplorerName(), exParams);
363
        } catch (Exception e) {
364
            throw new ReadException(this.getProviderName(), e);
365
        }
366
    }
367

    
368
    @Override
369
    protected void doDispose() throws BaseException {
370
        this.close();
371
        this.getHelper().dispose();
372
        super.doDispose();
373
    }
374

    
375
    @Override
376
    public String getSourceId() {
377
        try {
378
            return this.getHelper().getSourceId(this.getParameters());
379
        } catch(Exception ex) {
380
            return "unknow";
381
        }
382
    }
383

    
384
    @Override
385
    public String getName() {
386
        return this.getParameters().getTable();
387
    }
388

    
389
    @Override
390
    public String getFullName() {
391
        return this.getHelper().getSourceId(this.getParameters());
392
    }
393

    
394
    private static class DummyResource extends AbstractResource {
395

    
396
        private final String name;
397

    
398
        DummyResource(String name) throws InitializeException {
399
            super((ResourceParameters)null);
400
            this.name = name;
401
        }
402
        
403
        @Override
404
        public String getName() throws AccessResourceException {
405
            return MessageFormat.format("DummyResource({0})",
406
                                new Object[] { this.name });
407
        }
408

    
409
        @Override
410
        public Object get() throws AccessResourceException {
411
            return null;
412
        }
413

    
414
        @Override
415
        public boolean isThis(ResourceParameters parameters) throws ResourceException {
416
            return true;
417
        }
418
        
419
    }
420
    
421
    @Override
422
    public ResourceProvider getResource() {
423
        ResourceProvider r = getHelper().getResource();
424
        if( r == null ) {
425
            try {
426
                r = new DummyResource(this.getName());
427
            } catch (InitializeException ex) {
428
                LOGGER.warn("Can't create DummyResource",ex);
429
                // Do nothing
430
            }
431
        }
432
        return r;
433
    }
434

    
435
    @Override
436
    public void open() throws OpenException {
437

    
438
    }
439

    
440
    @Override
441
    public FeatureSetProvider createSet(
442
            FeatureQuery query,
443
            FeatureType featureType
444
        ) throws DataException {
445
        
446
        FeatureSetProvider set = new JDBCSetProvider(
447
                this,
448
                this.getHelper(), 
449
                query, 
450
                featureType
451
        );
452
        
453
        return set;
454
    }
455

    
456
    protected void initializeFeatureType() {
457
        EditableFeatureType type = this.getStoreServices().createFeatureType(getName());
458
        JDBCStoreParameters params = this.getParameters();
459
        List<String> primaryKeys = null;
460
        if( params.getPkFields() != null ) {
461
            primaryKeys = Arrays.asList(params.getPkFields());
462
        }
463
        FetchFeatureTypeOperation fetchFeatureType = 
464
             this.getOperations().createFetchFeatureType(
465
                type,
466
                this.getOperations().createTableReference(params),
467
                primaryKeys,
468
                params.getDefaultGeometryField(),
469
                params.getCRS()
470
            );
471
        fetchFeatureType.perform();
472

    
473
        if( !StringUtils.isEmpty(params.getDefaultGeometryField()) ) {
474
            if( !params.getDefaultGeometryField().equalsIgnoreCase(type.getDefaultGeometryAttributeName()) ) {
475
                type.setDefaultGeometryAttributeName(params.getDefaultGeometryField());
476
                EditableFeatureAttributeDescriptor attr = (EditableFeatureAttributeDescriptor) type.getDefaultGeometryAttribute();
477
                attr.setGeometryType(Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
478
            }
479
        }
480
        FeatureType defaultType = type.getNotEditableCopy();
481
        List<FeatureType> types = Collections.singletonList(defaultType);
482
        this.getStoreServices().setFeatureTypes(types, defaultType);
483
    }
484
    
485
    @Override
486
    protected FeatureProvider internalGetFeatureProviderByReference(
487
            FeatureReferenceProviderServices reference, 
488
            FeatureType featureType
489
        ) throws DataException {
490
        JDBCStoreParameters params = this.getParameters();
491
        FetchFeatureProviderByReferenceOperation fetchFeatureProviderByReference = 
492
            this.getOperations().createFetchFeatureProviderByReference(
493
                reference, 
494
                featureType, 
495
                this.getOperations().createTableReference(params)
496
            );
497
        FeatureProvider feature = (FeatureProvider) fetchFeatureProviderByReference.perform();
498
        return feature;
499
    }
500
    
501
    @Override
502
    public Envelope getEnvelope() throws DataException {
503
        return this.getEnvelopeValue().get();
504
    }
505

    
506
    @Override
507
    public void performChanges(Iterator deleteds, Iterator inserteds,
508
                    Iterator updateds, Iterator featureTypesChanged)
509
                    throws DataException {
510

    
511
        FeatureType type = this.getFeatureStore().getDefaultFeatureType();
512
        JDBCStoreParameters params = this.getParameters();
513
        PerformChangesOperation performChanges = this.getOperations().createPerformChanges(
514
                this.getOperations().createTableReference(params),
515
                type, 
516
                deleteds, 
517
                inserteds, 
518
                updateds, 
519
                featureTypesChanged
520
        );
521
        performChanges.perform();
522
        if( performChanges.isTypeChanged() ) {
523
            // Get rules before initializing feature type
524
            FeatureRules saved_rules = getFeatureStore().getDefaultFeatureType().getRules();
525

    
526
             // This initialization loses the feature type rules
527
            this.initializeFeatureType();
528

    
529
            // Get new feature type, clear rules and add the ones saved previously
530
            FeatureType featureType = getFeatureStore().getDefaultFeatureType();
531
            FeatureRules rules = featureType.getRules();
532
            rules.clear();
533
            for (FeatureRule rule : saved_rules) {
534
                rules.add(rule);
535
            }
536
        }
537
        this.getCountValue().reset();
538
        this.getEnvelopeValue().reset();
539
    }    
540
    
541
    @Override
542
    public boolean supportsAppendMode() {
543
        return true;
544
    }
545

    
546
    protected AppendOperation getAppendOperation() throws DataException {
547
        if( this.appendOperation == null ) {
548
            FeatureType type = this.getFeatureStore().getDefaultFeatureType();
549
            JDBCStoreParameters params = this.getParameters();
550
            this.appendOperation = this.getOperations().createAppend(
551
                this.getOperations().createTableReference(params),
552
                type 
553
            );
554
        }
555
        return this.appendOperation;
556
    }
557
    
558
    @Override
559
    public void endAppend() throws DataException {
560
        this.getAppendOperation().end();
561
    }
562

    
563
    @Override
564
    public void abortAppend() throws DataException {
565
        this.getAppendOperation().abort();
566
    }
567
    
568
    @Override
569
    public void beginAppend() throws DataException {
570
        this.getAppendOperation().begin();
571
    }
572

    
573
    @Override
574
    public void append(final FeatureProvider featureProvider) throws DataException {
575
        this.getAppendOperation().append(featureProvider);
576
    }    
577
    
578
    @Override
579
    public boolean canWriteGeometry(int geometryType, int geometrySubtype)
580
            throws DataException {
581
        return this.getHelper().canWriteGeometry(geometryType,geometrySubtype);
582
    }
583
}