View Javadoc

1   package migratool.datasources.geometric.textFile;
2   
3   import igis.datasources.DataSourceException;
4   import igis.datasources.Field;
5   import igis.datasources.InvalidFieldNumberException;
6   import igis.datasources.Registry;
7   import igis.datasources.Unit;
8   
9   import java.sql.ResultSet;
10  import java.sql.ResultSetMetaData;
11  import java.sql.SQLException;
12  import java.text.SimpleDateFormat;
13  import java.util.Collection;
14  import java.util.Iterator;
15  import java.util.Vector;
16  
17  import migratool.datasources.AbstractOriginDataSource;
18  import migratool.datasources.LogicTable;
19  import migratool.datasources.geometric.GeometricOriginDataSource;
20  import migratool.model.BDdescription;
21  import oracle.sdoapi.OraSpatialManager;
22  import oracle.sdoapi.adapter.GeometryAdapter;
23  import oracle.sdoapi.geom.CurveString;
24  import oracle.sdoapi.geom.Geometry;
25  import oracle.sdoapi.geom.LineString;
26  import oracle.sdoapi.geom.MultiLineString;
27  import oracle.sdoapi.geom.MultiPolygon;
28  import oracle.sdoapi.geom.Point;
29  import oracle.sdoapi.geom.Polygon;
30  import oracle.sql.STRUCT;
31  
32  import org.apache.log4j.Logger;
33  
34  /**
35   * 
36   * MIGRATOOL Program to migrate spatial databsets.
37   * Copyright (C) 2007 Fábio Luiz Leite Júnior
38   * Universidade Federal de Campina Grande
39   * contact: fabioleite@gmail.com
40   *
41   * This program is free software; you can redistribute it and/or
42   * modify it under the terms of the GNU General Public License
43   * as published by the Free Software Foundation; either version 2
44   * of the License, or (at your option) any later version.
45   *
46   * This program is distributed in the hope that it will be useful,
47   * but WITHOUT ANY WARRANTY; without even the implied warranty of
48   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
49   * GNU General Public License for more details.
50   *
51   * You should have received a copy of the GNU General Public License
52   * along with this program; if not, write to the Free Software
53   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
54   *
55   * @author fabio
56   *
57   */
58  
59  public class GeomTextFileOriginDataSource extends AbstractOriginDataSource {
60  
61  	static Logger logger = Logger.getLogger(GeometricOriginDataSource.class);
62  	private static String ETYPE_INTERPRETATION = "2, 1, ";
63  	private static String ETYPE_INTERPRETATION_MULTI_POLIGON = "1003, 1, ";
64  	
65  	public GeomTextFileOriginDataSource(BDdescription fromDescrition) {
66  		super(fromDescrition);
67  	}
68  
69  	public Collection getDataTable() throws DataSourceException, igis.datasources.DataSourceException{
70  		ResultSet rs = null;
71  		String cons = "select * from " + originDescription.getTableName();
72  		try {
73  			rs = dbConnection.createStatement().executeQuery(cons);
74  		} catch (SQLException e) {
75  			throw new DataSourceException("Problemas na consulta: \n" + cons,e);
76  		}
77  
78  		ResultSetMetaData rsmd = null;
79  		try {
80  			rsmd = rs.getMetaData();
81  		} catch (SQLException e) {
82  			throw new DataSourceException(
83  				"Problemas para obter os metadados da "
84  					+ " consulta: \n"
85  					+ cons,e);
86  		}
87  
88  		Iterator fieldsIt = null;
89  		Collection fields = null;
90  
91  		try {
92  
93  			fields = loadFields(rsmd);
94  			fieldsIt = fields.iterator();
95  		} catch (SQLException e) {
96  			throw new DataSourceException(
97  				"Problemas para preencher os campos da "
98  					+ " consulta: \n"
99  					+ cons,
100 				e);
101 		}
102 
103 		Unit result = new Unit();
104 
105 		result.setName(cons);
106 
107 		while (fieldsIt.hasNext()) {
108 			Field field = (Field) fieldsIt.next();
109 			result.defineField(field);
110 		}
111 
112 		Collection regs = createCollection();
113 
114 		try {
115 			while (rs.next()) {
116 				Registry reg = new Registry(result);
117 
118 				fieldsIt = fields.iterator();
119 
120 				boolean ok = true;
121 
122 				while (fieldsIt.hasNext()) {
123 					Field field = (Field) fieldsIt.next();
124 					int type = field.getType();
125 
126 					switch (type) {
127 
128 						case igis.datasources.Types.SPATIAL :
129 
130 							oracle.sdoapi.geom.Geometry geom = null;
131 							Object geomObj = null;
132 							try {
133 
134 								geomObj = rs.getObject(field.getName());
135 								if (geomObj == null)
136 									break;
137 								geom = getGeometryAdapter().importGeometry(geomObj);
138 								
139 							} catch (Exception e) {
140 								logger.fatal(
141 									"Geometria Inv�lida: "
142 										+ e.getMessage()
143 										+ "\nNo registro: "
144 										+ reg.toString());
145 								ok = false;
146 							}
147 
148 							reg.setObject(field.getName(), createStringGeometry(geom));
149 							break;
150 
151 						case igis.datasources.Types.INTEGER :
152 							reg.setInt(
153 								field.getName(),
154 								rs.getInt(field.getName()));
155 							break;
156 						case igis.datasources.Types.REAL :
157 							double value = rs.getDouble(field.getName());
158 							int valueInt = (int) value;
159 							if (value - valueInt == 0)
160 								reg.setInteger(field.getName(), valueInt);
161 							else
162 								reg.setDouble(field.getName(), value);
163 							break;
164 						case igis.datasources.Types.CHARACTER :
165 							reg.setString(
166 								field.getName(),
167 								rs.getString(field.getName()));
168 							break;
169 						case igis.datasources.Types.DATE :
170 							SimpleDateFormat sdf =
171 								new SimpleDateFormat("dd/MM/yyyy");
172 							reg.setString(
173 								field.getName(),
174 								sdf.format(rs.getDate(field.getName())));
175 							break;
176 
177 					}
178 				}
179 
180 				if (ok)
181 					regs.add(reg);
182 			}
183 		} catch (SQLException e) {
184 			throw new DataSourceException(
185 				"Problemas para preencher os dados da "
186 					+ " consulta: \n"
187 					+ cons,e);
188 		}
189 
190 		return regs;
191 	}
192 		
193 	/**
194 	 * M�todo que usa um adaptador de geometrias para o Oracle
195 	 * @param dataSource A fonte de dados
196 	 * @param con A conex�o
197 	 * @return O adaptador
198 	 */
199 	public GeometryAdapter getGeometryAdapter() {
200 		return OraSpatialManager.getGeometryAdapter("SDO", "8.1.6", STRUCT.class,
201 				STRUCT.class, null, dbConnection);
202 	}
203 
204 	private Collection createCollection() {
205 		return new Vector();
206 	}
207 
208 	/**
209 	 * Retorna o conjunto de fields de um ResultSetMetaData
210 	 * @param rsmd Os metadados de uma consulta
211 	 * @return Iterador com objetos do tipo field
212 	 * @throws SQLException
213 	 */
214 	public Collection loadFields(ResultSetMetaData rsmd) throws SQLException {
215 		Collection fields = new Vector();
216 		for (int i = 1; i <= rsmd.getColumnCount(); i++) {
217 			Field field = new Field();
218 			field.setName(rsmd.getColumnName(i));
219 			try {
220 				field.setNumber(i);
221 			} catch (InvalidFieldNumberException e) {
222 				e.printStackTrace();
223 			}
224 
225 			int fieldType = -1;
226 			int colType = rsmd.getColumnType(i);
227 
228 			switch (colType) {
229 
230 				case java.sql.Types.DOUBLE :
231 				case java.sql.Types.FLOAT :
232 				case java.sql.Types.DECIMAL :
233 				case java.sql.Types.NUMERIC :
234 					fieldType = igis.datasources.Types.REAL;
235 					break;
236 				case java.sql.Types.INTEGER :
237 				case java.sql.Types.SMALLINT :
238 					fieldType = igis.datasources.Types.INTEGER;
239 					break;
240 				case java.sql.Types.VARCHAR :
241 				case java.sql.Types.CHAR :
242 				case java.sql.Types.LONGVARCHAR :
243 					fieldType = igis.datasources.Types.CHARACTER;
244 					break;
245 				case java.sql.Types.DATE :
246 				case java.sql.Types.TIME :
247 				case java.sql.Types.TIMESTAMP :
248 					fieldType = igis.datasources.Types.DATE;
249 					break;
250 				case java.sql.Types.BINARY :
251 				case java.sql.Types.BLOB :
252 				case java.sql.Types.LONGVARBINARY :
253 				case java.sql.Types.VARBINARY :
254 					fieldType = igis.datasources.Types.BYTE;
255 					break;
256 				default :
257 					fieldType = igis.datasources.Types.SPATIAL;
258 					break;
259 			}
260 
261 			field.setType(fieldType);
262 
263 			fields.add(field);
264 		}
265 
266 		return fields;
267 	}
268 
269 
270 	public String toString() {
271 		return "GeometricOriginDataSource";
272 	}
273 
274 	public LogicTable getData() {
275 		return null;
276 	}
277 	
278 	public String createStringGeometry(Object geom){
279 		String strGeom = "";
280 		
281 		if (geom instanceof LineString) {
282 			strGeom = createLineString((LineString)geom);
283 		} else if(geom instanceof MultiLineString) {
284 			strGeom = createMultiLineString((MultiLineString)geom);
285 		} else if(geom instanceof Point) {
286 			strGeom = createPointString((Point)geom);
287 		} else if(geom instanceof Polygon) {
288 			strGeom = createPolygonString((Polygon)geom);
289 		} else if(geom instanceof MultiPolygon) {
290 			strGeom = createMultiPolygonString((MultiPolygon)geom);
291 		}
292 		
293 		return strGeom;
294 		
295 	}
296 
297 	/**
298 	 * @param polygon
299 	 * @return
300 	 */
301 	private String createPolygonString(Polygon geom) {
302 				
303 		String polygonStr = "";
304 		
305 		polygonStr += "MDSYS.SDO_GEOMETRY(2003, " 
306 			+ geom.getSpatialReference().getID() + ", null, MDSYS.SDO_ELEM_INFO_ARRAY(1, 1003, 1), " 
307 			+ "MDSYS.SDO_ORDINATE_ARRAY(" + printCurveStringArray(geom.getExteriorRing()) + "))";
308 		
309 		return polygonStr;
310 	}
311 	
312 	/**
313 	 * @param geom
314 	 * @return
315 	 */
316 	private String createMultiPolygonString(MultiPolygon geom) {
317 		String multiPoligonStr = "";
318 		
319 		multiPoligonStr += "MDSYS.SDO_GEOMETRY(2007, "
320 			+ geom.getSpatialReference().getID() + ", null, MDSYS.SDO_ELEM_INFO_ARRAY(";
321 
322 		Geometry [] polygons = geom.getGeometryArray();
323 		Polygon geomAux;
324 		String start = "1, ";
325 		String ordinate = "MDSYS.SDO_ORDINATE_ARRAY(";
326 		int numPoints = 1;
327 
328 		for (int currentPolygon = 0; currentPolygon < polygons.length; currentPolygon++) {
329 			multiPoligonStr += start + ETYPE_INTERPRETATION_MULTI_POLIGON;
330 			geomAux = (Polygon) polygons[currentPolygon];
331 			ordinate += printCurveStringArray(geomAux.getExteriorRing()) + ", ";
332 			numPoints += (geomAux.getExteriorRing().getNumPoints() * 2);
333 			start = (numPoints) + ", ";
334 		}
335 
336 		multiPoligonStr = multiPoligonStr.substring(0, multiPoligonStr.length() - 2);
337 		multiPoligonStr += "), ";
338 		ordinate = ordinate.substring(0, ordinate.length()-2);
339 		ordinate += ")";
340 		multiPoligonStr += ordinate + ")";
341 		return multiPoligonStr;
342 	}
343 
344 	/**
345 	 * @param geom
346 	 * @return
347 	 */
348 	private String createLineString(LineString geom) {
349 		String lineStr = "";
350 		
351 		lineStr += "MDSYS.SDO_GEOMETRY(2002, " 
352 			+ geom.getSpatialReference().getID() + ", null, MDSYS.SDO_ELEM_INFO_ARRAY(1, 2, 1), " 
353 			+ "MDSYS.SDO_ORDINATE_ARRAY(" + printCoordArray(geom.getCoordArray()) + "))";
354 		
355 		return lineStr;
356 	}
357 	
358 	/**
359 	 * @param geom
360 	 * @return
361 	 */
362 	private String createMultiLineString(MultiLineString geom) {
363 		String lineStr = "";
364 		
365 		lineStr += "MDSYS.SDO_GEOMETRY(2006, " 
366 			+ geom.getSpatialReference().getID() + ", null, MDSYS.SDO_ELEM_INFO_ARRAY(";
367 
368 		Geometry [] lines = geom.getGeometryArray();
369 		LineString geomAux;
370 		String start = "1, ";
371 		String ordinate = "MDSYS.SDO_ORDINATE_ARRAY(";
372 		int numPoints = 1;
373 
374 		for (int currentLine = 0; currentLine < lines.length; currentLine++) {
375 			lineStr += start + ETYPE_INTERPRETATION;
376 			geomAux = (LineString) lines[currentLine];
377 			ordinate += printCoordArray(geomAux.getCoordArray()) + ", ";
378 			numPoints += (geomAux.getNumPoints() * 2);
379 			start = (numPoints) + ", ";
380 		}
381 
382 		lineStr = lineStr.substring(0, lineStr.length()-2);
383 		lineStr += "), ";
384 		ordinate = ordinate.substring(0, ordinate.length()-2);
385 		ordinate += ")";
386 		lineStr += ordinate + ")";
387 		return lineStr;
388 	}
389 	
390 	private String createPointString(Point geom) {
391 		String pointStr = "";
392 		
393 		pointStr += "MDSYS.SDO_GEOMETRY(2001, " 
394 			+ geom.getSpatialReference().getID() + ", MDSYS.SDO_POINT_TYPE("
395 			+ geom.getX() + ", " + geom.getY() + ", null), null, null)";
396 		
397 		return pointStr; 
398 	}
399 
400 	/**
401 	 * @param coordArray
402 	 * @return
403 	 */
404 	private String printCoordArray(double[] coordArray) {
405 		String arrayStr = "";
406 		for (int curentPoint = 0; curentPoint < coordArray.length; curentPoint++) {
407 			arrayStr += coordArray[curentPoint] + ", ";
408 		}		
409 		arrayStr = arrayStr.substring(0,arrayStr.length()-2);
410 		return arrayStr;
411 	}
412 	
413 	/**
414 	 * @param coordArray
415 	 * @return
416 	 */
417 	private String printCurveStringArray(CurveString curve) {
418 		return printCoordArray(((LineString)curve).getCoordArray());
419 	}
420 }