Revision 726

View differences:

org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.33/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.33/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 org.gvsig.fmap.dal.DataTypes;
31
import org.gvsig.fmap.dal.exception.DataException;
32
import org.gvsig.fmap.dal.feature.EditableFeature;
33
import org.gvsig.fmap.dal.feature.Feature;
34
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
35
import org.gvsig.fmap.dal.feature.FeatureIndex;
36
import org.gvsig.fmap.dal.feature.FeatureIndexes;
37
import org.gvsig.fmap.dal.feature.FeatureSelection;
38
import org.gvsig.fmap.dal.feature.FeatureSet;
39
import org.gvsig.fmap.dal.feature.FeatureStore;
40
import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
41
import org.gvsig.fmap.geom.exception.CreateGeometryException;
42
import org.gvsig.fmap.geom.primitive.Envelope;
43
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
44
import org.gvsig.geoprocess.algorithm.dissolve.Summary;
45
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
46
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
47
import org.gvsig.tools.dispose.DisposableIterator;
48

  
49
/**
50
 * 
51
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
52
 */
53
public class IntersectsSpatialJoinOperation extends GeometryOperation {
54
	/**
55
	 * Specialized instance in nearest neighbor search.
56
	 */
57
	private FeatureIndex              index                 = null;
58
	private Summary                   summary               = null;
59
	private FeatureStore              storeOverlay          = null;
60
	private FeatureSelection          featureSelection      = null;
61
	
62
	public IntersectsSpatialJoinOperation(FlyrVectIVectorLayer targetLayer, String indexName, Summary summary, AbstractSextanteGeoProcess p) {
63
		super(p);
64
		FeatureIndexes indexes = targetLayer.getFeatureStore().getIndexes();
65
		index = indexes.getFeatureIndex(indexName);
66
		this.summary = summary;
67
		storeOverlay = targetLayer.getFeatureStore();
68
	}
69
	
70
	/*
71
	 * (non-Javadoc)
72
	 * @see org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org.gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.Feature)
73
	 */
74
	@SuppressWarnings("deprecation")
75
	public EditableFeature invoke(org.gvsig.fmap.geom.Geometry g, Feature featureInput) {
76
		if(g == null)
77
			return lastEditFeature;
78
		
79
		if(featureSelection == null) {
80
			try {
81
				featureSelection = storeOverlay.getFeatureSelection();
82
			} catch (DataException e1) {
83
				//Sin selecci?n tiramos
84
			}
85
		}
86

  
87
		try {
88

  
89
			Envelope rect = g.getEnvelope();
90
			FeatureSet featSet = index.getMatchFeatureSet(rect);
91
			
92
			boolean first = true;
93
			int numReg = 0;
94
			DisposableIterator it = featSet.iterator();
95
			while(it.hasNext()) {
96
				Feature feat = (Feature)it.next();
97
				if( featureSelection != null && 
98
					!featureSelection.isEmpty() && 
99
					!featureSelection.isSelected(feat))
100
					continue;
101
				
102
				if(first) {
103
					summary.loadDefaultSummarizes(feat);
104
					first = false;
105
				}
106
				
107
				summary.updateValues(feat);
108
				numReg ++;
109
			}
110
			
111
			buildNewFeature(featureInput, summary, numReg);
112
			
113
		} catch(FeatureIndexException e) {
114
			Sextante.addErrorToLog(e);
115
		} catch (DataException e) {
116
			Sextante.addErrorToLog(e);
117
		}
118
		
119
		return lastEditFeature;
120
	}
121
	
122
	/**
123
	 * Builds a new output feature and adds it to the output file
124
	 * @param feat1
125
	 * @param feat2
126
	 * @param value
127
	 * @param g
128
	 * @throws DataException
129
	 */
130
	@SuppressWarnings("unchecked")
131
	private void buildNewFeature(Feature feat, Summary summary, int numReg) throws DataException {
132
		EditableFeature outFeat = persister.getOutputFeatureStore().createNewFeature();
133
		FeatureAttributeDescriptor[] attrs = feat.getType().getAttributeDescriptors();
134
		
135
		//Loads the old feature
136
		int pos = 0;
137
		for (int i = 0; i < attrs.length; i++) {
138
			if (attrs[i].getDataType().getType() != DataTypes.GEOMETRY) {
139
				outFeat.set(pos, feat.get(i));
140
				pos ++;
141
			}
142
		}
143
		
144
		//Loads the statistics
145
		summary.loadEditableFeature(outFeat);
146
		
147
		//Loads the new field
148
		outFeat.set(SpatialJoinAlgorithm.NEW_FIELD, new Integer(numReg));
149
		
150
		//Saves the geometry
151
		try {
152
			List l = feat.getGeometries();
153
			if(l == null) {
154
				persister.addFeature(outFeat, feat.getDefaultGeometry());
155
			} else {
156
				EditableFeature editFeat = null;
157
				for (int i = 0; i < l.size(); i++) {
158
					if(editFeat == null) {
159
						editFeat = persister.addFeature(outFeat, (org.gvsig.fmap.geom.Geometry)l.get(i));
160
					} else {
161
						persister.addGeometryToExistingFeature(editFeat, (org.gvsig.fmap.geom.Geometry)l.get(i));
162
					}
163
				}
164
			}
165
		} catch (CreateGeometryException e) {
166
			Sextante.addErrorToLog(e);
167
		}
168
	}
169

  
170
	/*
171
	 * (non-Javadoc)
172
	 * @see org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org.gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.EditableFeature)
173
	 */
174
	public void invoke(org.gvsig.fmap.geom.Geometry g, EditableFeature featureInput) {
175
		
176
	}
177

  
178
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.33/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.33/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.ArrayList;
27
import java.util.Iterator;
28
import java.util.List;
29

  
30
import com.vividsolutions.jts.geom.Geometry;
31

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

  
34
import org.gvsig.fmap.dal.exception.DataException;
35
import org.gvsig.fmap.dal.feature.EditableFeature;
36
import org.gvsig.fmap.dal.feature.Feature;
37
import org.gvsig.fmap.dal.feature.FeatureIndex;
38
import org.gvsig.fmap.dal.feature.FeatureIndexes;
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.dal.feature.exception.FeatureIndexException;
43
import org.gvsig.fmap.geom.exception.CreateGeometryException;
44
import org.gvsig.fmap.geom.primitive.Envelope;
45
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
46
import org.gvsig.geoprocess.algorithm.base.util.GeometryUtil;
47
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
48
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
49
import org.gvsig.tools.dispose.DisposableIterator;
50

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

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

  
67
	/**
68
	 * Number of neighbors that nearestFinder must found.
69
	 */
70
	int                               numOfNeighbours       = DEFAULT_NUM_NEIGBOURS;
71

  
72
	/**
73
	 * Specialized instance in nearest neighbor search.
74
	 */
75
	private FeatureIndex              index                 = null;
76

  
77
	public SpatiallyIndexedSpatialJoinOperation(FlyrVectIVectorLayer targetLayer, String indexName, AbstractSextanteGeoProcess p) {
78
		super(p);
79
		FeatureIndexes indexes = targetLayer.getFeatureStore().getIndexes();
80
		index = indexes.getFeatureIndex(indexName);
81
		storeOverlay = targetLayer.getFeatureStore();
82
	}
83

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

  
94
		if(featureSelection == null) {
95
			try {
96
				featureSelection = storeOverlay.getFeatureSelection();
97
			} catch (DataException e1) {
98
				//Sin selecci?n tiramos
99
			}
100
		}
101

  
102
		try {
103
			Geometry gJts = GeometryUtil.geomToJTS(g);
104
            Envelope rect = null;
105
		    rect = g.getEnvelope();
106
			FeatureSet featSetMatch = index.getMatchFeatureSet(rect);
107
			FeatureSet featSetNearest = index.getNearestFeatureSet(numOfNeighbours, rect);
108
			double nearestDistance = Double.MAX_VALUE;
109
            DisposableIterator it = featSetMatch.iterator();
110

  
111
            //Recorremos el featSetMatch para calcular la nearestDistance
112
            while(it.hasNext()) {
113
                Feature feat = (Feature)it.next();
114
                if( featureSelection != null &&
115
                    !featureSelection.isEmpty() &&
116
                    !featureSelection.isSelected(feat))
117
                    continue;
118
                List geomList = feat.getGeometries();
119

  
120
                if(geomList == null) {
121
                    org.gvsig.fmap.geom.Geometry g2 = feat.getDefaultGeometry();
122
                    Geometry g2Jts = GeometryUtil.geomToJTS(g2);
123
                    double dist = gJts.distance(g2Jts);
124
                    if (dist <= nearestDistance) {
125
                        nearestDistance = dist;
126
                    }
127
                    continue;
128
                }
129

  
130
                Iterator<org.gvsig.fmap.geom.Geometry> itGeom = geomList.iterator();
131
                while(itGeom.hasNext()) {
132
                    org.gvsig.fmap.geom.Geometry g2 = itGeom.next();
133
                    Geometry g2Jts = GeometryUtil.geomToJTS(g2);
134
                    double dist = gJts.distance(g2Jts);
135
                    if (dist <= nearestDistance) {
136
                        nearestDistance = dist;
137
                    }
138
                }
139
            }
140
            it.dispose();
141

  
142
            //Recorremos el featSetNearest para calcular la nearestDistance
143
            it = featSetNearest.iterator();
144
            while(it.hasNext()) {
145
                Feature feat = (Feature)it.next();
146
                if( featureSelection != null &&
147
                    !featureSelection.isEmpty() &&
148
                    !featureSelection.isSelected(feat))
149
                    continue;
150
                List geomList = feat.getGeometries();
151

  
152
                if(geomList == null) {
153
                    org.gvsig.fmap.geom.Geometry g2 = feat.getDefaultGeometry();
154
                    Geometry g2Jts = GeometryUtil.geomToJTS(g2);
155
                    double dist = gJts.distance(g2Jts);
156
                    if (dist <= nearestDistance) {
157
                        nearestDistance = dist;
158
                    }
159
                    continue;
160
                }
161

  
162
                Iterator<org.gvsig.fmap.geom.Geometry> itGeom = geomList.iterator();
163
                while(itGeom.hasNext()) {
164
                    org.gvsig.fmap.geom.Geometry g2 = itGeom.next();
165
                    Geometry g2Jts = GeometryUtil.geomToJTS(g2);
166
                    double dist = gJts.distance(g2Jts);
167
                    if (dist <= nearestDistance) {
168
                        nearestDistance = dist;
169
                    }
170
                }
171
            }
172
            it.dispose();
173

  
174
            //Recorremos el featSetMatch para obtener las geometr?as que est?n a una distancia igual o menor a la nearestDistance
175

  
176
            it = featSetMatch.iterator();
177
            while (it.hasNext()) {
178
                Feature feat = (Feature) it.next();
179
                if (featureSelection != null && !featureSelection.isEmpty()
180
                    && !featureSelection.isSelected(feat))
181
                    continue;
182
                List geomList = feat.getGeometries();
183

  
184
                if (geomList == null) {
185
                    org.gvsig.fmap.geom.Geometry g2 = feat.getDefaultGeometry();
186
                    Geometry g2Jts = GeometryUtil.geomToJTS(g2);
187
                    double dist = gJts.distance(g2Jts);
188
                    if (dist <= nearestDistance) {
189
                        buildFeature(featureInput, feat, new Double(
190
                            nearestDistance), g);
191
                        addedFeature= true;
192
                    }
193
                     continue;
194
                }
195

  
196
                Iterator<org.gvsig.fmap.geom.Geometry> itGeom =
197
                    geomList.iterator();
198
                while (itGeom.hasNext()) {
199
                    org.gvsig.fmap.geom.Geometry g2 = itGeom.next();
200
                    Geometry g2Jts = GeometryUtil.geomToJTS(g2);
201
                    double dist = gJts.distance(g2Jts);
202
                    if (dist <= nearestDistance) {
203
                        buildFeature(featureInput, feat, new Double(
204
                            nearestDistance), g);
205
                        addedFeature= true;
206
                    }
207
                }
208
            }
209
            it.dispose();
210

  
211

  
212
            //Recorremos el featSetNearest para obtener las geometr?as que est?n a una distancia igual o menor a la nearestDistance
213
            //si no se ha a?adido todav?a ninguna feature
214

  
215
            if (!addedFeature) {
216
                it = featSetNearest.iterator();
217
                while (it.hasNext()) {
218
                    Feature feat = (Feature) it.next();
219

  
220
                    if (featureSelection != null && !featureSelection.isEmpty()
221
                        && !featureSelection.isSelected(feat))
222
                        continue;
223
                    List geomList = feat.getGeometries();
224

  
225
                    if (geomList == null) {
226
                        org.gvsig.fmap.geom.Geometry g2 =
227
                            feat.getDefaultGeometry();
228
                        Geometry g2Jts = GeometryUtil.geomToJTS(g2);
229
                        double dist = gJts.distance(g2Jts);
230
                        if (dist <= nearestDistance) {
231
                            buildFeature(featureInput, feat, new Double(
232
                                nearestDistance), g);
233
                            addedFeature = true;
234
                        }
235
                        continue;
236
                    }
237

  
238
                    Iterator<org.gvsig.fmap.geom.Geometry> itGeom =
239
                        geomList.iterator();
240
                    while (itGeom.hasNext()) {
241
                        org.gvsig.fmap.geom.Geometry g2 = itGeom.next();
242
                        Geometry g2Jts = GeometryUtil.geomToJTS(g2);
243
                        double dist = gJts.distance(g2Jts);
244
                        if (dist <= nearestDistance && !addedFeature) {
245
                            buildFeature(featureInput, feat, new Double(
246
                                nearestDistance), g);
247
                            addedFeature = true;
248
                        }
249
                    }
250
                }
251
                it.dispose();
252
            }
253

  
254
		} catch(FeatureIndexException e) {
255
			Sextante.addErrorToLog(e);
256
		} catch (DataException e) {
257
			Sextante.addErrorToLog(e);
258
		}
259

  
260
		return lastEditFeature;
261
	}
