Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.exportto / org.gvsig.exportto.swing / org.gvsig.exportto.swing.prov / org.gvsig.exportto.swing.prov.jdbc / src / main / java / org / gvsig / exportto / swing / prov / jdbc / ExporrtoJDBCService.java @ 42090

History | View | Annotate | Download (16.1 KB)

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

    
25
import java.util.Map;
26
import org.apache.commons.lang3.StringUtils;
27
import org.cresques.cts.ICoordTrans;
28
import org.cresques.cts.IProjection;
29
import org.gvsig.exportto.ExporttoService;
30
import org.gvsig.exportto.ExporttoServiceException;
31
import org.gvsig.exportto.ExporttoServiceFinishAction;
32
import org.gvsig.fmap.dal.DALLocator;
33
import org.gvsig.fmap.dal.DataManager;
34
import org.gvsig.fmap.dal.DataTypes;
35
import org.gvsig.fmap.dal.feature.EditableFeature;
36
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
37
import org.gvsig.fmap.dal.feature.EditableFeatureType;
38
import org.gvsig.fmap.dal.feature.Feature;
39
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
40
import org.gvsig.fmap.dal.feature.FeatureSet;
41
import org.gvsig.fmap.dal.feature.FeatureStore;
42
import org.gvsig.fmap.dal.feature.FeatureType;
43
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
44
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorer;
45
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
46
import org.gvsig.fmap.geom.Geometry;
47
import org.gvsig.tools.dispose.DisposableIterator;
48
import org.gvsig.tools.task.AbstractMonitorableTask;
49
import org.slf4j.Logger;
50
import org.slf4j.LoggerFactory;
51

    
52
/**
53
 * @author gvSIG Team
54
 * @version $Id$
55
 *
56
 */
57
public class ExporrtoJDBCService extends AbstractMonitorableTask implements
58
        ExporttoService {
59

    
60
    private static final Logger logger = LoggerFactory.getLogger(ExporrtoJDBCService.class);
61

    
62
    public static final int CHECK_NONE = 0;
63
    public static final int CHECK_IF_CORRUPT = 1;
64
    public static final int CHECK_IF_VALID = 2;
65

    
66
    public static final int ACTION_SET_GEOMETRY_TO_NULL = 0;
67
    public static final int ACTION_SKIP_FEATURE = 1;
68
    public static final int ACTION_ABORT = 2;
69

    
70
    private ExporttoServiceFinishAction exporttoServiceFinishAction = null;
71
    private ExporttoJDBCOptions options;
72
//    private Map<String,String> translationIds;
73

    
74
    public ExporrtoJDBCService(ExporttoJDBCOptions options) {
75
        this.options = options;
76
    }
77

    
78
    protected String getTranslatedIdentifier(String identifier) {
79
        String s = identifier;
80
        if (this.options.getTranslateIdentifiersToLowerCase()) {
81
            s = s.toLowerCase();
82
        }
83
        if (this.options.getRemoveSpacesInIdentifiers()) {
84
            s = StringUtils.normalizeSpace(s).replace(" ", "_");
85
        }
86
        return s;
87
    }
88

    
89
    protected void createTable(JDBCServerExplorer explorer) throws Exception {
90

    
91
        FeatureType targetFeatureType;
92
        EditableFeatureType targetEditableFeatureType;
93

    
94
        targetFeatureType = options.getSource().getDefaultFeatureType().getCopy();
95
        targetEditableFeatureType = targetFeatureType.getEditable();
96

    
97
        if (this.options.getTranslateIdentifiersToLowerCase()
98
                || this.options.getRemoveSpacesInIdentifiers()) {
99
            for (int i = 0; i < targetEditableFeatureType.size(); i++) {
100
                EditableFeatureAttributeDescriptor x = (EditableFeatureAttributeDescriptor) targetEditableFeatureType.get(i);
101
                x.setName(getTranslatedIdentifier(x.getName()));
102
            }
103
        }
104

    
105
        if (this.options.getPrimaryKey() != null) {
106
            EditableFeatureAttributeDescriptor pk = (EditableFeatureAttributeDescriptor) targetEditableFeatureType.get(getTranslatedIdentifier(options.getPrimaryKey()));
107
            if (pk == null) {
108
                pk = targetEditableFeatureType.add(
109
                        getTranslatedIdentifier(this.options.getPrimaryKey()),
110
                        DataTypes.LONG
111
                );
112
                pk.setIsPrimaryKey(true);
113
                pk.setIsAutomatic(true);
114
            } else {
115
                pk.setIsPrimaryKey(true);
116
            }
117
        }
118

    
119
        if (this.options.getCreateIndexInGeometryRow()) {
120
            EditableFeatureAttributeDescriptor x = (EditableFeatureAttributeDescriptor) targetEditableFeatureType.getDefaultGeometryAttribute();
121
            x.setIsIndexed(true);
122
        }
123

    
124
        // ======================================================
125
        // Reprojection: set SRS of geometry field to target SRS
126
        EditableFeatureAttributeDescriptor attrdescriptor
127
                = (EditableFeatureAttributeDescriptor) targetEditableFeatureType.getDefaultGeometryAttribute();
128
        if (attrdescriptor != null) {
129
            attrdescriptor.setSRS(this.options.getTargetProjection());
130
        }
131

    
132
        // ======================================
133
        JDBCNewStoreParameters createTableParams = (JDBCNewStoreParameters) explorer.getAddParameters();
134

    
135
        createTableParams.setSelectRole(this.options.getSelectRole());
136
        createTableParams.setInsertRole(this.options.getInsertRole());
137
        createTableParams.setUpdateRole(this.options.getUpdateRole());
138
        createTableParams.setDeleteRole(this.options.getDeleteRole());
139
        createTableParams.setTruncateRole(this.options.getTruncateRole());
140
        createTableParams.setReferenceRole(this.options.getReferenceRole());
141
        createTableParams.setTriggerRole(this.options.getTriggerRole());
142
        createTableParams.setAllRole(this.options.getAllRole());
143

    
144
        createTableParams.setSchema(this.options.getSchema());
145
        createTableParams.setPostCreatingStatement(this.options.getPostCreatingStatement());
146

    
147
        createTableParams.setDefaultFeatureType(targetEditableFeatureType);
148
        createTableParams.setTable(this.options.getTableName());
149
        explorer.add(explorer.getStoreName(), createTableParams, true);
150
    }
151

    
152
    private static class InvalidGeometryException extends ExporttoServiceException {
153

    
154
        public InvalidGeometryException(Feature feature, String checkMessage) {
155
            super(checkMessage, null, checkMessage, 0);
156
            this.feature = feature;
157
        }
158
    }
159

    
160
    public void export(FeatureSet featureSet) throws ExporttoServiceException {
161
        Geometry.ValidationStatus geometryCheck;
162

    
163
        DisposableIterator it = null;
164
        EditableFeature targetFeature = null;
165
        FeatureStore target = null;
166

    
167
        try {
168

    
169
            // ======================================
170
            // Reprojection 
171
            FeatureAttributeDescriptor geo_att = this.options.getSource().getDefaultFeatureType().getDefaultGeometryAttribute();
172
            IProjection sourceProjection = null;
173
            ICoordTrans coord_trans = null;
174
            Geometry reproj_geom = null;
175
            if (geo_att != null) {
176
                sourceProjection = geo_att.getSRS();
177
                // this comparison is perhaps too preventive
178
                // we could  have two instances of same projection
179
                // so we would do more computations than needed
180
                if (sourceProjection != null && sourceProjection != this.options.getTargetProjection()) {
181
                    coord_trans = sourceProjection.getCT(this.options.getTargetProjection());
182
                }
183
            }
184
            // ============================================
185

    
186
            DataManager dataManager = DALLocator.getDataManager();
187

    
188
            JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
189
                    this.options.getExplorerParameters().getExplorerName(),
190
                    this.options.getExplorerParameters()
191
            );
192

    
193
            if (this.options.canCreatetable()) {
194
                logger.debug("Creating table");
195
                taskStatus.message("Creating table");
196
                this.createTable(explorer);
197
            }
198

    
199
            JDBCStoreParameters openParams = (JDBCStoreParameters) explorer.getOpenParameters();
200
            openParams.setSchema(this.options.getSchema());
201
            openParams.setTable(this.options.getTableName());
202
            openParams.setCRS(this.options.getTargetProjection());
203
            openParams.setDefaultGeometryField(
204
                    this.options.getSource().getDefaultFeatureType().getDefaultGeometryAttributeName()
205
            );
206
            target = (FeatureStore) explorer.open(openParams);
207

    
208
            FeatureType targetFeatureType = target.getDefaultFeatureType();
209
            FeatureType sourceFeatureType = featureSet.getDefaultFeatureType();
210

    
211
            target.edit(FeatureStore.MODE_APPEND);
212

    
213
            int featureCount = 1;
214
            taskStatus.setRangeOfValues(0, featureSet.getSize());
215

    
216
            int targetGeometryIndex = -1;
217
            int sourceGeometryIndex = -1;
218
            if( getGeometryColumnCount(sourceFeatureType)==1 
219
                    && getGeometryColumnCount(targetFeatureType)==1 ) {
220
                // Solo si hay una columna de geometria asignaremos las geometrias 
221
                // independientemente de como se llamen los campos.
222
                targetGeometryIndex = targetFeatureType.getDefaultGeometryAttributeIndex();
223
                sourceGeometryIndex = sourceFeatureType.getDefaultGeometryAttributeIndex();
224
            }
225
            
226
            logger.debug("Inserting rows");
227
            taskStatus.message("Inserting rows");
228
            it = featureSet.fastIterator();
229
            while (it.hasNext()) {
230
                Feature feature = (Feature) it.next();
231
                this.taskStatus.setCurValue(featureCount);
232

    
233
                targetFeature = target.createNewFeature(targetFeatureType, feature);
234
                for (int i = 0; i < sourceFeatureType.size(); i++) {
235
                    if (i == sourceGeometryIndex) {
236
                        // Es facil que los campos geometria no se llamen igual, asi que
237
                        // el campo geometria lo asignamos a capon.
238
                        // Esto puede ocasionar problemas cuando la tabla destino no tenga
239
                        // geometria o tenga mas de una.
240
                        targetFeature.set(targetGeometryIndex, feature.get(sourceGeometryIndex));
241
                    } else {
242
                        FeatureAttributeDescriptor x = sourceFeatureType.getAttributeDescriptor(i);
243
                        int targetAttributeIndex = targetFeatureType.getIndex(getTranslatedIdentifier(x.getName()));
244
                        if (targetAttributeIndex < 0) {
245
                            throw new RuntimeException("Can't locate column '" + x.getName() + "' in the target table.");
246
                        }
247
                        targetFeature.set(targetAttributeIndex, feature.get(x.getName()));
248
                    }
249
                }
250

    
251
                Geometry geometry = targetFeature.getDefaultGeometry();
252
                if (geometry != null) {
253
                    switch (this.options.getGeometryChecks()) {
254
                        case CHECK_IF_CORRUPT:
255
                            geometryCheck = geometry.getValidationStatus();
256
                            if (geometryCheck.getStatusCode() == Geometry.ValidationStatus.CURRUPTED) {
257
                                switch (this.options.getGeometryChecksAction()) {
258
                                    case ACTION_SET_GEOMETRY_TO_NULL:
259
                                        targetFeature.setDefaultGeometry(null);
260
                                        break;
261
                                    case ACTION_SKIP_FEATURE:
262
                                        continue;
263
                                    case ACTION_ABORT:
264
                                    default:
265
                                        throw new InvalidGeometryException(targetFeature, geometryCheck.getMessage());
266
                                }
267
                            }
268

    
269
                            break;
270

    
271
                        case CHECK_IF_VALID:
272
                            geometryCheck = geometry.getValidationStatus();
273
                            if (!geometryCheck.isValid()) {
274
                                Geometry g = null;
275
                                if (this.options.getTryToFixGeometry()) {
276
                                    g = geometry.makeValid();
277
                                    if (g != null) {
278
                                        targetFeature.setDefaultGeometry(g);
279
                                    }
280
                                }
281
                                if (g == null) {
282
                                    switch (this.options.getGeometryChecksAction()) {
283
                                        case ACTION_SET_GEOMETRY_TO_NULL:
284
                                            targetFeature.setDefaultGeometry(null);
285
                                            break;
286
                                        case ACTION_SKIP_FEATURE:
287
                                            continue;
288
                                        case ACTION_ABORT:
289
                                        default:
290
                                            throw new InvalidGeometryException(targetFeature, geometryCheck.getMessage());
291
                                    }
292
                                }
293
                            }
294

    
295
                            break;
296
                        case CHECK_NONE:
297
                        default:
298
                            break;
299
                    }
300
                    // ================================================
301
                    // Reprojection 
302
                    if (geo_att != null && coord_trans != null) {
303
                        reproj_geom = targetFeature.getDefaultGeometry();
304
                        reproj_geom = reproj_geom.cloneGeometry();
305
                        reproj_geom.reProject(coord_trans);
306
                        targetFeature.setDefaultGeometry(reproj_geom);
307
                    }
308
                    // ================================================
309
                }
310

    
311
                target.insert(targetFeature);
312

    
313
                if (this.taskStatus.isCancellationRequested()) {
314
                    return;
315
                }
316
                featureCount++;
317
            }
318
            targetFeature = null;
319
            target.finishEditing();
320

    
321
            if (this.options.getUpdateTableStatistics()) {
322
                logger.debug("Updating statistics");
323
                taskStatus.message("Updating statistics");
324
                explorer.updateTableStatistics(openParams.tableID());
325
            }
326
            logger.debug("finish");
327

    
328
            if (exporttoServiceFinishAction != null) {
329
                exporttoServiceFinishAction.finished(
330
                        this.options.getTableName() + " (" + explorer.getStoreName() + ")",
331
                        openParams);
332
            }
333
            taskStatus.message("Exportation finished");
334

    
335
        } catch (Exception e) {
336
            logger.warn("Can't export data.", e);
337
            taskStatus.message("Problems exporting data");
338
            throw new ExporttoServiceException(e, targetFeature);
339

    
340
        } finally {
341
            if (it != null) {
342
                it.dispose();
343
            }
344
            featureSet.dispose();
345
            if (target != null) {
346
                target.dispose();
347
            }
348
            this.taskStatus.terminate();
349
            this.taskStatus.remove();
350
        }
351
    }
352
    
353
    private int getGeometryColumnCount(FeatureType featureType) {
354
        int count = 0;
355
        for( int i=0; i<featureType.size(); i++ ) {
356
            if( featureType.getAttributeDescriptor(i).getType()==DataTypes.GEOMETRY ) {
357
                count++;
358
            }
359
        }
360
        return count;
361
    }
362

    
363
    public void setFinishAction(
364
            ExporttoServiceFinishAction exporttoServiceFinishAction) {
365
        this.exporttoServiceFinishAction = exporttoServiceFinishAction;
366
    }
367

    
368
}