Revision 1164

View differences:

org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/resources/org/gvsig/geoprocess/algorithm/spatialjoin/spatialjoin.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
Spatialjoin=Enlace espacial
27
Input_layer=Capa de entrada
28
selected_geometries=Geometrias seleccionadas (Capa de entrada 1)
29
use_the_nearest=Usar el m?s cercano
30
input_layers=Capas de entrada
31
input_layers_join=Capa de revestimiento
32
summary_function=Funci?n resumen
33
use_the_nearest=Usar el m?s cercano
34
Selected_geometries_input_layer=Geometr?as seleccionadas (capa de entrada)
35
Selected_geometries_overlay_layer=Geometr?as seleccionadas (capa de union)
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/resources/org/gvsig/geoprocess/algorithm/spatialjoin/spatialjoin_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
Spatialjoin=Spatial Join
27
Input_layer=Input cover
28
selected_geometries=Selected geometries (input layer 1)
29
use_the_nearest=Use the nearest
30
input_layers=Input coverages
31
input_layers_join=Overlay layer
32
summary_function=Summary function
33
Selected_geometries_input_layer=Selected features (input layer)
34
Selected_geometries_overlay_layer=Selected features (overlay layer)
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/resources/help/SpatialJoinAlgorithm.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, al igual que un join entre tablas, permite transferir los atributos de una capa a otra en base a una caracter&#237;stica com&#250;n. A diferencia del join de las bases de datos relacionales, en este caso la caracter&#237;stica com&#250;n no es un que un campo de las dos tablas tome el mismo valor (la clave del join), sino que los elementos relacionados de las dos capas cumplan unos criterios espaciales.&#10;&#10;El geoproceso Enlace Espacial implementado por la extensi&#243;n de geoprocesamiento de gvSIG permite seguir dos tipos de criterios espaciales para establecer el enlace espacial:&#10;&#10;&lt;UL&gt;&#10;&lt;LI&gt; Vecino m&#225;s pr&#243;ximo (relaci&#243;n 1-&gt;1). Asigna a un elemento de la capa origen los atributos del elemento m&#225;s pr&#243;ximo de la capa enlazada. En el caso de que el elemento m&#225;s pr&#243;ximo intersecte (o est&#233; contenido para el caso de pol&#237;gonos) al elemento original, habiendo por tanto varias intersecciones, el algoritmo tomar&#225; el primer elemento analizado de las posibles intersecciones.&lt;/LI&gt;&#10;&lt;LI&gt;Contenido en (relaci&#243;n 1-&gt;M). Relaciona un elemento de la capa origen con varios elementos de la capa destino (en concreto, con aquellos que son intersectados). En este caso la capa origen no heredar&#225; los atributos de la capa relacionada, sino que la operativa ser&#225; muy parecida a la del geoproceso Disolver. Para los M elementos relacionados con un elemento de la capa origen, se dar&#225; al usuario la posibilidad de escoger una o varias funciones resumen (media, m&#237;nimo, m&#225;ximo, sumatorio) que se aplicar&#225;n sobre los atributos num&#233;ricos de la capa enlazada.&lt;/LI&gt;&#10;&lt;/UL&gt;&#10;&#10;Este Geoproceso puede ser de gran utilidad para la realizaci&#243;n de an&#225;lisis de corredor. Por ejemplo:&#10;&lt;UL&gt;&#10;&lt;LI&gt;Qu&#233; zonas urbanos no tienen una parada de autobuses en un radio de 500 m.&lt;/LI&gt;&#10;&lt;LI&gt;Qu&#233; zonas urbanas carecen de colegios en un radio de 1000 m.&lt;/LI&gt;&#10;&lt;LI&gt;Qu&#233; pozos incumplen la normativa al no respetar la distancia m&#237;nima entre dos consecutivos.&lt;/LI&gt;&#10;&lt;/UL&gt;&#10;Etc." description="Descripci&#243;n" type="0">
29
			<image description="" file="spatialjoindesc.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="LAYER1" text="" description="Capa de entrada" type="3">
41
		</element>
42
		<element name="LAYER2" text="" description="Capa de entrada" type="3">
43
		</element>
44
		<element name="SELECTED_GEOM" text="" description="Geometrias seleccionadas" type="3">
45
		</element>
46
		<element name="NEAREST" text="" description="Usar el m&#225;s cercano" type="3">
47
		</element>
48
		<element name="FUNCTION_LIST" text="" description="Function_list" type="3">
49
		</element>
50
		<element name="OUTPUT_DESCRIPTION" text="" description="Descripci&#243;n" type="2">
51
		</element>
52
		<element name="RESULT" text="" description="Spatial Join" type="2">
53
		</element>
54
	</help>
55
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/resources/help/SpatialJoinAlgorithm_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 transfer attributes from a source layer to a target layer (very similar to an alphanumerical join). The difference with a traditional join is that the transfer criteria is not the value of one (or many) given attributes. The criteria to transfer attribute values is spatial: intersection or proximity.&#10;&#10;If users select intersection like transfer criteria, each feature of the target layer could intersect many features of the source layer (a 1-N spatial relationship). If users select proximity (nearest neighbour) we have a 1-N spatial relationship." description="Descripci&#243;n" type="0">
29
			<image description="" file="spatialjoindesc.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="LAYER1" text="" description="Capa de entrada" type="3">
41
		</element>
42
		<element name="LAYER2" text="" description="Capa de entrada" type="3">
43
		</element>
44
		<element name="SELECTED_GEOM" text="" description="Geometrias seleccionadas" type="3">
45
		</element>
46
		<element name="NEAREST" text="" description="Usar el m&#225;s cercano" type="3">
47
		</element>
48
		<element name="FUNCTION_LIST" text="" description="Function_list" type="3">
49
		</element>
50
		<element name="OUTPUT_DESCRIPTION" text="" description="Descripci&#243;n" type="2">
51
		</element>
52
		<element name="RESULT" text="" description="Spatial Join" type="2">
53
		</element>
54
	</help>
