Revision 1259 org.gvsig.geoprocess/trunk/org.gvsig.geoprocess/org.gvsig.geoprocess.algorithm/org.gvsig.geoprocess.algorithm.spatialjoin/src/main/java/org/gvsig/geoprocess/algorithm/spatialjoin/SpatialJoinAlgorithm.java

View differences:

SpatialJoinAlgorithm.java
56 56
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
57 57
import org.gvsig.tools.dynobject.DynObject;
58 58
import org.gvsig.tools.exception.BaseException;
59
import org.gvsig.tools.namestranslator.NamesTranslator;
59 60
import org.gvsig.tools.visitor.VisitCanceledException;
60 61
import org.gvsig.tools.visitor.Visitor;
61 62

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

  
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>();
70
    public static final String NEW_FIELD = "NUM_RELA";
71
    public static final String RESULT = "RESULT";
72
    public static final String LAYER1 = "LAYER1";
73
    public static final String LAYER2 = "LAYER2";
74
    public static final String SELECTGEOM_INPUT = "SELECTGEOM_INPUT";
75
    public static final String SELECTGEOM_OVERLAY = "SELECTGEOM_OVERLAY";
76
    public static final String NEAREST = "NEAREST";
77
    public static final String FUNCTION_LIST = "FUNCTION_LIST";
78
    public static final String Summary[] = {"Min", "Max", "Sum", "Avg"};
79
    private boolean funcList[] = new boolean[Summary.length];
80
    private HashMap<String, String> funcMap = new HashMap<String, String>();
81
    public NamesTranslator namesTranslator;
79 82

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

  
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);
88
        try {
89
            m_Parameters.addInputVectorLayer(LAYER1,
90
                    getTranslation("Input_layer"),
91
                    IVectorLayer.SHAPE_TYPE_WRONG,
92
                    true);
93
            m_Parameters.addInputVectorLayer(LAYER2,
94
                    getTranslation("Input_layer"),
95
                    IVectorLayer.SHAPE_TYPE_WRONG,
96
                    true);
94 97
            m_Parameters.addBoolean(SELECTGEOM_INPUT,
95
            		getTranslation("Selected_geometries_input_layer"), false);
98
                    getTranslation("Selected_geometries_input_layer"), false);
96 99
            m_Parameters.addBoolean(SELECTGEOM_OVERLAY,
97
            		getTranslation("Selected_geometries_overlay_layer"), false);
100
                    getTranslation("Selected_geometries_overlay_layer"), false);
98 101
            m_Parameters.addBoolean(NEAREST, getTranslation("use_the_nearest"), false);
99 102
            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
	}
103
                    getTranslation("Function_list"));
104
        } catch (RepeatedParameterNameException e) {
105
            Sextante.addErrorToLog(e);
106
        }
107
        addOutputVectorLayer(RESULT, getTranslation("Spatialjoin"),
108
                OutputVectorLayer.SHAPE_TYPE_UNDEFINED);
109
    }
107 110

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

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

  
128
		DataManager dataManager = DALLocator.getDataManager();
131
        DataManager dataManager = DALLocator.getDataManager();
129 132

  
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
133
        //Builds the output and computes the operation
134
        try {
135
            FeatureType featureTypeInputLayer = inputLayer.getFeatureStore().getDefaultFeatureType(); //Capa de entrada
136
            FeatureType featureTypeOverlayLayer = overlayLayer.getFeatureStore().getDefaultFeatureType(); //Capa de revestimiento
134 137

  
135
			GeometryOperation operation = null;
136
			FeatureStore outFeatStore = null;
138
            GeometryOperation operation = null;
139
            FeatureStore outFeatStore = null;
140
            this.namesTranslator = NamesTranslator.createTrimTranslator(10);
137 141

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

  
144 148
                operation =
145 149
                    new SpatiallyIndexedSpatialJoinOperation(overlayLayer, createIndex(overlayLayer.getFeatureStore(), selectedGeomOverlay), this);
146 150
            } else {
147 151
                outFeatStore =
148 152
                    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);
153
                                inputLayer.getShapeType(), getTranslation("SpatialJoin"),
154
                                RESULT);
155
                IDissolveRule rule = new DissolveRule(featureTypeInputLayer.getAttributeName(0), funcMap);
156
                
157
                Summary summary
158
                        = new Summary(rule, outFeatStore.getDefaultFeatureType());
159
                operation
160
                        = new IntersectsSpatialJoinOperation(overlayLayer,
161
                                createIndex(overlayLayer.getFeatureStore(), selectedGeomOverlay), summary, this);
157 162
            }
158 163

  
159 164
            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);
165
            operation.computesGeometryOperation(inputLayer.getFeatureStore(),
166
                    outFeatStore,
167
                    attrNames,
168
                    selectedGeomInput,
169
                    selectedGeomOverlay,
170
                    true);
171
        } catch (Exception e) {
172
            Sextante.addErrorToLog(e);
168 173
        }
169 174

  
170
		return true;
171
	}
175
        return true;
176
    }
172 177

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

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

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

  
182
	    Visitor visitor = new Visitor() {
187
        Visitor visitor = new Visitor() {
183 188

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

  
198
	    return wrappedIndex;
199
	}
203
        return wrappedIndex;
204
    }
200 205

  
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
	}
206
    /**
207
     * Checks if the parameter is in Summary list
208
     *
209
     * @param it
210
     * @return the position in the list
211
     */
212
    private int isInList(String it) {
213
        for (int i = 0; i < Summary.length; i++) {
214
            if (Summary[i].compareTo(it) == 0) {
215
                return i;
216
            }
217
        }
218
        return -1;
219
    }
213 220

  
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
	}
221
    /**
222
     * Loads the list of functions to use
223
     *
224
     * @param functionList
225
     */
226
    private void loadSummary(String functionList) {
227
        String[] attrList = functionList.split(";");
228
        for (int i = 0; i < attrList.length; i++) {
229
            String[] func = attrList[i].split(",");
230
            for (int j = 1; j < func.length; j++) {
231
                int pos = isInList(func[j]);
232
                if (pos != -1) {
233
                    funcList[pos] = true;
234
                    funcMap.put(Summary[pos], func[0]);
235
                }
236
            }
237
        }
238
    }
231 239

  
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>();
240
    /**
241
     * Builds the output FeatureStore
242
     *
243
     * @param featureType
244
     * @return FeatureStore
245
     */
246
    protected FeatureStore buildSpatialJoinOutPutStore(FeatureType featureType1,
247
            int shapeType,
248
            String sextanteLayerName,
249
            String sextanteLayerLabel) {
250
        ArrayList<Class> typesList = new ArrayList<Class>();
251
        ArrayList<String> attr = new ArrayList<String>();
243 252

  
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
		}
253
        Iterator it = featureType1.iterator();
254
        while (it.hasNext()) {
255
            FeatureAttributeDescriptor attribute = (FeatureAttributeDescriptor) it.next();
256
            if (attribute.getDataType().getType() != DataTypes.GEOMETRY) {
257
                attr.add(attribute.getName());
258
                typesList.add(attribute.getObjectClass());
259
            }
260
        }
252 261

  
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
        for (int i = 0; i < funcList.length; i++) {
263
            if (funcList[i]) {
264
                String fieldName = funcMap.get(Summary[i]);
265
                if (fieldName.length() >= 6) {
266
                    fieldName = fieldName.substring(0, 7);
267
                }
268
                attr.add(fieldName + "_" + Summary[i]);
269
                typesList.add(Double.class);
270
            }
271
        }
262 272

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

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

  
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);
281
        try {
282
            IVectorLayer output = getNewVectorLayer(sextanteLayerLabel,
283
                    sextanteLayerName,
284
                    shapeType, types, attrNames);
285
            return ((FlyrVectIVectorLayer) output).getFeatureStore();
286
        } catch (UnsupportedOutputChannelException e) {
287
            Sextante.addErrorToLog(e);
278 288
        } catch (GeoAlgorithmExecutionException e) {
279 289
            Sextante.addErrorToLog(e);
280 290
        }
281
		return null;
282
	}
291
        return null;
292
    }
283 293

  
284 294
    @Override
285 295
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {

Also available in: Unified diff