Revision 1562

View differences:

org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.geoprocess.algorithm.intersection.IntersectionLibrary
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/resources/org/gvsig/geoprocess/algorithm/intersection/intersection.properties
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

  
25
basic_vect_algorithms=Capas vectoriales
26
Input_layer=Capa de entrada
27
Overlays_layer=Capa de intersecci?n
28
Selected_geometries=Geometrias seleccionadas
29
Intersection=Intersecci?n
30
Selected_geometries_input_layer_inters=Geom. seleccionadas (Capa entrada)
31
Selected_geometries_overlay_layer_inters=Geom. seleccionadas (Capa intersecci?n)
32
problems_with_some_geometries=El proceso ha terminado pero ocurri? un error en alguna geometr?a. Es posible que el resultado no sea del todo exacto. Consulte el log.
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/resources/org/gvsig/geoprocess/algorithm/intersection/intersection_en.properties
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

  
25
basic_vect_algorithms=Vector layers tools
26
Input_layer=Input cover
27
Overlays_layer=Intersection cover
28
Selected_geometries=Selected geometries
29
Intersection=Intersection
30
Selected_geometries_input_layer_inters=Selected features (Input cover)
31
Selected_geometries_overlay_layer_inters=Selected features (Intersection cover)
32
problems_with_some_geometries=The process has ended but an error happened in some geometry. Maybe the result not be totally accuracy. See the log.
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/resources/help/IntersectionAlgorithm.xml
1
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
2
<!--
3

  
4
    gvSIG. Desktop Geographic Information System.
5

  
6
    Copyright (C) 2007-2012 gvSIG Association.
7

  
8
    This program is free software; you can redistribute it and/or
9
    modify it under the terms of the GNU General Public License
10
    as published by the Free Software Foundation; either version 2
11
    of the License, or (at your option) any later version.
12

  
13
    This program is distributed in the hope that it will be useful,
14
    but WITHOUT ANY WARRANTY; without even the implied warranty of
15
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
    GNU General Public License for more details.
17

  
18
    You should have received a copy of the GNU General Public License
19
    along with this program; if not, write to the Free Software
20
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
    MA  02110-1301, USA.
22

  
23
    For any additional information, do not hesitate to contact us
24
    at info AT gvsig.com, or visit our website www.gvsig.com.
25

  
26
-->
27
	<help>
28
		<element name="DESCRIPTION" text='Este geoproceso opera sobre dos capas, la "capa de entrada" y la "capa de solape", las geometr&#237;as de estas capas pueden ser de pol&#237;gonos, l&#237;neas o puntos.&#10;&#10;Para cada geometr&#237;a de la capa de entrada, calcula la interseccion con las diferentes geometr&#237;as de la capa de solape, originando un nuevo elemento por cada intersecci&#243;n. Este elemento tomar&#225; todos los atributos alfanum&#233;ricos de las geometr&#237;as que lo originaron (de entrada y solape). Por este motivo (modela zonas del espacio que cumplen la condici&#243;n de pertenecer a los dos pol&#237;gonos que lo han originado) a este geoproceso se le conoce como operador AND espacial.&#10;&#10;Un ejemplo de aplicaci&#243;n de este geoproceso ser&#237;a para, dada una capa de usos del suelo Corine 2000, y una capa del mapa geol&#243;gico nacional, obtener una capa de pol&#237;gonos con informaci&#243;n homog&#233;nea de uso del suelo y material geol&#243;gico.' description="Descripci&#243;n" type="0">
29
			<image description="" file="intersectdesc.png">
30
			</image>
31
		</element>
32
		<element name="ADDITIONAL_INFO" text="" description="Informaci&#243;n adicional" type="0">
33
		</element>
34
		<element name="EXTENSION_AUTHOR" text="Nacho Brodin" description="Algoritmo creado por" type="0">
35
		</element>
36
		<element name="HELP_AUTHOR" text="" description="Ayuda creada por" type="0">
37
		</element>
38
		<element name="USER_NOTES" text="" description="Notas de usuario" type="0">
39
		</element>
40
		<element name="LAYER" text="" description="Capa de entrada" type="3">
41
		</element>
42
		<element name="INTER" text="" description="Capa de revestimiento" type="3">
