Revision 41610 trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.file/org.gvsig.fmap.dal.file.shp/src/main/java/org/gvsig/fmap/dal/store/shp/SHPStoreProvider.java

View differences:

SHPStoreProvider.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

  
25 23
package org.gvsig.fmap.dal.store.shp;
26 24

  
27 25
import java.io.File;
......
76 74
import org.gvsig.tools.exception.BaseException;
77 75

  
78 76
public class SHPStoreProvider extends DBFStoreProvider {
79
	private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
80
	private static final Logger logger = LoggerFactory.getLogger(GeometryManager.class);
81
	public static String NAME = "Shape";
82
	public static String DESCRIPTION = "Shape file";
83
	private ISHPFile shpFile;
84 77

  
85
	private MultiResource resource;
78
    private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
79
    private static final Logger logger = LoggerFactory.getLogger(GeometryManager.class);
80
    public static String NAME = "Shape";
81
    public static String DESCRIPTION = "Shape file";
82
    private ISHPFile shpFile;
86 83

  
87
	protected static final String GEOMETRY_ATTIBUTE_NAME = "GEOMETRY";
84
    private MultiResource resource;
88 85

  
89
	public static final String METADATA_DEFINITION_NAME = NAME;
86
    protected static final String GEOMETRY_ATTIBUTE_NAME = "GEOMETRY";
90 87

  
91
	private SHPFeatureWriter writer = null;
88
    public static final String METADATA_DEFINITION_NAME = NAME;
92 89

  
93
	public SHPStoreProvider(SHPStoreParameters params,
94
			DataStoreProviderServices storeServices)
95
			throws InitializeException {
96
		super(
97
			params, 
98
			storeServices,
99
			FileHelper.newMetadataContainer(METADATA_DEFINITION_NAME)
100
		);
101
	}
90
    private SHPFeatureWriter writer = null;
102 91

  
103
	protected void init(DBFStoreParameters params,
104
			DataStoreProviderServices storeServices) throws InitializeException {
92
    public SHPStoreProvider(SHPStoreParameters params,
93
            DataStoreProviderServices storeServices)
94
            throws InitializeException {
95
        super(
96
                params,
97
                storeServices,
98
                FileHelper.newMetadataContainer(METADATA_DEFINITION_NAME)
99
        );
100
    }
105 101

  
106
		this.shpFile = new SHPFile2((SHPStoreParameters) params);
107
		super.init(params, storeServices);
108
                this.shpFile.setUseNullGeometry(this.getShpParameters().getUseNullGeometry());
109
	}
102
    protected void init(DBFStoreParameters params,
103
            DataStoreProviderServices storeServices) throws InitializeException {
110 104

  
111
	public Object getDynValue(String name) throws DynFieldNotFoundException {
112
		if( DataStore.METADATA_CRS.equalsIgnoreCase(name) ) {
113
		    
114
			/*
115
			 * String srs =  this.shpFile.getSRSParameters();
116
			if (srs != null){
117
			// This can be non null but not sure how to handle
118
			}
119
			*/
120
			return this.getShpParameters().getCRS();
121
			
122
		} else if( DataStore.METADATA_ENVELOPE.equalsIgnoreCase(name) ) {
123
			try {
124
				return this.shpFile.getFullExtent();
125
			} catch (ReadException e) {
126
				return null;
127
			}
128
		}
129
		return super.getDynValue(name);
130
	}
131
	
132
	protected void initResource(DBFStoreParameters params,
133
			DataStoreProviderServices storeServices) throws InitializeException {
105
        this.shpFile = new SHPFile2((SHPStoreParameters) params);
106
        super.init(params, storeServices);
107
        this.shpFile.setUseNullGeometry(this.getShpParameters().getUseNullGeometry());
108
    }
134 109

  
135
		SHPStoreParameters shpParams = (SHPStoreParameters) params;
136
		resource =
137
				(MultiResource) createResource(MultiResource.TYPE_NAME,
138
						new Object[] { shpParams.getSHPFileName() });
110
    public Object getDynValue(String name) throws DynFieldNotFoundException {
111
        if (DataStore.METADATA_CRS.equalsIgnoreCase(name)) {
139 112

  
140
		resource.addResource(FileResource.NAME,
141
				new Object[] { shpParams.getSHPFileName() }, true);
142
		resource.addResource(FileResource.NAME,
143
				new Object[] { shpParams.getSHXFileName() }, true);
144
		resource.addResource(FileResource.NAME,
145
				new Object[] { shpParams.getDBFFileName() }, true);
113
            /*
114
             * String srs =  this.shpFile.getSRSParameters();
115
             if (srs != null){
116
             // This can be non null but not sure how to handle
117
             }
118
             */
119
            return this.getShpParameters().getCRS();
146 120

  
147
		resource.addConsumer(this);
148
	};
121
        } else if (DataStore.METADATA_ENVELOPE.equalsIgnoreCase(name)) {
122
            try {
123
                return this.shpFile.getFullExtent();
124
            } catch (ReadException e) {
125
                return null;
126
            }
127
        }
128
        return super.getDynValue(name);
129
    }
149 130

  
131
    protected void initResource(DBFStoreParameters params,
132
            DataStoreProviderServices storeServices) throws InitializeException {
133

  
134
        SHPStoreParameters shpParams = (SHPStoreParameters) params;
135
        resource
136
                = (MultiResource) createResource(MultiResource.TYPE_NAME,
137
                        new Object[]{shpParams.getSHPFileName()});
138

  
139
        resource.addResource(FileResource.NAME,
140
                new Object[]{shpParams.getSHPFileName()}, true);
141
        resource.addResource(FileResource.NAME,
142
                new Object[]{shpParams.getSHXFileName()}, true);
143
        resource.addResource(FileResource.NAME,
144
                new Object[]{shpParams.getDBFFileName()}, true);
145

  
146
        resource.addConsumer(this);
147
    }
148

  
149
    ;
150

  
150 151
	public ResourceProvider getResource() {
151
		return resource;
152
	}
152
        return resource;
153
    }