262

  
263
	/**
264
	 * Builds a feature and adds it to the output file
265
	 * @param feat1
266
	 * @param feat2
267
	 * @param value
268
	 * @param g
269
	 * @throws DataException
270
	 */
271
	private void buildFeature(Feature feat1, Feature feat2, Object value, org.gvsig.fmap.geom.Geometry g) throws DataException {
272
		EditableFeature outFeat = persister.getOutputFeatureStore().createNewFeature();
273
		int sizeFeat1 = feat1.getType().size() - 1;
274

  
275
		for (int i = 0; i < sizeFeat1; i++)
276
			outFeat.set(i, feat1.get(i));
277

  
278
		for (int i = sizeFeat1; i < sizeFeat1 + feat2.getType().size() - 1; i++)
279
			outFeat.set(i, feat2.get(i - sizeFeat1));
280

  
281
		outFeat.set(outFeat.getType().size() - 2, value);
282
		try {
283
			persister.addFeature(outFeat, g);
284
		} catch (CreateGeometryException e) {
285
			Sextante.addErrorToLog(e);
286
		}
287
	}
288

  
289
	/*
290
	 * (non-Javadoc)
291
	 * @see org.gvsig.geoprocess.algorithm.base.core.GeometryOperation#invoke(org.gvsig.fmap.geom.Geometry, org.gvsig.fmap.dal.feature.EditableFeature)
292
	 */