55
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.geoprocess.algorithm.spatialjoin.SpatialJoinLibrary
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/java/org/gvsig/geoprocess/algorithm/spatialjoin/SpatialJoinAlgorithm.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.spatialjoin;
25

  
26
import java.util.ArrayList;
27
import java.util.HashMap;
28
import java.util.Iterator;
29

  
30
import es.unex.sextante.core.Sextante;
31
import es.unex.sextante.dataObjects.IVectorLayer;
32
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
33
import es.unex.sextante.exceptions.RepeatedParameterNameException;
34
import es.unex.sextante.exceptions.UnsupportedOutputChannelException;
35
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
36
import es.unex.sextante.outputs.OutputVectorLayer;
37

  
38
import org.gvsig.fmap.dal.DALLocator;
39
import org.gvsig.fmap.dal.DataManager;
40
import org.gvsig.fmap.dal.DataTypes;
41
import org.gvsig.fmap.dal.feature.Feature;
42
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
43
import org.gvsig.fmap.dal.feature.FeatureReference;
44
import org.gvsig.fmap.dal.feature.FeatureStore;
45
import org.gvsig.fmap.dal.feature.FeatureType;
46
import org.gvsig.fmap.geom.Geometry;
47
import org.gvsig.fmap.geom.GeometryLocator;
48
import org.gvsig.fmap.geom.GeometryManager;
49
import org.gvsig.fmap.geom.SpatialIndex;
50
import org.gvsig.fmap.geom.SpatialIndexFactory;
51
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
52
import org.gvsig.geoprocess.algorithm.dissolve.DissolveRule;
53
import org.gvsig.geoprocess.algorithm.dissolve.IDissolveRule;
54
import org.gvsig.geoprocess.algorithm.dissolve.Summary;
55
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
56
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
57
import org.gvsig.tools.dynobject.DynObject;
58
import org.gvsig.tools.exception.BaseException;
59
import org.gvsig.tools.visitor.VisitCanceledException;
60
import org.gvsig.tools.visitor.Visitor;
61

  
62
/**
63
 * Spatial join algorithm
64
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
65
 */
66
public class SpatialJoinAlgorithm extends AbstractSextanteGeoProcess {
67

  
68
	public static final String        NEW_FIELD             = "NUM_RELA";
69
	public static final String        RESULT                = "RESULT";
70
	public static final String        LAYER1                = "LAYER1";
71
	public static final String        LAYER2                = "LAYER2";
72
	public static final String        SELECTGEOM_INPUT      = "SELECTGEOM_INPUT";
73
	public static final String        SELECTGEOM_OVERLAY    = "SELECTGEOM_OVERLAY";
74
	public static final String        NEAREST               = "NEAREST";
75
	public static final String        FUNCTION_LIST         = "FUNCTION_LIST";
76
	public static final String        Summary[]             = {"Min", "Max", "Sum", "Avg"};
77
	private boolean                   funcList[]            = new boolean[Summary.length];
78
	private HashMap<String, String>   funcMap               = new HashMap<String, String>();
79

  
80
	public void defineCharacteristics(){
81
        setName(getTranslation("Spatialjoin"));
82
        setGroup(getTranslation("basic_vect_algorithms"));
83
        // setGeneratesUserDefinedRasterOutput(false);
84

  
85
		try {
86
			m_Parameters.addInputVectorLayer(LAYER1,
87
                getTranslation("Input_layer"),
88
												IVectorLayer.SHAPE_TYPE_WRONG,
89
												true);
90
			m_Parameters.addInputVectorLayer(LAYER2,
91
                getTranslation("Input_layer"),
92
												IVectorLayer.SHAPE_TYPE_WRONG,
93
												true);
94
            m_Parameters.addBoolean(SELECTGEOM_INPUT,
95
            		getTranslation("Selected_geometries_input_layer"), false);
96
            m_Parameters.addBoolean(SELECTGEOM_OVERLAY,
97
            		getTranslation("Selected_geometries_overlay_layer"), false);
98
            m_Parameters.addBoolean(NEAREST, getTranslation("use_the_nearest"), false);
99
            m_Parameters.addString(FUNCTION_LIST,
100
                getTranslation("Function_list"));
101
		} catch (RepeatedParameterNameException e) {
102
			Sextante.addErrorToLog(e);
103
		}
104
		addOutputVectorLayer(RESULT,getTranslation("Spatialjoin"),
105
								OutputVectorLayer.SHAPE_TYPE_UNDEFINED);
106
	}
107

  
108
	public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
109
		if(existsOutPutFile(SpatialJoinAlgorithm.RESULT, 0)) {
110
    		throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
111
    	}
112
		IVectorLayer layer1 = m_Parameters.getParameterValueAsVectorLayer(LAYER1); //Capa de entrada
113
		IVectorLayer layer2 = m_Parameters.getParameterValueAsVectorLayer(LAYER2); //Capa de revestimiento
114
		boolean selectedGeomInput = m_Parameters.getParameter(SELECTGEOM_INPUT).getParameterValueAsBoolean();
115
		boolean selectedGeomOverlay = m_Parameters.getParameter(SELECTGEOM_OVERLAY).getParameterValueAsBoolean();
116
		boolean nearest = m_Parameters.getParameterValueAsBoolean(NEAREST);
117
		String functionList = m_Parameters.getParameterValueAsString(FUNCTION_LIST);
118
		loadSummary(functionList);
119

  
120
		FlyrVectIVectorLayer inputLayer = null;
121
		FlyrVectIVectorLayer overlayLayer = null;
122
		if(layer2 instanceof FlyrVectIVectorLayer && layer1 instanceof FlyrVectIVectorLayer) {
123
			overlayLayer = ((FlyrVectIVectorLayer)layer2); //Capa de revestimiento
124
			inputLayer = ((FlyrVectIVectorLayer)layer1); //Capa de entrada
125
		} else
126
			return false;
127

  
128
		DataManager dataManager = DALLocator.getDataManager();
129

  
130
		//Builds the output and computes the operation
131
		try {
132
			FeatureType featureTypeInputLayer = inputLayer.getFeatureStore().getDefaultFeatureType(); //Capa de entrada
133
			FeatureType featureTypeOverlayLayer = overlayLayer.getFeatureStore().getDefaultFeatureType(); //Capa de revestimiento
134

  
135
			GeometryOperation operation = null;
136
			FeatureStore outFeatStore = null;
137

  
138
            if (nearest) {
139
                outFeatStore =
140
                    buildOutPutStoreFromUnion(featureTypeInputLayer, featureTypeOverlayLayer,
141
                        inputLayer.getShapeType(), getTranslation("SpatialJoin"),
142
                        RESULT, "DIST", Double.class);
143

  
144
                operation =
145
                    new SpatiallyIndexedSpatialJoinOperation(overlayLayer, createIndex(overlayLayer.getFeatureStore(), selectedGeomOverlay), this);
146
            } else {
147
                outFeatStore =
148
                    buildSpatialJoinOutPutStore(featureTypeInputLayer,
149
                        inputLayer.getShapeType(), getTranslation("SpatialJoin"),
150
                        RESULT);
151
                IDissolveRule rule = new DissolveRule(0, funcMap);
152
                Summary summary =
153
                    new Summary(rule, outFeatStore.getDefaultFeatureType());
154
                operation =
155
                    new IntersectsSpatialJoinOperation(overlayLayer,
156
                        createIndex(overlayLayer.getFeatureStore(), selectedGeomOverlay), summary, this);
157
            }
158

  
159
            operation.setTaskStatus(getStatus());
160
			operation.computesGeometryOperation(inputLayer.getFeatureStore(),
161
					outFeatStore,
162
					attrNames,
163
					selectedGeomInput,
164
					selectedGeomOverlay,
165
					true);
166
		} catch (Exception e) {
167
			Sextante.addErrorToLog(e);
168
        }
169

  
170
		return true;
171
	}
172

  
173
	private SpatialIndex createIndex(FeatureStore store, boolean selectionOnly) throws BaseException{
174
	    GeometryManager geomManager = GeometryLocator.getGeometryManager();
175

  
176
	    SpatialIndexFactory factory = geomManager.getSpatialIndexFactory(geomManager.SPATIALINDEX_DEFAULT_RTREE);
177
	    DynObject parameters = factory.createParameters();
178

  
179
	    SpatialIndex index = (SpatialIndex) factory.create(parameters, geomManager);
180
	    final SpatialIndex wrappedIndex = store.wrapSpatialIndex(index);
181

  
182
	    Visitor visitor = new Visitor() {
183

  
184
            @Override
185
            public void visit(Object obj) throws VisitCanceledException, BaseException {
186
                Feature f=(Feature) obj;
187
                Geometry g = f.getDefaultGeometry();
188
                FeatureReference ref = f.getReference();
189
                wrappedIndex.insert(g, ref);
190
            }
191
        };
192
        if(selectionOnly){
193
            store.getFeatureSelection().accept(visitor);
194
        } else {
195
            store.accept(visitor);
196
        }
197

  
198
	    return wrappedIndex;
199
	}
200

  
201
	/**
202
	 * Checks if the parameter is in Summary list
203
	 * @param it
204
	 * @return the position in the list
205
	 */
206
	private int isInList(String it) {
207
		for (int i = 0; i < Summary.length; i++) {
208
			if(Summary[i].compareTo(it) == 0)
209
				return i;
210
		}
211
		return -1;
212
	}
213

  
214
	/**
215
	 * Loads the list of functions to use
216
	 * @param functionList
217
	 */
218
	private void loadSummary(String functionList) {
219
		String[] attrList = functionList.split(";");
220
		for (int i = 0; i < attrList.length; i++) {
221
			String[] func = attrList[i].split(",");
222
			for (int j = 1; j < func.length; j++) {
223
				int pos = isInList(func[j]);
224
				if(pos != -1) {
225
					funcList[pos] = true;
226
					funcMap.put(Summary[pos], func[0]);
227
				}
228
			}
229
		}
230
	}
231

  
232
	/**
233
	 * Builds the output FeatureStore
234
	 * @param featureType
235
	 * @return FeatureStore
236
	 */
237
	protected FeatureStore buildSpatialJoinOutPutStore(FeatureType featureType1,
238
											int shapeType,
239
											String sextanteLayerName,
240
											String sextanteLayerLabel) {
241
		ArrayList<Class> typesList = new ArrayList<Class>();
242
		ArrayList<String> attr = new ArrayList<String>();
243

  
244
		Iterator it = featureType1.iterator();
245
		while( it.hasNext() ) {
246
			FeatureAttributeDescriptor attribute = (FeatureAttributeDescriptor)it.next();
247
			if (attribute.getDataType().getType() != DataTypes.GEOMETRY) {
248
				attr.add(attribute.getName());
249
				typesList.add(attribute.getObjectClass());
250
			}
251
		}
252

  
253
		for (int i = 0; i < funcList.length; i++) {
254
			if(funcList[i]) {
255
				String fieldName = funcMap.get(Summary[i]);
256
				if(fieldName.length() >= 6)
257
					fieldName = fieldName.substring(0, 7);
258
				attr.add(fieldName + "_" + Summary[i]);
259
				typesList.add(Double.class);
260
			}
261
		}
262

  
263
		attr.add(NEW_FIELD);
264
		typesList.add(Integer.class);
265

  
266
		attrNames = new String[attr.size()];
267
		attr.toArray(attrNames);
268
		Class[] types = new Class[typesList.size()];
269
		typesList.toArray(types);
270

  
271
		try {
272
			IVectorLayer output = getNewVectorLayer(sextanteLayerLabel,
273
													sextanteLayerName,
274
													shapeType, types, attrNames);
275
			return ((FlyrVectIVectorLayer)output).getFeatureStore();
276
		} catch (UnsupportedOutputChannelException e) {
277
			Sextante.addErrorToLog(e);
278
        } catch (GeoAlgorithmExecutionException e) {
279
            Sextante.addErrorToLog(e);
280
        }
281
		return null;
282
	}
283

  
284
    @Override
285
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {
286
        return SpatialJoinParametersPanel.class;
287
    }
288
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/java/org/gvsig/geoprocess/algorithm/spatialjoin/SpatialJoinParametersPanel.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.spatialjoin;
25

  
26
import java.awt.BorderLayout;
27
import java.awt.Color;
28
import java.awt.Dimension;
29
import java.awt.GridBagConstraints;
30
import java.awt.GridBagLayout;
31
import java.awt.Insets;
32
import java.awt.event.ActionEvent;
33
import java.awt.event.ActionListener;
34

  
35
import javax.swing.BorderFactory;
36
import javax.swing.ComboBoxModel;
37
import javax.swing.DefaultComboBoxModel;
38
import javax.swing.JCheckBox;
39
import javax.swing.JComboBox;
40
import javax.swing.JLabel;
41
import javax.swing.JPanel;
42

  
43
import org.gvsig.geoprocess.lib.api.GeoProcessLocator;
44
import org.gvsig.geoprocess.sextante.gui.algorithm.AlgorithmOutputPanel;
45
import org.gvsig.gui.beans.table.TableContainer;
46
import org.gvsig.gui.beans.table.exceptions.NotInitializeException;
47

  
48
import es.unex.sextante.core.GeoAlgorithm;
49
import es.unex.sextante.core.ObjectAndDescription;
50
import es.unex.sextante.core.OutputObjectsSet;
51
import es.unex.sextante.core.ParametersSet;
52
import es.unex.sextante.core.Sextante;
53
import es.unex.sextante.dataObjects.IVectorLayer;
54
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
55
import es.unex.sextante.gui.algorithm.OutputChannelSelectionPanel;
56
import es.unex.sextante.gui.core.SextanteGUI;
57
import es.unex.sextante.outputs.Output;
58

  
59
/**
60
 * Panel for dissolve algorithm
61
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
62
 */
63
public class SpatialJoinParametersPanel extends GeoAlgorithmParametersPanel implements ActionListener {
64
	private static final long                serialVersionUID   = 1L;
65
	private GeoAlgorithm                     m_Algorithm        = null;
66
	private JComboBox                        layersCombo        = null;
67
	private JComboBox                        layersJoinCombo    = null;
68
	private JCheckBox                        selectionInput     = null;
69
	private JCheckBox                        selectionOverlay   = null;
70
	private JCheckBox                        nearest       = null;
71
	private AlgorithmOutputPanel             output             = null;
72
	private final String[]                   columnNames        = { "Min", "Max", "Sum", "Avg", "Field ID" };
73
	private final int[]                      columnWidths       = { 35, 35, 35, 35, 334 };
74
	private TableContainer                   table              = null;
75
	private OutputChannelSelectionPanel      outputChannelSelectionPanel;
76
	private JPanel                           outputPanel;
77

  
78
	public SpatialJoinParametersPanel() {
79
		super();
80
	}
81

  
82
    public void init(GeoAlgorithm algorithm) {
83
    	m_Algorithm = algorithm;
84
    	initGUI();
85
    }
86

  
87
	private void initGUI() {
88
		GridBagLayout gbl = new GridBagLayout();
89
		this.setLayout(gbl);
90
		this.setBorder(BorderFactory.createLineBorder(Color.gray));
91

  
92
		GridBagConstraints gbc = new GridBagConstraints();
93
		gbc.fill = GridBagConstraints.HORIZONTAL;
94
		gbc.weightx = 1.0;
95
		gbc.gridx = 0;
96
		gbc.gridy = 0;
97
		gbc.insets = new Insets(0, 0, 8, 0);
98
		this.add(getComboPanel(GeoProcessLocator.getGeoProcessManager().getTranslation("input_layers"), getLayers1Combo()), gbc);
99

  
100
		gbc.gridy = 1;
101
		this.add(getComboPanel(GeoProcessLocator.getGeoProcessManager().getTranslation("input_layers_join"), getLayers2Combo()), gbc);
102

  
103
		gbc.gridy = 2;
104
		this.add(getSelectionInputCheck(), gbc);
105

  
106
		gbc.gridy = 3;
107
		this.add(getSelectionOverlayCheck(), gbc);
108

  
109
		gbc.gridy = 4;
110
		this.add(getNearestCheck(), gbc);
111

  
112
		gbc.gridy = 5;
113
		this.add(new JLabel(GeoProcessLocator.getGeoProcessManager().getTranslation("summary_function")), gbc);
114

  
115
		gbc.gridy = 6;
116
		gbc.fill = GridBagConstraints.BOTH;
117
		gbc.insets = new Insets(0, 0, 12, 0);
118
		gbc.weighty = 1.0;
119
		this.add(getRadioButtonTable(), gbc);
120

  
121
		gbc.gridy = 7;
122
		gbc.fill = GridBagConstraints.HORIZONTAL;
123
		gbc.weighty = 0.0;
124
		this.add(getOutputChannelSelectionPanel(), gbc);
125

  
126
		initTable();
127
		getRadioButtonTable().setVisible(false);
128
	}
129

  
130
	/**
131
	 * Gets the output panel (SEXTANTE)
132
	 * @return
133
	 */
134
	private JPanel getOutputChannelSelectionPanel() {
135
		if(outputPanel == null) {
136
			try {
137
				outputPanel = new JPanel();
138
				outputPanel.setLayout(new BorderLayout());
139
				final OutputObjectsSet ooSet = m_Algorithm.getOutputObjects();
140
				final Output out = ooSet.getOutput(SpatialJoinAlgorithm.RESULT);
141
				outputChannelSelectionPanel = new OutputChannelSelectionPanel(out, m_Algorithm.getParameters());
142
				outputPanel.add(new JLabel(GeoProcessLocator.getGeoProcessManager().getTranslation("Spatialjoin") +
143
						" [" + GeoProcessLocator.getGeoProcessManager().getTranslation("Vectorial") +"]                        "), BorderLayout.WEST);
144
				outputPanel.add(outputChannelSelectionPanel, BorderLayout.CENTER);
145
			} catch (final Exception e) {
146
				Sextante.addErrorToLog(e);
147
			}
148
		}
149
		return outputPanel;
150
	}
151

  
152
	/**
153
	 * Gets the output panel (DAL)
154
	 * @return
155
	 */
156
	@SuppressWarnings("unused")
157
	private AlgorithmOutputPanel getAlgorithmOutputPanel() {
158
		if(output == null) {
159
			output = new AlgorithmOutputPanel();
160
		}
161
		return output;
162
	}
163

  
164
	/**
165
	 * Gets a new JPanel with the text and JComboBox
166
	 * @param text
167
	 * @param combo
168
	 * @return
169
	 */
170
	public JPanel getComboPanel(String text, JComboBox combo) {
171
		JPanel panel = new JPanel();
172
		GridBagLayout gbl = new GridBagLayout();
173
		panel.setLayout(gbl);
174

  
175
		GridBagConstraints gbc = new GridBagConstraints();
176
		gbc.fill = GridBagConstraints.NONE;
177
		gbc.weightx = 0;
178
		gbc.gridx = 0;
179
		gbc.insets = new Insets(0, 2, 0, 5);
180
		JLabel label = new JLabel(text);
181
		label.setPreferredSize(new Dimension(180, 18));
182
		panel.add(label, gbc);
183

  
184
		gbc.fill = GridBagConstraints.HORIZONTAL;
185
		gbc.weightx = 1.0;
186
		gbc.gridx = 1;
187
		gbc.anchor = GridBagConstraints.EAST;
188
		gbc.insets = new Insets(0, 2, 0, 0);
189
		panel.add(combo, gbc);
190
		return panel;
191
	}
192

  
193
	/**
194
	 * Gets a ComboBox
195
	 * @return
196
	 */
197
	public JComboBox getLayers1Combo() {
198
		if(layersCombo == null) {
199
			layersCombo = new JComboBox();
200
			layersCombo.setPreferredSize(new Dimension(0, 18));
201
			ComboBoxModel comboModel = new DefaultComboBoxModel(getLayerList());
202
			layersCombo.setModel(comboModel);
203
			layersCombo.addActionListener(this);
204
		}
205
		return layersCombo;
206
	}
207

  
208
	/**
209
	 * Gets a ComboBox
210
	 * @return
211
	 */
212
	public JComboBox getLayers2Combo() {
213
		if(layersJoinCombo == null) {
214
			layersJoinCombo = new JComboBox();
215
			layersJoinCombo.setPreferredSize(new Dimension(0, 18));
216
			ComboBoxModel comboModel = new DefaultComboBoxModel(getLayerList());
217
			layersJoinCombo.setModel(comboModel);
218
			layersJoinCombo.addActionListener(this);
219
		}
220
		return layersJoinCombo;
221
	}
222

  
223
	/**
224
	 * Gets a CheckBox
225
	 * @return
226
	 */
227
	public JCheckBox getSelectionInputCheck() {
228
		if(selectionInput == null) {
229
			selectionInput = new JCheckBox(GeoProcessLocator.getGeoProcessManager().getTranslation("Selected_geometries_input_layer"));
230
		}
231
		return selectionInput;
232
	}
233

  
234
	/**
235
	 * Gets a CheckBox
236
	 * @return
237
	 */
238
	public JCheckBox getSelectionOverlayCheck() {
239
		if(selectionOverlay == null) {
240
			selectionOverlay = new JCheckBox(GeoProcessLocator.getGeoProcessManager().getTranslation("Selected_geometries_overlay_layer"));
241
		}
242
		return selectionOverlay;
243
	}
244

  
245
	/**
246
	 * Gets a CheckBox
247
	 * @return
248
	 */
249
	public JCheckBox getNearestCheck() {
250
		if(nearest == null) {
251
			nearest = new JCheckBox(GeoProcessLocator.getGeoProcessManager().getTranslation("use_the_nearest"));
252
			nearest.setSelected(true);
253
			nearest.addActionListener(this);
254
		}
255
		return nearest;
256
	}
257

  
258
	/**
259
	 * Gets the summary table
260
	 * @return TableContainer
261
	 */
262
	public TableContainer getRadioButtonTable() {
263
		if (table == null) {
264
			table = new TableContainer(columnNames, columnWidths, null);
265
			table.setModel("ARGBBandSelectorModel");
266
			table.setControlVisible(false);
267
			table.initialize();
268
		}
269
		return table;
270
	}
271

  
272
	//------------------------------------------------------------
273

  
274
	public void actionPerformed(ActionEvent e) {
275
		if(e.getSource() == getNearestCheck()) {
276
			if(!getNearestCheck().isSelected())
277
				getRadioButtonTable().setVisible(true);
278
			else
279
				getRadioButtonTable().setVisible(false);
280
		}
281

  
282
		if(e.getSource() ==  getLayers2Combo()) {
283
			initTable();
284

  
285
			//If the second layer has not numerical fields only the nearest method can be applied
286
			IVectorLayer lyr = getSelectedVectorLayer2();
287
			Class[] types = lyr.getFieldTypes();
288
			boolean hasNumericField = false;
289
			for (int i = 0; i < types.length; i++) {
290
				if(types[i] == Integer.class
291
						|| types[i] == Double.class
292
						|| types[i] == Float.class
293
						|| types[i] == Short.class) {
294
					hasNumericField = true;
295
					break;
296
				}
297
			}
298
			if(!hasNumericField){
299
				getNearestCheck().setSelected(true);
300
			}
301
		}
302
	}
303

  
304
	/**
305
	 * Adds to the table one entry for each field
306
	 */
307
	private void initTable() {
308
		try {
309
			getRadioButtonTable().removeAllRows();
310
			if(getSelectedVectorLayer2() == null)
311
				return;
312
			Class<?>[] types = getSelectedVectorLayer2().getFieldTypes();
313
			for (int i = 0; i < getSelectedVectorLayer2().getFieldCount(); i++) {
314
				if(Number.class.isAssignableFrom(types[i])) {
315
					addTableRow(getSelectedVectorLayer2().getFieldName(i));
316
				}
317
			}
318
		} catch (NotInitializeException e) {
319
			Sextante.addErrorToLog(e);
320
		}
321
	}
322

  
323
	/**
324
	 * A?ade una banda a la tabla bandas de la imagen asignandole un nombre y
325
	 * valor a los checkbox
326
	 * @param bandName Nombre de la banda
327
	 * @throws NotInitializeException
328
	 */
329
	private void addTableRow(String fieldName) throws NotInitializeException {
330
		Object[] row = {	new Boolean(false),
331
							new Boolean(false),
332
							new Boolean(false),
333
							new Boolean(false),
334
							fieldName };
335
		getRadioButtonTable().addRow(row);
336
	}
337

  
338
	@Override
339
	public void assignParameters() {
340
		try {
341
			ParametersSet params = m_Algorithm.getParameters();
342
			params.getParameter(SpatialJoinAlgorithm.LAYER1).setParameterValue(getSelectedVectorLayer());
343
			params.getParameter(SpatialJoinAlgorithm.LAYER2).setParameterValue(getSelectedVectorLayer2());
344
			params.getParameter(SpatialJoinAlgorithm.SELECTGEOM_INPUT).setParameterValue(getSelectionInputCheck().isSelected());
345
			params.getParameter(SpatialJoinAlgorithm.SELECTGEOM_OVERLAY).setParameterValue(getSelectionOverlayCheck().isSelected());
346
			params.getParameter(SpatialJoinAlgorithm.NEAREST).setParameterValue(getNearestCheck().isSelected());
347
			params.getParameter(SpatialJoinAlgorithm.FUNCTION_LIST).setParameterValue(getValues());
348

  
349
			OutputObjectsSet ooSet = m_Algorithm.getOutputObjects();
350
			Output out = ooSet.getOutput(SpatialJoinAlgorithm.RESULT);
351

  
352
			//Reponer estas l?neas para cambiar el panel de salida y comentar la siguiente
353
			//AlgorithmOutputPanel fsp = getAlgorithmOutputPanel();
354
			//out.setOutputChannel(new CompositeSourceOutputChannel(fsp.getOutputParameters()));
355
	         out.setOutputChannel(outputChannelSelectionPanel.getOutputChannel());
356
		} catch (Exception e) {
357
			Sextante.addErrorToLog(e);
358
        }
359
	}
360

  
361
	@Override
362
	public void setOutputValue(String arg0, String arg1) {
363

  
364
	}
365

  
366
	@Override
367
	public void setParameterValue(String arg0, String arg1) {
368

  
369
	}
370

  
371
	/**
372
	 * Gets the input layer list
373
	 * @return
374
	 */
375
	private ObjectAndDescription[] getLayerList() {
376
		IVectorLayer[] layers = SextanteGUI.getInputFactory()
377
					.getVectorLayers(IVectorLayer.SHAPE_TYPE_WRONG);
378
		ObjectAndDescription[] oad = new ObjectAndDescription[layers.length];
379
		for (int i = 0; i < layers.length; i++)
380
			oad[i] = new ObjectAndDescription(layers[i].getName(), layers[i]);
381
		return oad;
382
	}
383

  
384
	/**
385
	 * Gets the selected vector layer in the JComboBox
386
	 * @return
387
	 */
388
	private IVectorLayer getSelectedVectorLayer() {
389
		if(layersCombo.getSelectedItem() != null)
390
			return (IVectorLayer)((ObjectAndDescription)layersCombo.getSelectedItem()).getObject();
391
		return null;
392
	}
393

  
394
	/**
395
	 * Gets the selected vector layer in the JComboBox
396
	 * @return
397
	 */
398
	private IVectorLayer getSelectedVectorLayer2() {
399
		if(layersJoinCombo.getSelectedItem() != null)
400
			return (IVectorLayer)((ObjectAndDescription)layersJoinCombo.getSelectedItem()).getObject();
401
		return null;
402
	}
403

  
404
	/**
405
	 * Gets the field list of the selected layer
406
	 * @return
407
	 */
408
	public String[] getFieldList() {
409
		IVectorLayer layer = getSelectedVectorLayer2();
410
		String[] data = new String[layer.getFieldCount()];
411
		for (int i = 0; i < layer.getFieldCount(); i++)
412
			data[i] = layer.getFieldName(i);
413
		return data;
414
	}
415

  
416
	/**
417
	 * Formats the content of the table
418
	 * @return
419
	 */
420
	private String getValues() {
421
    	String str = "";
422
    	try {
423
			for (int i = 0; i < getRadioButtonTable().getRowCount(); i++) {
424
				str = str + (String)getRadioButtonTable().getModel().getValueAt(i, 4) + ",";
425
				for (int j = 0; j < getRadioButtonTable().getModel().getColumnCount() - 1; j++)
426
					if(((Boolean)getRadioButtonTable().getModel().getValueAt(i, j)).booleanValue())
427
						str = str + SpatialJoinAlgorithm.Summary[j] + ",";
428
				str = str.substring(0, str.length() - 1) + ";";
429
			}
430
		} catch (NotInitializeException e) {
431
			Sextante.addErrorToLog(e);
432
		}
433
    	if (str.isEmpty()) {
434
    		return str;
435
    	}
436
    	return str.substring(0, str.length() - 1);
437
    }
438

  
439
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/java/org/gvsig/geoprocess/algorithm/spatialjoin/IntersectsSpatialJoinOperation.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.spatialjoin;
25

  
26
import java.util.List;
27

  
28
import es.unex.sextante.core.Sextante;
29

  
30
import java.util.Iterator;
31

  
32
import org.apache.commons.lang3.mutable.MutableBoolean;
33
import org.apache.commons.lang3.mutable.MutableInt;
34
import org.jfree.base.config.ModifiableConfiguration;
35

  
36
import org.gvsig.fmap.dal.DataTypes;
37
import org.gvsig.fmap.dal.exception.DataException;
38
import org.gvsig.fmap.dal.feature.EditableFeature;
39
import org.gvsig.fmap.dal.feature.Feature;
40
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
41
import org.gvsig.fmap.dal.feature.FeatureIndex;
42
import org.gvsig.fmap.dal.feature.FeatureIndexes;
43
import org.gvsig.fmap.dal.feature.FeatureReference;
44
import org.gvsig.fmap.dal.feature.FeatureSelection;
45
import org.gvsig.fmap.dal.feature.FeatureSet;
46
import org.gvsig.fmap.dal.feature.FeatureStore;
47
import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
48
import org.gvsig.fmap.geom.Geometry;
49
import org.gvsig.fmap.geom.SpatialIndex;
50
import org.gvsig.fmap.geom.exception.CreateGeometryException;
51
import org.gvsig.fmap.geom.primitive.Envelope;
52
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
53
import org.gvsig.geoprocess.algorithm.dissolve.Summary;
54
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
55
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
56
import org.gvsig.tools.exception.BaseException;
57
import org.gvsig.tools.visitor.VisitCanceledException;
58
import org.gvsig.tools.visitor.Visitor;
59

  
60
/**
61
 *
62
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
63
 */
64
public class IntersectsSpatialJoinOperation extends GeometryOperation {
65
	/**
66
	 * Specialized instance in nearest neighbor search.
67
	 */
68
	private SpatialIndex              index                 = null;
69
	private Summary                   summary               = null;
70
	private FeatureStore              storeOverlay          = null;
71
	private FeatureSelection          featureSelection      = null;
72

  
73
	public IntersectsSpatialJoinOperation(FlyrVectIVectorLayer targetLayer, SpatialIndex index, Summary summary, AbstractSextanteGeoProcess p) {
74
		super(p);
75
	    this.index = index;
76
		this.summary = summary;
77
		storeOverlay = targetLayer.getFeatureStore();
78
	}
79

  
80
	/*
81
	 * (non-Javadoc)
82
	 * @see org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org.gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.Feature)
83
	 */
84
	@SuppressWarnings("deprecation")
85
	public EditableFeature invoke(final org.gvsig.fmap.geom.Geometry g, Feature featureInput) {
86
		if(g == null)
87
			return lastEditFeature;
88

  
89
		if(featureSelection == null) {
90
			try {
91
				featureSelection = storeOverlay.getFeatureSelection();
92
			} catch (DataException e1) {
93
				//Sin selecci?n tiramos
94
			}
95
		}
96

  
97
		try {
98
	          final MutableBoolean first = new MutableBoolean(true);
99
	          final MutableInt numReg = new MutableInt(0);
100

  
101
            index.query(g, new Visitor() {
102

  
103
                @Override
104
                public void visit(Object obj) throws VisitCanceledException, BaseException {
105
                    FeatureReference ref = (FeatureReference) obj;
106
                    Feature feat = ref.getFeature();
107
                    Geometry g2 = feat.getDefaultGeometry();
108
                    if(g.intersects(g2)){
109
                        if(first.getValue()) {
110
                            summary.loadDefaultSummarizes(feat);
111
                            first.setFalse();
112
                        }
113
                        summary.updateValues(feat);
114
                        numReg.increment();
115
                    }
116
                }
117
            });
118

  
119
			buildNewFeature(featureInput, summary, numReg.getValue());
120

  
121
		} catch(FeatureIndexException e) {
122
			Sextante.addErrorToLog(e);
123
		} catch (DataException e) {
124
			Sextante.addErrorToLog(e);
125
		}
126

  
127
		return lastEditFeature;
128
	}
129

  
130
	/**
131
	 * Builds a new output feature and adds it to the output file
132
	 * @param feat1
133
	 * @param feat2
134
	 * @param value
135
	 * @param g
136
	 * @throws DataException
137
	 */
138
	@SuppressWarnings("unchecked")
139
	private void buildNewFeature(Feature feat, Summary summary, int numReg) throws DataException {
140
		EditableFeature outFeat = persister.getOutputFeatureStore().createNewFeature();
141
		FeatureAttributeDescriptor[] attrs = feat.getType().getAttributeDescriptors();
142

  
143
		//Loads the old feature
144
		int pos = 0;
145
		for (int i = 0; i < attrs.length; i++) {
146
			if (attrs[i].getDataType().getType() != DataTypes.GEOMETRY) {
147
				outFeat.set(pos, feat.get(i));
148
				pos ++;
149
			}
150
		}
151

  
152
		//Loads the statistics
153
		summary.loadEditableFeature(outFeat);
154

  
155
		//Loads the new field
156
		outFeat.set(SpatialJoinAlgorithm.NEW_FIELD, new Integer(numReg));
157

  
158
		//Saves the geometry
159
		try {
160
			List l = feat.getGeometries();
161
			if(l == null) {
162
				persister.addFeature(outFeat, feat.getDefaultGeometry());
163
			} else {
164
				EditableFeature editFeat = null;
165
				for (int i = 0; i < l.size(); i++) {
166
					if(editFeat == null) {
167
						editFeat = persister.addFeature(outFeat, (org.gvsig.fmap.geom.Geometry)l.get(i));
168
					} else {
169
						persister.addGeometryToExistingFeature(editFeat, (org.gvsig.fmap.geom.Geometry)l.get(i));
170
					}
171
				}
172
			}
173
		} catch (CreateGeometryException e) {
174
			Sextante.addErrorToLog(e);
175
		}
176
	}
177

  
178
	/*
179
	 * (non-Javadoc)
180
	 * @see org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org.gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.EditableFeature)
181
	 */
182
	public void invoke(org.gvsig.fmap.geom.Geometry g, EditableFeature featureInput) {
183

  
184
	}
185

  
186
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/java/org/gvsig/geoprocess/algorithm/spatialjoin/SpatialJoinLibrary.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.spatialjoin;
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 SpatialJoinLibrary library.
32
 * 
33
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
34
 */
35
public class SpatialJoinLibrary 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.spatialjoin.spatialjoin",
46
            SpatialJoinLibrary.class.getClassLoader(), SpatialJoinLibrary.class
47
                .getClass().getName());
48
        registerGeoProcess(new SpatialJoinAlgorithm());
49
    }
50

  
51
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/java/org/gvsig/geoprocess/algorithm/spatialjoin/SpatiallyIndexedSpatialJoinOperation.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.spatialjoin;
25

  
26
import java.util.Iterator;
27

  
28
import org.apache.commons.lang3.mutable.MutableDouble;
29
import org.apache.commons.lang3.mutable.MutableObject;
30

  
31
import es.unex.sextante.core.Sextante;
32

  
33
import org.gvsig.fmap.dal.exception.DataException;
34
import org.gvsig.fmap.dal.feature.EditableFeature;
35
import org.gvsig.fmap.dal.feature.Feature;
36
import org.gvsig.fmap.dal.feature.FeatureIndex;
37
import org.gvsig.fmap.dal.feature.FeatureIndexes;
38
import org.gvsig.fmap.dal.feature.FeatureReference;
39
import org.gvsig.fmap.dal.feature.FeatureSelection;
40
import org.gvsig.fmap.dal.feature.FeatureSet;
41
import org.gvsig.fmap.dal.feature.FeatureStore;
42
import org.gvsig.fmap.geom.Geometry;
43
import org.gvsig.fmap.geom.GeometryLocator;
44
import org.gvsig.fmap.geom.GeometryManager;
45
import org.gvsig.fmap.geom.SpatialIndex;
46
import org.gvsig.fmap.geom.exception.CreateGeometryException;
47
import org.gvsig.fmap.geom.primitive.Envelope;
48
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
49
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
50
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
51
import org.gvsig.tools.exception.BaseException;
52
import org.gvsig.tools.visitor.VisitCanceledException;
53
import org.gvsig.tools.visitor.Visitor;
54

  
55
/**
56
 *
57
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
58
 */
59
public class SpatiallyIndexedSpatialJoinOperation extends GeometryOperation {
60
	private FeatureStore               storeOverlay        = null;
61
	private FeatureSelection           featureSelection    = null;
62

  
63
	/**
64
	 * Geometry.distance() is a costly operation. Thats the reason for we are
65
	 * only using a nearest neighbor. TODO SpatialIndex works with Rectangle2D,
66
	 * and this may be a simplification that drives to errors. Make additional
67
	 * probes to use a number of default neighbors
68
	 */
69
	static final int                  DEFAULT_NUM_NEIGBOURS = 1;
70

  
71
	/**
72
	 * Number of neighbors that nearestFinder must found.
73
	 */
74
	int                               numOfNeighbours       = DEFAULT_NUM_NEIGBOURS;
75

  
76
	/**
77
	 * Specialized instance in nearest neighbor search.
78
	 */
79
	private SpatialIndex              index                 = null;
80

  
81
	public SpatiallyIndexedSpatialJoinOperation(FlyrVectIVectorLayer targetLayer, SpatialIndex index, AbstractSextanteGeoProcess p) {
82
		super(p);
83
		this.index = index;
84
		storeOverlay = targetLayer.getFeatureStore();
85
	}
86

  
87
	/*
88
	 * (non-Javadoc)
89
	 * @see org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org.gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.Feature)
90
	 */
91
	@SuppressWarnings({ "unchecked", "deprecation" })
92
    public EditableFeature invoke(final org.gvsig.fmap.geom.Geometry g, Feature featureInput) {
93
	    final MutableObject<Feature> foundFeature = new MutableObject<Feature>(null);
94
        boolean addedFeature = false;
95
        if (g == null)
96
            return lastEditFeature;
97

  
98
        try {
99
            final MutableDouble nearestDistance = new MutableDouble(Double.POSITIVE_INFINITY);
100

  
101
            index.query(g, new Visitor() {
102

  
103
                @Override
104
                public void visit(Object obj) throws VisitCanceledException, BaseException {
105
                    FeatureReference ref = (FeatureReference) obj;
106
                    Feature feat = ref.getFeature();
107
                    Geometry g2 = feat.getDefaultGeometry();
108
                    double dist = g.distance(g2);
109
                    if (dist <= nearestDistance.getValue()) {
110
                        nearestDistance.setValue(dist);
111
                        foundFeature.setValue(feat.getCopy());
112
                    }
113
                }
114
            });
115

  
116
            Iterator<?> iterator = index.queryNearest(g);
117
            while (iterator.hasNext()) {
118
                FeatureReference ref = (FeatureReference) iterator.next();
119
                Feature feat = ref.getFeature();
120
                Geometry g2 = feat.getDefaultGeometry();
121
                double dist = g.distance(g2);
122
                if (dist <= nearestDistance.getValue()) {
123
                    nearestDistance.setValue(dist);
124
                    foundFeature.setValue(feat.getCopy());
125
                }
126
            }
127

  
128
            if(foundFeature!=null){
129
                buildFeature(featureInput, foundFeature.getValue(), new Double(nearestDistance.getValue()), g);
130
                addedFeature = true;
131
            }
132

  
133
        } catch (Exception e) {
134
            Sextante.addErrorToLog(e);
135
        }
136

  
137
        return lastEditFeature;
138
    }
139

  
140
	/**
141
	 * Builds a feature and adds it to the output file
142
	 * @param feat1
143
	 * @param feat2
144
	 * @param value
145
	 * @param g
146
	 * @throws DataException
147
	 */
148
	private void buildFeature(Feature feat1, Feature feat2, Object value, org.gvsig.fmap.geom.Geometry g) throws DataException {
149
		EditableFeature outFeat = persister.getOutputFeatureStore().createNewFeature();
150
		int sizeFeat1 = feat1.getType().size() - 1;
151

  
152
		for (int i = 0; i < sizeFeat1; i++)
153
			outFeat.set(i, feat1.get(i));
154

  
155
		for (int i = sizeFeat1; i < sizeFeat1 + feat2.getType().size() - 1; i++)
156
			outFeat.set(i, feat2.get(i - sizeFeat1));
157

  
158
		outFeat.set(outFeat.getType().size() - 2, value);
159
		try {
160
			persister.addFeature(outFeat, g);
161
		} catch (CreateGeometryException e) {
162
			Sextante.addErrorToLog(e);
163
		}
164
	}
165

  
166
	/*
167
	 * (non-Javadoc)
168
	 * @see org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org.gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.EditableFeature)
169
	 */
170
	public void invoke(org.gvsig.fmap.geom.Geometry g, EditableFeature featureInput) {
171

  
172
	}
173

  
174
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/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.spatialjoin</artifactId>
5
  <packaging>jar</packaging>
6
  <name>org.gvsig.geoprocess.algorithm.spatialjoin</name>
7
	
8
	<parent>
9
		<groupId>org.gvsig</groupId>
10
		<artifactId>org.gvsig.geoprocess.algorithm</artifactId>
11
		<version>2.2.107</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
   		<dependency>
21
		    <groupId>org.gvsig</groupId>
22
   			<artifactId>org.gvsig.geoprocess.algorithm.dissolve</artifactId>
23
            <scope>compile</scope>
24
   		</dependency>
25
	</dependencies>
26
	
27
</project>
0 28

  
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.lateralbuffer/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.geoprocess.algorithm.lateralbuffer.LateralBufferLibrary
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.lateralbuffer/src/main/resources/org/gvsig/geoprocess/algorithm/lateralbuffer/lateralbuffer.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
lateral_buffer=Buffer lateral
25
left=Izquierda
26
right=Derecha
27
select_lateral=Seleccionar lateral
28
SplitLines._Introduccion_de_datos=Cortar l\u00edneas. Introducci\u00f3n de datos
29
split_lines=Cortar l\u00edneas
30
distance_section=Distancia de la secci\u00f3n
31
Mensaje_split=Geoproceso split....
32
Mensaje_procesando_split=Partiendo geometr\u00edas...
33
new_geoprocess=Geoprocesos nuevos
34
concentrical_rings=N\u00famero de anillos concentricos
35
ignore_invalid_lines=Ignorar l\u00edneas inv\u00e1lidas
36
Use_simplified_geometries=Usar geometr\u00edas simplificadas
0 37

  
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.107/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.lateralbuffer/src/main/resources/org/gvsig/geoprocess/algorithm/lateralbuffer/lateralbuffer_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
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff