Revision 31889

View differences:

branches/v2_0_0_prep/extensions/org.gvsig.oracle/src/org/gvsig/fmap/dal/store/oracle/OracleSetProvider.java
54 54
	 */
55 55
	public boolean canFilter() {
56 56
		// TODO more checks
57
		if (!super.canFilter()) {
58
			return false;
59
		}
60
		return true;
57
		// return true;
58
		return false;
61 59

  
62 60
	}
63 61

  
branches/v2_0_0_prep/extensions/org.gvsig.oracle/src/org/gvsig/fmap/dal/store/oracle/OracleServerExplorer.java
58 58
import org.gvsig.fmap.dal.store.jdbc.TransactionalAction;
59 59
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
60 60
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
61
import org.gvsig.fmap.geom.primitive.Envelope;
62
import org.gvsig.oracle.extension.ExportToOracle;
61 63
import org.slf4j.Logger;
62 64
import org.slf4j.LoggerFactory;
63 65

  
......
377 379
			throw new RuntimeException(e);
378 380
		}
379 381

  
380
		return result.booleanValue();	}
381
	/**
382
	 * create new table
383
	 * 
384
	 * @params ndsp
385
	 * @params overwrite
386
	 * @return
387
	 */
388
	public boolean add(NewDataStoreParameters ndsp, boolean overwrite)
389
			throws DataException {
382
		return result.booleanValue();
383
	}
384
	
385
	public void addWithEnvelopeAndDims(NewFeatureStoreParameters params, boolean b,
386
			Rectangle2D envelope, int thedims) throws DataException {
387
		
388
		String sql_create = add_SqlCreate(params, b);
389
		String sql_index = add_SqlIndex(params, b);
390
		String sql_meta = add_SqlMeta(params, b, envelope, new Integer(thedims));
391
		doAdd(sql_create, sql_index, sql_meta);
392
	}
390 393

  
391
		if (!(ndsp instanceof NewFeatureStoreParameters)) {
392
			throw new IllegalArgumentException();
393
		}
394
		this.checkIsMine(ndsp);
395

  
396
		NewFeatureStoreParameters nfdsp = (NewFeatureStoreParameters) ndsp;
397

  
398
		// SQL CREATE NEW TABLE
399
		StringBuilder sqlnewtable = new StringBuilder();
400

  
401
		if (!nfdsp.isValid()) {
402
			throw new InitializeException(this.getName(), new Exception(
403
					"Parameters not valid"));
404
		}
405
		try {
406
			nfdsp.validate();
407
		} catch (ValidateDataParametersException e1) {
408
			throw new InitializeException(this.getName(), e1);
409
		}
410

  
411
		FeatureType fType = nfdsp.getDefaultFeatureType();
412

  
413
		sqlnewtable.append("CREATE TABLE "
414
				+ ((JDBCStoreParameters) ndsp).tableID() + "(");
415
		Iterator<FeatureAttributeDescriptor> attrs = fType.iterator();
416
		String sqlAttr;
417
		List<String> sqlAttrs = new ArrayList<String>();
418

  
419
		while (attrs.hasNext()) {
420
			sqlAttr = helper
421
					.getSqlFieldDescription((FeatureAttributeDescriptor) attrs
422
							.next());
423
			if (sqlAttr != null) {
424
				sqlAttrs.add(sqlAttr);
425
			}
426
		}
427

  
428
		helper.stringJoin(sqlAttrs, ", ", sqlnewtable);
429

  
430
		String pk = "CONSTRAINT "
431
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) ndsp)
432
						.tableID(), "PK") + " PRIMARY KEY (\""
433
				+ OracleValues.DEFAULT_ID_FIELD_CASE_SENSITIVE + "\") ENABLE";
434

  
435
		sqlnewtable.append(", ");
436
		sqlnewtable.append(pk);
437

  
438
		sqlnewtable.append(")");
439
		final String sqlCreateNew = sqlnewtable.toString();
440

  
441
		// SQL CREATE SPATIAL INDEX
442
		final String sqlindex = "CREATE INDEX "
443
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) ndsp)
444
						.tableID(), "SX") + " ON "
445
				+ ((JDBCStoreParameters) ndsp).tableID() + " (\""
446
				+ OracleValues.DEFAULT_GEO_FIELD
447
				+ "\") INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\" ";
448

  
449
		// SQL CREATE TABLE METADATA
450
		Rectangle2D bbox = new Rectangle2D.Double(0, 0, 1, 1);
451
		final String sqlmeta = ((OracleHelper) helper).getSqlUpdateMetadata(
452
				(OracleStoreParameters) ndsp, null, bbox, 2, true);
453

  
394
	private boolean doAdd(final String sql_create, final String sql_index, final String sql_meta) {
395
		
454 396
		TransactionalAction action = new TransactionalAction() {
455 397

  
456 398
			public boolean continueTransactionAllowed() {
......
471 413

  
472 414
				// new table
473 415
				try {
474
					sqlnew = sqlCreateNew;
416
					sqlnew = sql_create;
475 417
					st.execute(sqlnew);
476 418

  
477 419
				} catch (SQLException e) {
......
480 422
				}
481 423
				// new metadata
482 424
				try {
483
					sqlmetadata = sqlmeta;
425
					sqlmetadata = sql_meta;
484 426
					st.execute(sqlmetadata);
485 427
				} catch (SQLException e) {
486 428
					try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
......
488 430
				}
489 431
				// new spatial index
490 432
				try {
491
					sqlspatialindex = sqlindex;
433
					sqlspatialindex = sql_index;
492 434
					st.execute(sqlspatialindex);
493 435

  
494 436
				} catch (SQLException e) {
......
512 454
		return result.booleanValue();
513 455
	}
514 456

  
457
	private String add_SqlMeta(NewFeatureStoreParameters params, boolean b,
458
			Rectangle2D bbox, Integer thedims) {
459

  
460
		// SQL CREATE TABLE METADATA
461
		Rectangle2D _bbox = bbox;
462
		if (_bbox == null) {
463
			logger.warn("Envelope not found in parameters: set (0,0) - (1,1)");
464
			_bbox = OracleUtils.DEFAULT_BBOX;
465
		}
466
		
467
		int _dims = 2;
468
		if (thedims == null) {
469
			logger.warn("Dimensions not found in parameters: assumed 2");
470
		} else {
471
			_dims = thedims.intValue();
472
		}
473

  
474
		String sqlmeta = ((OracleHelper) helper).getSqlUpdateMetadata(
475
				(OracleStoreParameters) params, null, _bbox, _dims, true);
476
		// TODO Auto-generated method stub
477
		return sqlmeta;
478
	}
479

  
480
	private String add_SqlIndex(NewFeatureStoreParameters params, boolean b) {
481
		
482
		// SQL CREATE SPATIAL INDEX
483
		String sqlindex = "CREATE INDEX "
484
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) params)
485
						.tableID(), "SX") + " ON "
486
				+ ((JDBCStoreParameters) params).tableID() + " (\""
487
				+ OracleValues.DEFAULT_GEO_FIELD
488
				+ "\") INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\" ";
489
		return sqlindex;
490
	}
491

  
492
	private String add_SqlCreate(NewFeatureStoreParameters nfdsp, boolean b) throws DataException {
493

  
494
		// SQL CREATE NEW TABLE
495
		StringBuilder sqlnewtable = new StringBuilder();
496

  
497
		FeatureType fType = nfdsp.getDefaultFeatureType();
498

  
499
		sqlnewtable.append("CREATE TABLE "
500
				+ ((JDBCStoreParameters) nfdsp).tableID() + "(");
501
		Iterator<FeatureAttributeDescriptor> attrs = fType.iterator();
502
		String sqlAttr;
503
		List<String> sqlAttrs = new ArrayList<String>();
504

  
505
		while (attrs.hasNext()) {
506
			sqlAttr = helper
507
					.getSqlFieldDescription((FeatureAttributeDescriptor) attrs
508
							.next());
509
			if (sqlAttr != null) {
510
				sqlAttrs.add(sqlAttr);
511
			}
512
		}
513

  
514
		helper.stringJoin(sqlAttrs, ", ", sqlnewtable);
515

  
516
		String pk = "CONSTRAINT "
517
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) nfdsp)
518
						.tableID(), "PK") + " PRIMARY KEY (\""
519
				+ OracleValues.DEFAULT_ID_FIELD_CASE_SENSITIVE + "\") ENABLE";
520

  
521
		sqlnewtable.append(", ");
522
		sqlnewtable.append(pk);
523

  
524
		sqlnewtable.append(")");
525
		return sqlnewtable.toString();		
526

  
527
	}
528

  
515 529
	/**
530
	 * create new table
531
	 * 
532
	 * @params ndsp
533
	 * @params overwrite
534
	 * @return
535
	 */
536
	public boolean add(NewDataStoreParameters ndsp, boolean overwrite)
537
			throws DataException {
538

  
539
		if (!(ndsp instanceof NewFeatureStoreParameters)) {
540
			throw new IllegalArgumentException("Expected: NewFeatureStoreParameters");
541
		}
542
		
543
		checkIsMine(ndsp);
544
		NewFeatureStoreParameters nfdsp = (NewFeatureStoreParameters) ndsp;
545

  
546
		if (!nfdsp.isValid()) {
547
			throw new InitializeException(this.getName(), new Exception(
548
					"Parameters not valid"));
549
		}
550
		try {
551
			nfdsp.validate();
552
		} catch (ValidateDataParametersException e1) {
553
			throw new InitializeException(this.getName(), e1);
554
		}
555

  
556
		String sql_create = add_SqlCreate(nfdsp, overwrite);
557
		String sql_index = add_SqlIndex(nfdsp, overwrite);
558
		String sql_meta = add_SqlMeta(nfdsp, overwrite, null, null);
559
		return doAdd(sql_create, sql_index, sql_meta);
560
	}
561

  
562
	/**
516 563
	 * create helper
517 564
	 */
518 565
	protected JDBCHelper createHelper() throws InitializeException {
......
601 648
	private OracleServerExplorerParameters getOracleServerExplorerParameters() {
602 649
		return (OracleServerExplorerParameters) getParameters();
603 650
	}
604

  
651
	
605 652
}
branches/v2_0_0_prep/extensions/org.gvsig.oracle/src/org/gvsig/fmap/dal/store/oracle/OracleStoreProvider.java
27 27

  
28 28
package org.gvsig.fmap.dal.store.oracle;
29 29

  
30
import java.sql.ResultSet;
31
import java.sql.SQLException;
30 32
import java.util.ArrayList;
31 33
import java.util.List;
32 34
import java.util.regex.Matcher;
......
34 36

  
35 37
import oracle.sql.STRUCT;
36 38

  
39
import org.cresques.cts.IProjection;
37 40
import org.gvsig.fmap.dal.DALLocator;
38 41
import org.gvsig.fmap.dal.DataManager;
39 42
import org.gvsig.fmap.dal.DataServerExplorer;
......
51 54
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
52 55
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
53 56
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreProviderWriter;
57
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
54 58
import org.gvsig.fmap.geom.Geometry;
55 59
import org.gvsig.tools.ToolsLocator;
56 60
import org.gvsig.tools.dynobject.DynClass;
57 61
import org.gvsig.tools.dynobject.DynObjectManager;
62
import org.gvsig.tools.exception.BaseException;
58 63
import org.slf4j.Logger;
59 64
import org.slf4j.LoggerFactory;
60 65

  
......
102 107
	protected String fixFilter(String filter) {
103 108
		if (filter == null) {
104 109
			return null;
110
		} else {
111
			throw new RuntimeException("Not implemented: fixFilter in OracleStoreProvider. Input was: " + filter);
105 112
		}
106

  
107
		// Transform SRS to code
108
		// GeomFromText\s*\(\s*'[^']*'\s*,\s*('[^']*')\s*\)
109
		Pattern pattern = Pattern
110
				.compile("GeomFromText\\s*\\(\\s*'[^']*'\\s*,\\s*'([^']*)'\\s*\\)");
111
		Matcher matcher = pattern.matcher(filter);
112
		StringBuilder strb = new StringBuilder();
113
		int pos = 0;
114
		String srsCode;
115
		while (matcher.find(pos)) {
116
			strb.append(filter.substring(pos, matcher.start(1)));
117
			srsCode = matcher.group(1).trim();
118
			if (srsCode.startsWith("'")) {
119
				srsCode = srsCode.substring(1);
120
			}
121
			if (srsCode.endsWith("'")) {
122
				srsCode = srsCode.substring(0, srsCode.length() - 1);
123
			}
124
			strb.append(helper.getProviderSRID(srsCode));
125
			strb.append(filter.substring(matcher.end(1), matcher.end()));
126
			pos = matcher.end();
127

  
128
		}
129
		strb.append(filter.substring(pos));
130

  
131
		return strb.toString();
132 113
	}
133 114

  
134 115
	public String getName() {
......
360 341

  
361 342
		return strb.toString();
362 343
	}
344
	
345
	
346
	protected void loadFeatureProviderValue(FeatureProvider data, ResultSet rs,
347
			FeatureAttributeDescriptor attr) throws DataException {
348
		if (attr.getDataType() == DataTypes.GEOMETRY) {
363 349

  
350
			try {
351
				Object geo_str_obj = rs.getObject(attr.getIndex() + 1);
352
				if (geo_str_obj == null) {
353
					data.set(attr.getIndex(), null);
354
				} else {
355
					STRUCT geo_str = (STRUCT) geo_str_obj;
356
					
357
					IProjection proj = attr.getSRS();
358
					// OracleUtils.
359
					
360
					Geometry geom = OracleUtils.getGeometry(
361
							geo_str,
362
							false,
363
							true,
364
							"88888",
365
							helper.getConnection());
366
					data.set(attr.getIndex(), geom);
367
				}
368
			} catch (SQLException e) {
369
				throw new JDBCSQLException(e);
370
			} catch (BaseException e) {
371
				throw new ReadException(getName(), e);
372
			}
373

  
374
		} else {
375
			try {
376
				data.set(attr.getIndex(), rs.getObject(attr.getIndex() + 1));
377
			} catch (SQLException e) {
378
				throw new JDBCSQLException(e);
379
			}
380
		}
381
	}
382

  
364 383
}
branches/v2_0_0_prep/extensions/org.gvsig.oracle/src/org/gvsig/fmap/dal/store/oracle/OracleHelper.java
34 34
import java.sql.SQLException;
35 35
import java.sql.Statement;
36 36
import java.util.ArrayList;
37
import java.util.Arrays;
37 38
import java.util.Iterator;
38 39
import java.util.List;
39 40

  
......
41 42
import oracle.sql.Datum;
42 43
import oracle.sql.STRUCT;
43 44

  
44
import org.apache.commons.dbcp.DelegatingConnection;
45
import org.apache.commons.dbcp.PoolingDataSource;
46 45
import org.cresques.cts.IProjection;
47 46
import org.gvsig.fmap.crs.CRSFactory;
48 47
import org.gvsig.fmap.dal.DALLocator;
......
58 57
import org.gvsig.fmap.dal.feature.FeatureQuery;
59 58
import org.gvsig.fmap.dal.feature.FeatureSet;
60 59
import org.gvsig.fmap.dal.feature.FeatureStore;
60
import org.gvsig.fmap.dal.feature.FeatureType;
61 61
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
62 62
import org.gvsig.fmap.dal.feature.exception.UnsupportedGeometryException;
63
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
63
import org.gvsig.fmap.dal.feature.impl.DefaultEditableFeatureAttributeDescriptor;
64
import org.gvsig.fmap.dal.feature.impl.DefaultEditableFeatureType;
65
import org.gvsig.fmap.dal.feature.impl.DefaultFeatureType;
64 66
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
65 67
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
66 68
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
......
69 71
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
70 72
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
71 73
import org.gvsig.fmap.geom.Geometry;
72
import org.gvsig.fmap.geom.GeometryLocator;
74
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
75
import org.gvsig.fmap.geom.Geometry.TYPES;
73 76
import org.gvsig.fmap.geom.primitive.Envelope;
74 77
import org.gvsig.fmap.geom.primitive.Point;
75 78
import org.gvsig.fmap.geom.primitive.impl.Envelope2D;
......
87 90
 */
88 91
public class OracleHelper extends JDBCHelper {
89 92

  
90
	private static final double ORACLE_SPATIAL_DEFAULT_TOLERANCE = 0.0005;;
93
	private static final double ORACLE_SPATIAL_DEFAULT_TOLERANCE = 0.0005;
91 94

  
95
	private static final String IDENTIFIER_QUOTE_STRING = "\"";
96

  
92 97
	private static Logger logger = LoggerFactory.getLogger(OracleHelper.class);
93 98

  
94 99
	private boolean tableHasSrid = true;
......
449 454
	}
450 455

  
451 456
	/**
452
	 * Get oracle srid from srs code(EPSG code)
453 457
	 * 
454
	 * @param epsg
455
	 * @return oraSRID
456 458
	 */
457
	public int getProviderSRID(String epsg) {
458

  
459
		DataManager manager = DALLocator.getDataManager();
460
		Integer isrs = null;
461
		if (epsg != null) {
462
			FeatureStore oraSrsStore = (FeatureStore) OracleLibrary
463
					.getSRSDataStore();
464

  
465
			FeatureSet set = null;
466
			try {
467
				FeatureQuery query = oraSrsStore.createFeatureQuery();
468
				query.setFilter(manager.createExpresion("EPSG = " + epsg));
469
				set = (FeatureSet) oraSrsStore.getDataSet(query);
470
				if (set.getSize() > 0) {
471
					Iterator<Feature> it = set.iterator();
472
					while (it.hasNext()) {
473
						Feature feat = it.next();
474
						Double ora = feat.getDouble("ORACLE");
475
						int iora = ora.intValue();
476
						double prefe = feat.getDouble("PRF_ORACLE");
477
						if (prefe == 1) {
478
							isrs = new Integer(iora);
479
							break;
480
						}
481
					}
482
				}
483
			} catch (DataException e) {
484
				e.printStackTrace();
485
			}
486
			if (isrs != null) {
487
				return isrs;
488
			}
489
		}
490
		return -1;
491
	}
492

  
493
	/**
494
	 * Get EPSG SRS from Oracle SRS
495
	 * 
496
	 * @param oraSRID
497
	 * @return
498
	 */
499
	public int getProviderEPSG(String oraSRID) {
500

  
501
		DataManager manager = DALLocator.getDataManager();
502
		Integer isrs = null;
503
		if (oraSRID != null) {
504
			FeatureStore oraSrsStore = (FeatureStore) OracleLibrary
505
					.getSRSDataStore();
506

  
507
			FeatureSet set = null;
508
			try {
509
				FeatureQuery query = oraSrsStore.createFeatureQuery();
510
				query.setFilter(manager.createExpresion("ORACLE = " + oraSRID));
511
				set = (FeatureSet) oraSrsStore.getDataSet(query);
512
				if (set.getSize() > 0) {
513
					Iterator<Feature> it = set.iterator();
514
					while (it.hasNext()) {
515
						Feature feat = it.next();
516
						Double ora = feat.getDouble("EPSG");
517
						int iora = ora.intValue();
518
						isrs = new Integer(iora);
519
					}
520
				}
521
			} catch (DataException e) {
522
				e.printStackTrace();
523
			}
524
			if (isrs != null) {
525
				return isrs;
526
			}
527
		}
528
		return -1;
529
	}
530

  
531
	/**
532
	 * Get Oracle SRS from gvSIG projection
533
	 * 
534
	 * @param proj
535
	 * @return
536
	 */
537
	public int getProviderSRID(IProjection proj) {
538
		if (proj != null) {
539
			String epsg = proj.getAbrev().trim();
540
			int ocu = epsg.indexOf(":");
541
			if (ocu != -1) {
542
				epsg = epsg.substring(ocu + 1);
543
			}
544
			Integer oraSRID = getProviderSRID(epsg);
545
			if (oraSRID != null) {
546
				return oraSRID.intValue();
547
			}
548
		}
549
		return -1;
550
	}
551

  
552
	/**
553
	 * 
554
	 */
555 459
	public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
556
		// TODO
460
		/*
557 461
		if (attribute.getDataType() == DataTypes.GEOMETRY) {
558 462
			return "asBinary(" + super.getSqlFieldName(attribute) + ")";
559 463
		}
464
		*/
560 465
		return super.getSqlFieldName(attribute);
561 466
	}
467
	
468
	protected String getIdentifierQuoteString() {
469
		return IDENTIFIER_QUOTE_STRING;
470
	}
562 471

  
563 472
	/**
564 473
	 * 
......
799 708
	public void loadFeatureType(EditableFeatureType featureType,
800 709
			JDBCStoreParameters storeParams) throws DataException {
801 710
		
711
		if ((storeParams.getDefaultGeometry() == null) && (storeParams instanceof OracleNewStoreParameters)) {
712
			OracleNewStoreParameters osp = (OracleNewStoreParameters) storeParams;
713
			String geoname = osp.getDefaultFeatureType().getDefaultGeometryAttributeName();
714
			storeParams.setDefaultGeometry(geoname);
715
		}
716

  
802 717
		String sqlstr = storeParams.getSQL();
803 718
		
804 719
		if (sqlstr != null && sqlstr.trim().length() > 0) {
......
810 725
		
811 726
		loadFeatureType(featureType, storeParams, sqlstr, storeParams
812 727
				.getSchema(), storeParams.getTable());
728
		
729
		storeParams.setSQL(null);
813 730
		// super.loadFeatureType(featureType, storeParams);
814 731
	}
815 732

  
......
828 745

  
829 746
		Statement st = null;
830 747
		ResultSet rs = null;
748
		String reserved_geocolname = null;
749
		
831 750
		try {
832 751
			// Sacamos la lista de los attributos geometricos
833 752

  
834 753
			EditableFeatureAttributeDescriptor attr;
835
			List<FeatureAttributeDescriptor> geoAttrs = new ArrayList<FeatureAttributeDescriptor>();
754
			ArrayList geoAttrs = new ArrayList();
836 755

  
837 756
			Iterator iter = featureType.iterator();
838 757
			while (iter.hasNext()) {
......
861 780
			}
862 781
			String srID;
863 782

  
864
			Iterator it = geoAttrs.iterator();
783
			EditableFeatureAttributeDescriptor auxdesc;
784
			
865 785

  
866
			while (it.hasNext()) {
867
				attr = (EditableFeatureAttributeDescriptor) it.next();
868
				String fieldName = attr.getName();
869 786
				while (rs.next()) {
870
					String rsName = rs
871
							.getString(OracleValues.USER_ORACLE_GEOMETADATA_VIEW_COLUMN_NAME);
872
					if (fieldName.compareTo(rsName) == 0) {
787
					String rsName =
788
						rs.getString(OracleValues.USER_ORACLE_GEOMETADATA_VIEW_COLUMN_NAME);
789
					reserved_geocolname = rsName;
790
					auxdesc = getAttrDescForCol(geoAttrs, rsName);
791
					if (auxdesc != null) {
873 792
						Object sridobj = rs.getObject("SRID");
874
						
875 793
						if (sridobj == null) {
876
							attr.setSRS(null);
794
							auxdesc.setSRS(null);
877 795
						} else {
878 796
							srID = (String) sridobj;
879
							int epsg = this.getProviderEPSG(srID);
797
							int epsg = OracleUtils.oracleSridToEpsg(srID);
880 798
							String sepsg = "EPSG:" + Integer.toString(epsg);
881
							attr.setSRS(CRSFactory.getCRS(sepsg));
799
							auxdesc.setSRS(CRSFactory.getCRS(sepsg));
882 800
						}
883
						break;
884
					} else {
885
						continue;
886 801
					}
887
				}
802
					if (featureType.getDefaultGeometryAttribute() == null) {
803
						((DefaultEditableFeatureType) featureType).setDefaultGeometryAttributeName(reserved_geocolname);
804
					}
805
					
806
			}
807
		} catch (java.sql.SQLException e) {
808
			throw new JDBCSQLException(e);
809
		} finally {
810
			try { rs.close(); } catch (Exception e) { };
811
			try { st.close(); } catch (Exception e) { };
812
		}
813
		
814
		// guess shape type
815
		String geoColName = featureType.getDefaultGeometryAttributeName();
816
		if (geoColName == null) {
817
			geoColName = reserved_geocolname; 
818
		}
819
		
820
		try {
821
			String str_geo = "SELECT " + geoColName + " FROM " + baseTable +
822
			" WHERE (" + geoColName + " IS NOT NULL) AND " + OracleUtils.EXPONENTIAL_INDICES_CONDITION; 
888 823

  
824
			st = conn.createStatement();
825
			try {
826
				rs = st.executeQuery(str_geo);
827
			} catch (SQLException e) {
828
				throw new JDBCExecuteSQLException(str_geo, e);
889 829
			}
830
			
831
            int aux = 0;
832
            int guess_type = TYPES.GEOMETRY;
833
            int guess_subtype = SUBTYPES.GEOM2D;
834
            
835
            STRUCT sample_geo;
836
            ArrayList shptypes = new ArrayList();
837
            int[] ty_subty;
838
            while (rs.next()) {
839
                sample_geo = (STRUCT) rs.getObject(1);
840
                ty_subty = OracleUtils.getGeoTypeSubTypeOfStruct(sample_geo); 
841
                aux = ty_subty[0];
842
                guess_subtype = ty_subty[1];
843
                shptypes.add(new Integer(aux));
844
            }
890 845

  
846
            if (shptypes.size() > 0) {
847
            	guess_type = OracleUtils.getShapeTypeFromArray(shptypes);
848
            } else {
849
            	logger.warn("Did not find geometries to sample. Assumed TYPE = GEOMETRY, SUBTYPE = 2D");
850
            }
851

  
852
            DefaultEditableFeatureAttributeDescriptor dfad = null;
853
            try {
854
                dfad = (DefaultEditableFeatureAttributeDescriptor) featureType.getDefaultGeometryAttribute();
855
                dfad.setGeometryType(guess_type);
856
                dfad.setGeometrySubType(guess_subtype);
857
            } catch (ClassCastException cce) {
858
            	logger.error("Unexpected non editable feature type. Did not set geo types.");
859
            }
891 860
		} catch (java.sql.SQLException e) {
892 861
			throw new JDBCSQLException(e);
893 862
		} finally {
894
			try {
895
				rs.close();
896
			} catch (Exception e) {
863
			try {rs.close();} catch (Exception e) {	};
864
			try {st.close();} catch (Exception e) { };
865
		}
866
	}
867

  
868
	private EditableFeatureAttributeDescriptor getAttrDescForCol(ArrayList list, String name) {
869
		
870
		int sz = list.size();
871
		for (int i=0; i<sz; i++) {
872
			EditableFeatureAttributeDescriptor aux = (EditableFeatureAttributeDescriptor) list.get(i);
873
			if (aux.getName().compareToIgnoreCase(name) == 0) {
874
				return aux;
897 875
			}
898
			;
899
			try {
900
				st.close();
901
			} catch (Exception e) {
902
			}
903
			;
904 876
		}
905

  
877
		// not found
878
		return null;
906 879
	}
907 880

  
908 881
	/**
......
940 913

  
941 914
		return sqls;
942 915
	}
916
	
917
	
918
	
919
//	protected void loadFeatureType(Connection conn,
920
//			EditableFeatureType featureType, String sql, String[] pks,
921
//			String defGeomName, String schema, String table)
922
//			throws DataException {
923
//
924
//		Statement stAux = null;
925
//		ResultSet rs = null;
926
//		try {
927
//
928
//			stAux = conn.createStatement();
929
//			stAux.setFetchSize(1);
930
//
931
//			try {
932
//				rs = stAux.executeQuery(sql);
933
//			} catch (SQLException e) {
934
//				throw new JDBCExecuteSQLException(sql, e);
935
//			}
936
//			ResultSetMetaData rsMetadata = rs.getMetaData();
937
//
938
//			List pksList = null;
939
//			if (pks != null) {
940
//				pksList = Arrays.asList(pks);
941
//			}
942
//
943
//			int i;
944
//			int geometriesColumns = 0;
945
//			String lastGeometry = null;
946
//
947
//			EditableFeatureAttributeDescriptor attr;
948
//			for (i = 1; i <= rsMetadata.getColumnCount(); i++) {
949
//				attr = getAttributeFromJDBC(featureType, conn, rsMetadata, i);
950
//				if (pksList != null && pksList.contains(attr.getName())) {
951
//					attr.setIsPrimaryKey(true);
952
//				}
953
//				if (attr.getDataType() == DataTypes.GEOMETRY) {
954
//					geometriesColumns++;
955
//					lastGeometry = attr.getName();
956
//					if (lastGeometry.equals(defGeomName)) {
957
//						featureType.setDefaultGeometryAttributeName(defGeomName);
958
//					}
959
//				}
960
//			}
961
//
962
//			if (geometriesColumns > 0) {
963
//				loadSRS_and_shapeType(conn, rsMetadata, featureType, schema,
964
//						table);
965
//			}
966
//
967
//			if (defGeomName == null && geometriesColumns == 1) {
968
//				featureType.setDefaultGeometryAttributeName(lastGeometry);
969
//				defGeomName = lastGeometry;
970
//			}
971
//
972
//		} catch (java.sql.SQLException e) {
973
//			throw new JDBCSQLException(e); // FIXME exception
974
//		} finally {
975
//			try {
976
//				rs.close();
977
//			} catch (Exception e) {
978
//			}
979
//			try {
980
//				stAux.close();
981
//			} catch (Exception e) {
982
//			}
983
//
984
//		}
985
//
986
//	}
943 987

  
944 988

  
945 989
}
branches/v2_0_0_prep/extensions/org.gvsig.oracle/src/org/gvsig/fmap/dal/store/oracle/OracleUtils.java
56 56
import oracle.sql.StructDescriptor;
57 57

  
58 58
import org.apache.log4j.Logger;
59
import org.cresques.cts.IProjection;
60
import org.geotools.xml.filter.FilterOpsComplexTypes.UpperBoundaryType;
61
import org.gvsig.fmap.dal.DALLocator;
62
import org.gvsig.fmap.dal.DataManager;
63
import org.gvsig.fmap.dal.exception.DataException;
64
import org.gvsig.fmap.dal.feature.EditableFeatureType;
65
import org.gvsig.fmap.dal.feature.Feature;
66
import org.gvsig.fmap.dal.feature.FeatureQuery;
67
import org.gvsig.fmap.dal.feature.FeatureSet;
68
import org.gvsig.fmap.dal.feature.FeatureStore;
59 69
import org.gvsig.fmap.geom.Geometry;
60 70
import org.gvsig.fmap.geom.GeometryLocator;
61 71
import org.gvsig.fmap.geom.GeometryManager;
72
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
73
import org.gvsig.fmap.geom.Geometry.TYPES;
74
import org.gvsig.fmap.geom.aggregate.MultiPrimitive;
62 75
import org.gvsig.fmap.geom.aggregate.impl.MultiPoint2D;
63 76
import org.gvsig.fmap.geom.aggregate.impl.MultiPoint2DZ;
64 77
import org.gvsig.fmap.geom.complex.Complex;
......
66 79
import org.gvsig.fmap.geom.primitive.Curve;
67 80
import org.gvsig.fmap.geom.primitive.GeneralPathX;
68 81
import org.gvsig.fmap.geom.primitive.Point;
82
import org.gvsig.fmap.geom.primitive.Primitive;
69 83
import org.gvsig.fmap.geom.primitive.Surface;
70 84
import org.gvsig.fmap.geom.primitive.impl.Circle2D;
71 85
import org.gvsig.fmap.geom.primitive.impl.Curve2DZ;
......
95 109
	private static double FLATNESS = 0.8;
96 110
	private static GeometryFactory geomFactory = new GeometryFactory();
97 111
	private static final double IRRELEVANT_DISTANCE = 0.00000001;
112
	public static final Rectangle2D DEFAULT_BBOX = new Rectangle2D.Double(-180, -90, 360, 180);;
98 113
	private static Random rnd = new Random();
99 114
	private static DecimalFormat df = new DecimalFormat();
100 115
	private static DecimalFormatSymbols dfs = new DecimalFormatSymbols();
116
	
117
	public static final String ENVELOPE_ID = "Envelope_Key";
118
	public static final String DIMENSIONS_ID = "Dimensions_Key";
101 119

  
120

  
102 121
	/**
103 122
	 * COnstructs a geometry from a file that contains a vertex per line:
104 123
	 * 
......
2396 2415
		return resp;
2397 2416
	}
2398 2417
	
2399
	/**
2400
	 * 
2401
	 * @param oGeom
2402
	 * @return
2403
	 */
2404
	public static int[] getGeometryTypeAndSubtypeFromOracleGeom(int oGeom){
2405
		
2406
		int[] gTypes = new int[2];
2407
		
2408
		int type = oGeom % 10;
2409
		int subtype = oGeom / 1000;
2410
		// type 0
2411
		if(type == OracleValues.ORACLE_GTYPE_UNKNOWN){
2412
			gTypes[0] = Geometry.TYPES.GEOMETRY;
2413
			if(subtype == 2){
2414
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2415
			}else if(subtype == 3){
2416
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2417
			}else{
2418
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2419
			}
2420
		}
2421
		// type 1
2422
		else if(type == OracleValues.ORACLE_GTYPE_POINT){
2423
			gTypes[0] = Geometry.TYPES.POINT;
2424
			if(subtype == 2){
2425
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2426
			}else if(subtype == 3){
2427
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2428
			}else{
2429
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2430
			}
2431
		}
2432
		// type 2
2433
		else if(type == OracleValues.ORACLE_GTYPE_LINE){
2434
			gTypes[0] = Geometry.TYPES.CURVE;
2435
			if(subtype == 2){
2436
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2437
			}else if(subtype == 3){
2438
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2439
			}else{
2440
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2441
			}
2442
		}
2443
		// type 3
2444
		else if(type == OracleValues.ORACLE_GTYPE_POLYGON){
2445
			gTypes[0] = Geometry.TYPES.SURFACE;
2446
			if(subtype == 2){
2447
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2448
			}else if(subtype == 3){
2449
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2450
			}else{
2451
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2452
			}
2453
		}
2454
		// type 4
2455
		else if(type == OracleValues.ORACLE_GTYPE_COLLECTION){
2456
			gTypes[0] = Geometry.TYPES.AGGREGATE;
2457
			if(subtype == 2){
2458
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2459
			}else if(subtype == 3){
2460
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2461
			}else{
2462
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2463
			}
2464
		}
2465
		// type 5
2466
		else if(type == OracleValues.ORACLE_GTYPE_MULTIPOINT){
2467
			gTypes[0] = Geometry.TYPES.MULTIPOINT;
2468
			if(subtype == 2){
2469
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2470
			}else if(subtype == 3){
2471
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2472
			}else{
2473
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2474
			}
2475
		}
2476
		// type 6
2477
		else if(type == OracleValues.ORACLE_GTYPE_MULTILINE){
2478
			gTypes[0] = Geometry.TYPES.MULTICURVE;
2479
			if(subtype == 2){
2480
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2481
			}else if(subtype == 3){
2482
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2483
			}else{
2484
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2485
			}
2486
		}
2487
		// type 7
2488
		else if(type == OracleValues.ORACLE_GTYPE_MULTIPOLYGON){
2489
			gTypes[0] = Geometry.TYPES.MULTISURFACE;
2490
			if(subtype == 2){
2491
				gTypes[1] = Geometry.SUBTYPES.GEOM2D;
2492
			}else if(subtype == 3){
2493
				gTypes[1] = Geometry.SUBTYPES.GEOM2DZ;
2494
			}else{
2495
				gTypes[1] = Geometry.SUBTYPES.GEOM3DM;
2496
			}
2497
		}
2498
		
2499
		return gTypes;
2500
	}