293
	public void invoke(org.gvsig.fmap.geom.Geometry g, EditableFeature featureInput) {
294

  
295
	}
296

  
297
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.33/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 org.gvsig.fmap.dal.DALLocator;
31
import org.gvsig.fmap.dal.DataManager;
32
import org.gvsig.fmap.dal.DataTypes;
33
import org.gvsig.fmap.dal.exception.DataException;
34
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
35
import org.gvsig.fmap.dal.feature.FeatureStore;
36
import org.gvsig.fmap.dal.feature.FeatureType;
37
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
38
import org.gvsig.geoprocess.algorithm.dissolve.DissolveRule;
39
import org.gvsig.geoprocess.algorithm.dissolve.IDissolveRule;
40
import org.gvsig.geoprocess.algorithm.dissolve.Summary;
41
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
42
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
43

  
44
import es.unex.sextante.core.Sextante;
45
import es.unex.sextante.dataObjects.IVectorLayer;
46
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
47
import es.unex.sextante.exceptions.RepeatedParameterNameException;
48
import es.unex.sextante.exceptions.UnsupportedOutputChannelException;
49
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
50
import es.unex.sextante.outputs.OutputVectorLayer;
51

  
52
/**
53
 * Spatial join algorithm
54
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
55
 */
56
public class SpatialJoinAlgorithm extends AbstractSextanteGeoProcess {
57

  
58
	public static final String        NEW_FIELD             = "NUM_RELA";
59
	public static final String        RESULT                = "RESULT";
60
	public static final String        LAYER1                = "LAYER1";
61
	public static final String        LAYER2                = "LAYER2";
62
	public static final String        SELECTGEOM_INPUT      = "SELECTGEOM_INPUT";
63
	public static final String        SELECTGEOM_OVERLAY    = "SELECTGEOM_OVERLAY";
64
	public static final String        NEAREST               = "NEAREST";
65
	public static final String        FUNCTION_LIST         = "FUNCTION_LIST";
66
	public static final String        Summary[]             = {"Min", "Max", "Sum", "Avg"};
67
	private boolean                   funcList[]            = new boolean[Summary.length];
68
	private HashMap<String, String>   funcMap               = new HashMap<String, String>();
69
	
70
	public void defineCharacteristics(){
71
        setName(getTranslation("Spatialjoin"));
72
        setGroup(getTranslation("basic_vect_algorithms"));
73
        // setGeneratesUserDefinedRasterOutput(false);
74
		
75
		try {
76
			m_Parameters.addInputVectorLayer(LAYER1, 
77
                getTranslation("Input_layer"),
78
												IVectorLayer.SHAPE_TYPE_WRONG, 
79
												true);
80
			m_Parameters.addInputVectorLayer(LAYER2, 
81
                getTranslation("Input_layer"),
82
												IVectorLayer.SHAPE_TYPE_WRONG, 
83
												true);
84
            m_Parameters.addBoolean(SELECTGEOM_INPUT, 
85
            		getTranslation("Selected_geometries_input_layer"), false);
86
            m_Parameters.addBoolean(SELECTGEOM_OVERLAY, 
87
            		getTranslation("Selected_geometries_overlay_layer"), false);
88
            m_Parameters.addBoolean(NEAREST, getTranslation("use_the_nearest"), false);
89
            m_Parameters.addString(FUNCTION_LIST,
90
                getTranslation("Function_list"));
91
		} catch (RepeatedParameterNameException e) {
92
			Sextante.addErrorToLog(e);
93
		}
94
		addOutputVectorLayer(RESULT,getTranslation("Spatialjoin"),
95
								OutputVectorLayer.SHAPE_TYPE_UNDEFINED);
96
	}
97
	
98
	public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
99
		if(existsOutPutFile(SpatialJoinAlgorithm.RESULT, 0)) {
100
    		throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
101
    	}
102
		IVectorLayer layer1 = m_Parameters.getParameterValueAsVectorLayer(LAYER1);
103
		IVectorLayer layer2 = m_Parameters.getParameterValueAsVectorLayer(LAYER2);
104
		boolean selectedGeomInput = m_Parameters.getParameter(SELECTGEOM_INPUT).getParameterValueAsBoolean();
105
		boolean selectedGeomOverlay = m_Parameters.getParameter(SELECTGEOM_OVERLAY).getParameterValueAsBoolean();
106
		boolean nearest = m_Parameters.getParameterValueAsBoolean(NEAREST);
107
		String functionList = m_Parameters.getParameterValueAsString(FUNCTION_LIST);
108
		loadSummary(functionList);
109

  
110
		FlyrVectIVectorLayer lyr1 = null;
111
		FlyrVectIVectorLayer lyr2 = null;
112
		if(layer2 instanceof FlyrVectIVectorLayer && layer1 instanceof FlyrVectIVectorLayer) { 
113
			lyr2 = ((FlyrVectIVectorLayer)layer2);
114
			lyr1 = ((FlyrVectIVectorLayer)layer1);
115
		} else 
116
			return false;
117

  
118
		DataManager dataManager = DALLocator.getDataManager();
119

  
120
		//Builds a new JSIRTree index. To do that we have to replace the default index and 
121
		//when the operation has finished then it restores the original default index 
122
		String indexName = "GEOMETRY";
123
		
124
		try {
125
			indexName = lyr2.getFeatureStore().getDefaultFeatureType().getDefaultGeometryAttributeName();
126
			FeatureAttributeDescriptor fat = lyr2.getFeatureStore().getDefaultFeatureType().getAttributeDescriptor(indexName);
127
			String defaultIndex = dataManager.getDefaultFeatureIndexProviderName(
128
					fat.getDataType().getType());
129
			dataManager.setDefaultFeatureIndexProviderName(
130
					fat.getDataType().getType(), "JSIRSpatialIndexProvider");
131
			lyr2.getFeatureStore().createIndex(
132
					lyr2.getFeatureStore().getDefaultFeatureType(), indexName, indexName + "_idx");
133
			dataManager.setDefaultFeatureIndexProviderName(
134
					fat.getDataType().getType(), defaultIndex);
135
		} catch (DataException e) {
136
			Sextante.addErrorToLog(e);
137
		}
138

  
139
		//Builds the output and computes the operation
140
		try {
141
			FeatureType featureType1 = lyr1.getFeatureStore().getDefaultFeatureType();
142
			FeatureType featureType2 = lyr2.getFeatureStore().getDefaultFeatureType();
143
			
144
			GeometryOperation operation = null;
145
			FeatureStore outFeatStore = null;
146
			
147
            if (nearest) {
148
                outFeatStore =
149
                    buildOutPutStoreFromUnion(featureType1, featureType2,
150
                        lyr1.getShapeType(), getTranslation("SpatialJoin"),
151
                        RESULT, "DIST", Double.class);
152

  
153
                operation =
154
                    new SpatiallyIndexedSpatialJoinOperation(lyr2, indexName
155
                        + "_idx", this);
156
            } else {
157
                outFeatStore =
158
                    buildSpatialJoinOutPutStore(featureType1,
159
                        lyr1.getShapeType(), getTranslation("SpatialJoin"),
160
                        RESULT);
161
                IDissolveRule rule = new DissolveRule(0, funcMap);
162
                Summary summary =
163
                    new Summary(rule, outFeatStore.getDefaultFeatureType());
164
                operation =
165
                    new IntersectsSpatialJoinOperation(lyr2,
166
                        indexName + "_idx", summary, this);
167
            }
168
			
169
            operation.setTaskStatus(getStatus());
170
			operation.computesGeometryOperation(lyr1.getFeatureStore(), 
171
					outFeatStore, 
172
					attrNames, 
173
					selectedGeomInput, 
174
					selectedGeomOverlay, 
175
					true);		
176
		} catch (DataException e) {
177
			Sextante.addErrorToLog(e);
178
		}
179

  
180
		return true;
181
	}
182

  
183
	/**
184
	 * Checks if the parameter is in Summary list
185
	 * @param it
186
	 * @return the position in the list
187
	 */
188
	private int isInList(String it) {
189
		for (int i = 0; i < Summary.length; i++) {
190
			if(Summary[i].compareTo(it) == 0)
191
				return i;
192
		}
193
		return -1;
194
	}
195
	
196
	/**
197
	 * Loads the list of functions to use
198
	 * @param functionList
199
	 */
200
	private void loadSummary(String functionList) {
201
		String[] attrList = functionList.split(";");
202
		for (int i = 0; i < attrList.length; i++) {
203
			String[] func = attrList[i].split(",");
204
			for (int j = 1; j < func.length; j++) {
205
				int pos = isInList(func[j]);
206
				if(pos != -1) {
207
					funcList[pos] = true;
208
					funcMap.put(Summary[pos], func[0]);
209
				}
210
			}
211
		}
212
	}
213
	
214
	/**
215
	 * Builds the output FeatureStore 
216
	 * @param featureType
217
	 * @return FeatureStore
218
	 */
219
	protected FeatureStore buildSpatialJoinOutPutStore(FeatureType featureType1,
220
											int shapeType,
221
											String sextanteLayerName, 
222
											String sextanteLayerLabel) {
223
		ArrayList<Class> typesList = new ArrayList<Class>();
224
		ArrayList<String> attr = new ArrayList<String>();
225
		
226
		Iterator it = featureType1.iterator();
227
		while( it.hasNext() ) {
228
			FeatureAttributeDescriptor attribute = (FeatureAttributeDescriptor)it.next();
229
			if (attribute.getDataType().getType() != DataTypes.GEOMETRY) {
230
				attr.add(attribute.getName());
231
				typesList.add(attribute.getObjectClass());
232
			}
233
		}
234
		
235
		for (int i = 0; i < funcList.length; i++) {
236
			if(funcList[i]) {
237
				String fieldName = funcMap.get(Summary[i]);
238
				if(fieldName.length() >= 6)
239
					fieldName = fieldName.substring(0, 7);
240
				attr.add(fieldName + "_" + Summary[i]);
241
				typesList.add(Double.class);
242
			}
243
		}
244
		
245
		attr.add(NEW_FIELD);
246
		typesList.add(Integer.class);
247
		
248
		attrNames = new String[attr.size()];
249
		attr.toArray(attrNames);
250
		Class[] types = new Class[typesList.size()];
251
		typesList.toArray(types);
252
		
253
		try {
254
			IVectorLayer output = getNewVectorLayer(sextanteLayerLabel,
255
													sextanteLayerName,
256
													shapeType, types, attrNames);
257
			return ((FlyrVectIVectorLayer)output).getFeatureStore();
258
		} catch (UnsupportedOutputChannelException e) {
259
			Sextante.addErrorToLog(e);
260
        } catch (GeoAlgorithmExecutionException e) {
261
            Sextante.addErrorToLog(e);
262
        }
263
		return null;
264
	}
265

  
266
    @Override
267
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {
268
        return SpatialJoinParametersPanel.class;
269
    }
270
}
org.gvsig.geoprocess/tags/org.gvsig.geoprocess-2.2.33/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.33/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.33/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.33/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.33/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.33/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.33</version>
12
	</parent>
13
	
14
	<dependencies>
15
		<dependency>
16
		    <groupId>org.gvsig</groupId>
17
   			<artifactId>org.gvsig.geoprocess.algorithm.base</artifactId>
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff