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

History | View | Annotate | Download (12.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 org.cresques.cts.ICoordTrans;
26
import org.cresques.cts.IProjection;
27
import org.gvsig.exportto.ExporttoService;
28
import org.gvsig.exportto.ExporttoServiceException;
29
import org.gvsig.exportto.ExporttoServiceFinishAction;
30
import org.gvsig.fmap.dal.DALLocator;
31
import org.gvsig.fmap.dal.DataManager;
32
import org.gvsig.fmap.dal.DataTypes;
33
import org.gvsig.fmap.dal.feature.EditableFeature;
34
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
35
import org.gvsig.fmap.dal.feature.EditableFeatureType;
36
import org.gvsig.fmap.dal.feature.Feature;
37
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
38
import org.gvsig.fmap.dal.feature.FeatureSet;
39
import org.gvsig.fmap.dal.feature.FeatureStore;
40
import org.gvsig.fmap.dal.feature.FeatureType;
41
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
42
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorer;
43
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
44
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
45
import org.gvsig.fmap.geom.Geometry;
46
import org.gvsig.tools.dispose.DisposableIterator;
47
import org.gvsig.tools.task.AbstractMonitorableTask;
48
import org.slf4j.Logger;
49
import org.slf4j.LoggerFactory;
50

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

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

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

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

    
69
    private final FeatureStore source;
70
    private final JDBCServerExplorerParameters explorerParameters;
71
    private final String tableName;
72
    private final String pkname;
73
    private final int geometryChecks;
74
    private final int geometryChecksAction;
75
    private final IProjection tarjetProjection;
76
    private final boolean canCreateTable;
77
    private final boolean tryToFixGeometries;
78

    
79
    private ExporttoServiceFinishAction exporttoServiceFinishAction = null;
80

    
81
    public ExporrtoJDBCService(FeatureStore source,
82
            JDBCServerExplorerParameters explorerParameters,
83
            String tablename,
84
            String primaryKeyName,
85
            IProjection tarjetProjection,
86
            boolean canCreatetable,
87
            int geometryChecks,
88
            int geometryChecksAction,
89
            boolean tryToFixGeometries) {
90
        this.source = source;
91
        this.explorerParameters = explorerParameters;
92
        this.tableName = tablename;
93
        this.pkname = primaryKeyName;
94
        this.tarjetProjection = tarjetProjection;
95
        this.canCreateTable = canCreatetable;
96
        this.geometryChecks = geometryChecks;
97
        this.geometryChecksAction = geometryChecksAction;
98
        this.tryToFixGeometries = tryToFixGeometries;
99
    }
100

    
101
    protected void createTable(JDBCServerExplorer explorer) throws Exception {
102

    
103
        FeatureType targetFeatureType;
104
        EditableFeatureType targetEditableFeatureType;
105

    
106
        targetFeatureType = source.getDefaultFeatureType().getCopy();
107
        targetEditableFeatureType = targetFeatureType.getEditable();
108

    
109
        if (this.pkname != null) {
110
            EditableFeatureAttributeDescriptor pk = (EditableFeatureAttributeDescriptor) targetEditableFeatureType.get(pkname);
111
            if (pk == null) {
112
                pk = targetEditableFeatureType.add(this.pkname, DataTypes.LONG);
113
                pk.setIsPrimaryKey(true);
114
                pk.setIsAutomatic(true);
115
            } else {
116
                pk.setIsPrimaryKey(true);
117
            }
118
        }
119

    
120
        // ======================================================
121
        // Reprojection: set SRS of geometry field to target SRS
122
        EditableFeatureAttributeDescriptor attrdescriptor
123
                = (EditableFeatureAttributeDescriptor) targetEditableFeatureType.getDefaultGeometryAttribute();
124
        if (attrdescriptor != null) {
125
            attrdescriptor.setSRS(this.tarjetProjection);
126
        }
127

    
128
        // ======================================
129
        NewFeatureStoreParameters createTableParams = (NewFeatureStoreParameters) explorer.getAddParameters();
130

    
131
        createTableParams.setDefaultFeatureType(targetEditableFeatureType);
132
        //createTableParams.setTable(this.tableName); // ?????
133
        explorer.add(explorer.getStoreName(), createTableParams, true);
134
    }
135

    
136
    private static class InvalidGeometryException extends ExporttoServiceException {
137

    
138
        public InvalidGeometryException(Feature feature, String checkMessage) {
139
            super(checkMessage, null, checkMessage, 0);
140
            this.feature = feature;
141
        }
142
    }
143

    
144
    public void export(FeatureSet featureSet) throws ExporttoServiceException {
145
        Geometry.ValidationStatus geometryCheck;
146

    
147
        DisposableIterator it = null;
148
        EditableFeature targetFeature = null;
149
        FeatureStore target = null;
150

    
151
        try {
152

    
153
            // ======================================
154
            // Reprojection 
155
            FeatureAttributeDescriptor geo_att = source.getDefaultFeatureType().getDefaultGeometryAttribute();
156
            IProjection sourceProjection = null;
157
            ICoordTrans coord_trans = null;
158
            Geometry reproj_geom = null;
159
            if (geo_att != null) {
160
                sourceProjection = geo_att.getSRS();
161
                // this comparison is perhaps too preventive
162
                // we could  have two instances of same projection
163
                // so we would do more computations than needed
164
                if (sourceProjection != this.tarjetProjection) {
165
                    coord_trans = sourceProjection.getCT(this.tarjetProjection);
166
                }
167
            }
168
            // ============================================
169

    
170
            DataManager dataManager = DALLocator.getDataManager();
171

    
172
            JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
173
                    this.explorerParameters.getExplorerName(),
174
                    this.explorerParameters
175
            );
176

    
177
            if (this.canCreateTable) {
178
                this.createTable(explorer);
179
            }
180

    
181
            JDBCStoreParameters openParams = (JDBCStoreParameters) explorer.getOpenParameters();
182
            openParams.setTable(this.tableName);
183
            openParams.setCRS(this.tarjetProjection);
184
            openParams.setDefaultGeometryField(
185
                    source.getDefaultFeatureType().getDefaultGeometryAttributeName()
186
            );
187
            target = (FeatureStore) explorer.open(openParams);
188

    
189
            FeatureType targetFeatureType = target.getDefaultFeatureType();
190

    
191
            target.edit(FeatureStore.MODE_APPEND);
192

    
193
            int featureCount = 1;
194
            taskStatus.setRangeOfValues(0, featureSet.getSize());
195

    
196
            it = featureSet.fastIterator();
197
            while (it.hasNext()) {
198
                Feature feature = (Feature) it.next();
199
                targetFeature = target.createNewFeature(targetFeatureType, feature);
200

    
201
                Geometry geometry = targetFeature.getDefaultGeometry();
202
                if (geometry != null) {
203
                    switch (this.geometryChecks) {
204
                        case CHECK_IF_CORRUPT:
205
                            geometryCheck = geometry.getValidationStatus();
206
                            if (geometryCheck.getStatusCode() == Geometry.ValidationStatus.CURRUPTED) {
207
                                switch (this.geometryChecksAction) {
208
                                    case ACTION_SET_GEOMETRY_TO_NULL:
209
                                        targetFeature.setDefaultGeometry(null);
210
                                        break;
211
                                    case ACTION_SKIP_FEATURE:
212
                                        continue;
213
                                    case ACTION_ABORT:
214
                                    default:
215
                                        throw new InvalidGeometryException(targetFeature, geometryCheck.getMessage());
216
                                }
217
                            }
218

    
219
                            break;
220

    
221
                        case CHECK_IF_VALID:
222
                            geometryCheck = geometry.getValidationStatus();
223
                            if (!geometryCheck.isValid()) {
224
                                Geometry g = null;
225
                                if (this.tryToFixGeometries) {
226
                                    g = geometry.makeValid();
227
                                    if (g != null) {
228
                                        targetFeature.setDefaultGeometry(g);
229
                                    }
230
                                }
231
                                if (g == null) {
232
                                    switch (this.geometryChecksAction) {
233
                                        case ACTION_SET_GEOMETRY_TO_NULL:
234
                                            targetFeature.setDefaultGeometry(null);
235
                                            break;
236
                                        case ACTION_SKIP_FEATURE:
237
                                            continue;
238
                                        case ACTION_ABORT:
239
                                        default:
240
                                            throw new InvalidGeometryException(targetFeature, geometryCheck.getMessage());
241
                                    }
242
                                }
243
                            }
244

    
245
                            break;
246
                        case CHECK_NONE:
247
                        default:
248
                            break;
249
                    }
250
                    // ================================================
251
                    // Reprojection 
252
                    if (geo_att != null && coord_trans != null) {
253
                        reproj_geom = targetFeature.getDefaultGeometry();
254
                        reproj_geom = reproj_geom.cloneGeometry();
255
                        reproj_geom.reProject(coord_trans);
256
                        targetFeature.setDefaultGeometry(reproj_geom);
257
                    }
258
                    // ================================================
259
                }
260

    
261
                target.insert(targetFeature);
262
                this.taskStatus.setCurValue(featureCount);
263

    
264
                if (this.taskStatus.isCancellationRequested()) {
265
                    return;
266
                }
267
                featureCount++;
268
            }
269
            targetFeature = null;
270
            target.finishEditing();
271

    
272
            if (exporttoServiceFinishAction != null) {
273
                exporttoServiceFinishAction.finished(
274
                        this.tableName + " (" + explorer.getStoreName() + ")",
275
                        openParams);
276
            }
277

    
278
        } catch (Exception e) {
279
            logger.warn("Can't export data.", e);
280
            taskStatus.message(e.getMessage());
281
            throw new ExporttoServiceException(e, targetFeature);
282

    
283
        } finally {
284
            if (it != null) {
285
                it.dispose();
286
            }
287
            featureSet.dispose();
288
            if (target != null) {
289
                target.dispose();
290
            }
291
            this.taskStatus.terminate();
292
            this.taskStatus.remove();
293
        }
294
    }
295

    
296
    public void setFinishAction(
297
            ExporttoServiceFinishAction exporttoServiceFinishAction) {
298
        this.exporttoServiceFinishAction = exporttoServiceFinishAction;
299
    }
300

    
301
}