Revision 41486 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

View differences:

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

  
26
import java.util.Iterator;
27

  
28 25
import org.cresques.cts.ICoordTrans;
29 26
import org.cresques.cts.IProjection;
30

  
31 27
import org.gvsig.exportto.ExporttoService;
32 28
import org.gvsig.exportto.ExporttoServiceException;
33 29
import org.gvsig.exportto.ExporttoServiceFinishAction;
34 30
import org.gvsig.fmap.dal.DALLocator;
35 31
import org.gvsig.fmap.dal.DataManager;
36 32
import org.gvsig.fmap.dal.DataTypes;
37
import org.gvsig.fmap.dal.exception.DataException;
38
import org.gvsig.fmap.dal.exception.InitializeException;
39
import org.gvsig.fmap.dal.exception.OpenException;
40
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
41
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
42 33
import org.gvsig.fmap.dal.feature.EditableFeature;
43 34
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
44 35
import org.gvsig.fmap.dal.feature.EditableFeatureType;
......
48 39
import org.gvsig.fmap.dal.feature.FeatureStore;
49 40
import org.gvsig.fmap.dal.feature.FeatureType;
50 41
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
51
import org.gvsig.fmap.dal.store.db.DBStoreParameters;
52
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
53 42
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorer;
54 43
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
55 44
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
56 45
import org.gvsig.fmap.geom.Geometry;
57 46
import org.gvsig.tools.dispose.DisposableIterator;
58
import org.gvsig.tools.service.ServiceException;
59 47
import org.gvsig.tools.task.AbstractMonitorableTask;
60 48

  
61 49
/**
62 50
 * @author gvSIG Team
63 51
 * @version $Id$
64
 * 
52
 *
65 53
 */
66 54
public class ExporrtoJDBCService extends AbstractMonitorableTask implements
67
    ExporttoService {
55
        ExporttoService {
68 56

  
69
    private static final DataManager DATA_MANAGER = DALLocator.getDataManager();
57
    public static final int CHECK_NONE = 0;
58
    public static final int CHECK_IF_CORRUPT = 1;
59
    public static final int CHECK_IF_VALID = 2;
70 60

  
71
    private String dbName = null;
72
    private String schema = null;
73
    private String tableName = null;
74
    private String pkField = null;
75
    private String userName = null;
76
    private String password = null;
77
    private String host = null;
78
    private int port = -1;
79
    private String explorerName = null;
80
    private String storeName = null;
61
    public static final int ACTION_SET_GEOMETRY_TO_NULL = 0;
62
    public static final int ACTION_SKIP_FEATURE = 1;
63
    public static final int ACTION_ABORT = 2;
81 64

  
82
    private NewFeatureStoreParameters newFeatureStoreParameters;
83
    private JDBCServerExplorer explorer;
84
    private FeatureStore featureStore;
85
    private IProjection targetProjection;
65
    private final FeatureStore source;
66
    private final JDBCServerExplorerParameters explorerParameters;
67
    private final String tableName;
68
    private final String pkname;
69
    private final int geometryChecks;
70
    private final int geometryChecksAction;
71
    private final IProjection tarjetProjection;
72
    private final boolean canCreateTable;
86 73

  
87 74
    private ExporttoServiceFinishAction exporttoServiceFinishAction = null;
88 75

  
89
    /**
90
     * @param taskName
91
     * @throws ServiceException
92
     */
93
    protected ExporrtoJDBCService(FeatureStore featureStore, String dbName,
94
        String schema, String tableName, String pkField, String userName,
95
        String password, String host, int port, String explorerName,
96
        String storeName, IProjection target_projetion) {
97
        super("Export to JDBC");
98
        this.featureStore = featureStore;
99
        this.dbName = dbName;
100
        this.schema = schema;
101
        this.tableName = tableName;
102
        this.pkField = pkField;
103
        this.userName = userName;
104
        this.password = password;
105
        this.host = host;
106
        this.port = port;
107
        this.storeName = storeName;
108
        this.explorerName = explorerName;
109
        this.targetProjection = target_projetion;
76
    public ExporrtoJDBCService(FeatureStore source,
77
            JDBCServerExplorerParameters explorerParameters,
78
            String tablename,
79
            String primaryKeyName,
80
            IProjection tarjetProjection,
81
            boolean canCreatetable,
82
            int geometryChecks,
83
            int geometryChecksAction) {
84
        this.source = source;
85
        this.explorerParameters = explorerParameters;
86
        this.tableName = tablename;
87
        this.pkname = primaryKeyName;
88
        this.tarjetProjection = tarjetProjection;
89
        this.canCreateTable = canCreatetable;
90
        this.geometryChecks = geometryChecks;
91
        this.geometryChecksAction = geometryChecksAction;
110 92
    }
111 93

  
112
    public void export(FeatureSet featureSet) throws ExporttoServiceException {
94
    protected void createTable(JDBCServerExplorer explorer) throws Exception {
113 95

  
114
        initializeParams(featureSet);
96
        FeatureType targetFeatureType ;
97
        EditableFeatureType targetEditableFeatureType ;
115 98

  
116
        DisposableIterator it1 = null;
99
        targetFeatureType = source.getDefaultFeatureType().getCopy();
100
        targetEditableFeatureType = targetFeatureType.getEditable();
101

  
102
        if (this.pkname != null) {
103
            EditableFeatureAttributeDescriptor pk
104
                    = targetEditableFeatureType.add(this.pkname, DataTypes.LONG);
105
            pk.setIsPrimaryKey(true);
106
            pk.setIsAutomatic(true);
107
        }
108

  
109
        // ======================================================
110
        // Reprojection: set SRS of geometry field to target SRS
111
        EditableFeatureAttributeDescriptor attrdescriptor
112
                = (EditableFeatureAttributeDescriptor) targetEditableFeatureType.getDefaultGeometryAttribute();
113
        if (attrdescriptor != null) {
114
            attrdescriptor.setSRS(this.tarjetProjection);
115
        }
116

  
117
        // ======================================
118
        NewFeatureStoreParameters createTableParams = (NewFeatureStoreParameters) explorer.getAddParameters();
119

  
120
        createTableParams.setDefaultFeatureType(targetEditableFeatureType);
121

  
122
        explorer.add(explorer.getStoreName(), createTableParams, true);
123
    }
124

  
125
    private static class InvalidGeometryException extends ExporttoServiceException {
126

  
127
        public InvalidGeometryException(Feature feature, String checkMessage) {
128
            super(checkMessage, null, checkMessage, 0);
129
            this.feature = feature;
130
        }
131
    }
132

  
133
    public void export(FeatureSet featureSet) throws ExporttoServiceException {
134
        Geometry.ValidationStatus geometryCheck;
135

  
136
        DisposableIterator it = null;
137
        EditableFeature targetFeature = null;
117 138
        FeatureStore target = null;
118 139
        
119
        EditableFeatureType ef_type = null;
120
        FeatureType f_type = null;
121
        EditableFeature edit_feat = null;
122 140
        try {
123
            f_type = featureStore.getDefaultFeatureType();
124
            f_type = f_type.getCopy();
125
            ef_type = f_type.getEditable();
126

  
127
            if (pkField != null) {
128
                EditableFeatureAttributeDescriptor pk =
129
                    ef_type.add(pkField, DataTypes.LONG);
130
                pk.setIsPrimaryKey(true);
131
                pk.setIsAutomatic(true);
132
            }
133 141
            
134
            // ========================================
135
            // Reprojection: set SRS of geometry field to
136
            // target SRS
137
            EditableFeatureAttributeDescriptor eatt =
138
                (EditableFeatureAttributeDescriptor)
139
                ef_type.getDefaultGeometryAttribute();
140
            if (eatt != null) {
141
                eatt.setSRS(this.targetProjection);
142
            }
143 142
            // ======================================
144

  
145
            newFeatureStoreParameters.setDefaultFeatureType(ef_type);
146
            explorer.add(storeName, newFeatureStoreParameters, true);
147
            
148
            // ======================================
149 143
            // Reprojection 
150
            FeatureAttributeDescriptor geo_att = f_type.getDefaultGeometryAttribute();
144
            FeatureAttributeDescriptor geo_att = source.getDefaultFeatureType().getDefaultGeometryAttribute();
151 145
            IProjection sourceProjection = null;
152 146
            ICoordTrans coord_trans = null;
147
            Geometry reproj_geom = null;
153 148
            if (geo_att != null) {
154 149
                sourceProjection = geo_att.getSRS();
155 150
                // this comparison is perhaps too preventive
156 151
                // we could  have two instances of same projection
157 152
                // so we would do more computations than needed
158
                if (sourceProjection != this.targetProjection) {
159
                    coord_trans = sourceProjection.getCT(this.targetProjection); 
153
                if (sourceProjection != this.tarjetProjection) {
154
                    coord_trans = sourceProjection.getCT(this.tarjetProjection);
160 155
                }
161 156
            }
162 157
            // ============================================
163 158

  
164
            target =
165
                (FeatureStore) DATA_MANAGER.openStore(
166
                		storeName,
167
                		newFeatureStoreParameters);
168 159
            
169
            FeatureType targetType = target.getDefaultFeatureType();
160
            DataManager dataManager = DALLocator.getDataManager();
170 161

  
162
            JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
163
                    this.explorerParameters.getExplorerName(),
164
                    this.explorerParameters
165
            );
166

  
167
            if (this.canCreateTable) {
168
                this.createTable(explorer);
169
            }
170

  
171
            JDBCStoreParameters openParams = (JDBCStoreParameters) explorer.getOpenParameters();
172
            openParams.setTable(this.tableName);
173
            openParams.setCRS(this.tarjetProjection);
174
            openParams.setDefaultGeometryField(
175
                    source.getDefaultFeatureType().getDefaultGeometryAttributeName()
176
            );
177
            target = (FeatureStore) explorer.open(openParams);
178

  
179
            FeatureType targetFeatureType = target.getDefaultFeatureType();
180

  
171 181
            target.edit(FeatureStore.MODE_APPEND);
172 182

  
173
            taskStatus.setRangeOfValues(0, featureSet.getSize());
174 183
            int featureCount = 1;
175
            it1 = featureSet.fastIterator();
176
            
177
            Geometry reproj_geom = null;
178
            
179
            while (it1.hasNext()) {
180
                Feature feature = (Feature) it1.next();
181
                edit_feat = target.createNewFeature(targetType, feature);
184
            taskStatus.setRangeOfValues(0, featureSet.getSize());
185

  
186
            it = featureSet.fastIterator();
187
            while (it.hasNext()) {
188
                Feature feature = (Feature) it.next();
189
                targetFeature = target.createNewFeature(targetFeatureType, feature);
190

  
191
                Geometry geometry = targetFeature.getDefaultGeometry();
192
                switch (this.geometryChecks) {
193
                    case CHECK_IF_CORRUPT:
194
                        geometryCheck = geometry.getValidationStatus();
195
                        if (geometryCheck.getStatusCode() == Geometry.ValidationStatus.CURRUPTED) {
196
                            switch (this.geometryChecksAction) {
197
                                case ACTION_SET_GEOMETRY_TO_NULL:
198
                                    targetFeature.setDefaultGeometry(null);
199
                                    break;
200
                                case ACTION_SKIP_FEATURE:
201
                                    continue;
202
                                case ACTION_ABORT:
203
                                default:
204
                                    throw new InvalidGeometryException(targetFeature, geometryCheck.getMessage());
205
                            }
206
                        }
207

  
208
                        break;
209

  
210
                    case CHECK_IF_VALID:
211
                        geometryCheck = geometry.getValidationStatus();
212
                        if (!geometryCheck.isValid()) {
213
                            switch (this.geometryChecksAction) {
214
                                case ACTION_SET_GEOMETRY_TO_NULL:
215
                                    targetFeature.setDefaultGeometry(null);
216
                                    break;
217
                                case ACTION_SKIP_FEATURE:
218
                                    continue;
219
                                case ACTION_ABORT:
220
                                default:
221
                                    throw new InvalidGeometryException(targetFeature, geometryCheck.getMessage());
222
                            }
223
                        }
224

  
225
                        break;
226
                    case CHECK_NONE:
227
                    default:
228
                        break;
229
                }
230

  
182 231
                // ================================================
183 232
                // Reprojection 
184 233
                if (geo_att != null && coord_trans != null) {
185
                    reproj_geom = edit_feat.getDefaultGeometry();
234
                    reproj_geom = targetFeature.getDefaultGeometry();
186 235
                    reproj_geom = reproj_geom.cloneGeometry();
187 236
                    reproj_geom.reProject(coord_trans);
188
                    edit_feat.setDefaultGeometry(reproj_geom);
237
                    targetFeature.setDefaultGeometry(reproj_geom);
189 238
                }
190 239
                // ================================================
191
                target.insert(edit_feat);
240
                target.insert(targetFeature);
192 241
                this.taskStatus.setCurValue(featureCount);
193 242

  
194 243
                if (this.taskStatus.isCancellationRequested()) {
......
196 245
                }
197 246
                featureCount++;
198 247
            }
199
            edit_feat = null;
248
            targetFeature = null;
200 249
            target.finishEditing();
201 250

  
202
            /*
203
             * Creating normal parameters (not "new store parameters")
204
             * to add layer
205
             */
206
            String storename = newFeatureStoreParameters.getDataStoreName();
207
            JDBCStoreParameters params = getParams(explorer, tableName, schema, storename);
208
            
209
            if (geo_att != null) {
210
                params.setCRS(targetProjection);
211
                params.setDefaultGeometryField(targetType.getDefaultGeometryAttributeName());
212
            }
213
            
214 251
            if (exporttoServiceFinishAction != null) {
215 252
                exporttoServiceFinishAction.finished(
216
                    tableName + " (" + storename + ")",
217
                    params);
253
                        this.tableName + " (" + explorer.getStoreName() + ")",
254
                        openParams);
218 255
            }
219 256

  
220 257
        } catch (Exception e) {
221 258
            taskStatus.message(e.getMessage());
222
            throw new ExporttoServiceException(e,edit_feat);
259
            throw new ExporttoServiceException(e, targetFeature);
260

  
223 261
        } finally {
224
            if (it1 != null) {
225
                it1.dispose();
262
            if (it != null) {
263
                it.dispose();
226 264
            }
227 265
            featureSet.dispose();
228 266
            if (target != null) {
......
233 271
        }
234 272
    }
235 273

  
236
    private JDBCStoreParameters getParams(
237
    		JDBCServerExplorer explo,
238
    		String tab, String sche, String storename) throws DataException {
239
    	
240
    	Iterator iter = explo.list().iterator();
241
    	JDBCStoreParameters item = null;
242
    	while (iter.hasNext()) {
243
    		item = (JDBCStoreParameters) iter.next();
244
    		if (item.getTable().compareTo(tab) == 0
245
    				&&
246
    				(sche == null || item.getSchema().compareTo(sche) == 0)) {
247
    			return item;
248
    		}
249
    	}
250
    	throw new OpenException(storename, new Exception("Table not found: " + tab));
251
	}
252

  
253
	private void initializeParams(FeatureSet featureSet)
254
        throws ExporttoServiceException {
255
        JDBCServerExplorerParameters explorerParam;
256
        try {
257
            explorerParam =
258
                (JDBCServerExplorerParameters) DATA_MANAGER
259
                    .createServerExplorerParameters(explorerName);
260

  
261
            explorerParam.setHost(host);
262
            if (port > -1) {
263
                explorerParam.setPort(port);
264
            }
265
            explorerParam.setDBName(dbName);
266
            explorerParam.setUser(userName);
267
            explorerParam.setPassword(password);
268
            if (schema != null && schema.length() > 0) {
269
                explorerParam.setSchema(schema);
270
            }
271

  
272
            explorer =
273
                (JDBCServerExplorer) DATA_MANAGER.openServerExplorer(
274
                    explorerName, explorerParam);
275

  
276
            newFeatureStoreParameters =
277
                (NewFeatureStoreParameters) explorer.getAddParameters();
278

  
279
            ((DBStoreParameters) newFeatureStoreParameters).setTable(tableName);
280
            ((DBStoreParameters) newFeatureStoreParameters)
281
                .setDefaultGeometryField(featureSet.getDefaultFeatureType()
282
                    .getDefaultGeometryAttributeName());
283

  
284
        } catch (InitializeException e) {
285
            throw new ExporttoServiceException(e);
286
        } catch (ProviderNotRegisteredException e) {
287
            throw new ExporttoServiceException(e);
288
        } catch (ValidateDataParametersException e) {
289
            throw new ExporttoServiceException(e);
290
        } catch (DataException e) {
291
            throw new ExporttoServiceException(e);
292
        }
293
    }
294

  
295 274
    public void setFinishAction(
296
        ExporttoServiceFinishAction exporttoServiceFinishAction) {
275
            ExporttoServiceFinishAction exporttoServiceFinishAction) {
297 276
        this.exporttoServiceFinishAction = exporttoServiceFinishAction;
298 277
    }
299 278

  

Also available in: Unified diff