Statistics
| Revision:

gvsig-geoprocess / 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 @ 313

History | View | Annotate | Download (10.3 KB)

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        SELECTED_GEOM     = "SELECTED_GEOM";
63
        public static final String        NEAREST           = "NEAREST";
64
        public static final String        FUNCTION_LIST     = "FUNCTION_LIST";
65
        public static final String        Summary[]         = {"Min", "Max", "Sum", "Avg"};
66
        private boolean                   funcList[]        = new boolean[Summary.length];
67
        private HashMap<String, String>   funcMap           = new HashMap<String, String>();
68
        
69
        /*
70
         * (non-Javadoc)
71
         * @see es.unex.sextante.core.GeoAlgorithm#defineCharacteristics()
72
         */
73
        public void defineCharacteristics(){
74
        setName(getTranslation("Spatialjoin"));
75
        setGroup(getTranslation("basic_vect_algorithms"));
76
        // setGeneratesUserDefinedRasterOutput(false);
77
                
78
                try {
79
                        m_Parameters.addInputVectorLayer(LAYER1, 
80
                getTranslation("Input_layer"),
81
                                                                                                IVectorLayer.SHAPE_TYPE_WRONG, 
82
                                                                                                true);
83
                        m_Parameters.addInputVectorLayer(LAYER2, 
84
                getTranslation("Input_layer"),
85
                                                                                                IVectorLayer.SHAPE_TYPE_WRONG, 
86
                                                                                                true);
87
            m_Parameters.addBoolean(SELECTED_GEOM,
88
                getTranslation("selected_geometries"), false);
89
            m_Parameters.addBoolean(NEAREST, getTranslation("use_the_nearest"),
90
                false);
91
            m_Parameters.addString(FUNCTION_LIST,
92
                getTranslation("Function_list"));
93
                } catch (RepeatedParameterNameException e) {
94
                        Sextante.addErrorToLog(e);
95
                }
96
                addOutputVectorLayer(RESULT,getTranslation("Spatialjoin"),
97
                                                                OutputVectorLayer.SHAPE_TYPE_UNDEFINED);
98
        }
99
        
100
        /*
101
         * (non-Javadoc)
102
         * @see es.unex.sextante.core.GeoAlgorithm#processAlgorithm()
103
         */
104
        public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
105
                if(existsOutPutFile(SpatialJoinAlgorithm.RESULT, 0)) {
106
                    throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
107
            }
108
                IVectorLayer layer1 = m_Parameters.getParameterValueAsVectorLayer(LAYER1);
109
                IVectorLayer layer2 = m_Parameters.getParameterValueAsVectorLayer(LAYER2);
110
                boolean selectedGeom = m_Parameters.getParameterValueAsBoolean(SELECTED_GEOM);
111
                boolean nearest = m_Parameters.getParameterValueAsBoolean(NEAREST);
112
                String functionList = m_Parameters.getParameterValueAsString(FUNCTION_LIST);
113
                loadSummary(functionList);
114

    
115
                FlyrVectIVectorLayer lyr1 = null;
116
                FlyrVectIVectorLayer lyr2 = null;
117
                if(layer2 instanceof FlyrVectIVectorLayer && layer1 instanceof FlyrVectIVectorLayer) { 
118
                        lyr2 = ((FlyrVectIVectorLayer)layer2);
119
                        lyr1 = ((FlyrVectIVectorLayer)layer1);
120
                } else 
121
                        return false;
122

    
123
                DataManager dataManager = DALLocator.getDataManager();
124

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

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

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

    
184
                return true;
185
        }
186

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

    
271
    @Override
272
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {
273
        return SpatialJoinParametersPanel.class;
274
    }
275
}