2501 2418

  
2419

  
2420

  
2502 2421
	/**
2503 2422
	 * Gets a struct's coordinates array.
2504 2423
	 * 
......
2740 2659
				break;
2741 2660

  
2742 2661
			case OracleValues.ORACLE_GTYPE_COLLECTION:
2743
				resp = Geometry.TYPES.GEOMETRY;
2662
				resp = Geometry.TYPES.AGGREGATE;
2744 2663
				break;
2745 2664
			}
2746 2665
			// =========== not complex =================
......
3523 3442

  
3524 3443
	/**
3525 3444
	 * 
3526
	 * @param sample
3527
	 * @return
3445
	 * @param sample input STRUCT
3446
	 * @return type and subtype of geometry
3528 3447
	 * @throws SQLException
3529 3448
	 */
3530
	public static int getShapeTypeOfStruct(STRUCT sample) throws SQLException {
3449
	public static int[] getGeoTypeSubTypeOfStruct(STRUCT sample) throws SQLException {
3531 3450

  
3532
		int code = ((NUMBER) sample.getOracleAttributes()[0]).intValue();
3451
		int _code = ((NUMBER) sample.getOracleAttributes()[0]).intValue();
3452
		return getGeoTypeSubTypeOfOracleCode(_code);
3453
	}
3533 3454

  
3455
	
3456
	public static int[] getGeoTypeSubTypeOfOracleCode(int code) {
3457

  
3458
		// [TYPES.?, SUBTYPES.?]
3459
		int[] resp = new int[2];
3460
		
3534 3461
		int type_part = code % 10;
3535 3462
		int dim_part = code / 1000;
3536 3463

  
3537
		int z_added = 0;
3464
		resp[1] = SUBTYPES.GEOM2D;
3538 3465
		if (dim_part == 3) {
3539
			z_added = Geometry.SUBTYPES.GEOM3D;
3466
			resp[1] = SUBTYPES.GEOM3D;
3540 3467
		} else {
3541 3468
			if (dim_part == 4) {
3542
				z_added = Geometry.SUBTYPES.GEOM3DM;
3469
				resp[1] = SUBTYPES.GEOM3DM;
3543 3470
			}
3544 3471
		}
3545 3472

  
3473
		resp[0] = TYPES.GEOMETRY;
3474
		
3546 3475
		switch (type_part) {
3547 3476
		case 1:
3548
			return z_added + Geometry.TYPES.POINT;
3549

  
3477
			resp[0] = Geometry.TYPES.POINT;
3478
			break;
3550 3479
		case 2:
3551
			return z_added + Geometry.TYPES.CURVE;
3552

  
3480
			resp[0] = Geometry.TYPES.CURVE;
3481
			break;
3553 3482
		case 3:
3554
			return z_added + Geometry.TYPES.SURFACE;
3555

  
3483
			resp[0] = Geometry.TYPES.SURFACE;
3484
			break;
3556 3485
		case 4:
3557
			return z_added + Geometry.TYPES.AGGREGATE;
3558

  
3486
			resp[0] = Geometry.TYPES.AGGREGATE;
3487
			break;
3559 3488
		case 5:
3560
			return z_added + Geometry.TYPES.MULTIPOINT;
3561

  
3489
			resp[0] = Geometry.TYPES.MULTIPOINT;
3490
			break;
3562 3491
		case 6:
3563
			return z_added + Geometry.TYPES.MULTICURVE;
3564

  
3492
			resp[0] = Geometry.TYPES.CURVE;
3493
			break;
3565 3494
		case 7:
3566
			return z_added + Geometry.TYPES.MULTISURFACE;
3495
			resp[0] = Geometry.TYPES.SURFACE;
3496
			break;
3497
		default:
3498
			logger.error("Unknown geometry type: " + code);
3499
		break;
3567 3500
		}
3568 3501

  
3569
		logger.error("Unknown geometry type: " + code);
3570

  
3571
		return Geometry.TYPES.NULL;
3502
		return resp;
3572 3503
	}
3573

  
3574 3504
	/**
3575 3505
	 * 
3576 3506
	 * @param info
......
3816 3746

  
3817 3747
		return resp;
3818 3748
	}
3749
	
3750
	
3751
	
3819 3752

  
3753

  
3754

  
3755
	public static int getShapeTypeFromArray(ArrayList arrlist) {
3756
		
3757
		int resp = ((Integer) arrlist.get(0)).intValue();
3758
		
3759
		int sz = arrlist.size();
3760
		int aux = 0;
3761
		for (int i=1; i<sz; i++) {
3762
			aux = ((Integer) arrlist.get(i)).intValue();
3763
			if (aux != resp) return TYPES.GEOMETRY;
3764
		}
3765
		return resp;
3766
	}
3767

  
3768
	// condition using ROWNUM with growing indexs to do a size-independent sample
3769
    public static String EXPONENTIAL_INDICES_CONDITION = null;
3770
    static {
3771
    	
3772
    	String sb = "";
3773
    	int i=0;
3774
    	sb = "(rownum = 1)";
3775
    	for (i=2; i<20; i++) {
3776
    		sb = "(" + sb + " OR (rownum = " + i + "))";
3777
    	}
3778
    	int cnt = 0;
3779
    	float aux = 1;
3780
    	while (cnt < 35) {
3781
    		aux = aux * 1.5f;
3782
    		i = 20 + Math.round(aux);
3783
    		sb = "(" + sb + " OR (rownum = " + i + "))";
3784
    		cnt++;
3785
    	}
3786
		aux = aux * 1.5f;
3787
		i = 20 + Math.round(aux);
3788
		sb = "(" + sb + " OR (rownum = " + i + "))";
3789
		EXPONENTIAL_INDICES_CONDITION = sb;
3790
    }
3791
    
3792
    
3793
	public static void copyFeatureTypeToOracleStoreParams(
3794
			EditableFeatureType efType, OracleStoreParameters params) {
3795
		
3796
		
3797
		// TODO Auto-generated method stub
3798
		
3799
	}
3800
	
3801

  
3802
    
3803
    /**
3804
     * Utility method to transform a struct into a IGeometry.
3805
     *
3806
     * @param st the struct to be converted
3807
     * @param complex comes from a complex sdo geometry
3808
     * @return the IGeometry
3809
     */
3810
    public static Geometry getGeometry(
3811
    		STRUCT st,
3812
    		boolean complex,
3813
    		boolean __tablehassrid,
3814
    		String __tablesrid,
3815
    		Connection _conn) {
3816

  
3817
    	GeometryManager gm = GeometryLocator.getGeometryManager();
3818
    	
3819
    	if (st == null) {
3820
    		Geometry aux = null;
3821
    		try {
3822
				aux = gm.createNullGeometry(SUBTYPES.GEOM2D);
3823
			} catch (CreateGeometryException e) {
3824
				logger.error("While creating null Geometry: " + e.getMessage());
3825
			}
3826
    		return aux;
3827
    	}
3828

  
3829
        Datum[] the_data = null;
3830

  
3831
        try {
3832
            the_data = st.getOracleAttributes();
3833

  
3834
            int jgtype = ((NUMBER) the_data[0]).intValue() % 1000;
3835
            jgtype = oracleGTypeToFShapeType(jgtype, complex);
3836

  
3837
            int dim = ((NUMBER) the_data[0]).intValue() / 1000;
3838

  
3839
            if (dim < 2) {
3840
                dim = 2;
3841
            }
3842

  
3843
            int subty = getSubTypeFromDims(dim);
3844
            Geometry ig = gm.createNullGeometry(subty);
3845

  
3846
            if (isActuallyACollection(the_data)) {
3847
                jgtype = TYPES.AGGREGATE;
3848
            }
3849

  
3850
            switch (jgtype) {
3851
            case TYPES.AGGREGATE:
3852
                ig = getFMapGeometryCollection(the_data, dim, __tablehassrid, __tablesrid, _conn);
3853
                break;
3854

  
3855
            case TYPES.POINT:
3856
                ig = getFMapGeometryPoint(the_data, dim);
3857
                break;
3858

  
3859
            case TYPES.CURVE:
3860
                ig = getFMapGeometryMultiLineString(the_data, dim);
3861
                break;
3862

  
3863
            case TYPES.SURFACE:
3864
                ig = getFMapGeometryMultipolygon(the_data, dim);
3865
                break;
3866
            }
3867

  
3868
            return ig;
3869
        } catch (Exception e) {
3870
            logger.error("While creating Geometry from STRUCT: " + e.getMessage());
3871
        }
3872
        return null;
3873
    }
3874
    
3875
    
3876
    /**
3877
     * Utility method to transform a struct into a IGeometry.
3878
     *
3879
     * @param st the struct to be converted
3880
     * @param complex comes from a complex sdo geometry
3881
     * @return the IGeometry
3882
     */
3883
    public static Primitive getPrimitive(STRUCT st, boolean complex) {
3884

  
3885
    	GeometryManager gm = GeometryLocator.getGeometryManager();
3886
    	Primitive resp = null;
3887
    	
3888
    	if (st == null) {
3889
    		try {
3890
				resp = gm.createNullGeometry(SUBTYPES.GEOM2D);
3891
			} catch (CreateGeometryException e) {
3892
				logger.error("While creating null geometry: " + e.getMessage());
3893
			}
3894
			return resp;
3895
    	}
3896

  
3897
        Datum[] the_data = null;
3898
        try {
3899
            the_data = st.getOracleAttributes();
3900

  
3901
            int jgtype = ((NUMBER) the_data[0]).intValue() % 1000;
3902
            jgtype = oracleGTypeToFShapeType(jgtype, complex);
3903

  
3904
            int dim = ((NUMBER) the_data[0]).intValue() / 1000;
3905

  
3906
            if (dim < 2) {
3907
                dim = 2;
3908
            }
3909

  
3910
        	int subty = getSubTypeFromDims(dim);
3911
        	Primitive ig = null;
3912
        	try {
3913
				ig = gm.createNullGeometry(subty);
3914
			} catch (CreateGeometryException e) {
3915
				logger.error("While creating null geometry: " + e.getMessage());
3916
			}
3917

  
3918
            if (isActuallyACollection(the_data)) {
3919
                jgtype = TYPES.AGGREGATE;
3920
            }
3921

  
3922
            try {
3923
                switch (jgtype) {
3924
                case TYPES.POINT:
3925
                    ig = (Primitive) getFMapGeometryPoint(the_data, dim);
3926
                    break;
3927

  
3928
                case TYPES.CURVE:
3929
                    ig = (Primitive) getFMapGeometryMultiLineString(the_data, dim);
3930
                    break;
3931

  
3932
                case TYPES.SURFACE:
3933
                    ig = (Primitive) getFMapGeometryMultipolygon(the_data, dim);
3934
                    break;
3935
                default:
3936
                	logger.error("Aggregate of non primitives not supported.");
3937
                    break;
3938
                }
3939
            } catch (Exception ex) {
3940
            	logger.error("While creating primitive: " + ex.getMessage());
3941
            }
3942

  
3943
            return ig;
3944
        } catch (SQLException e) {
3945
            logger.error(e);
3946
        }
3947

  
3948
        return null;
3949
    }
3950
    
3951
    
3952
    private static int getSubTypeFromDims(int dim) {
3953
    	
3954
    	switch (dim) {
3955
    	case 3:
3956
    		return SUBTYPES.GEOM3D;
3957
    	case 4:
3958
    		return SUBTYPES.GEOM3DM;
3959
    	default:
3960
    			return SUBTYPES.GEOM2D;
3961
    	}
3962
	}
3963

  
3964
	public static Geometry getFMapGeometryCollection(
3965
    		Datum[] the_data,
3966
    		int dim,
3967
    		boolean tableHasSrid,
3968
    		String table_srid,
3969
    		Connection _conn) {
3970

  
3971
    	NUMBER _srid = new NUMBER(0);
3972
        NUMBER main_type = new NUMBER((dim * 1000) + getStructType(the_data));
3973

  
3974

  
3975
        Datum[] all_info_array = null;
3976
        Object[] elems_info_aray = null;
3977
        Datum[] all_ords = null;
3978

  
3979
        Object[] ords_of_groups = null;
3980
        Object[] _elems_info_aray = null;
3981
        try {
3982
            all_info_array = ((ARRAY) the_data[3]).getOracleArray();
3983
            elems_info_aray = groupByElement(all_info_array);
3984
            all_ords = ((ARRAY) the_data[4]).getOracleArray();
3985

  
3986
            ords_of_groups = getOrdOfGroups(all_ords, elems_info_aray);
3987
            _elems_info_aray = new Object[elems_info_aray.length];
3988
        }
3989
        catch (SQLException e) {
3990
            logger.error("Unexpected error: " + e.getMessage());
3991
        }
3992

  
3993

  
3994
        for (int i = 0; i < elems_info_aray.length; i++) {
3995
            _elems_info_aray[i] = updateIndexes((Datum[]) elems_info_aray[i]);
3996
        }
3997

  
3998
        // _elems_info_aray, ords_of_groups
3999
        int no_of_elems = ords_of_groups.length;
4000
        Primitive[] geoms = new Primitive[no_of_elems];
4001

  
4002
        for (int i = 0; i < no_of_elems; i++) {
4003
            Datum[] item_info_array = null;
4004
            Datum[] item_ords = null;
4005
            NUMBER gtype = null;
4006

  
4007
            try {
4008
                item_info_array = (Datum[]) _elems_info_aray[i];
4009
                item_ords = (Datum[]) ords_of_groups[i];
4010

  
4011
                gtype = new NUMBER((dim * 1000) +
4012
                        (item_info_array[1].intValue() % 1000));
4013

  
4014
                if (tableHasSrid) {
4015
                	_srid = new NUMBER(Integer.parseInt(table_srid));
4016
                }
4017
            }
4018
            catch (SQLException se) {
4019
                logger.error("Unexpected error: " + se.getMessage());
4020
            }
4021

  
4022
            // if it's the first geometry, the type is the collection's main type (no?) - no
4023
            // if (i == 0) gtype = main_type;
4024

  
4025
            STRUCT itemst = null;
4026

  
4027
            if (tableHasSrid) {
4028

  
4029
                itemst = createStruct(gtype, _srid,
4030
                        item_info_array, item_ords, _conn);
4031
            }
4032
            else {
4033
                itemst = createStruct(gtype, null,
4034
                        item_info_array, item_ords, _conn);
4035
            }
4036
            geoms[i] = getPrimitive(itemst, true);
4037
        }
4038
        
4039
    	GeometryManager gm = GeometryLocator.getGeometryManager();
4040
    	int subt = getSubTypeFromDims(dim);
4041
        MultiPrimitive resp = null;
4042
        
4043
        try {
4044
			resp = (MultiPrimitive) gm.create(TYPES.AGGREGATE, subt);
4045
	        for (int i = 0; i < no_of_elems; i++) {
4046
	        	resp.addPrimitive(geoms[i]);
4047
	        }
4048
		} catch (Exception e) {
4049
			logger.error("While creating multi primitive: " + e.getMessage());
4050
		}
4051
        return resp;
4052
    }
4053
	
4054
	// ===========================================================
4055
	
4056
	/**
4057
	 * Get oracle srid from srs code(EPSG code)
4058
	 * 
4059
	 * @param epsg
4060
	 * @return oraSRID
4061
	 */
4062
	public static String epsgToOracleSrid(String epsg) {
4063
		
4064
		DataManager manager = DALLocator.getDataManager();
4065
		int isrs = -1;
4066
		if (epsg != null) {
4067
			FeatureStore oraSrsStore = (FeatureStore) OracleLibrary
4068
					.getSRSDataStore();
4069

  
4070
			FeatureSet set = null;
4071
			try {
4072
				FeatureQuery query = oraSrsStore.createFeatureQuery();
4073
				query.setFilter(manager.createExpresion("EPSG = " + epsg));
4074
				set = (FeatureSet) oraSrsStore.getDataSet(query);
4075
				if (set.getSize() > 0) {
4076
					Iterator<Feature> it = set.iterator();
4077
					while (it.hasNext()) {
4078
						Feature feat = it.next();
4079
						Double ora = feat.getDouble("ORACLE");
4080
						int iora = ora.intValue();
4081
						double prefe = feat.getDouble("PRF_ORACLE");
4082
						if (prefe == 1) {
4083
							isrs = iora;
4084
							break;
4085
						}
4086
					}
4087
				}
4088
			} catch (DataException e) {
4089
				e.printStackTrace();
4090
			}
4091
			if (isrs >= 0) {
4092
				return Integer.toString(isrs);
4093
			}
4094
		}
4095
		return null;
4096
	}
4097

  
4098
	/**
4099
	 * Get EPSG SRS from Oracle SRS
4100
	 * 
4101
	 * @param oraSRID
4102
	 * @return
4103
	 */
4104
	public static Integer oracleSridToEpsg(String oraSRID) {
4105

  
4106
		DataManager manager = DALLocator.getDataManager();
4107
		Integer isrs = null;
4108
		
4109
		if (oraSRID != null) {
4110
			FeatureStore oraSrsStore = (FeatureStore) OracleLibrary
4111
					.getSRSDataStore();
4112

  
4113
			FeatureSet set = null;
4114
			try {
4115
				FeatureQuery query = oraSrsStore.createFeatureQuery();
4116
				query.setFilter(manager.createExpresion("ORACLE = " + oraSRID));
4117
				set = (FeatureSet) oraSrsStore.getDataSet(query);
4118
				if (set.getSize() > 0) {
4119
					Iterator<Feature> it = set.iterator();
4120
					while (it.hasNext()) {
4121
						Feature feat = it.next();
4122
						isrs = new Integer(feat.getInt("EPSG"));
4123
					}
4124
				}
4125
			} catch (DataException e) {
4126
				logger.error("While getting EPSG from oracle srid: " + e.getMessage());
4127
			}
4128
			return isrs;
4129
		} else {
4130
			return null;
4131
		}
4132
	}
4133

  
4134
	/**
4135
	 * Get Oracle SRS from gvSIG projection
4136
	 * 
4137
	 * @param proj
4138
	 * @return  
4139
	 */
4140
	public static String projectionToOracleSrid(IProjection proj) {
4141
		if (proj != null) {
4142
			String epsg = proj.getAbrev().trim();
4143
			int ocu = epsg.indexOf(":");
4144
			if (ocu != -1) {
4145
				epsg = epsg.substring(ocu + 1);
4146
			}
4147
			return epsgToOracleSrid(epsg);
4148
		} else {
4149
			return null;
4150
		}
4151
	}
4152

  
4153
	public static int dimensionsFromSubtype(int subtype) {
4154
		
4155
		switch (subtype) {
4156
		
4157
		case SUBTYPES.GEOM2D:
4158
			return 2;
4159
		case SUBTYPES.GEOM3D:
4160
		case SUBTYPES.GEOM2DZ:
4161
		case SUBTYPES.GEOM2DM:
4162
			return 3;
4163
		case SUBTYPES.GEOM3DM:
4164
			return 4;
4165
		default:
4166
				logger.error("Unknown subtype: " + subtype + ". Returned 2 as number of dimensions.");
4167
			return 2;
4168
		}
4169
	}
4170

  
4171
	public static Rectangle2D envelopeToRectangle2D(org.gvsig.fmap.geom.primitive.Envelope envelope) {
4172
			
4173
		double x = envelope.getMinimum(0);
4174
		double y = envelope.getMinimum(1);
4175
		double w = envelope.getLength(0);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff