Revision 754

View differences:

org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/AbstractDistance.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import org.cresques.cts.IProjection;
27
import org.gvsig.fmap.dal.feature.Feature;
28
import org.gvsig.fmap.mapcontext.MapContext;
29

  
30
/**
31
 * Abstract distance implementation.
32
 * 
33
 * @author gvSIG Team
34
 * @version $Id$
35
 */
36
public abstract class AbstractDistance implements IDistance {
37

  
38
    public static final double EARTH_RADIUS = 6378137d;
39
    protected int numberOfRings = 1;
40
    protected Feature feature = null;
41
    
42
    public void setFeature(Feature feature) {
43
        this.feature = feature;
44
    }
45

  
46
    /**
47
     * For computing with geodetic coordinates:
48
     * returns the angular measure (in radians)
49
     * for a distance over the earth along a
50
     * meridiam.
51
     * Because this consideration is an approximation,
52
     * we consideer the eart like an sphere (not an
53
     * ellipsoid)
54
     * 
55
     * @param dist
56
     *            distance in meters
57
     * @return arc of meridian whose length is the specified
58
     *         distance
59
     */
60
    private double toSexaAngularMeasure(double dist) {
61
        /*
62
         * dist = 6378km(terrestrial radius) -> 2PI
63
         * passed distance -> incognite
64
         */
65
        return Math.toDegrees((2 * Math.PI * dist) / EARTH_RADIUS);
66
    }
67

  
68
    /**
69
     * Converts a distance entered by user in the GUI in the same distance
70
     * in internal units (measure units)
71
     */
72
    protected double getInInternalUnits(double userEntryDistance,
73
        IProjection proj, int distanceUnits, int mapUnits) {
74

  
75
       /* double[] trans2Meter = MapContext.getDistanceTrans2Meter();
76
        double distInInternalUnits =
77
            (userEntryDistance / trans2Meter[mapUnits])
78
                * trans2Meter[distanceUnits];
79

  
80
        if ((proj != null) && !(proj.isProjected()))
81
            distInInternalUnits = toSexaAngularMeasure(distInInternalUnits);
82
            
83
        return distInInternalUnits;*/
84
    	
85
    	/*
86
    	 * En caso de que el sistema de referencia sea proyectado se usa la distancia
87
    	 * que el usuario ha definido, ya que esta se supone en metros. En caso de que
88
    	 * las coordenadas sean en geogr?ficas se toma la distancia que el usuario ha
89
    	 * definido en metros en el ecuador. Esto supone una desviaci?n a medida que 
90
    	 * nos alejamos del ecuador. Una posible soluci?n ser?a obtener esa distancia 
91
    	 * para la posici?n en el planeta en la que se encuentra la cartograf?a en la
92
    	 * proyecci?n en la que est? definida. 
93
    	 */
94

  
95
    	if ((proj != null) && !(proj.isProjected()))
96
    		return userEntryDistance / 111352D;
97
        return userEntryDistance;
98
    }
99
    
100
    public void setNumberOfRings(int n) {
101
    	numberOfRings = n;
102
    }
103

  
104
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/BufferLibrary.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import org.gvsig.geoprocess.algorithm.base.core.AlgorithmAbstractLibrary;
27
import org.gvsig.i18n.Messages;
28
import org.gvsig.tools.library.LibraryException;
29

  
30
/**
31
 * Initialization of BufferLibrary library.
32
 * 
33
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
34
 * @author gvSIG Team
35
 */
36
public class BufferLibrary extends AlgorithmAbstractLibrary {
37

  
38
    @Override
39
    protected void doInitialize() throws LibraryException {
40
        // Nothing to do
41
    }
42

  
43
    @Override
44
    protected void doPostInitialize() throws LibraryException {
45
        Messages.addResourceFamily(
46
            "org.gvsig.geoprocess.algorithm.buffer.buffer", BufferLibrary.class
47
                .getClassLoader(), BufferLibrary.class.getClass().getName());
48
        registerGeoProcess(new BufferAlgorithm());
49
    }
50

  
51
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/FieldDistance.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import org.cresques.cts.IProjection;
27

  
28
/**
29
 * Computes a constant size of each geometry built
30
 * 
31
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
32
 */
33
public class FieldDistance extends AbstractDistance {
34

  
35
    private int attributePosition = 0;
36

  
37
    public FieldDistance(int attributePosition) {
38
        this.attributePosition = attributePosition;
39
    }
40

  
41
    public double getBufferDistance(IProjection projection, int distanceUnits, int mapUnits) {
42
        double attr = 0D;
43
        Object obj = feature.get(attributePosition);
44
        if (obj instanceof Double)
45
            attr = ((Double) obj).doubleValue();
46
        else
47
            if (obj instanceof Integer)
48
                attr = ((Integer) obj).doubleValue();
49
            else
50
                if (obj instanceof Float)
51
                    attr = ((Float) obj).doubleValue();
52
                else
53
                    return 0;
54

  
55
        return getInInternalUnits(attr, projection, distanceUnits, mapUnits) * numberOfRings;
56
    }
57

  
58
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/BufferAlgorithm.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import java.io.File;
27

  
28
import javax.swing.JOptionPane;
29

  
30
import org.cresques.cts.IProjection;
31
import org.gvsig.fmap.dal.DALLocator;
32
import org.gvsig.fmap.dal.DataManager;
33
import org.gvsig.fmap.dal.DataStoreParameters;
34
import org.gvsig.fmap.dal.DataTypes;
35
import org.gvsig.fmap.dal.exception.DataException;
36
import org.gvsig.fmap.dal.exception.InitializeException;
37
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
38
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
39
import org.gvsig.fmap.dal.feature.EditableFeatureType;
40
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
41
import org.gvsig.fmap.dal.feature.FeatureStore;
42
import org.gvsig.fmap.dal.feature.FeatureType;
43
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
44
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
45
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
46
import org.gvsig.fmap.geom.Geometry;
47
import org.gvsig.geoprocess.lib.api.GeoProcessLocator;
48
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
49
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
50

  
51
import es.unex.sextante.additionalInfo.AdditionalInfoNumericalValue;
52
import es.unex.sextante.core.Sextante;
53
import es.unex.sextante.dataObjects.IVectorLayer;
54
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
55
import es.unex.sextante.exceptions.NullParameterValueException;
56
import es.unex.sextante.exceptions.OptionalParentParameterException;
57
import es.unex.sextante.exceptions.RepeatedParameterNameException;
58
import es.unex.sextante.exceptions.UndefinedParentParameterNameException;
59
import es.unex.sextante.exceptions.UnsupportedOutputChannelException;
60
import es.unex.sextante.exceptions.WrongParameterIDException;
61
import es.unex.sextante.exceptions.WrongParameterTypeException;
62
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
63
import es.unex.sextante.outputs.OutputVectorLayer;
64

  
65
/**
66
 * Geoprocess that computes a buffer area around each feature's geometry of the
67
 * input layer. <br>
68
 * All the points interior to this buffer area has to be at a distance inferior
69
 * to "buffer distance" to the original geometry. This buffer distance could be
70
 * constant, or it could be a function of the value of a feature attribute.<br>
71
 * 
72
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
73
 * @author gvSIG Team
74
 */
75
public class BufferAlgorithm extends AbstractSextanteGeoProcess {
76

  
77
    public static final String RESULT                   = "RESULT";
78
    public static final String LAYER                    = "LAYER";
79
    public static final String SELECTED_GEOM            = "SELECTED_GEOM";
80
    public static final String DISTANCE                 = "DISTANCE";
81
    public static final String FIELD                    = "FIELD";
82
    public static final String DISSOLVE                 = "DISSOLVE";
83
    public static final String ROUND_BORDER             = "ROUND_BORDER";
84
    public static final String AREA                     = "AREA";
85
    public static final String RING_NUMBER              = "RING_NUMBER";
86
    
87
	/**
88
	 * For polygonal buffers, only compute exterior buffers
89
	 * (is the default operation, it applies to any geometry type)
90
	 */
91
	public static final byte BUFFER_OUTSIDE_POLY        = 0;
92
	/**
93
	 * For polygonal buffers, only compute interior buffers
94
	 */
95
	public static final byte BUFFER_INSIDE_POLY         = 1;
96
	/**
97
	 * For polygonal buffers, compute interior and exterior buffers
98
	 */
99
	public static final byte BUFFER_INSIDE_OUTSIDE_POLY = 2;
100
	
101
    public static final byte SOURCE_FIELDS              = 0;
102
    public static final byte FID_DIST_FIELDS            = 1;
103
    public static final byte FID_FROM_TO_FIELDS         = 2;
104
    protected byte           tableFields                = -1; 
105
    
106
    private int              inflArea                   = BUFFER_OUTSIDE_POLY;
107
    protected boolean        dissolve                   = false;
108
    protected int            rings                      = 0;
109
    protected boolean        selectedGeom               = false;
110
    protected FeatureStore   inputStore                 = null;
111
    protected FeatureStore   outputStore                = null;
112
    protected IVectorLayer   sextanteInputLayer         = null;
113
    protected boolean        round_border               = false; 
114
	
115
    public static String[] sOptions = {
116
    	GeoProcessLocator.getGeoProcessManager().getTranslation("poly_out"), 
117
    	GeoProcessLocator.getGeoProcessManager().getTranslation("poly_in"),
118
    	GeoProcessLocator.getGeoProcessManager().getTranslation("poly_inandout") 
119
    };
120

  
121
    public void defineCharacteristics() {
122
        setName(getTranslation("Buffer"));
123
        setGroup(getTranslation("basic_vect_algorithms"));
124
        // setGeneratesUserDefinedRasterOutput(false);
125
       
126
        try {
127
            m_Parameters.addInputVectorLayer(LAYER, getTranslation("Input_layer"), 
128
            	IVectorLayer.SHAPE_TYPE_WRONG, true);
129
            m_Parameters.addBoolean(SELECTED_GEOM, getTranslation("Selected_geometries"), false);
130
            m_Parameters.addNumericalValue(DISTANCE, getTranslation("area_distance"), 0,
131
                AdditionalInfoNumericalValue.NUMERICAL_VALUE_DOUBLE);
132
            m_Parameters.addTableField(FIELD, getTranslation("area_field"), "LAYER");
133
            m_Parameters.addBoolean(DISSOLVE, getTranslation("Dissolve_entities"), false);
134
            m_Parameters.addBoolean(ROUND_BORDER, getTranslation("Round_border"), true);
135
            m_Parameters.addSelection(AREA, getTranslation("Builds_influence_area"), sOptions);
136
            m_Parameters.addSelection(RING_NUMBER, getTranslation("Number_of_rings"),
137
                new String[] { "1", "2", "3" });
138
        } catch (RepeatedParameterNameException e) {
139
            Sextante.addErrorToLog(e);
140
        } catch (UndefinedParentParameterNameException e) {
141
            Sextante.addErrorToLog(e);
142
        } catch (OptionalParentParameterException e) {
143
            Sextante.addErrorToLog(e);
144
        }
145
        addOutputVectorLayer(RESULT, getTranslation("Buffer"),
146
            OutputVectorLayer.SHAPE_TYPE_POLYGON);
147
    }
148
    
149
    protected void readParameters() throws WrongParameterTypeException, NullParameterValueException, WrongParameterIDException {
150
    	sextanteInputLayer = m_Parameters.getParameterValueAsVectorLayer(LAYER);
151
    	selectedGeom = m_Parameters.getParameter(SELECTED_GEOM).getParameterValueAsBoolean();
152
    	rings = m_Parameters.getParameterValueAsInt(RING_NUMBER);
153
        dissolve = m_Parameters.getParameter(DISSOLVE).getParameterValueAsBoolean();
154
        round_border = m_Parameters.getParameter(ROUND_BORDER).getParameterValueAsBoolean();
155
    }
156

  
157
    public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
158
    	if(existsOutPutFile(BufferAlgorithm.RESULT, 0)) {
159
    		throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
160
    	}
161
        
162
        double distanceValue = m_Parameters.getParameter(DISTANCE).getParameterValueAsDouble();
163
        int attributePosition = m_Parameters.getParameterValueAsInt(FIELD);
164
        inflArea = m_Parameters.getParameterValueAsInt(AREA);
165
        readParameters();
166

  
167
        if (sextanteInputLayer.getShapeType() != IVectorLayer.SHAPE_TYPE_POLYGON
168
            && inflArea != BUFFER_OUTSIDE_POLY) {
169
            JOptionPane.showMessageDialog(null,
170
                getTranslation("Wrong_type_for_this_shapetype"), "Error",
171
                JOptionPane.WARNING_MESSAGE);
172
            inflArea = BUFFER_OUTSIDE_POLY;
173
        }
174
        
175
        if (sextanteInputLayer instanceof FlyrVectIVectorLayer)
176
            inputStore = ((FlyrVectIVectorLayer) sextanteInputLayer).getFeatureStore();
177
        else
178
            return false;
179

  
180
        try {
181
            // Object to compute the distance
182
            IDistance distance = null;
183
            if (distanceValue == 0)
184
                distance = new FieldDistance(attributePosition);
185
            else
186
                distance = new ConstantDistance(distanceValue);
187
            
188
            // Object to compute the buffer operation
189
            BufferOperation operation = null;
190
            switch (inflArea) {
191
            case BUFFER_OUTSIDE_POLY:
192
                operation = new OutBufferOperation(distance, inputStore, this, getTableFieldsStructure());
193
                break;
194
            case BUFFER_INSIDE_POLY:
195
                operation = new InBufferOperation(distance, inputStore, this, getTableFieldsStructure());
196
                break;
197
            case BUFFER_INSIDE_OUTSIDE_POLY:
198
                operation = new InOutBufferOperation(distance, inputStore, this, getTableFieldsStructure());
199
                break;
200
            }
201
            operation.setTypeOfCap(round_border ? BufferOperation.CAP_ROUND : BufferOperation.CAP_SQUARE);
202
            operation.setGeoProcess(this, 100);
203
            
204
        	// Builds the output FeatureStore
205
            outputStore = buildOutPutStore(IVectorLayer.SHAPE_TYPE_POLYGON,
206
        					getTranslation("Buffer"), RESULT);
207
        	
208
        	if(!dissolve) {
209
        		computesBufferAlgWithoutDissolve(operation);
210
        	} else {
211
        		computesBufferAlgWithDissolve(operation);
212
        	}
213
        	
214
        } catch (DataException e) {
215
            Sextante.addErrorToLog(e);
216
            return false;
217
        }
218
        
219
		if(getTaskMonitor().isCanceled())
220
			return false;
221

  
222
        return true;
223
    }
224
    
225
    private void computesOneRingBufferWithDissolve(
226
    		BufferOperation operation, 
227
    		FuseOperation fuseOp, 
228
    		String idFile,
229
    		int initialPosition,
230
    		int ringPosition) throws ValidateDataParametersException, DataException {
231
    	String file = System.getProperty("java.io.tmpdir") + File.separator + (idFile) + ".shp";
232
		FeatureStore outAuxFeatStore = buildTemporalStore(org.gvsig.fmap.geom.Geometry.TYPES.SURFACE, file, 
233
				inputStore.getDefaultFeatureType().getDefaultSRS());
234
		
235
		operation.getDistance().setNumberOfRings(ringPosition + 1);
236
		
237
		operation.setNumberOfRadialBuffers(1);
238
		operation.setTaskStatus(getStatus());
239
		m_Task.setProgressText(getTranslation("calc_buffer") + " [Ring:" + (rings - ringPosition) + "]");
240
		operation.computesGeometryOperation(inputStore, outAuxFeatStore,
241
				attrNames, selectedGeom, false, true);
242
		
243
		outAuxFeatStore = open(file, inputStore.getDefaultFeatureType().getDefaultSRS());
244
		
245
		m_Task.setProgressText(getTranslation("fuse_spatially") + " [Ring:" + (rings - ringPosition) + "]");
246
		fuseOp.computesGeometryOperation(outAuxFeatStore, outputStore, attrNames, ringPosition == initialPosition ? true : false);
247
		outAuxFeatStore.dispose();
248
    }
249
    
250
    protected void computesBufferAlgWithDissolve(BufferOperation operation) throws DataException {
251
    	long fileTmpId = System.currentTimeMillis();
252
    	FuseOperation fuseOp = new FuseOperation(this);
253
    	
254
    	if(inflArea == BUFFER_OUTSIDE_POLY || inflArea == BUFFER_INSIDE_OUTSIDE_POLY) {
255
    		try {
256
    			for (int i = rings; i >= 0 ; i--) {
257
    				computesOneRingBufferWithDissolve(
258
    						operation, 
259
    						fuseOp, 
260
    						fileTmpId + i + "",
261
    						rings,
262
    						i);
263
    			}
264
    		} catch (ValidateDataParametersException e) {
265
    			Sextante.addErrorToLog(e);
266
    		}
267
    	}
268
    	
269
    	if(inflArea == BUFFER_INSIDE_POLY) {
270
    		try {
271
    			for (int i = 0; i < rings + 1 ; i++) {
272
    				computesOneRingBufferWithDissolve(
273
    						operation, 
274
    						fuseOp, 
275
    						fileTmpId + i + "",
276
    						0,
277
    						i);
278
    			}
279
    		} catch (ValidateDataParametersException e) {
280
    			Sextante.addErrorToLog(e);
281
    		}
282
    	}
283
    	
284
    	fuseOp.end();
285
    }
286
    
287
    protected void computesBufferAlgWithoutDissolve(BufferOperation operation) throws DataException {
288
    	operation.setNumberOfRadialBuffers(rings + 1);
289
    	operation.setTaskStatus(getStatus());
290
    	operation.computesGeometryOperation(inputStore, 
291
    			outputStore,
292
    			attrNames, 
293
    			selectedGeom, 
294
    			false, 
295
    			true);
296
    }
297
    
298
    
299
    /**
300
     * Gets the constant with the table structure 
301
     * @return
302
     */
303
    protected byte getTableFieldsStructure() {
304
    	if(tableFields == -1) {
305
            if(!dissolve) {
306
            	tableFields = SOURCE_FIELDS;
307
        	} else {
308
                if (inflArea == BUFFER_INSIDE_OUTSIDE_POLY) 
309
                	tableFields = FID_FROM_TO_FIELDS;
310
                else
311
                	tableFields = FID_DIST_FIELDS;
312
        	}
313
    	}
314
    	return tableFields;
315
    }
316
    
317
    /**
318
     * Open a <code>DataStore</code>
319
     * @param file
320
     * @param proj
321
     * @return
322
     * @throws InitializeException
323
     * @throws ProviderNotRegisteredException
324
     * @throws ValidateDataParametersException
325
     */
326
    private FeatureStore open(String file, IProjection proj) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
327
    	DataManager manager = DALLocator.getDataManager();
328
    	DataStoreParameters params = manager.createStoreParameters("Shape");
329
    	params.setDynValue("shpfile", file);
330
    	params.setDynValue("crs", proj);
331
    	FeatureStore featureStore = (FeatureStore) manager.openStore(params.getDataStoreName(), params);
332
    	return featureStore;
333
    }
334

  
335
    /**
336
     * Builds the output FeatureStore
337
     * 
338
     * @param featureType
339
     * @return FeatureStore
340
     * @throws DataException 
341
     */
342
    protected FeatureStore buildOutPutStore(int shapeType, 
343
    		String sextanteLayerName, 
344
    		String sextanteLayerLabel) throws DataException {
345
    	FeatureType featureType = inputStore.getDefaultFeatureType();
346
    	
347
    	if(getTableFieldsStructure() == SOURCE_FIELDS) {
348
    		return super.buildOutPutStore(featureType, shapeType,sextanteLayerName, sextanteLayerLabel);
349
    	} 
350
    	Class<?>[] types = null;
351
    	if (getTableFieldsStructure() == FID_FROM_TO_FIELDS) {
352
    		types = new Class[] { Integer.class, Double.class, Double.class };
353
    		attrNames = new String[] { "FID", "FROM", "TO" };
354
    	} 
355
    	if (getTableFieldsStructure() == FID_DIST_FIELDS) {
356
    		types = new Class[] { Integer.class, Double.class };
357
    		attrNames = new String[] { "FID", "DIST" };
358
    	}
359
    	try {
360
    		IVectorLayer output =
361
    				getNewVectorLayer(sextanteLayerLabel, sextanteLayerName,
362
    						shapeType, types, attrNames);
363
    		return ((FlyrVectIVectorLayer) output).getFeatureStore();
364
    	} catch (UnsupportedOutputChannelException e) {
365
    		Sextante.addErrorToLog(e);
366
    	} catch (GeoAlgorithmExecutionException e) {
367
    		Sextante.addErrorToLog(e);
368
    	}
369
    	
370
    	return null;
371
    }
372

  
373
    /**
374
     * Builds the output FeatureStore
375
     * 
376
     * @param featureType
377
     * @return FeatureStore
378
     * @throws DataException 
379
     * @throws ValidateDataParametersException 
380
     */
381
    protected FeatureStore buildTemporalStore(int shapeType, 
382
    		String file, 
383
    		IProjection crs) throws DataException, ValidateDataParametersException {
384
    	FeatureType featureType = inputStore.getDefaultFeatureType();
385
    	
386
        int[] types = null;
387
        if(getTableFieldsStructure() == SOURCE_FIELDS) {
388
        	FeatureAttributeDescriptor[] desc = featureType.getAttributeDescriptors();
389
        	types = new int[desc.length - 1];
390
        	attrNames = new String[desc.length - 1];
391
        	int attrCount = 0;
392
        	for (int i = 0; i < desc.length; i++) {
393
        		if(desc[i].getType() != DataTypes.GEOMETRY) {
394
        			types[attrCount] = desc[i].getType();
395
        			attrNames[attrCount] = desc[i].getName();
396
        			attrCount ++;
397
        		}
398
			}
399
        }
400
        if (getTableFieldsStructure() == FID_FROM_TO_FIELDS) {
401
            types = new int[] { java.sql.Types.INTEGER, java.sql.Types.DOUBLE, java.sql.Types.DOUBLE };
402
            attrNames = new String[] { "FID", "FROM", "TO" };
403
        }
404
        if (getTableFieldsStructure() == FID_DIST_FIELDS) {
405
            types = new int[] { java.sql.Types.INTEGER, java.sql.Types.DOUBLE };
406
            attrNames = new String[] { "FID", "DIST" };
407
        }
408

  
409
        return create(file, types, attrNames, crs);
410
    }
411
    
412
	@SuppressWarnings("deprecation")
413
	public FeatureStore create(String sFilename,
414
			int[] types, String[] attrNames, IProjection crs) {
415
		try {
416
			DataManager manager = DALLocator.getDataManager();
417
			FilesystemServerExplorerParameters explorerParams =
418
			    (FilesystemServerExplorerParameters) manager.createServerExplorerParameters("FilesystemExplorer");
419
			explorerParams.setRoot(new File(sFilename).getParent());
420
			FilesystemServerExplorer explorer = (FilesystemServerExplorer) manager.createServerExplorer(explorerParams);
421
			NewFeatureStoreParameters newParams = (NewFeatureStoreParameters) explorer.getAddParameters(new File(sFilename));
422
			
423
			EditableFeatureType ft = newParams.getDefaultFeatureType();
424
			for (int i = 0; i < attrNames.length; i++) {
425
				ft.add(attrNames[i], types[i], 7);
426
			}
427
			ft.add("GEOMETRY", DataTypes.GEOMETRY).setGeometryType(
428
					Geometry.TYPES.SURFACE).setGeometrySubType(Geometry.SUBTYPES.GEOM2D);
429
			
430
			newParams.setDefaultFeatureType(ft);
431
			newParams.setDynValue("CRS", crs);
432
			newParams.setDynValue("geometryType", Geometry.TYPES.SURFACE);
433

  
434
			manager.newStore("FilesystemExplorer",
435
                newParams.getDataStoreName(), newParams, true);
436
                
437
			FeatureStore featureStore = (FeatureStore) manager.openStore(newParams.getDataStoreName(), newParams);			
438
			featureStore.edit(FeatureStore.MODE_APPEND);
439
			return featureStore;
440
		} catch (Exception e) {
441
			Sextante.addErrorToLog(e);
442
		}
443
		return null;
444
	}
445

  
446

  
447
    @Override
448
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {
449
        return BufferParametersPanel.class;
450
    }
451
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/InBufferOperation.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import org.gvsig.fmap.dal.exception.DataException;
27
import org.gvsig.fmap.dal.feature.EditableFeature;
28
import org.gvsig.fmap.dal.feature.Feature;
29
import org.gvsig.fmap.dal.feature.FeatureStore;
30
import org.gvsig.fmap.geom.exception.CreateGeometryException;
31
import org.gvsig.geoprocess.algorithm.base.util.GeometryUtil;
32
import org.gvsig.geoprocess.algorithm.base.util.JTSFacade;
33
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
34

  
35
import com.vividsolutions.jts.geom.Geometry;
36
import com.vividsolutions.jts.operation.buffer.BufferOp;
37
import com.vividsolutions.jts.operation.buffer.BufferParameters;
38
import com.vividsolutions.jts.simplify.TopologyPreservingSimplifier;
39

  
40
import es.unex.sextante.core.Sextante;
41

  
42
/**
43
 * Buffer operation
44
 * 
45
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
46
 * @author gvSIG Team
47
 */
48
public class InBufferOperation extends BufferOperation {
49

  
50
    /**
51
     * Builds an instance of this operation.
52
     * 
53
     * @param distance
54
     * @param layer
55
     * @param userDistance
56
     */
57
    public InBufferOperation(IDistance distance, 
58
    	FeatureStore inputStore,
59
        AbstractSextanteGeoProcess p,
60
        byte tableFieldStructure) {
61
        super(distance, inputStore, p, tableFieldStructure);
62
    }
63

  
64
    public EditableFeature invoke(org.gvsig.fmap.geom.Geometry g,
65
        Feature feature) {
66
        // if we have radial internal buffers, we start by most interior buffer
67
        Geometry newGeom = null;
68
        Geometry previousInteriorRing = null;
69
        Geometry originalGeometry = GeometryUtil.geomToJTS(g);
70
        Geometry inputParam = originalGeometry;
71
        distance.setFeature(feature);
72
        double bufferDistance =
73
            distance.getBufferDistance(projection,
74
                getDistanceUnits(), getMapUnits());
75

  
76
        if (originalGeometry.getDimension() != 0)
77
            inputParam =
78
                TopologyPreservingSimplifier.simplify(originalGeometry,
79
                    bufferDistance / 10d);
80

  
81
        /*for (int i = 1; i <= numberOfRadialBuffers; i++) {
82
            double distRing = i * bufferDistance;
83
            BufferOp bufOp = new BufferOp(inputParam);
84
            bufOp.setEndCapStyle(capBuffer == CAP_ROUND
85
                ? BufferParameters.CAP_ROUND : BufferParameters.CAP_SQUARE);
86
            Geometry newGeometry = bufOp.getResultGeometry(-1 * distRing);
87

  
88
            if (verifyNilGeometry(newGeometry))
89
                return lastEditFeature;
90

  
91
            try {
92
            	if (newGeometry != null && !newGeometry.isEmpty()) {
93
            		lastEditFeature = persister.addFeature(newGeometry, id, distRing);
94
            		id++;
95
            	}
96
            } catch (CreateGeometryException e) {
97
                Sextante.addErrorToLog(e);
98
            } catch (DataException e) {
99
                Sextante.addErrorToLog(e);
100
            }
101
        }*/
102
        
103
        for (int i = numberOfRadialBuffers; i >= 1; i--) {
104
            double distRing = i * bufferDistance;
105
            BufferOp bufOp = new BufferOp(inputParam);
106
            bufOp.setEndCapStyle(capBuffer == CAP_ROUND
107
                ? BufferParameters.CAP_ROUND : BufferParameters.CAP_SQUARE);
108
            newGeom = bufOp.getResultGeometry(-1 * distRing);
109

  
110
            if (verifyNilGeometry(newGeom))
111
                continue;
112

  
113
            if(previousInteriorRing == null)
114
            	previousInteriorRing = newGeom;
115
            else {
116
            	Geometry complete = newGeom;
117
            	newGeom = JTSFacade.difference(newGeom, previousInteriorRing);  
118
            	previousInteriorRing = complete;
119
            }
120

  
121
            try {
122
            	if (newGeom != null && !newGeom.isEmpty()) {
123
            		if(getTableFieldStructure() == BufferAlgorithm.SOURCE_FIELDS) {
124
            			lastEditFeature = persister.addFeature(feature, newGeom);
125
            		} else
126
            			lastEditFeature = persister.addFeature(newGeom, id, distRing);
127
            		id++;
128
            	}
129
            } catch (CreateGeometryException e) {
130
                Sextante.addErrorToLog(e);
131
            } catch (DataException e) {
132
                Sextante.addErrorToLog(e);
133
            }
134
        }
135
        return lastEditFeature;
136
    }
137

  
138
    /*
139
     * (non-Javadoc)
140
     * 
141
     * @see
142
     * org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org
143
     * .gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.EditableFeature)
144
     */
145
    public void invoke(org.gvsig.fmap.geom.Geometry g, EditableFeature feature) {
146
        invoke(g, (Feature) feature);
147
    }
148
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/OutBufferOperation.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import org.gvsig.fmap.dal.exception.DataException;
27
import org.gvsig.fmap.dal.feature.EditableFeature;
28
import org.gvsig.fmap.dal.feature.Feature;
29
import org.gvsig.fmap.dal.feature.FeatureStore;
30
import org.gvsig.fmap.geom.exception.CreateGeometryException;
31
import org.gvsig.geoprocess.algorithm.base.util.GeometryUtil;
32
import org.gvsig.geoprocess.algorithm.base.util.JTSFacade;
33
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
34

  
35
import com.vividsolutions.jts.geom.Geometry;
36
import com.vividsolutions.jts.operation.buffer.BufferOp;
37
import com.vividsolutions.jts.operation.buffer.BufferParameters;
38
import com.vividsolutions.jts.simplify.TopologyPreservingSimplifier;
39

  
40
import es.unex.sextante.core.Sextante;
41

  
42
/**
43
 * Buffer operation
44
 * 
45
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
46
 */
47
public class OutBufferOperation extends BufferOperation {
48

  
49
    /**
50
     * Builds an instance of this operation.
51
     * 
52
     * @param distance
53
     * @param layer
54
     * @param userDistance
55
     */
56
    public OutBufferOperation(IDistance distance, 
57
    	FeatureStore inputStore,
58
        AbstractSextanteGeoProcess p,
59
        byte tableFields) {
60
        super(distance, inputStore, p, tableFields);
61
    }
62

  
63
    public EditableFeature invoke(org.gvsig.fmap.geom.Geometry g,
64
        Feature feature) {
65
        Geometry newGeom = null;
66
        Geometry previousExteriorRing = null;
67
        Geometry originalGeometry = GeometryUtil.geomToJTS(g);
68
        Geometry inputParam = originalGeometry;
69
        distance.setFeature(feature);
70
        double bufferDistance =
71
            distance.getBufferDistance(projection,
72
                getDistanceUnits(), getMapUnits());
73
        
74
        if(originalGeometry == null)
75
        	return null;
76
        
77
        if (originalGeometry.getDimension() != 0)
78
            inputParam =
79
                TopologyPreservingSimplifier.simplify(originalGeometry,
80
                    bufferDistance / 10d);
81

  
82
        /*for (int i = numberOfRadialBuffers; i >= 1; i--) {
83
            double distRing = i * bufferDistance;
84
            BufferOp bufOp = new BufferOp(inputParam);
85
            bufOp.setEndCapStyle(capBuffer == CAP_ROUND
86
                ? BufferParameters.CAP_ROUND : BufferParameters.CAP_SQUARE);
87
            Geometry newGeometry = bufOp.getResultGeometry(distRing);
88

  
89
            try {
90
                if (newGeometry != null && !newGeometry.isEmpty()) {
91
                    lastEditFeature = persister.addFeature(newGeometry, id, distRing);
92
                    id++;
93
                }
94
            } catch (CreateGeometryException e) {
95
                Sextante.addErrorToLog(e);
96
            } catch (DataException e) {
97
                Sextante.addErrorToLog(e);
98
            }
99
        }*/
100
        
101
        for (int i = 1; i <= numberOfRadialBuffers; i++) {
102
            double distRing = i * bufferDistance;
103
            BufferOp bufOp = new BufferOp(inputParam);
104
            bufOp.setEndCapStyle(capBuffer == CAP_ROUND
105
                ? BufferParameters.CAP_ROUND : BufferParameters.CAP_SQUARE);
106
            newGeom = bufOp.getResultGeometry(distRing);
107
            
108
            if(i == 1)
109
            	previousExteriorRing = newGeom;
110
            else {
111
            	Geometry complete = newGeom;
112
            	newGeom = JTSFacade.difference(newGeom, previousExteriorRing);  
113
            	previousExteriorRing = complete;
114
            }
115

  
116
            try {
117
                if (newGeom != null && !newGeom.isEmpty()) {
118
                	if(getTableFieldStructure() == BufferAlgorithm.SOURCE_FIELDS)
119
            			lastEditFeature = persister.addFeature(feature, newGeom);
120
            		else
121
            			lastEditFeature = persister.addFeature(newGeom, id, distRing);
122
                    id++;
123
                }
124
            } catch (CreateGeometryException e) {
125
                Sextante.addErrorToLog(e);
126
            } catch (DataException e) {
127
                Sextante.addErrorToLog(e);
128
            }
129
        }
130
        
131
        return lastEditFeature;
132
    }
133

  
134
    /*
135
     * (non-Javadoc)
136
     * 
137
     * @see
138
     * org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org
139
     * .gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.EditableFeature)
140
     */
141
    public void invoke(org.gvsig.fmap.geom.Geometry g, EditableFeature feature) {
142
        invoke(g, (Feature) feature);
143
    }
144
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/FuseOperation.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 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 2 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
/*
24

  
25
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
26
 *
27
 * Copyright (C) 2010 Generalitat Valenciana.
28
 *
29
 * This program is free software; you can redistribute it and/or
30
 * modify it under the terms of the GNU General Public License
31
 * as published by the Free Software Foundation; either version 2
32
 * of the License, or (at your option) any later version.
33
 *
34
 * This program is distributed in the hope that it will be useful,
35
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37
 * GNU General Public License for more details.
38
 *
39
 * You should have received a copy of the GNU General Public License
40
 * along with this program; if not, write to the Free Software
41
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
42
 */
43
package org.gvsig.geoprocess.algorithm.buffer;
44

  
45
import java.util.ArrayList;
46
import java.util.List;
47

  
48
import org.gvsig.fmap.dal.exception.DataException;
49
import org.gvsig.fmap.dal.feature.EditableFeature;
50
import org.gvsig.fmap.dal.feature.Feature;
51
import org.gvsig.fmap.dal.feature.FeatureSet;
52
import org.gvsig.fmap.dal.feature.FeatureStore;
53
import org.gvsig.fmap.geom.exception.CreateGeometryException;
54
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
55
import org.gvsig.geoprocess.algorithm.base.util.GeometryUtil;
56
import org.gvsig.geoprocess.algorithm.base.util.JTSFacade;
57
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
58
import org.slf4j.Logger;
59
import org.slf4j.LoggerFactory;
60

  
61
import com.vividsolutions.jts.geom.Geometry;
62
import java.util.Iterator;
63

  
64
/**
65
 * Fuse operation
66
 *
67
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
68
 */
69
public class FuseOperation extends GeometryOperation {
70

  
71
    private static Logger logger = LoggerFactory.getLogger(FuseOperation.class.getName());
72
    private List<Element> featureList = null;
73
    private String nameIdField = "FID";
74
    private int iFeat = 0;
75

  
76
    class Element {
77

  
78
        public int id = -1;
79
        public Feature feat = null;
80
        public List<Element> overlapList = new ArrayList<Element>();
81
        public boolean insertedToJoin = false;
82
        public Geometry jtsGeom = null;
83

  
84
        public void finalize() throws Throwable {
85
            super.finalize();
86
            overlapList.clear();
87
        }
88
    }
89

  
90
    class NodeTree {
91

  
92
        public Element element = null;
93
        public int pos = 0;
94
        public NodeTree parent = null;
95

  
96
        public NodeTree(Element node, NodeTree parent) {
97
            this.element = node;
98
            this.parent = parent;
99
        }
100

  
101
        public Element getNext() {
102
            if (pos < element.overlapList.size()) {
103
                return element.overlapList.get(pos++);
104
            }
105
            return null;
106
        }
107
    }
108

  
109
    public FuseOperation(AbstractSextanteGeoProcess process) {
110
        super(process);
111
        featureList = new ArrayList<Element>();
112
    }
113

  
114
    @Override
115
    public EditableFeature invoke(org.gvsig.fmap.geom.Geometry g,
116
            Feature featureInput) {
117
        // TODO Auto-generated method stub
118
        return null;
119
    }
120

  
121
    @Override
122
    public void invoke(org.gvsig.fmap.geom.Geometry g,
123
            EditableFeature featureInput) {
124
		// TODO Auto-generated method stub
125

  
126
    }
127

  
128
    /**
129
     * Computes a complete operation over the input FeatureStore. The result of
130
     * this operation is stored in the output FeatureStore. This method will
131
     * call once for each geometry.
132
     *
133
     * @param inFeatStore Input FeatureStore
134
     * @param outFeatStore Output FeatureStore
135
     * @throws DataException
136
     */
137
    @SuppressWarnings("deprecation")
138
    public void computesGeometryOperation(FeatureStore inFeatStore,
139
            FeatureStore outFeatStore,
140
            String[] attrNames,
141
            boolean first) throws DataException {
142
        if (featureList != null) {
143
            featureList.clear();
144
        }
145
        this.inFeatureStore = inFeatStore;
146
        FeatureSet featuresSet = inFeatStore.getFeatureSet();
147

  
148
        if (first) {
149
            setFeatureStore(outFeatStore, attrNames);
150
        }
151
        Iterator it = featuresSet.iterator();
152

  
153
        numberOfFeatures = (int) featuresSet.getSize();
154

  
155
        if (status != null) {
156
            status.setRangeOfValues(0, numberOfFeatures);
157
        }
158
        if (process != null) {
159
            process.setProgress(0, numberOfFeatures);
160
        }
161

  
162
        //Crear lista de elementos
163
        int iCount = 0;
164
        while (it.hasNext() && !process.getTaskMonitor().isCanceled()) {
165
            Feature feat = (Feature) it.next();
166
            Element el = new Element();
167
            el.feat = feat;
168
            el.id = iCount;
169
            featureList.add(el);
170
            if (status != null && process != null) {
171
                status.setCurValue(iCount);
172
            }
173
            if (process != null) {
174
                process.setProgress(iCount, numberOfFeatures);
175
            }
176
            iCount++;
177
        }
178
        //it.dispose();
179

  
180
        //Crear listas de solapes para cada feature
181
        iCount = 0;
182
        while (iCount < featureList.size() && !process.getTaskMonitor().isCanceled()) {
183
            Element elem1 = featureList.get(iCount);
184
            org.gvsig.fmap.geom.Geometry geom1 = elem1.feat.getDefaultGeometry();
185
            if (status != null) {
186
                status.setCurValue(iCount);
187
            }
188
            if (process != null) {
189
                process.setProgress(iCount, numberOfFeatures);
190
            }
191

  
192
            for (int i = iCount + 1; i < featureList.size(); i++) {
193
                Element elem2 = featureList.get(i);
194
                org.gvsig.fmap.geom.Geometry geom2 = elem2.feat.getDefaultGeometry();
195
                if (areBBoxesOverlaping(geom1, geom2)) {
196
                    if (elem1.jtsGeom == null) {
197
                        elem1.jtsGeom = GeometryUtil.geomToJTS(geom1);
198
                    }
199
                    elem2.jtsGeom = GeometryUtil.geomToJTS(geom2);
200
                    if (elem1.jtsGeom.intersects(elem2.jtsGeom)) {
201
                        elem1.overlapList.add(elem2);
202
                        elem2.overlapList.add(elem1);
203
                    }
204
                }
205
            }
206
            iCount++;
207
        }
208

  
209
        iCount = 0;
210

  
211
        while (iCount < featureList.size() && !process.getTaskMonitor().isCanceled()) {
212
            Element elem1 = featureList.get(iCount);
213
            if (status != null) {
214
                status.setCurValue(iCount);
215
            }
216
            if (process != null) {
217
                process.setProgress(iCount, numberOfFeatures);
218
            }
219

  
220
            if (!elem1.insertedToJoin) {
221
                buildListToJoin(elem1);
222
            }
223

  
224
            iCount++;
225
        }
226

  
227
    }
228

  
229
    public void end() {
230
        if (persister != null) {
231
            persister.end();
232
        }
233
    }
234

  
235
    private boolean areBBoxesOverlaping(org.gvsig.fmap.geom.Geometry g1, org.gvsig.fmap.geom.Geometry g2) {
236
        if (g1.getEnvelope().getMaximum(0) < g2.getEnvelope().getMinimum(0)) {
237
            return false;
238
        }
239
        if (g1.getEnvelope().getMinimum(0) > g2.getEnvelope().getMaximum(0)) {
240
            return false;
241
        }
242
        if (g1.getEnvelope().getMaximum(1) < g2.getEnvelope().getMinimum(1)) {
243
            return false;
244
        }
245
        if (g1.getEnvelope().getMinimum(1) > g2.getEnvelope().getMaximum(1)) {
246
            return false;
247
        }
248
        return true;
249
    }
250

  
251
    private Geometry computesUnion(List<Geometry> listResult) {
252
        Geometry newGeom = null;
253
        int iCount = 0;
254
        int max = listResult.size();
255
        if (process != null) {
256
            process.setName("Generating union");
257
        }
258
        while (listResult.size() > 1) {
259
            List<Geometry> list = new ArrayList<Geometry>();
260
            if (status != null) {
261
                status.setCurValue(iCount);
262
            }
263
            if (process != null) {
264
                process.setProgress(iCount, max);
265
            }
266
            for (int i = 0; i < listResult.size(); i = i + 2) {
267
                if (i == (listResult.size() - 1)) {
268
                    list.add(listResult.get(i));
269
                } else {
270
                    newGeom = JTSFacade.union(listResult.get(i), listResult.get(i + 1));
271
                    list.add(newGeom);
272
                }
273
            }
274
            listResult = list;
275
        }
276
        return newGeom;
277
    }
278

  
279
    /**
280
     * Builds the union of all lists
281
     *
282
     * @param listResult
283
     * @param listToJoin
284
     */
285
    private void buildListToJoin(Element elem) {
286
        Geometry newGeom = null;
287

  
288
        if (elem.overlapList.size() == 0) {
289
            if (!elem.insertedToJoin) {
290
                elem.insertedToJoin = true;
291
            }
292
            try {
293
                addFeatureToOutput(elem.feat.getDefaultGeometry(), elem.feat);
294
            } catch (DataException e) {
295
                logger.info("Imposible insertar en la tabla", e);
296
            } catch (CreateGeometryException e) {
297
                logger.info("Error a?adiendo geometr?a", e);
298
            }
299
        } else {
300
            List<Geometry> listResult = new ArrayList<Geometry>();
301
            NodeTree subtree = new NodeTree(elem, null);
302
			//Hacemos un recorrido en profundidad del ?rbol para a?adir
303
            //todos los elementos a la lista de geometrias a unir sin
304
            //repetir ninguna.
305
            while (subtree != null) {
306
                if (!subtree.element.insertedToJoin) {
307
                    listResult.add(subtree.element.jtsGeom);
308
                    subtree.element.insertedToJoin = true;
309
                }
310

  
311
                boolean back = false;
312

  
313
                Element l = subtree.getNext();
314
                if (l == null) {
315
                    back = true;
316
                }
317

  
318
                while (!back && l.insertedToJoin) {
319
                    l = subtree.getNext();
320
                    if (l == null) {
321
                        back = true;
322
                    }
323
                }
324

  
325
                if (back) {
326
                    subtree = subtree.parent;
327
                    continue;
328
                }
329
                subtree = new NodeTree(l, subtree);
330
            }
331
            newGeom = computesUnion(listResult);
332

  
333
            try {
334
                addFeatureToOutput(newGeom, elem.feat);
335
            } catch (DataException e) {
336
                logger.info("Imposible insertar en la tabla", e);
337
            } catch (CreateGeometryException e) {
338
                logger.info("Error a?adiendo geometr?a", e);
339
            }
340
        }
341

  
342
    }
343

  
344
    /**
345
     * Adds a feature to the output
346
     *
347
     * @param newGeom
348
     * @param feat
349
     * @param newFeatID
350
     * @throws DataException
351
     * @throws CreateGeometryException
352
     */
353
    private void addFeatureToOutput(org.gvsig.fmap.geom.Geometry newGeom,
354
            Feature feat) throws DataException, CreateGeometryException {
355
        String[] fieldNames = persister.getFieldNamesWithoutGeom();
356
        ArrayList<String> fields = new ArrayList<String>();
357
        ArrayList<Object> values = new ArrayList<Object>();
358
        fields.add(nameIdField);
359
        values.add(iFeat);
360
        for (int j = 0; j < fieldNames.length; j++) {
361
            Object obj = feat.get(fieldNames[j]);
362
            if (obj != null && fieldNames[j].compareTo(nameIdField) != 0) {
363
                fields.add(fieldNames[j]);
364
                values.add(obj);
365
            }
366
        }
367
        lastEditFeature = persister.addFeature(newGeom, fields, values);
368
        iFeat++;
369

  
370
    }
371

  
372
    /**
373
     * Adds a feature to the output
374
     *
375
     * @param newGeom
376
     * @param feat
377
     * @param newFeatID
378
     * @throws DataException
379
     * @throws CreateGeometryException
380
     */
381
    private void addFeatureToOutput(Geometry newGeom,
382
            Feature feat) throws DataException, CreateGeometryException {
383
        String[] fieldNames = persister.getFieldNamesWithoutGeom();
384
        ArrayList<String> fields = new ArrayList<String>();
385
        ArrayList<Object> values = new ArrayList<Object>();
386
        fields.add(nameIdField);
387
        values.add(iFeat);
388
        for (int j = 0; j < fieldNames.length; j++) {
389
            Object obj = feat.get(fieldNames[j]);
390
            if (obj != null && fieldNames[j].compareTo(nameIdField) != 0) {
391
                fields.add(fieldNames[j]);
392
                values.add(obj);
393
            }
394
        }
395
        lastEditFeature = persister.addFeature(newGeom, fields, values);
396
        iFeat++;
397
    }
398
}
0 399

  
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/IDistance.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import org.cresques.cts.IProjection;
27
import org.gvsig.fmap.dal.feature.Feature;
28

  
29
/**
30
 * Computes a size of each geometry built
31
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
32
 */
33
public interface IDistance {
34
	
35
	/**
36
	 * Sets the current feature
37
	 * @param feature
38
	 */
39
	public void setFeature(Feature feature);
40
	
41
	/**
42
	 * Gets the distance using the specific method
43
	 * @param viewProj
44
	 *        Projection
45
	 * @param distanceUnits
46
	 *        distance units
47
	 * @param mapUnits
48
	 *        map units
49
	 * @return
50
	 */
51
	public double getBufferDistance(IProjection viewProj, int distanceUnits, int mapUnits);
52
	
53
	/**
54
	 * Sets the number of rings. This number is multiplied by the Buffer distance. 
55
	 * For instance, for a constant distance of 500 meters and two rings, the 
56
	 * <code>getBufferDistance</code> will give a value of 1000 
57
	 */
58
	public void setNumberOfRings(int n);
59
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.37/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.buffer/src/main/java/org/gvsig/geoprocess/algorithm/buffer/ConstantDistance.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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 2
9
 * of the License, or (at your option) any later version.
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.
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.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.buffer;
25

  
26
import org.cresques.cts.IProjection;
27

  
28
/**
29
 * Computes a constant size of each geometry built
30
 * 
31
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
32
 * @author gvSIG team
33
 */
34
public class ConstantDistance extends AbstractDistance {
35
    private double distance = 0;
36
    
37
    public ConstantDistance(double distance) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff