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

History | View | Annotate | Download (16.3 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
            IProjection targetProjection = this.options.getTargetProjection();
176
            if (geo_att != null) {
177
                sourceProjection = geo_att.getSRS();
178
                // this comparison is perhaps too preventive
179
                // we could  have two instances of same projection
180
                // so we would do more computations than needed
181
                if (sourceProjection != null && targetProjection != null && sourceProjection != targetProjection) {
182
                    coord_trans = sourceProjection.getCT(targetProjection);
183
                }
184
            }
185
            // ============================================
186

    
187
            DataManager dataManager = DALLocator.getDataManager();
188

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

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

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

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

    
212
            target.edit(FeatureStore.MODE_APPEND);
213

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

    
217
            int targetGeometryIndex = -1;
218
            int sourceGeometryIndex = -1;
219
            if( getGeometryColumnCount(sourceFeatureType)==1
220
                    && getGeometryColumnCount(targetFeatureType)==1 ) {
221
                // Solo si hay una columna de geometria asignaremos las geometrias
222
                // independientemente de como se llamen los campos.
223
                targetGeometryIndex = targetFeatureType.getDefaultGeometryAttributeIndex();
224
                sourceGeometryIndex = sourceFeatureType.getDefaultGeometryAttributeIndex();
225
            }
226

    
227
            logger.debug("Inserting rows");
228
            taskStatus.message("Inserting rows");
229
            it = featureSet.fastIterator();
230
            while (it.hasNext()) {
231
                Feature feature = (Feature) it.next();
232
                this.taskStatus.setCurValue(featureCount);
233

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

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

    
270
                            break;
271

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

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

    
312
                target.insert(targetFeature);
313

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

    
322
            if (this.options.getUpdateTableStatistics()) {
323
                logger.debug("Updating statistics");
324
                taskStatus.message("Updating statistics");
325
                explorer.updateTableStatistics(
326
                        openParams.getDBName(),
327
                        openParams.getSchema(),
328
                        openParams.getTable()
329
                );
330
            }
331
            logger.debug("finish");
332

    
333
            if (exporttoServiceFinishAction != null) {
334
                exporttoServiceFinishAction.finished(
335
                        this.options.getTableName() + " (" + explorer.getStoreName() + ")",
336
                        openParams);
337
            }
338
            taskStatus.message("Exportation finished");
339

    
340
        } catch (Exception e) {
341
            logger.warn("Can't export data.", e);
342
            taskStatus.message("Problems exporting data");
343
            throw new ExporttoServiceException(e, targetFeature);
344

    
345
        } finally {
346
            if (it != null) {
347
                it.dispose();
348
            }
349
            featureSet.dispose();
350
            if (target != null) {
351
                target.dispose();
352
            }
353
            this.taskStatus.terminate();
354
            this.taskStatus.remove();
355
        }
356
    }
357

    
358
    private int getGeometryColumnCount(FeatureType featureType) {
359
        int count = 0;
360
        for( int i=0; i<featureType.size(); i++ ) {
361
            if( featureType.getAttributeDescriptor(i).getType()==DataTypes.GEOMETRY ) {
362
                count++;
363
            }
364
        }
365
        return count;
366
    }
367

    
368
    public void setFinishAction(
369
            ExporttoServiceFinishAction exporttoServiceFinishAction) {
370
        this.exporttoServiceFinishAction = exporttoServiceFinishAction;
371
    }
372

    
373
}