153 154

  
154
	/**
155
	 *
156
	 * @throws ResourceNotifyChangesException
157
	 */
158
	protected void resourcesNotifyChanges()
159
			throws ResourceNotifyChangesException {
155
    /**
156
     *
157
     * @throws ResourceNotifyChangesException
158
     */
159
    protected void resourcesNotifyChanges()
160
            throws ResourceNotifyChangesException {
160 161
		// super.resourcesNotifyChanges();
161
		// this.shpResource.notifyChanges();
162
		// this.shxResource.notifyChanges();
163
		getResource().notifyChanges();
164
		// TODO .prj
162
        // this.shpResource.notifyChanges();
163
        // this.shxResource.notifyChanges();
164
        getResource().notifyChanges();
165
        // TODO .prj
165 166

  
166
	}
167
    }
167 168

  
168
	/**
169
	 * @throws ResourceNotifyCloseException
170
	 *
171
	 */
172
	protected void resourcesNotifyClose() throws ResourceNotifyCloseException {
169
    /**
170
     * @throws ResourceNotifyCloseException
171
     *
172
     */
173
    protected void resourcesNotifyClose() throws ResourceNotifyCloseException {
173 174
//		super.resourcesNotifyClose();
174 175
//		this.shpResource.notifyClose();
175 176
//		this.shxResource.notifyClose();
176
		getResource().notifyClose();
177
		// TODO .prj
177
        getResource().notifyClose();
178
        // TODO .prj
178 179

  
179
	}
180
    }
180 181

  
181
	@Override
182
	protected void doDispose() throws BaseException {
183
		super.doDispose();
184
		getResource().removeConsumer(this);
185
		this.writer = null;
186
		this.shpFile = null;
187
	}
182
    @Override
183
    protected void doDispose() throws BaseException {
184
        super.doDispose();
185
        getResource().removeConsumer(this);
186
        this.writer = null;
187
        this.shpFile = null;
188
    }
188 189

  
189
	protected void disposeResource() {
190
		getResource().removeConsumer(this);
191
	}
190
    protected void disposeResource() {
191
        getResource().removeConsumer(this);
192
    }
192 193

  
193
	/**
194
	 * @throws ResourceNotifyOpenException
195
	 *
196
	 */
197
	protected void resourcesOpen() throws ResourceNotifyOpenException {
194
    /**
195
     * @throws ResourceNotifyOpenException
196
     *
197
     */
198
    protected void resourcesOpen() throws ResourceNotifyOpenException {
198 199
		// super.resourcesOpen();
199
		// this.shpResource.notifyOpen();
200
		// this.shxResource.notifyOpen();
201
		getResource().notifyOpen();
202
	}
200
        // this.shpResource.notifyOpen();
201
        // this.shxResource.notifyOpen();
202
        getResource().notifyOpen();
203
    }
203 204

  
204
	protected static EditableFeatureAttributeDescriptor addGeometryColumn(
205
			EditableFeatureType fType) {
205
    protected static EditableFeatureAttributeDescriptor addGeometryColumn(
206
            EditableFeatureType fType) {
206 207

  
207
		EditableFeatureAttributeDescriptor attrTmp = null;
208
		EditableFeatureAttributeDescriptor attr = null;
209
		Iterator iter = fType.iterator();
210
		while (iter.hasNext()) {
211
			attrTmp = (EditableFeatureAttributeDescriptor) iter.next();
212
			if (attrTmp.getType() == DataTypes.GEOMETRY) {
213
				if (attr != null) {
214
					// Two geom fields not allowed
215
					fType.remove(attrTmp.getName());
216
				} else {
217
					attr = attrTmp;
218
					// attr.setName(GEOMETRY_ATTIBUTE_NAME);
219
				}
220
			}
221
		}
208
        EditableFeatureAttributeDescriptor attrTmp = null;
209
        EditableFeatureAttributeDescriptor attr = null;
210
        Iterator iter = fType.iterator();
211
        while (iter.hasNext()) {
212
            attrTmp = (EditableFeatureAttributeDescriptor) iter.next();
213
            if (attrTmp.getType() == DataTypes.GEOMETRY) {
214
                if (attr != null) {
215
                    // Two geom fields not allowed
216
                    fType.remove(attrTmp.getName());
217
                } else {
218
                    attr = attrTmp;
219
                    // attr.setName(GEOMETRY_ATTIBUTE_NAME);
220
                }
221
            }
222
        }
222 223

  
224
        if (attr == null) {
225
            String geofield = createGeometryFieldName(fType);
226
            attr = fType.add(geofield, DataTypes.GEOMETRY);
227
            attr.setDefaultValue(null);
228
        }
223 229

  
224
		if (attr == null){
225
		    
226
		    String geofield = createGeometryFieldName(fType);
227
			attr = fType.add(geofield, DataTypes.GEOMETRY);
228
			try {
229
				attr.setDefaultValue(geomManager
230
						.createNullGeometry(SUBTYPES.GEOM2D));
231
			} catch (CreateGeometryException e) {
232
				logger.error("Error creating the envelope", e);
233
			}
234
		}
230
        attr.setObjectClass(Geometry.class);
231
        fType.setDefaultGeometryAttributeName(attr.getName());
232
        return attr;
235 233

  
236
		attr.setObjectClass(Geometry.class);		
237
		fType.setDefaultGeometryAttributeName(attr.getName());
238
		return attr;
234
    }
239 235

  
240
	}
236
    private static String createGeometryFieldName(FeatureType ft) {
241 237

  
242
	private static String createGeometryFieldName(FeatureType ft) {
243
	    
244
	    if (ft.getAttributeDescriptor(GEOMETRY_ATTIBUTE_NAME) == null) {
245
	        return GEOMETRY_ATTIBUTE_NAME;
246
	    }
238
        if (ft.getAttributeDescriptor(GEOMETRY_ATTIBUTE_NAME) == null) {
239
            return GEOMETRY_ATTIBUTE_NAME;
240
        }
247 241

  
248
	    int i = 0;
249
	    String candidate = GEOMETRY_ATTIBUTE_NAME + i;
250
	    while (ft.getAttributeDescriptor(candidate) != null) {
251
	        i++;
252
	        candidate = GEOMETRY_ATTIBUTE_NAME + i;
253
	    }
242
        int i = 0;
243
        String candidate = GEOMETRY_ATTIBUTE_NAME + i;
244
        while (ft.getAttributeDescriptor(candidate) != null) {
245
            i++;
246
            candidate = GEOMETRY_ATTIBUTE_NAME + i;
247
        }
254 248
        return candidate;
255 249
    }
256 250

  
257 251
    protected static FeatureType removeGeometryColumn(
258
			EditableFeatureType fType) {
259
		Iterator iter = fType.iterator();
260
		FeatureAttributeDescriptor attr;
261
		while (iter.hasNext()) {
262
			attr = (FeatureAttributeDescriptor) iter.next();
263
			if (attr.getType() == DataTypes.GEOMETRY) {
264
				iter.remove();
265
			}
266
		}
267
		fType.setDefaultGeometryAttributeName(null);
268
		return fType.getNotEditableCopy();
269
	}
252
            EditableFeatureType fType) {
253
        Iterator iter = fType.iterator();
254
        FeatureAttributeDescriptor attr;
255
        while (iter.hasNext()) {
256
            attr = (FeatureAttributeDescriptor) iter.next();
257
            if (attr.getType() == DataTypes.GEOMETRY) {
258
                iter.remove();
259
            }
260
        }
261
        fType.setDefaultGeometryAttributeName(null);
262
        return fType.getNotEditableCopy();
263
    }
270 264

  
271
	protected EditableFeatureType getTheFeatureType()
272
			throws InitializeException, OpenException {
273
		final EditableFeatureType fType = super.getTheFeatureType();
274
		this.open();
265
    protected EditableFeatureType getTheFeatureType()
266
            throws InitializeException, OpenException {
267
        final EditableFeatureType fType = super.getTheFeatureType();
268
        this.open();
275 269
		// try {
276
		// this.resourcesBegin();
277
		// } catch (DataException e) {
278
		// throw new InitializeException(this.getName(), e);
279
		// }
280
		try {
281
			getResource().execute(new ResourceAction() {
282
				public Object run() throws Exception {
283
					EditableFeatureAttributeDescriptor attr =
284
							addGeometryColumn(fType);
285
					attr.setGeometryType(shpFile.getGeometryType());
286
					attr.setGeometrySubType(shpFile.getGeometrySubType());
270
        // this.resourcesBegin();
271
        // } catch (DataException e) {
272
        // throw new InitializeException(this.getName(), e);
273
        // }
274
        try {
275
            getResource().execute(new ResourceAction() {
276
                public Object run() throws Exception {
277
                    EditableFeatureAttributeDescriptor attr
278
                            = addGeometryColumn(fType);
279
                    attr.setGeometryType(shpFile.getGeometryType());
280
                    attr.setGeometrySubType(shpFile.getGeometrySubType());
287 281

  
288
					IProjection srs = getShpParameters().getCRS();
289
					attr.setSRS(srs);
282
                    IProjection srs = getShpParameters().getCRS();
283
                    attr.setSRS(srs);
290 284

  
291
					return null;
292
				}
293
			});
294
			return fType;
295
		} catch (ResourceExecuteException e) {
296
			throw new InitializeException(e);
285
                    return null;
286
                }
287
            });
288
            return fType;
289
        } catch (ResourceExecuteException e) {
290
            throw new InitializeException(e);
297 291
			// } finally {
298
			// this.resourcesEnd();
299
		}
300
	}
292
            // this.resourcesEnd();
293
        }
294
    }
301 295

  
302 296
//	private String getSRSFromPrj(String srsParameters) {
303 297
//		// TODO identificar que SRS hay que usar, ya sea
......
306 300
//		// prg... y si ninguna de las dos que?
307 301
//		return null;
308 302
//	}
303
    protected SHPStoreParameters getShpParameters() {
304
        return (SHPStoreParameters) getParameters();
305
    }
309 306

  
310
	protected SHPStoreParameters getShpParameters() {
311
		return (SHPStoreParameters) getParameters();
312
	}
307
    public String getProviderName() {
308
        return NAME;
309
    }
313 310

  
314
	public String getProviderName() {
315
		return NAME;
316
	}
311
    public boolean allowWrite() {
312
        return this.shpFile.isEditable();
313
    }
317 314

  
318
	public boolean allowWrite() {
319
		return this.shpFile.isEditable();
320
	}
321

  
322
	/**
323
	 *
324
	 * @param index
325
	 * @param featureType
326
	 * @return
327
	 * @throws ReadException
328
	 */
329
	protected FeatureProvider getFeatureProviderByIndex(long index,
330
			FeatureType featureType) throws DataException {
315
    /**
316
     *
317
     * @param index
318
     * @param featureType
319
     * @return
320
     * @throws ReadException
321
     */
322
    protected FeatureProvider getFeatureProviderByIndex(long index,
323
            FeatureType featureType) throws DataException {
331 324
		// this.open();
332
		// this.resourcesBegin();
333
		try {
325
        // this.resourcesBegin();
326
        try {
334 327

  
335
			FeatureProvider featureProvider = super.getFeatureProviderByIndex(index,
336
					featureType);
337
			featureProvider.setDefaultEnvelope(this.shpFile.getBoundingBox(index));
338
			return featureProvider;
339
		} catch (DataException e) {
340
			throw e;
341
		} catch (CreateEnvelopeException e) {
342
			throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);		
343
		} catch (CreateGeometryException e) {
344
		    throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);
328
            FeatureProvider featureProvider = super.getFeatureProviderByIndex(index,
329
                    featureType);
330
            featureProvider.setDefaultEnvelope(this.shpFile.getBoundingBox(index));
331
            return featureProvider;
332
        } catch (DataException e) {
333
            throw e;
334
        } catch (CreateEnvelopeException e) {
335
            throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);
336
        } catch (CreateGeometryException e) {
337
            throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);
345 338
        }
346 339

  
347
	}
340
    }
348 341

  
349
	protected void initFeatureProviderByIndex(FeatureProvider featureProvider,
350
			long index, FeatureType featureType) throws DataException {
342
    protected void initFeatureProviderByIndex(FeatureProvider featureProvider,
343
            long index, FeatureType featureType) throws DataException {
351 344
		// this.open();
352
		// this.resourcesBegin();
353
		try {
354
			super.initFeatureProviderByIndex(featureProvider, index, featureType);
355
			featureProvider.setDefaultEnvelope(this.shpFile.getBoundingBox(index));
356
		} catch (CreateEnvelopeException e) {
357
			throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);			
358
		} catch (CreateGeometryException e) {
359
		    throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);       
345
        // this.resourcesBegin();
346
        try {
347
            super.initFeatureProviderByIndex(featureProvider, index, featureType);
348
            featureProvider.setDefaultEnvelope(this.shpFile.getBoundingBox(index));
349
        } catch (CreateEnvelopeException e) {
350
            throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);
351
        } catch (CreateGeometryException e) {
352
            throw new org.gvsig.fmap.dal.feature.exception.CreateGeometryException(e);
360 353
        }
361
	}
354
    }
362 355

  
363
	/**
364
	 *
365
	 * @param featureProvider
366
	 * @throws DataException
367
	 */
368
        protected void loadFeatureProviderByIndex(FeatureProvider featureProvider)
369
                throws DataException {
356
    /**
357
     *
358
     * @param featureProvider
359
     * @throws DataException
360
     */
361
    protected void loadFeatureProviderByIndex(FeatureProvider featureProvider)
362
            throws DataException {
370 363

  
371
            FeatureType featureType = featureProvider.getType();
372
            long index = ((Long) featureProvider.getOID()).longValue();
373
            boolean hasGeometry = false;
374
            int i = featureType.getDefaultGeometryAttributeIndex();
375
            if (i >= 0) {
376
                if (!featureProvider.isReadOnly(i)) {
377
                    try {
378
                        Geometry geom = this.shpFile.getGeometry(index);
379
                        featureProvider.set(i, geom);
380
                    } catch (CreateGeometryException e) {
381
                        throw new ReadException(getProviderName(), e);
382
                    }
364
        FeatureType featureType = featureProvider.getType();
365
        long index = ((Long) featureProvider.getOID()).longValue();
366
        boolean hasGeometry = false;
367
        int i = featureType.getDefaultGeometryAttributeIndex();
368
        if (i >= 0) {
369
            if (!featureProvider.isReadOnly(i)) {
370
                try {
371
                    Geometry geom = this.shpFile.getGeometry(index);
372
                    featureProvider.set(i, geom);
373
                } catch (CreateGeometryException e) {
374
                    throw new ReadException(getProviderName(), e);
383 375
                }
384
                hasGeometry = true;
385 376
            }
386
            if (hasDBFAttributes(featureType, hasGeometry)) {
387
                super.loadFeatureProviderByIndex(featureProvider);
388
            }
389

  
377
            hasGeometry = true;
390 378
        }
379
        if (hasDBFAttributes(featureType, hasGeometry)) {
380
            super.loadFeatureProviderByIndex(featureProvider);
381
        }
391 382

  
392
	private boolean hasDBFAttributes(FeatureType featureType,
393
			boolean hasGeometry) {
394
		FeatureAttributeDescriptor[] attributes =
395
				featureType.getAttributeDescriptors();
396
		// If there aren't any attributes, nor has any DBF attributes
397
		if (attributes == null || attributes.length == 0) {
398
			return false;
399
		}
400
		// If there is only one attribute and it is the geometry one
401
		if (attributes.length == 1 && hasGeometry) {
402
			return false;
403
		}
404
		// In any other case
405
		return true;
406
	}
383
    }
407 384

  
408
	protected void loadValue(FeatureProvider featureProvider, int rowIndex,
409
			FeatureAttributeDescriptor descriptor) throws ReadException {
410
		if (descriptor.getType() == DataTypes.GEOMETRY) {
411
			return;
412
		} else {
413
			super.loadValue(featureProvider, rowIndex, descriptor);
414
		}
415
	}
385
    private boolean hasDBFAttributes(FeatureType featureType,
386
            boolean hasGeometry) {
387
        FeatureAttributeDescriptor[] attributes
388
                = featureType.getAttributeDescriptors();
389
        // If there aren't any attributes, nor has any DBF attributes
390
        if (attributes == null || attributes.length == 0) {
391
            return false;
392
        }
393
        // If there is only one attribute and it is the geometry one
394
        if (attributes.length == 1 && hasGeometry) {
395
            return false;
396
        }
397
        // In any other case
398
        return true;
399
    }
416 400

  
417
	public FeatureProvider createFeatureProvider(FeatureType type) throws DataException {
418
		FeatureProvider data = new SHPFeatureProvider(this, type);
419
		return data;
420
	}
401
    protected void loadValue(FeatureProvider featureProvider, int rowIndex,
402
            FeatureAttributeDescriptor descriptor) throws ReadException {
403
        if (descriptor.getType() == DataTypes.GEOMETRY) {
404
            return;
405
        } else {
406
            super.loadValue(featureProvider, rowIndex, descriptor);
407
        }
408
    }
421 409

  
410
    public FeatureProvider createFeatureProvider(FeatureType type) throws DataException {
411
        FeatureProvider data = new SHPFeatureProvider(this, type);
412
        return data;
413
    }
422 414

  
423
	protected void openFile() throws IOException, DataException {
424
		super.openFile();
425
		this.shpFile.open();
415
    protected void openFile() throws IOException, DataException {
416
        super.openFile();
417
        this.shpFile.open();
426 418

  
427
	}
419
    }
428 420

  
429
	protected void closeFile() throws CloseException {
430
		super.closeFile();
431
		if (!this.shpFile.isOpen()) {
432
			return;
433
		}
434
		this.shpFile.close();
435
	}
421
    protected void closeFile() throws CloseException {
422
        super.closeFile();
423
        if (!this.shpFile.isOpen()) {
424
            return;
425
        }
426
        this.shpFile.close();
427
    }
436 428

  
437
	public boolean canWriteGeometry(final int geometryType, int geometrySubType)
438
			throws DataException {
439
		this.open();
440
		return ((Boolean) getResource().execute(new ResourceAction() {
441
			public Object run() throws Exception {
442
				boolean value = shpFile.canWriteGeometry(geometryType);
443
				return value ? Boolean.TRUE : Boolean.FALSE;
444
			}
445
		})).booleanValue();
429
    public boolean canWriteGeometry(final int geometryType, int geometrySubType)
430
            throws DataException {
431
        this.open();
432
        return ((Boolean) getResource().execute(new ResourceAction() {
433
            public Object run() throws Exception {
434
                boolean value = shpFile.canWriteGeometry(geometryType);
435
                return value ? Boolean.TRUE : Boolean.FALSE;
436
            }
437
        })).booleanValue();
446 438
//		this.resourcesBegin();
447 439
//		try {
448 440
//			return this.shpFile.canWriteGeometry(geometryType);
......
450 442
//		} finally {
451 443
//			this.resourcesEnd();
452 444
//		}
453
	}
454
	
455
	public void performChanges(Iterator deleteds, Iterator inserteds,
456
			Iterator updateds, Iterator originalFeatureTypesUpdated)
457
					throws PerformEditingException {
458
		
459
		
460
		/*
461
		 * This will throw an exception if there are new fields
462
		 * with names too long
463
		 */
464
		checkNewFieldsNameSize(originalFeatureTypesUpdated);
445
    }
465 446

  
466
		
467
		final FeatureType fType;
468
		try {
469
			fType = this.getStoreServices().getDefaultFeatureType();
470
		} catch (DataException e) {
471
			throw new PerformEditingException(this.getProviderName(), e);
472
		}
473
		// TODO Comprobar el campo de geometria
447
    public void performChanges(Iterator deleteds, Iterator inserteds,
448
            Iterator updateds, Iterator originalFeatureTypesUpdated)
449
            throws PerformEditingException {
474 450

  
475
		final EditableFeatureType dbfFtype = fType.getEditable();
451
        /*
452
         * This will throw an exception if there are new fields
453
         * with names too long
454
         */
455
        checkNewFieldsNameSize(originalFeatureTypesUpdated);
476 456

  
477
		removeGeometryColumn(dbfFtype);
457
        final FeatureType fType;
458
        try {
459
            fType = this.getStoreServices().getDefaultFeatureType();
460
        } catch (DataException e) {
461
            throw new PerformEditingException(this.getProviderName(), e);
462
        }
463
        // TODO Comprobar el campo de geometria
478 464

  
465
        final EditableFeatureType dbfFtype = fType.getEditable();
466

  
467
        removeGeometryColumn(dbfFtype);
468

  
479 469
		// try {
480
		// this.resourcesBegin();
481
		// } catch (ResourceExecuteException e1) {
482
		// throw new PerformEditingException(this.getName(), e1);
483
		// }
470
        // this.resourcesBegin();
471
        // } catch (ResourceExecuteException e1) {
472
        // throw new PerformEditingException(this.getName(), e1);
473
        // }
474
        try {
484 475

  
485
		try {
476
            getResource().execute(new ResourceAction() {
477
                public Object run() throws Exception {
478
                    FeatureSet set = null;
479
                    DisposableIterator iter = null;
480
                    try {
481
                        set = getFeatureStore().getFeatureSet();
482
                        writer = new SHPFeatureWriter(getProviderName());
486 483

  
487
			getResource().execute(new ResourceAction() {
488
				public Object run() throws Exception {
489
					FeatureSet set = null;
490
					DisposableIterator iter = null;
491
					try {
492
						set = getFeatureStore().getFeatureSet();
493
						writer = new SHPFeatureWriter(getProviderName());
484
                        SHPStoreParameters shpParams = getShpParameters();
485
                        SHPStoreParameters tmpParams
486
                                = (SHPStoreParameters) shpParams.getCopy();
494 487

  
495
						SHPStoreParameters shpParams = getShpParameters();
496
						SHPStoreParameters tmpParams =
497
								(SHPStoreParameters) shpParams.getCopy();
498
						
499
						File tmp_base = File.createTempFile(
500
						    "tmp_" + System.currentTimeMillis(), null);
501
						String str_base = tmp_base.getCanonicalPath();
502
						
503
						tmpParams.setDBFFile(str_base + ".dbf");
504
						tmpParams.setSHPFile(str_base + ".shp");
505
						tmpParams.setSHXFile(str_base + ".shx");
488
                        File tmp_base = File.createTempFile(
489
                                "tmp_" + System.currentTimeMillis(), null);
490
                        String str_base = tmp_base.getCanonicalPath();
506 491

  
507
						writer.begin(tmpParams, fType, dbfFtype, set.getSize());
492
                        tmpParams.setDBFFile(str_base + ".dbf");
493
                        tmpParams.setSHPFile(str_base + ".shp");
494
                        tmpParams.setSHXFile(str_base + ".shx");
508 495

  
509
						iter = set.fastIterator();
510
						while (iter.hasNext()) {
511
							Feature feature = (Feature) iter.next();
512
							writer.append(feature);
513
						}
496
                        writer.begin(tmpParams, fType, dbfFtype, set.getSize());
514 497

  
515
						writer.end();
498
                        iter = set.fastIterator();
499
                        while (iter.hasNext()) {
500
                            Feature feature = (Feature) iter.next();
501
                            writer.append(feature);
502
                        }
516 503

  
517
						close();
518
						resourceCloseRequest();
504
                        writer.end();
519 505

  
520
						if (!shpParams.getDBFFile().delete()) {
521
							throw new PerformEditingException(getProviderName(),
522
									new IOException(shpParams.getDBFFileName()));
523
						}
524
						if (!shpParams.getSHPFile().delete()) {
525
							throw new PerformEditingException(getProviderName(),
526
									new IOException(shpParams.getSHPFileName()));
527
						}
528
						if (!shpParams.getSHXFile().delete()) {
529
							throw new PerformEditingException(getProviderName(),
530
									new IOException(shpParams.getSHXFileName()));
531
						}
532
						
533
						if (!tmpParams.getDBFFile().renameTo(
534
								shpParams.getDBFFile())) {
535
						    logger.info("Warning: copying tmp file instead of renaming: "
536
						        + shpParams.getDBFFile());
537
						    FileUtils.copyFile(
538
						        tmpParams.getDBFFile(),
539
						        shpParams.getDBFFile());
540
						}
541
						if (!tmpParams.getSHPFile().renameTo(
542
								shpParams.getSHPFile())) {
506
                        close();
507
                        resourceCloseRequest();
508

  
509
                        if (!shpParams.getDBFFile().delete()) {
510
                            throw new PerformEditingException(getProviderName(),
511
                                    new IOException(shpParams.getDBFFileName()));
512
                        }
513
                        if (!shpParams.getSHPFile().delete()) {
514
                            throw new PerformEditingException(getProviderName(),
515
                                    new IOException(shpParams.getSHPFileName()));
516
                        }
517
                        if (!shpParams.getSHXFile().delete()) {
518
                            throw new PerformEditingException(getProviderName(),
519
                                    new IOException(shpParams.getSHXFileName()));
520
                        }
521

  
522
                        if (!tmpParams.getDBFFile().renameTo(
523
                                shpParams.getDBFFile())) {
543 524
                            logger.info("Warning: copying tmp file instead of renaming: "
544
                                + shpParams.getSHPFile());
525
                                    + shpParams.getDBFFile());
545 526
                            FileUtils.copyFile(
546
                                tmpParams.getSHPFile(),
547
                                shpParams.getSHPFile());
548
						}
549
						if (!tmpParams.getSHXFile().renameTo(
550
								shpParams.getSHXFile())) {
527
                                    tmpParams.getDBFFile(),
528
                                    shpParams.getDBFFile());
529
                        }
530
                        if (!tmpParams.getSHPFile().renameTo(
531
                                shpParams.getSHPFile())) {
551 532
                            logger.info("Warning: copying tmp file instead of renaming: "
552
                                + shpParams.getSHXFile());
533
                                    + shpParams.getSHPFile());
553 534
                            FileUtils.copyFile(
554
                                tmpParams.getSHXFile(),
555
                                shpParams.getSHXFile());
556
						}
535
                                    tmpParams.getSHPFile(),
536
                                    shpParams.getSHPFile());
537
                        }
538
                        if (!tmpParams.getSHXFile().renameTo(
539
                                shpParams.getSHXFile())) {
540
                            logger.info("Warning: copying tmp file instead of renaming: "
541
                                    + shpParams.getSHXFile());
542
                            FileUtils.copyFile(
543
                                    tmpParams.getSHXFile(),
544
                                    shpParams.getSHXFile());
545
                        }
557 546

  
558
						resourcesNotifyChanges();
559
						initFeatureType();
560
						return null;
561
					} finally {
562
						dispose(set);
563
						dispose(iter);
564
					}
565
				}
566
			});
547
                        resourcesNotifyChanges();
548
                        initFeatureType();
549
                        return null;
550
                    } finally {
551
                        dispose(set);
552
                        dispose(iter);
553
                    }
554
                }
555
            });
567 556

  
568
		} catch (Exception e) {
569
			throw new PerformEditingException(this.getProviderName(), e);
557
        } catch (Exception e) {
558
            throw new PerformEditingException(this.getProviderName(), e);
570 559
			// } finally {
571
			// this.resourcesEnd();
572
		}
560
            // this.resourcesEnd();
561
        }
573 562

  
563
    }
574 564

  
575
	}
576

  
577

  
578

  
579
	protected void resourceCloseRequest() throws ResourceException {
565
    protected void resourceCloseRequest() throws ResourceException {
580 566
		// super.resourceCloseRequest();
581
		// this.shpResource.closeRequest();
582
		// this.shxResource.closeRequest();
583
		getResource().closeRequest();
584
	}
567
        // this.shpResource.closeRequest();
568
        // this.shxResource.closeRequest();
569
        getResource().closeRequest();
570
    }
585 571

  
586
	public Envelope getEnvelope() throws DataException {
587
		this.open();
588
		return (Envelope) this.getDynValue("Envelope");
589
	}
572
    public Envelope getEnvelope() throws DataException {
573
        this.open();
574
        return (Envelope) this.getDynValue("Envelope");
575
    }
590 576

  
591
	public void append(final FeatureProvider featureProvider) throws DataException {
577
    public void append(final FeatureProvider featureProvider) throws DataException {
592 578
//		this.resourcesBegin();
593 579
//		try {
594 580

  
595
		getResource().execute(new ResourceAction() {
596
			public Object run() throws Exception {
597
				writer.append(getStoreServices().createFeature(featureProvider));
598
				return null;
599
			}
600
		});
581
        getResource().execute(new ResourceAction() {
582
            public Object run() throws Exception {
583
                writer.append(getStoreServices().createFeature(featureProvider));
584
                return null;
585
            }
586
        });
601 587
//		} finally {
602 588
//			this.resourcesEnd();
603 589
//		}
604 590

  
605
	}
591
    }
606 592

  
607
	public void beginAppend() throws DataException {
593
    public void beginAppend() throws DataException {
608 594
		// this.resourcesBegin();
609
		// try {
595
        // try {
610 596

  
611
		getResource().execute(new ResourceAction() {
612
			public Object run() throws Exception {
613
				FeatureStore store = getFeatureStore();
614
				FeatureType fType = store.getDefaultFeatureType();
597
        getResource().execute(new ResourceAction() {
598
            public Object run() throws Exception {
599
                FeatureStore store = getFeatureStore();
600
                FeatureType fType = store.getDefaultFeatureType();
615 601

  
616 602
				// TODO Comprobar el campo de geometria
603
                EditableFeatureType dbfFtype = fType.getEditable();
617 604

  
618
				EditableFeatureType dbfFtype = fType.getEditable();
605
                removeGeometryColumn(dbfFtype);
606
                FeatureSet set = store.getFeatureSet();
619 607

  
620
				removeGeometryColumn(dbfFtype);
621
				FeatureSet set = store.getFeatureSet();
608
                writer = new SHPFeatureWriter(getProviderName());
622 609

  
623
				writer = new SHPFeatureWriter(getProviderName());
624

  
625
				writer.begin(getShpParameters(), fType, dbfFtype, set.getSize());
626
				return null;
627
			}
628
		});
610
                writer.begin(getShpParameters(), fType, dbfFtype, set.getSize());
611
                return null;
612
            }
613
        });
629 614
		// } finally {
630
		// this.resourcesEnd();
631
		// }
615
        // this.resourcesEnd();
616
        // }
632 617

  
633
	}
618
    }
634 619

  
635
	public void endAppend() throws DataException {
620
    public void endAppend() throws DataException {
636 621
//		this.resourcesBegin();
637 622
//		try {
638
		getResource().execute(new ResourceAction() {
639
			public Object run() throws Exception {
640
				writer.end();
641
				resourcesNotifyChanges();
642
				return null;
643
			}
644
		});
623
        getResource().execute(new ResourceAction() {
624
            public Object run() throws Exception {
625
                writer.end();
626
                resourcesNotifyChanges();
627
                return null;
628
            }
629
        });
645 630
//		} finally {
646 631
//			this.resourcesEnd();
647 632
//		}
648 633

  
649
	}
634
    }
650 635

  
651
	public Object getSourceId() {
652
		return this.getShpParameters().getFile();
653
	}
654
}
636
    public Object getSourceId() {
637
        return this.getShpParameters().getFile();
638
    }
639
}

Also available in: Unified diff