43
		</element>
44
		<element name="CHECK" text="" description="Geometrias seleccionadas" type="3">
45
		</element>
46
		<element name="OUTPUT_DESCRIPTION" text="" description="Descripci&#243;n" type="2">
47
		</element>
48
		<element name="RESULT" text="" description="Intersecci&#243;n" type="2">
49
		</element>
50
	</help>
51
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/resources/help/IntersectionAlgorithm_en.xml
1
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
2
<!--
3

  
4
    gvSIG. Desktop Geographic Information System.
5

  
6
    Copyright (C) 2007-2012 gvSIG Association.
7

  
8
    This program is free software; you can redistribute it and/or
9
    modify it under the terms of the GNU General Public License
10
    as published by the Free Software Foundation; either version 2
11
    of the License, or (at your option) any later version.
12

  
13
    This program is distributed in the hope that it will be useful,
14
    but WITHOUT ANY WARRANTY; without even the implied warranty of
15
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
    GNU General Public License for more details.
17

  
18
    You should have received a copy of the GNU General Public License
19
    along with this program; if not, write to the Free Software
20
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
    MA  02110-1301, USA.
22

  
23
    For any additional information, do not hesitate to contact us
24
    at info AT gvsig.com, or visit our website www.gvsig.com.
25

  
26
-->
27
	<help>
28
		<element name="DESCRIPTION" text='This geoprocess works with two layers: the input layer and the overlay layer.&#10;&#10;For each geometry in the input layer, it computes its intersections with the geometries of the overlay layer. For each intersection, it adds a new feature with the intersection as geometry and all attributes of the features which originates it. It is called "Spatial AND", because features of the result layer models a space common to both layers.' description="Descripci&#243;n" type="0">
29
			<image description="" file="intersectdesc.png">
30
			</image>
31
		</element>
32
		<element name="ADDITIONAL_INFO" text="" description="Informaci&#243;n adicional" type="0">
33
		</element>
34
		<element name="EXTENSION_AUTHOR" text="Nacho Brodin" description="Algoritmo creado por" type="0">
35
		</element>
36
		<element name="HELP_AUTHOR" text="" description="Ayuda creada por" type="0">
37
		</element>
38
		<element name="USER_NOTES" text="" description="Notas de usuario" type="0">
39
		</element>
40
		<element name="LAYER" text="" description="Capa de entrada" type="3">
41
		</element>
42
		<element name="INTER" text="" description="Capa de revestimiento" type="3">
43
		</element>
44
		<element name="CHECK" text="" description="Geometrias seleccionadas" type="3">
45
		</element>
46
		<element name="OUTPUT_DESCRIPTION" text="" description="Descripci&#243;n" type="2">
47
		</element>
48
		<element name="RESULT" text="" description="Intersecci&#243;n" type="2">
49
		</element>
50
	</help>
51
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/java/org/gvsig/geoprocess/algorithm/intersection/IntersectionLibrary.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.intersection;
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 IntersectionLibrary library.
32
 * 
33
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
34
 */
35
public class IntersectionLibrary extends AlgorithmAbstractLibrary {
36

  
37
    @Override
38
    protected void doInitialize() throws LibraryException {
39

  
40
    }
41

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

  
51
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/java/org/gvsig/geoprocess/algorithm/intersection/IntersectionAlgorithm.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.intersection;
25

  
26
import javax.swing.JOptionPane;
27

  
28
import org.gvsig.fmap.dal.exception.DataException;
29
import org.gvsig.fmap.dal.feature.FeatureStore;
30
import org.gvsig.fmap.dal.feature.FeatureType;
31
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
32
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
33

  
34
import es.unex.sextante.core.Sextante;
35
import es.unex.sextante.dataObjects.IVectorLayer;
36
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
37
import es.unex.sextante.exceptions.RepeatedParameterNameException;
38
import es.unex.sextante.outputs.OutputVectorLayer;
39
import org.gvsig.tools.namestranslator.NamesTranslator;
40

  
41
/**
42
 * Intersection algorithm
43
 * <UL>
44
 * <LI>Pol-Pol: 3 layers (polygon, point, line)</LI>
45
 * <LI>Pol-Line: 2 layers (point, line)</LI>
46
 * <LI>Pol-Point: 1 layer (point)</LI>
47
 * <LI>Line-Point: 1 layer (point)</LI>
48
 * <LI>Line-Line: 2 layers (point, line)</LI>
49
 * <LI>Point-Point: 1 layer (point)</LI>
50
 * </UL>
51
 *
52
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
53
 */
54
public class IntersectionAlgorithm extends AbstractSextanteGeoProcess {
55

  
56
    public static final String RESULT_POL = "RESULT_POL";
57
    public static final String RESULT_POINT = "RESULT_POINT";
58
    public static final String RESULT_LINE = "RESULT_LINE";
59
    public static final String LAYER = "LAYER";
60
    public static final String INTER = "INTER";
61
    public static final String SELECTGEOM_INPUT = "SELECTGEOM_INPUT";
62
    public static final String SELECTGEOM_OVERLAY = "SELECTGEOM_OVERLAY";
63

  
64

  
65
    /*
66
	 * (non-Javadoc)
67
	 * @see es.unex.sextante.core.GeoAlgorithm#defineCharacteristics()
68
     */
69
    public void defineCharacteristics() {
70
        setName(getTranslation("Intersection"));
71
        setGroup(getTranslation("basic_vect_algorithms"));
72
        // setGeneratesUserDefinedRasterOutput(false);
73

  
74
        try {
75
            m_Parameters.addInputVectorLayer(LAYER,
76
                    getTranslation("Input_layer"),
77
                    IVectorLayer.SHAPE_TYPE_WRONG,
78
                    true);
79
            m_Parameters.addInputVectorLayer(INTER,
80
                    getTranslation("Overlays_layer"),
81
                    IVectorLayer.SHAPE_TYPE_WRONG,
82
                    true);
83
            m_Parameters.addBoolean(SELECTGEOM_INPUT,
84
                    getTranslation("Selected_geometries_input_layer_inters"), false);
85
            m_Parameters.addBoolean(SELECTGEOM_OVERLAY,
86
                    getTranslation("Selected_geometries_overlay_layer_inters"), false);
87
        } catch (RepeatedParameterNameException e) {
88
            Sextante.addErrorToLog(e);
89
        }
90
        addOutputVectorLayer(RESULT_POL, getTranslation("Intersection_polygon"),
91
                OutputVectorLayer.SHAPE_TYPE_POLYGON);
92
        addOutputVectorLayer(RESULT_LINE, getTranslation("Intersection_line"),
93
                OutputVectorLayer.SHAPE_TYPE_LINE);
94
        addOutputVectorLayer(RESULT_POINT, getTranslation("Intersection_point"),
95
                OutputVectorLayer.SHAPE_TYPE_POINT);
96
    }
97

  
98
    /*
99
	 * (non-Javadoc)
100
	 * @see es.unex.sextante.core.GeoAlgorithm#processAlgorithm()
101
     */
102
    public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
103
        if (existsOutPutFile(IntersectionAlgorithm.RESULT_LINE, 0)) {
104
            throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
105
        }
106
        if (existsOutPutFile(IntersectionAlgorithm.RESULT_POINT, 0)) {
107
            throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
108
        }
109
        if (existsOutPutFile(IntersectionAlgorithm.RESULT_LINE, 0)) {
110
            throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
111
        }
112
        IVectorLayer inter = m_Parameters.getParameterValueAsVectorLayer(INTER);
113
        IVectorLayer layer = m_Parameters.getParameterValueAsVectorLayer(LAYER);
114
        boolean selectedGeomInput = m_Parameters.getParameter(SELECTGEOM_INPUT).getParameterValueAsBoolean();
115
        boolean selectedGeomOverlay = m_Parameters.getParameter(SELECTGEOM_OVERLAY).getParameterValueAsBoolean();
116
        boolean error = false;
117

  
118
        try {
119
            error = computesIntersection(layer, inter, layer.getShapeType(), selectedGeomInput, selectedGeomOverlay);
120
        } catch (DataException e) {
121
            Sextante.addErrorToLog(e);
122
            return false;
123
        }
124

  
125
        if (getTaskMonitor().isCanceled()) {
126
            return false;
127
        }
128
        if (error) {
129
            JOptionPane.showMessageDialog(null,
130
                    getTranslation("problems_with_some_geometries"), "Error",
131
                    JOptionPane.WARNING_MESSAGE);
132
        }
133
        return true;
134
    }
135

  
136
    /**
137
     * Builds a layer with the intersection between the input layer and the
138
     * templateGeometry
139
     *
140
     * @param layer Input layer
141
     * @param templateGeometry
142
     * @param shapeType Output shape type
143
     * @param selectedGeom If it's true only selected geometries will be
144
     * computed
145
     * @throws GeoAlgorithmExecutionException
146
     */
147
    private boolean computesIntersection(IVectorLayer layer,
148
            IVectorLayer overlay,
149
            int shapeType,
150
            boolean selectedGeomInput,
151
            boolean selectedGeomOverlay) throws DataException, GeoAlgorithmExecutionException {
152
        FeatureStore storeLayer = null;
153
        FeatureStore storeOverlay = null;
154
        if (layer instanceof FlyrVectIVectorLayer
155
                && overlay instanceof FlyrVectIVectorLayer) {
156
            storeLayer = ((FlyrVectIVectorLayer) layer).getFeatureStore();
157
            storeOverlay = ((FlyrVectIVectorLayer) overlay).getFeatureStore();
158
        } else {
159
            return false;
160
        }
161

  
162
        FeatureType featureType1 = storeLayer.getDefaultFeatureType();
163
        FeatureType featureType2 = storeOverlay.getDefaultFeatureType();
164

  
165
        FeatureStore outFeatStorePol = null;
166
        FeatureStore outFeatStoreLine = null;
167
        FeatureStore outFeatStorePoint = null;
168

  
169
        IntersectionOperation operation = new IntersectionOperation(storeOverlay, this);
170
        operation.setTaskStatus(getStatus());
171
        this.namesTranslator = NamesTranslator.createTrimTranslator(11);
172

  
173
        //La de puntos se genera siempre
174
        outFeatStorePoint
175
                = buildOutPutStoreFromUnion(featureType1, featureType2,
176
                        IVectorLayer.SHAPE_TYPE_POINT,
177
                        getTranslation("Intersection_point"), RESULT_POINT);
178

  
179
        if (outFeatStorePoint != null) {
180
            getStatus().setTitle("Point");
181
            operation.computesGeometryOperation(storeLayer, outFeatStorePoint,
182
                    attrNames, selectedGeomInput, selectedGeomOverlay, true);
183
        }
184
        //La de pol?gonos solo si es intersecci?n entre pol?gonos
185
        if (isPolygon(storeLayer) && isPolygon(storeOverlay)) {
186
            outFeatStorePol
187
                    = buildOutPutStoreFromUnion(featureType1, featureType2,
188
                            IVectorLayer.SHAPE_TYPE_MULTIPOLYGON, getTranslation("Intersection_polygon"), RESULT_POL);
189
            if (outFeatStorePol != null) {
190
                getStatus().setTitle("Polygon");
191
                operation.computesGeometryOperation(storeLayer,
192
                        outFeatStorePol, attrNames, selectedGeomInput,
193
                        selectedGeomOverlay, true);
194
            }
195
        }
196

  
197
        //La capa de l?neas se genera cuando ning?na de las dos es de puntos
198
        if (!isPoint(storeLayer) && !isPoint(storeOverlay)) {
199
            outFeatStoreLine
200
                    = buildOutPutStoreFromUnion(featureType1, featureType2,
201
                            IVectorLayer.SHAPE_TYPE_MULTILINE, getTranslation("Intersection_line"), RESULT_LINE);
202
            if (outFeatStoreLine != null) {
203
                getStatus().setTitle("Line");
204
                operation.computesGeometryOperation(storeLayer,
205
                        outFeatStoreLine, attrNames, selectedGeomInput,
206
                        selectedGeomOverlay, true);
207
            }
208
        }
209

  
210
        if (outFeatStorePol == null) {
211
            getNewVectorLayer(RESULT_POL, getTranslation("Null_polygon"),
212
                    OutputVectorLayer.SHAPE_TYPE_POLYGON, new Class[]{Integer.class}, new String[]{""});
213
        }
214

  
215
        if (outFeatStoreLine == null) {
216
            getNewVectorLayer(RESULT_LINE, getTranslation("Null_line"),
217
                    OutputVectorLayer.SHAPE_TYPE_LINE, new Class[]{Integer.class}, new String[]{""});
218
        }
219

  
220
        if (outFeatStorePoint == null) {
221
            getNewVectorLayer(RESULT_POINT, getTranslation("Null_point"),
222
                    OutputVectorLayer.SHAPE_TYPE_POINT, new Class[]{Integer.class}, new String[]{""});
223
        }
224

  
225
        return operation.getErrorInfo();
226
    }
227

  
228
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/src/main/java/org/gvsig/geoprocess/algorithm/intersection/IntersectionOperation.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.intersection;
25

  
26
import java.util.Iterator;
27
import java.util.List;
28

  
29
import org.gvsig.fmap.dal.exception.DataException;
30
import org.gvsig.fmap.dal.feature.EditableFeature;
31
import org.gvsig.fmap.dal.feature.Feature;
32
import org.gvsig.fmap.dal.feature.FeatureSet;
33
import org.gvsig.fmap.dal.feature.FeatureStore;
34
import org.gvsig.fmap.geom.GeometryLocator;
35
import org.gvsig.fmap.geom.GeometryManager;
36
import org.gvsig.fmap.geom.Geometry.TYPES;
37
import org.gvsig.fmap.geom.exception.CreateGeometryException;
38
import org.gvsig.fmap.geom.operation.GeometryOperationContext;
39
import org.gvsig.fmap.geom.operation.GeometryOperationException;
40
import org.gvsig.fmap.geom.operation.GeometryOperationNotSupportedException;
41
import org.gvsig.fmap.geom.operation.fromjts.FromJTS;
42
import org.gvsig.fmap.geom.primitive.Curve;
43
import org.gvsig.fmap.geom.primitive.Surface;
44
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
45
import org.gvsig.geoprocess.algorithm.base.util.GeometryUtil;
46
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
47
import org.slf4j.Logger;
48
import org.slf4j.LoggerFactory;
49

  
50
import com.vividsolutions.jts.geom.Geometry;
51
import com.vividsolutions.jts.geom.GeometryCollection;
52
import com.vividsolutions.jts.geom.LineString;
53
import com.vividsolutions.jts.geom.MultiLineString;
54
import com.vividsolutions.jts.geom.MultiPoint;
55
import com.vividsolutions.jts.geom.MultiPolygon;
56
import com.vividsolutions.jts.geom.Point;
57
import com.vividsolutions.jts.geom.Polygon;
58
import com.vividsolutions.jts.precision.EnhancedPrecisionOp;
59

  
60
import es.unex.sextante.core.Sextante;
61

  
62
/**
63
 * Builds a geometry with the intersection between two layers
64
 *
65
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
66
 */
67
public class IntersectionOperation extends GeometryOperation {
68

  
69
    private FeatureStore storeOverlay = null;
70
    protected GeometryManager geomManager = GeometryLocator.getGeometryManager();
71
    private Logger log = LoggerFactory.getLogger(IntersectionOperation.class);
72
    private boolean errorInfo = false;
73

  
74
    public IntersectionOperation(FeatureStore overlayLayer, AbstractSextanteGeoProcess p) {
75
        super(p);
76
        this.storeOverlay = overlayLayer;
77
    }
78

  
79
    public boolean getErrorInfo() {
80
        return errorInfo;
81
    }
82

  
83
    /**
84
     * Computes intersection between the geometry and the overlay layer. The
85
     * fields of the intersected features will be added.
86
     *
87
     * @param g
88
     * @param featureInput
89
     * @return
90
     */
91
    @SuppressWarnings({"unchecked", "deprecation"})
92
    public EditableFeature invoke(org.gvsig.fmap.geom.Geometry g, Feature featureInput) {
93
        if (g == null) {
94
            return lastEditFeature;
95
        }
96

  
97
        FeatureSet features = null;
98
        Iterator it = null;
99
        try {
100
            if (selectedGeomOverlay) {
101
                features = (FeatureSet) storeOverlay.getSelection();
102
            } else {
103
                features = storeOverlay.getFeatureSet();
104
            }
105
            it = features.iterator();
106
        } catch (DataException e) {
107
            Sextante.addErrorToLog(e);
108
            return lastEditFeature;
109
        }
110

  
111
        while (it.hasNext()) {
112
            Feature featureOverlay = (Feature) it.next();
113
            List<org.gvsig.fmap.geom.Geometry> geomList = featureOverlay.getGeometries();
114
            if (geomList == null) {
115
                org.gvsig.fmap.geom.Geometry geom = featureOverlay.getDefaultGeometry();
116
                lastEditFeature = intersection(g, geom, featureInput, featureOverlay);
117
                continue;
118
            }
119

  
120
            Iterator<org.gvsig.fmap.geom.Geometry> itGeom = geomList.iterator();
121
            while (itGeom.hasNext()) {
122
                org.gvsig.fmap.geom.Geometry geom = itGeom.next();
123
                lastEditFeature = intersection(g, geom, featureInput, featureOverlay);
124
            }
125
        }
126
//		it.dispose();
127
        return lastEditFeature;
128
    }
129

  
130
    private EditableFeature intersection(org.gvsig.fmap.geom.Geometry g1,
131
            org.gvsig.fmap.geom.Geometry g2,
132
            Feature featureInput,
133
            Feature featureOverlay) {
134
        if (g1 == null || g2 == null) {
135
            return null;
136
        }
137
        Geometry overlaysGeom = null;
138
        Geometry jtsGeom = null;
139
        int outPutType = TYPES.SURFACE;
140

  
141
        try {
142
            outPutType = persister.getOutputFeatureStore().getDefaultFeatureType()
143
                    .getDefaultGeometryAttribute().getGeomType().getType();
144
        } catch (DataException e2) {
145
            Sextante.addErrorToLog(e2);
146
        }
147

  
148
        try {
149
            if (((g1 instanceof Surface && g2 instanceof Curve)
150
                    || (g2 instanceof Surface && g1 instanceof Curve))
151
                    && outPutType == TYPES.MULTIPOINT) {
152
                org.gvsig.fmap.geom.Geometry overGeom = (g1 instanceof Surface) ? g1 : g2;
153
                jtsGeom = (g1 instanceof Surface) ? GeometryUtil.geomToJTS(g2) : GeometryUtil.geomToJTS(g1);
154
                overlaysGeom = (Geometry) overGeom.invokeOperation("toJTSLineString", null);
155
            } else {
156
                if (g1 instanceof Surface
157
                        && g2 instanceof Surface
158
                        && (outPutType == TYPES.MULTIPOINT)) {
159
                    jtsGeom = (Geometry) g1.invokeOperation("toJTSLineString", null);
160
                    overlaysGeom = (Geometry) g2.invokeOperation("toJTSLineString", null);
161
                } else {
162
                    jtsGeom = GeometryUtil.geomToJTS(g1);
163
                    overlaysGeom = GeometryUtil.geomToJTS(g2);
164
                }
165
            }
166

  
167
            if (!jtsGeom.getEnvelope().intersects(overlaysGeom.getEnvelope())) {
168
                return lastEditFeature;
169
            }
170

  
171
            if (jtsGeom.intersects(overlaysGeom)) {
172
                Geometry newGeom = EnhancedPrecisionOp.intersection(jtsGeom, overlaysGeom);
173
                if (!newGeom.isEmpty()) {
174
                    if (typesMatch(outPutType, newGeom) || newGeom instanceof GeometryCollection) {
175
                        lastEditFeature = persister.addFeature(featureInput, featureOverlay, newGeom);
176
                    } else {
177
                        //Para intersecciones entre pol?gonos cuando la salida es de tipo l?nea
178
                        //la generamos a partir del pol?gono resultante de la intersecci?n
179
                        if (g1 instanceof Surface
180
                                && g2 instanceof Surface
181
                                && outPutType == TYPES.MULTICURVE
182
                                && (newGeom instanceof Polygon || newGeom instanceof MultiPolygon)) {
183
                            GeometryOperationContext ctx = new GeometryOperationContext();
184
                            ctx.setAttribute(FromJTS.PARAM, newGeom);
185
                            org.gvsig.fmap.geom.Geometry newDalGeom = (org.gvsig.fmap.geom.Geometry) geomManager.invokeOperation(FromJTS.NAME, ctx);
186
                            newGeom = (Geometry) newDalGeom.invokeOperation("toJTSLineString", null);
187
                        }
188

  
189
                        lastEditFeature = persister.addFeature(featureInput, featureOverlay, newGeom);
190
                    }
191
                }
192
            }
193
        } catch (CreateGeometryException e) {
194
            Sextante.addErrorToLog(e);
195
        } catch (DataException e) {
196
            Sextante.addErrorToLog(e);
197
        } catch (GeometryOperationNotSupportedException e1) {
198
            Sextante.addErrorToLog(e1);
199
        } catch (GeometryOperationException e1) {
200
            Sextante.addErrorToLog(e1);
201
        } catch (com.vividsolutions.jts.geom.TopologyException e) {
202
            errorInfo = true;
203
            log.info("Problems operating intersection: ", e);
204
        }
205
        return lastEditFeature;
206
    }
207

  
208
    private boolean typesMatch(int dalType, Geometry newGeom) {
209

  
210
        return ((geomManager.isSubtype(TYPES.MULTICURVE, dalType)
211
                && (newGeom instanceof MultiLineString || newGeom instanceof LineString))
212
                || (geomManager.isSubtype(TYPES.MULTIPOINT, dalType)
213
                && (newGeom instanceof MultiPoint || newGeom instanceof Point))
214
                || (geomManager.isSubtype(TYPES.MULTISURFACE, dalType)
215
                && (newGeom instanceof Polygon || newGeom instanceof MultiPolygon))
216
                || (geomManager.isSubtype(TYPES.CURVE, dalType) && newGeom instanceof LineString)
217
                || (geomManager.isSubtype(TYPES.SURFACE, dalType) && newGeom instanceof Polygon)
218
                || (geomManager.isSubtype(TYPES.POINT, dalType) && newGeom instanceof Point));
219

  
220
    }
221

  
222
    /**
223
     * clips feature's geometry with the clipping geometry, preserving feature's
224
     * original attributes. If feature's geometry doesn't touch clipping
225
     * geometry, it will be ignored.
226
     */
227
    public void invoke(org.gvsig.fmap.geom.Geometry g, EditableFeature featureInput) {
228
    }
229

  
230
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.intersection/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
  <modelVersion>4.0.0</modelVersion>
4
  <artifactId>org.gvsig.geoprocess.algorithm.intersection</artifactId>
5
  <packaging>jar</packaging>
6
  <name>org.gvsig.geoprocess.algorithm.intersection</name>
7
	
8
	<parent>
9
		<groupId>org.gvsig</groupId>
10
		<artifactId>org.gvsig.geoprocess.algorithm</artifactId>
11
		<version>2.2.182</version>
12
	</parent>
13
	
14
	<dependencies>
15
		<dependency>
16
		    <groupId>org.gvsig</groupId>
17
   			<artifactId>org.gvsig.geoprocess.algorithm.base</artifactId>
18
            <scope>compile</scope>
19
   		</dependency>
20
	</dependencies>
21
	
22
</project>
0 23

  
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/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.182/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.182/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 String attributeName = null;
36

  
37
    public FieldDistance(String attributeName) {
38
        this.attributeName = attributeName;
39
    }
40

  
41
    public double getBufferDistance(IProjection projection, int distanceUnits, int mapUnits) {
42
        double value = 0D;
43
        Object obj;
44
        obj = feature.get(attributeName);
45
        if (obj instanceof Number) {
46
            value = ((Number) obj).doubleValue();
47
        } else {
48
            return 0;
49
        }
50
        return getInInternalUnits(value, projection, distanceUnits, mapUnits) * numberOfRings;
51
    }
52

  
53
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/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
        String attributeName = m_Parameters.getParameterValueAsString(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

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

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

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

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

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

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

  
448

  
449
    @Override
450
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {
451
        return BufferParametersPanel.class;
452
    }
453
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.182/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

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff