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 @ 41681

History | View | Annotate | Download (15.9 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 != 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
                taskStatus.message("Creating table");
195
                this.createTable(explorer);
196
            }
197

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

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

    
210
            target.edit(FeatureStore.MODE_APPEND);
211

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

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

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

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

    
267
                            break;
268

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

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

    
309
                target.insert(targetFeature);
310

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

    
319
            if (this.options.getUpdateTableStatistics()) {
320
                taskStatus.message("Updating statistics");
321
                explorer.updateTableStatistics(openParams.tableID());
322
            }
323

    
324
            if (exporttoServiceFinishAction != null) {
325
                exporttoServiceFinishAction.finished(
326
                        this.options.getTableName() + " (" + explorer.getStoreName() + ")",
327
                        openParams);
328
            }
329
            taskStatus.message("Exportation finished");
330

    
331
        } catch (Exception e) {
332
            logger.warn("Can't export data.", e);
333
            taskStatus.message("Problems exporting data");
334
            throw new ExporttoServiceException(e, targetFeature);
335

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

    
359
    public void setFinishAction(
360
            ExporttoServiceFinishAction exporttoServiceFinishAction) {
361
        this.exporttoServiceFinishAction = exporttoServiceFinishAction;
362
    }
363

    
364
}