Revision 1987

View differences:

org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/docs/Notas.txt
1
- COpetation.getInverted() no est? teniendo en cuenta si hay par?metros de transformaci?n -HECHO-
2
- Resolver el tema del cacheado de CRSs en los repositorios.
3
- Por qu? no est?n implementados  getPOrig() y getPDest() de COperation? -HECHO-
4
- Plantearse la necesidad de ICOperation:
5
	- COperation ya no la implementa. La conservo preventivamente. -HECHO-
6
- Crs y CrsGT: No construir los objetos CrsProj en el constructor, hacerlo la primera vez que se pidan.
7
- Habr?a que reducir el tiempo de arranque de la extensi?n.
8
- Depuraciones para detectar ineficiencias.
9
	- COperation.operate se llama para cada punto: optimizar su contenido (creaci?n de objetos). -HECHO-
10
	- Hacer que CrsGT.getCT no construya nuevos CrsProj cada vez que se llama.
11
- libJCrs y windows?????????????'
12
- ICrs: mirar qu? m?todos no tienen por qu? estar en la interfaz.
13
- Dependencias de gvSIG en libJCrs:
14
	- COperation.convert(...) utiliza: NotificationManager.addError(e) de andami;
15
	- Persistencia: depende de PluginServices de andami. -> subir la persistencia a la extension. -HECHO-
16
	- dependencia de CMS: IProjection, ICoordTrans, IDatum, ICRSFactory, org.cresques.geo.ViewPortData.
17
	
18
- Crs.getScale(): double invF = getDatum().getEIFlattening(); if (invF == Double.POSITIVE_INFINITY){}
19
	?Qu? valor da getDatum().getEIFlattening() en el caso de una esfera? geoltools da Double.POSITIVE_INFINITY.
20

  
21
- Busqueda IAU por zona: en mayusculas no encuentra. -HECHO-
22
- Persistencia de transformaciones en F2. -HECHO-
23
- Persistencia en el proyecto: Implementar IProyectio.getFullCode() y lo que esto implica. -HECHO-
24

  
25
- OGR y WINDOWS....!!!!???? 
26
- Revisar classpath de extJCRS (?log4j-1.2.8.jar?,etc...)
27
- Cuando CRS fuente y destino son iguales -> no operar, devolver el mismo punto.
28

  
29

  
30
BUGS:
31

  
32
- Cargas un shp 23030 diciendole que es 4258 con transf. EPSG (7) y salta una excepcci?n de proj4: controlar o subir estos
33
	errores (es un error como el que silenciamos de nadgrids).
34
	En este caso el error es debido a que las coordenadas se salen del rango del CRS elegido. Esta situaci?n ArcMap la maneja desavilitando
35
	la capa y dejando de visualizarla (algo parecedo a cuando gvSIG le pone la x de erroneo a una capa).
36

  
37
- Cuando hay un fallo al elegir el CRS de la vista y despu?s guardas el proyecto, parece ser que se guarda como null (o algo as?)
38
	y falla al abrirlo. Posibles soluciones: en esos casos guardar el CRS por defecto.
39

  
40
- Nomenclator: Cuando pulsas localizar, debe dibuajar el punto en la vista y hacer zoom a el. Lo dibuja pero aparece una
41
	excepci?n y no hace el zoom.
0 42

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/resources/META-INF/services/org.geotools.referencing.operation.MathTransformProvider
1
org.geotools.referencing.operation.projection.IdrAitoff$Provider
2
org.geotools.referencing.operation.projection.IdrAzimuthalEquidistant$Provider
3
org.geotools.referencing.operation.projection.IdrAzimuthalEquidistant$Provider_Modified
4
org.geotools.referencing.operation.projection.IdrAzimuthalEquidistant$Provider_Guam
5
org.geotools.referencing.operation.projection.IdrBonne$Provider
6
org.geotools.referencing.operation.projection.IdrBonne$Provider_SouthOrientated
7
org.geotools.referencing.operation.projection.IdrCassiniSoldner$Provider
8
org.geotools.referencing.operation.projection.IdrCassiniSoldner$Provider_Hyperbolic
9
org.geotools.referencing.operation.projection.IdrCrasterParabolic$Provider
10
org.geotools.referencing.operation.projection.IdrCylindricalEqualArea$Provider
11
org.geotools.referencing.operation.projection.IdrEckertI$Provider
12
org.geotools.referencing.operation.projection.IdrEckertII$Provider
13
org.geotools.referencing.operation.projection.IdrEckertIII$Provider
14
org.geotools.referencing.operation.projection.IdrEckertIV$Provider
15
org.geotools.referencing.operation.projection.IdrEckertV$Provider
16
org.geotools.referencing.operation.projection.IdrEckertVI$Provider
17
org.geotools.referencing.operation.projection.IdrEquidistantConic$Provider
18
org.geotools.referencing.operation.projection.IdrEquidistantCylindrical$Provider
19
org.geotools.referencing.operation.projection.IdrEquirectangular$Provider
20
org.geotools.referencing.operation.projection.IdrFlatPolarQuartic$Provider
21
org.geotools.referencing.operation.projection.IdrGallStereographic$Provider
22
org.geotools.referencing.operation.projection.IdrGnomonic$Provider
23
org.geotools.referencing.operation.projection.IdrGoode$Provider
24
org.geotools.referencing.operation.projection.IdrHammerAitoff$Provider
25
org.geotools.referencing.operation.projection.IdrKrovak$Provider
26
org.geotools.referencing.operation.projection.IdrLabordeMadagascar$Provider
27
org.geotools.referencing.operation.projection.IdrLambertAzimuthalEqualArea$Provider
28
org.geotools.referencing.operation.projection.IdrLambertConformalWestOrientated$Provider
29
org.geotools.referencing.operation.projection.IdrLambertConicNearConformal$Provider
30
org.geotools.referencing.operation.projection.IdrLoximuthal$Provider
31
org.geotools.referencing.operation.projection.IdrMercator$Provider1SP
32
org.geotools.referencing.operation.projection.IdrMillerCylindrical$Provider
33
org.geotools.referencing.operation.projection.IdrMollweide$Provider
34
org.geotools.referencing.operation.projection.IdrNearSidedPerspective$Provider
35
org.geotools.referencing.operation.projection.IdrNewZealandMapGrid$Provider
36
org.geotools.referencing.operation.projection.IdrObliqueMercator$Provider
37
org.geotools.referencing.operation.projection.IdrObliqueMercator$Provider_Hotine
38
org.geotools.referencing.operation.projection.IdrObliqueMercator$Provider_TwoPoint
39
org.geotools.referencing.operation.projection.IdrObliqueMercator$Provider_Hotine_TwoPoint
40
org.geotools.referencing.operation.projection.IdrOrthographic$Provider
41
org.geotools.referencing.operation.projection.IdrPlateCarree$Provider
42
org.geotools.referencing.operation.projection.IdrPolyconic$Provider
43
org.geotools.referencing.operation.projection.IdrQuarticAuthalic$Provider
44
org.geotools.referencing.operation.projection.IdrRobinson$Provider
45
org.geotools.referencing.operation.projection.IdrSinusoidal$Provider
46
org.geotools.referencing.operation.projection.IdrTransverseMercator$Provider
47
org.geotools.referencing.operation.projection.IdrTransverseMercator$Provider_SouthOrientated
48
org.geotools.referencing.operation.projection.IdrTransverseMercator$Provider_TransverseMercatorZonedGridSystem
49
org.geotools.referencing.operation.projection.IdrTunisiaMiningGrid$Provider
50
org.geotools.referencing.operation.projection.IdrVanDerGrinten$Provider
51
org.geotools.referencing.operation.projection.IdrWinkelI$Provider
52
org.geotools.referencing.operation.projection.IdrWinkelII$Provider
53
org.geotools.referencing.operation.projection.IdrWinkelTripel$Provider
54

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.crs.JCRSLibrary
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/resources/META-INF/services/org.opengis.referencing.crs.CRSAuthorityFactory
1
es.idr.teledeteccion.connection.esri.FactoryUsingHSQL
2
es.idr.teledeteccion.connection.usr.FactoryUsingHSQL
3
es.idr.teledeteccion.connection.iau2000.FactoryUsingHSQL
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/java/es/idr/teledeteccion/connection/Query.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha)
34
 *   Campus Universitario s/n
35
 *   02071 Alabacete
36
 *   Spain
37
 *
38
 *   +34 967 599 200
39
 */
40

  
41
package es.idr.teledeteccion.connection;
42

  
43
import java.io.Serializable;
44
import java.sql.Connection;
45
import java.sql.ResultSet;
46
import java.sql.ResultSetMetaData;
47
import java.sql.SQLException;
48
import java.sql.Statement;
49

  
50
import org.slf4j.Logger;
51
import org.slf4j.LoggerFactory;
52

  
53
/**
54
 * Clase para realizar las consultas a las bases de datos utilizadas
55
 * 
56
 * @author Jos? Luis G?mez Mart?nez (jolugomar@gmail.com)
57
 *
58
 */
59
public class Query implements Serializable{
60
	
61
	/**
62
	 * 
63
	 */
64
	private static final long serialVersionUID = 1L;
65
	private static Logger logger = LoggerFactory.getLogger(Query.class);
66
	
67
	/**
68
	 * Acepta la sentencia y la conexi?n a la base de datos actual,
69
	 * realiza una selecci?n y devuelve los datos en un ResultSet
70
	 * @param sentence
71
	 * @param conn
72
	 * @return
73
	 */
74
	public static synchronized ResultSet select(String sentence, Connection conn){
75
		Statement st = null;
76
		ResultSet rs = null;
77
				
78
		try {
79
			st = conn.createStatement();
80
			rs = st.executeQuery(sentence);
81
			st.close();
82
		} catch (SQLException e) {
83
			String connid = conn.toString();
84
			try {
85
				connid = conn.getMetaData().getURL();
86
			} catch (SQLException e1) {
87
			}
88
			logger.error("Can't create ResulSet from sentece '"+sentence+"' in connection '"+connid +"'.",e);
89
		}		
90
		return rs;
91
	}	
92
}
93

  
0 94

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/java/es/idr/teledeteccion/connection/usr/FactoryUsingHSQL.java
1
/*
2
 *    GeoTools - OpenSource mapping toolkit
3
 *    http://geotools.org
4
 *    (C) 2005-2006, GeoTools Project Managment Committee (PMC)
5
 * 
6
 *    This library is free software; you can redistribute it and/or
7
 *    modify it under the terms of the GNU Lesser General Public
8
 *    License as published by the Free Software Foundation;
9
 *    version 2.1 of the License.
10
 *
11
 *    This library 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 GNU
14
 *    Lesser General Public License for more details.
15
 */
16
package es.idr.teledeteccion.connection.usr;
17

  
18
// J2SE dependencies
19

  
20
import java.io.IOException;
21
import java.sql.Connection;
22
import java.sql.PreparedStatement;
23
import java.sql.ResultSet;
24
import java.sql.SQLException;
25
import java.sql.Statement;
26
import java.text.ParseException;
27
import java.util.Hashtable;
28
import java.util.Set;
29

  
30
import org.geotools.metadata.iso.citation.CitationImpl;
31
import org.geotools.referencing.wkt.Parser;
32
import org.gvsig.crs.CrsFactory;
33
import org.hsqldb.jdbc.jdbcDataSource;
34
import org.opengis.metadata.citation.Citation;
35
import org.opengis.referencing.FactoryException;
36
import org.opengis.referencing.IdentifiedObject;
37
import org.opengis.referencing.crs.CRSAuthorityFactory;
38
import org.opengis.referencing.crs.CRSFactory;
39
import org.opengis.referencing.crs.CompoundCRS;
40
import org.opengis.referencing.crs.CoordinateReferenceSystem;
41
import org.opengis.referencing.crs.DerivedCRS;
42
import org.opengis.referencing.crs.EngineeringCRS;
43
import org.opengis.referencing.crs.GeocentricCRS;
44
import org.opengis.referencing.crs.GeographicCRS;
45
import org.opengis.referencing.crs.ImageCRS;
46
import org.opengis.referencing.crs.ProjectedCRS;
47
import org.opengis.referencing.crs.TemporalCRS;
48
import org.opengis.referencing.crs.VerticalCRS;
49
import org.opengis.util.InternationalString;
50

  
51

  
52
public class FactoryUsingHSQL extends jdbcDataSource implements CRSAuthorityFactory {
53
   
54

  
55
    
56
    /**
57
     * The connection to the EPSG database.
58
     */
59
    protected Connection connection;
60
      
61
    //  object factory
62
    protected CRSFactory crsFactory;
63
    
64
    /** Cache of parsed CoordinateReferenceSystem WKT by ESRI_NUMBER */
65
    private Hashtable cache = new Hashtable();
66
      
67
    /**
68
     * The database name.
69
     *
70
     * @since 2.3
71
     */
72
    public static final String DATABASE_NAME = "USR";
73
    
74
    public FactoryUsingHSQL() {
75
    	 try {
76
             loadDefault();
77
         }
78
         catch( IOException oops ){
79
             System.err.println("Could not load "+ oops );
80
         }
81
    	//this(FactoryFinder.getCRSFactory(null));
82
    }   
83

  
84
	protected FactoryUsingHSQL(CRSFactory factory) {
85
		this.crsFactory = factory;
86
        try {
87
            loadDefault();
88
        }
89
        catch( IOException oops ){
90
            System.err.println("Could not load "+ oops );
91
        }
92
	}
93
	
94
	protected void loadDefault() throws IOException {
95
		String db = "jdbc:hsqldb:file:" + CrsFactory.getDataBaseFolder().getAbsolutePath() + "/usr";
96
		setDatabase(db);
97
		setUser("sa");
98
		try {
99
			connection = super.getConnection();
100
		} catch (SQLException e) {
101
			// TODO Auto-generated catch block
102
			e.printStackTrace();
103
		}
104
        
105
    }
106
	
107
	public CoordinateReferenceSystem createCoordinateReferenceSystem(String code) throws FactoryException {
108
		// TODO Auto-generated method stub
109
		CoordinateReferenceSystem returnValue = null;
110
		String wkt = null;
111
		String USR_NUMBER = code.substring(code.indexOf(":")+1, code.length());
112
		int cod = Integer.parseInt(USR_NUMBER);
113
        
114
		if( cache.contains( USR_NUMBER ) ){
115
            Object value = cache.get( USR_NUMBER );
116
            if( value instanceof Throwable ){
117
                throw new FactoryException( "WKT for "+code+" could not be parsed", (Throwable) value );
118
            }
119
            if( value instanceof CoordinateReferenceSystem){
120
                return (CoordinateReferenceSystem) value;
121
            }            
122
        }
123
		
124
		try {        	
125
        	final PreparedStatement stmt;
126
            
127
            String sentence = "SELECT USR_WKT"
128
            + " FROM USR"
129
            + " WHERE USR_CODE = " + code.substring(code.indexOf(":")+1, code.length());
130
        
131
        	Statement st = null;
132
    		ResultSet result = null;
133
    		loadDefault();
134
        	st = connection.createStatement();			
135
        	result = st.executeQuery(sentence);
136
			st.close();
137
			connection.close();
138
        	while (result.next()) {
139
                wkt    = result.getString("usr_wkt"); 	
140
            }
141
            result.close();
142
            if( wkt.indexOf( cod ) == -1){
143
            	wkt = wkt.trim();
144
            	wkt = wkt.substring(0, wkt.length()-1 );
145
            	wkt += ",AUTHORITY[\"USR\",\""+cod+"\"]]";
146
            }
147
        } catch (SQLException exception) {
148
            System.out.println(exception);
149
        } catch (IOException e) {
150
			// TODO Auto-generated catch block
151
			e.printStackTrace();
152
		}
153
        Parser parser = new Parser();
154
        
155
		try {
156
			returnValue = parser.parseCoordinateReferenceSystem(wkt);
157
		} catch (ParseException e) {
158
			// TODO Auto-generated catch block
159
			System.out.println("Cadena WKT no ha podido ser parseada");
160
			e.printStackTrace();
161
		}
162
		
163
        return returnValue;					
164
	}
165

  
166
	public CompoundCRS createCompoundCRS(String arg0) throws FactoryException {
167
		// TODO Auto-generated method stub
168
		return null;
169
	}
170

  
171
	public DerivedCRS createDerivedCRS(String arg0) throws FactoryException {
172
		// TODO Auto-generated method stub
173
		return null;
174
	}
175

  
176
	public EngineeringCRS createEngineeringCRS(String arg0) throws FactoryException {
177
		// TODO Auto-generated method stub
178
		return null;
179
	}
180

  
181
	public GeographicCRS createGeographicCRS(String arg0) throws FactoryException {
182
		// TODO Auto-generated method stub
183
		return null;
184
	}
185

  
186
	public GeocentricCRS createGeocentricCRS(String arg0) throws FactoryException {
187
		// TODO Auto-generated method stub
188
		return null;
189
	}
190

  
191
	public ImageCRS createImageCRS(String arg0) throws FactoryException {
192
		// TODO Auto-generated method stub
193
		return null;
194
	}
195

  
196
	public ProjectedCRS createProjectedCRS(String arg0) throws FactoryException {
197
		// TODO Auto-generated method stub
198
		return null;
199
	}
200

  
201
	public TemporalCRS createTemporalCRS(String arg0) throws FactoryException {
202
		// TODO Auto-generated method stub
203
		return null;
204
	}
205

  
206
	public VerticalCRS createVerticalCRS(String arg0) throws FactoryException {
207
		// TODO Auto-generated method stub
208
		return null;
209
	}
210

  
211
	public Citation getAuthority() {
212
		Citation citation = CitationImpl.createCitation("USR");
213
		citation.getIdentifiers().add("USR");
214
		return citation;
215
	}
216

  
217
	public Set getAuthorityCodes(Class arg0) throws FactoryException {
218
		// TODO Auto-generated method stub
219
		return null;
220
	}
221

  
222
	public InternationalString getDescriptionText(String arg0) throws FactoryException {
223
		// TODO Auto-generated method stub
224
		return null;
225
	}
226

  
227
	public IdentifiedObject createObject(String code) throws FactoryException {
228
		// TODO Auto-generated method stub
229
		return createCoordinateReferenceSystem(code);
230
	}
231

  
232
	public Citation getVendor() {
233
		// TODO Auto-generated method stub
234
		return null;
235
	}
236
}
0 237

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/java/es/idr/teledeteccion/connection/EpsgConnection.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 */
20
package es.idr.teledeteccion.connection;
21

  
22
import java.sql.Connection;
23
import java.sql.SQLException;
24
import java.sql.Statement;
25

  
26
import org.gvsig.crs.CrsFactory;
27
import org.hsqldb.jdbc.jdbcDataSource;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

  
31
import es.idr.teledeteccion.connection.epsg.HSQLDataSource;
32

  
33
/**
34
 * Clase para la conexi?n con la base de datos de hsqldb.
35
 * Establece el driver necesario, as? como la cadena de
36
 * conexi?n a la base de datos de la EPSG y la IAU2000
37
 *
38
 * @author Jos? Luis G?mez Mart?nez (jolugomar@gmail.com)
39
 *
40
 */
41
public class EpsgConnection extends jdbcDataSource {
42

  
43
    private static final Logger logger = LoggerFactory.getLogger(EpsgConnection.class);
44
    
45
    Connection connect = null;
46
    String connectionType = null;
47

  
48
    public EpsgConnection() {
49
        /*	try {
50
         Class.forName("org.hsqldb.jdbcDriver");
51
         } catch (ClassNotFoundException e) {
52
         logger.error("Can't create EpsgConnection",e); 
53
         }*/
54
    }
55

  
56
    private void setConnection(Connection connection, String type) {
57
        this.connect = connection;
58
        this.connectionType = type;
59
        logger.debug("Created connection to '"+connectionType+"'.");
60
    }
61

  
62
    public void setConnectionEPSG() {
63
        HSQLDataSource ds = new HSQLDataSource();
64

  
65
        try {
66
            setConnection(ds.getConnection(), "EPSG");
67
        } catch (SQLException e) {
68
            logger.warn("Cant get conection from HSQLDataSource.", e);
69
        }
70
    }
71

  
72
    /**
73
     * Establece la conexi?n con la base de datos de la IAU2000
74
     *
75
     */
76
    public void setConnectionIAU2000() {
77
        String db = "jdbc:hsqldb:file:" + CrsFactory.getDataBaseFolder().getAbsolutePath() + "/iau2000";
78
        setDatabase(db);
79
        setUser("sa");
80
        try {
81
            setConnection(super.getConnection(),"IAU2000");
82
        } catch (SQLException e) {
83
            logger.warn("Can't get conection from database '" + db + "'.", e);
84
        }
85
    }
86

  
87
    /**
88
     * Establece la conexi?n con la base de datos de ESRI
89
     *
90
     */
91
    public void setConnectionEsri() {
92
        String db = "jdbc:hsqldb:file:" + CrsFactory.getDataBaseFolder().getAbsolutePath() + "/esri";
93
        setDatabase(db);
94
        setUser("sa");
95
        try {
96
            setConnection(super.getConnection(),"Esri");
97
        } catch (SQLException e) {
98
            logger.warn("Can't get conection from database '" + db + "'.", e);
99
        }
100
    }
101

  
102
    /**
103
     * Sets connection for CRS:* coordinate reference systems
104
     * such as CRS:84
105
     *
106
     */
107
    public void setConnectionNoAuth() {
108
        String db = "jdbc:hsqldb:file:" + CrsFactory.getDataBaseFolder().getAbsolutePath() + "/noauth";
109
        setDatabase(db);
110
        setUser("sa");
111
        try {
112
            setConnection(super.getConnection(),"NoAuth");
113
        } catch (SQLException e) {
114
            logger.warn("Can't get conection from database '" + db + "'.", e);
115
        }
116
    }
117

  
118
    /**
119
     * Establece la conexi?n con la base de datos de USR
120
     *
121
     */
122
    public void setConnectionUsr() {
123
        String db = "jdbc:hsqldb:file:" + CrsFactory.getDataBaseFolder().getAbsolutePath() + "/usr";
124
        setDatabase(db);
125
        setUser("sa");
126
        try {
127
            setConnection(super.getConnection(),"Usr");
128
        } catch (SQLException e) {
129
            logger.warn("Can't get conection from database '" + db + "'.", e);
130
        }
131
    }
132

  
133
    public Connection getConnection() {
134
        return connect;
135
    }
136

  
137
    public void close() throws SQLException {
138

  
139
        try {
140
            connect.close();    // if there are no other open connection
141
            logger.debug("Shutdown connection to '" + connectionType + "' database.");
142
        } catch (Exception ex) {
143
            logger.warn("Can't shutdown the conexion.",ex);
144
        }
145
    }
146

  
147
    public void shutdown() throws SQLException {
148

  
149
        // db writes out to files and performs clean shuts down
150
        // otherwise there will be an unclean shutdown
151
        // when program ends
152
        try {
153
            Statement st = connect.createStatement();
154
            st.execute("SHUTDOWN");
155
            connect.close();    // if there are no other open connection
156
            logger.debug("Shutdown connection to '" + connectionType + "' database.");
157
        } catch (Exception ex) {
158
            logger.warn("Can't shutdown the conexion.",ex);
159
        }
160
    }
161

  
162
    public synchronized void update(String expression) throws SQLException {
163

  
164
        Statement st = null;
165
        st = connect.createStatement();
166
        int i = st.executeUpdate(expression);
167
        if ( i == -1 ) {
168
            logger.warn("db("+connectionType+")  error in statement: " + expression);
169
        }
170
        st.close();
171
    }
172
}
0 173

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/java/es/idr/teledeteccion/connection/epsg/HSQLDataSource.java
1
/*
2
 * Geotools 2 - OpenSource mapping toolkit
3
 * (C) 2005, Geotools Project Managment Committee (PMC)
4
 *
5
 *    This library is free software; you can redistribute it and/or
6
 *    modify it under the terms of the GNU Lesser General Public
7
 *    License as published by the Free Software Foundation; either
8
 *    version 2.1 of the License, or (at your option) any later version.
9
 *
10
 *    This library is distributed in the hope that it will be useful,
11
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 *    Lesser General Public License for more details.
14
 *
15
 *    You should have received a copy of the GNU Lesser General Public
16
 *    License along with this library; if not, write to the Free Software
17
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
package es.idr.teledeteccion.connection.epsg;
20

  
21
// J2SE dependencies
22
import java.awt.AWTEvent;
23
import java.awt.EventQueue;
24
import java.awt.SecondaryLoop;
25
import java.awt.Toolkit;
26
import java.io.BufferedReader;
27
import java.io.File;
28
import java.io.FileInputStream;
29
import java.io.IOException;
30
import java.io.InputStreamReader;
31
import java.lang.management.ManagementFactory;
32
import java.nio.channels.FileChannel;
33
import java.sql.Connection;
34
import java.sql.ResultSet;
35
import java.sql.SQLException;
36
import java.sql.SQLFeatureNotSupportedException;
37
import java.sql.Statement;
38
import java.util.Date;
39
import java.util.logging.Level;
40
import javax.swing.SwingUtilities;
41

  
42
import org.apache.commons.io.FileUtils;
43
import org.apache.commons.lang3.StringUtils;
44
import org.apache.commons.lang3.mutable.MutableBoolean;
45
import org.geotools.referencing.factory.AbstractAuthorityFactory;
46
import org.geotools.referencing.factory.FactoryGroup;
47
import org.geotools.referencing.factory.epsg.DataSource;
48
import org.geotools.referencing.factory.epsg.FactoryUsingSQL;
49
import org.gvsig.crs.CrsFactory;
50
import org.gvsig.tools.ToolsLocator;
51
import org.gvsig.tools.task.SimpleTaskStatus;
52
// HSQL dependencies
53
import org.hsqldb.jdbc.jdbcDataSource;
54
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
56

  
57
/**
58
 * Connection to the EPSG database in HSQL database engine format using JDBC.
59
 * The EPSG database can be downloaded from <A
60
 * HREF="http://www.epsg.org">http://www.epsg.org</A>. The SQL scripts (modified
61
 * for the HSQL syntax as <A HREF="doc-files/HSQL.html">explained here</A>) are
62
 * bundled into this plugin. The database version is given in the
63
 * {@linkplain org.opengis.metadata.citation.Citation#getEdition edition attribute}
64
 * of the
65
 * {@linkplain org.opengis.referencing.AuthorityFactory#getAuthority authority}.
66
 * The HSQL database is read only.
67
 * <P>
68
 * <H3>Implementation note</H3>
69
 * The SQL scripts are executed the first time a connection is required. The
70
 * database is then created as cached tables ({@code HSQL.properties} and
71
 * {@code HSQL.data} files) in a temporary directory. Future connections to the
72
 * EPSG database while reuse the cached tables, if available. Otherwise, the
73
 * scripts will be executed again in order to recreate them.
74
 *
75
 * @version $Id: HSQLDataSource.java 14624 2005-06-29 02:19:08Z desruisseaux $
76
 * @author Martin Desruisseaux
77
 * @author Didier Richard
78
 *
79
 * @since 2.2
80
 */
81
public class HSQLDataSource extends jdbcDataSource implements DataSource {
82

  
83
    // 20090518 cmartinez: Use a different tmp dir for each geotools instance
84
    private static File tmpDir = null;
85

  
86
    private static final Logger logger = LoggerFactory.getLogger(HSQLDataSource.class);
87

  
88
    /**
89
     * Creates a new instance of this data source
90
     */
91
    public HSQLDataSource() {
92
        File directory = getGtTmpDir();
93
        if ( directory.isDirectory() || directory.mkdir() ) {
94
            directory = new File(directory, "Cached databases");
95
            if ( directory.isDirectory() || directory.mkdir() ) {
96
                /*
97
                 * Constructs the full path to the HSQL database. Note: we do not use
98
                 * File.toURI() because HSQL doesn't seem to expect an encoded URL
99
                 * (e.g. "%20" instead of spaces).
100
                 */
101
                final StringBuffer url = new StringBuffer("jdbc:hsqldb:file:");
102
                final String path = directory.getAbsolutePath().replace(File.separatorChar, '/');
103
                if ( path.length() == 0 || path.charAt(0) != '/' ) {
104
                    url.append('/');
105
                }
106
                url.append(path);
107
                if ( url.charAt(url.length() - 1) != '/' ) {
108
                    url.append('/');
109
                }
110
                url.append("EPSG");
111
                setDatabase(url.toString());
112
            }
113
            /*
114
             * If the temporary directory do not exists or can't be created,
115
             * lets the 'database' attribute unset. If the user do not set it
116
             * explicitly (for example through JNDI), an exception will be thrown
117
             * when 'getConnection()' will be invoked.
118
             */
119
        }
120
        setUser("SA"); // System administrator. No password.
121
    }
122

  
123
    private File getGtTmpDir() {
124
        if ( tmpDir == null ) {
125
            tmpDir = new File(CrsFactory.getDataBaseFolder(), "temp-" + getProcessId());
126
            Runtime.getRuntime().addShutdownHook(new cleanOnShutdown(this));
127
        }
128
        return tmpDir;
129
    }
130

  
131
    private static String getProcessId() {
132
        String fallback = "time" + System.currentTimeMillis();
133

  
134
        // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
135
        final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
136
        final int index = jvmName.indexOf('@');
137
        if ( index < 1 ) {
138
            // part before '@' empty (index = 0) / '@' not found (index = -1)
139
            return fallback;
140
        }
141
        try {
142
            return "pid" + Long.toString(Long.parseLong(jvmName.substring(0, index)));
143
        } catch (NumberFormatException e) {
144
            // ignore
145
        }
146
        return fallback;
147
    }
148

  
149
    public static class cleanOnShutdown extends Thread {
150

  
151
        private HSQLDataSource ds;
152

  
153
        public cleanOnShutdown(HSQLDataSource ds) {
154
            this.ds = ds;
155
        }
156

  
157
        public void run() {
158
            this.shutdown();
159
            this.delete();
160
        }
161

  
162
        private void delete() {
163
            File folder = HSQLDataSource.tmpDir;
164
            if ( folder == null ) {
165
                return;
166
            }
167
            try {
168
                logger.info("Deleting CRS temporary database folder (" + folder.getAbsolutePath() + ").");
169
                FileUtils.deleteDirectory(folder);
170
            } catch (IOException e) {
171
                logger.error("Can't delete CRS temporary database folder (" + folder + ".", e);
172
            }
173
        }
174

  
175
        private void shutdown() {
176
            try {
177
                logger.info("Shutdown the data-base.");
178
                Connection connection = this.ds.getConnection(false);
179
                final Statement statement = connection.createStatement();
180
                statement.execute("SHUTDOWN");
181
                statement.close();
182
                connection.close();
183
            } catch (Exception ex) {
184
                logger.error("Can't shutdown the database.", ex);
185
            }
186
        }
187
    }
188

  
189
    /**
190
     * Returns the priority for this data source. This priority is set to a
191
     * lower value than the {@linkplain AccessDataSource}'s one in order to give
192
     * the priority to the Access-backed database, if presents. Priorities are
193
     * set that way because:
194
     * <ul>
195
     * <li>The MS-Access format is the primary EPSG database format.</li>
196
     * <li>If a user downloads the MS-Access database himself, he probably wants
197
     * to use it.</li>
198
     * </ul>
199
     */
200
    public int getPriority() {
201
        return NORMAL_PRIORITY - 30;
202
    }
203

  
204
    /**
205
     * Returns {@code true} if the database contains data. This method returns
206
     * {@code false} if an empty EPSG database has been automatically created by
207
     * HSQL and not yet populated.
208
     */
209
    private static boolean dataExists(final Connection connection) throws SQLException {
210
        final ResultSet tables = connection.getMetaData().getTables(
211
                null, null, "EPSG_%", new String[]{"TABLE"});
212
        final boolean exists = tables.next();
213
        tables.close();
214
        return exists;
215
    }
216

  
217
    /**
218
     * Opens a connection to the database. If the cached tables are not
219
     * available, they will be created now from the SQL scripts bundled in this
220
     * plugin.
221
     */
222
    public Connection getConnection() throws SQLException {
223
        return getConnection(true);
224
    }
225

  
226
    public synchronized Connection getConnection(boolean initialize) throws SQLException {
227
        final String database = getDatabase();
228
        if ( StringUtils.isEmpty(database) ) {
229
            /*
230
             * The 'database' attribute is unset if the constructor has been unable
231
             * to locate the temporary directory, or to create the subdirectory.
232
             */
233
            throw new SQLException("Can't write to the temporary directory.");
234
        }
235
        Connection connection = super.getConnection();
236
        if ( initialize ) {
237
            initializeDatabase();
238
        }
239
        return connection;
240
    }
241

  
242
    public synchronized void initializeDatabase() throws SQLException {
243
        final Connection connection = super.getConnection();
244
        if ( dataExists(connection) ) {
245
            // Database already initialized
246
            return;
247
        }
248
        initializeDatabase2(connection);
249
    }
250
    
251
    private void initializeDatabase2(Connection connection) throws SQLException {
252
        /*
253
         * HSQL has created automatically an empty database. We need to populate it.
254
         * Executes the SQL scripts bundled in the JAR. In theory, each line contains
255
         * a full SQL statement. For this plugin however, we have compressed "INSERT
256
         * INTO" statements using Compactor class in this package.
257
         */
258
        Date t1 = new Date();
259
        logger.info("Creating temporary cached EPSG database in '"
260
                + getGtTmpDir().getAbsolutePath()
261
                + "' from '"
262
                + CrsFactory.getEpsgDatabaseFile()
263
                + "'."
264
        );
265
        final Statement statement = connection.createStatement();
266
        SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("Creating EPSG DB");
267
        try {
268
            int lineCounter = 0;
269
            File f = CrsFactory.getEpsgDatabaseFile();
270
            status.setAutoremove(true);
271
            status.setRangeOfValues(0, f.length());
272
            FileInputStream sqlInputStream = new FileInputStream(f);
273
            FileChannel chanel = sqlInputStream.getChannel();
274
            final BufferedReader in = new BufferedReader(new InputStreamReader(
275
                    sqlInputStream, "ISO-8859-1"));
276
            StringBuffer insertStatement = null;
277
            String line;
278
            while ( (line = in.readLine()) != null ) {
279
                status.setCurValue(chanel.position());
280
                line = line.trim();
281
                if( line.startsWith("-- " ) ) {
282
                    continue;
283
                }
284
                final int length = line.length();
285
                if ( length != 0 ) {
286
                    if ( line.startsWith("INSERT INTO") ) {
287
                        /*
288
                         * We are about to insert many rows into a single table.
289
                         * The row values appear in next lines; the current line
290
                         * should stop right after the VALUES keyword.
291
                         */
292
                        insertStatement = new StringBuffer(line);
293
                        continue;
294
                    }
295
                    if ( insertStatement != null ) {
296
                        /*
297
                         * We are about to insert a row. Prepend the "INSERT INTO"
298
                         * statement and check if we will have more rows to insert
299
                         * after this one.
300
                         */
301
                        final int values = insertStatement.length();
302
                        insertStatement.append(line);
303
                        final boolean hasMore = (line.charAt(length - 1) == ',');
304
                        if ( hasMore ) {
305
                            insertStatement.setLength(insertStatement.length() - 1);
306
                        }
307
                        line = insertStatement.toString();
308
                        insertStatement.setLength(values);
309
                        if ( !hasMore ) {
310
                            insertStatement = null;
311
                        }
312
                    }
313
                    statement.execute(line);
314
                    lineCounter++;
315
                    if( (lineCounter % 100) == 0) {
316
                        Thread.yield();
317
                    }
318
                }
319
            }
320
            in.close();
321
            Date t2 = new Date();
322
            logger.info("Created temporary EPSG database in "+ (t2.getTime()-t1.getTime())+ "ms.");
323
        } catch (IOException exception) {
324
            throw new SQLException("Can't read the SQL script.", exception);
325
        } finally {
326
            status.terminate();
327
            statement.close();
328
            connection.close();
329
        }
330
    }
331
    
332
    /**
333
     * Open a connection and creates an
334
     * {@linkplain FactoryUsingSQL EPSG factory} for it.
335
     *
336
     * @param factories The low-level factories to use for CRS creation.
337
     * @return The EPSG factory using HSQLDB SQL syntax.
338
     * @throws SQLException if connection to the database failed.
339
     */
340
    public AbstractAuthorityFactory createFactory(final FactoryGroup factories) throws SQLException {
341
        return new FactoryUsingHSQL(factories, getConnection());
342
    }
343

  
344
    public java.util.logging.Logger getParentLogger()
345
            throws SQLFeatureNotSupportedException {
346
        // TODO Auto-generated method stub
347
        return null;
348
    }
349

  
350
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
351
        // TODO Auto-generated method stub
352
        return false;
353
    }
354

  
355
    public <T> T unwrap(Class<T> iface) throws SQLException {
356
        // TODO Auto-generated method stub
357
        return null;
358
    }
359
}
0 360

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/java/es/idr/teledeteccion/connection/epsg/FactoryUsingHSQL.java
1
/*
2
 * Geotools 2 - OpenSource mapping toolkit
3
 * (C) 2005, Geotools Project Managment Committee (PMC)
4
 *
5
 *    This library is free software; you can redistribute it and/or
6
 *    modify it under the terms of the GNU Lesser General Public
7
 *    License as published by the Free Software Foundation; either
8
 *    version 2.1 of the License, or (at your option) any later version.
9
 *
10
 *    This library is distributed in the hope that it will be useful,
11
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 *    Lesser General Public License for more details.
14
 *
15
 *    You should have received a copy of the GNU Lesser General Public
16
 *    License along with this library; if not, write to the Free Software
17
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
package es.idr.teledeteccion.connection.epsg;
20

  
21
// J2SE dependencies
22
import java.sql.Connection;
23
import java.sql.SQLException;
24
import java.sql.Statement;
25
import java.util.regex.Matcher;
26
import java.util.regex.Pattern;
27

  
28
import org.geotools.referencing.factory.FactoryGroup;
29
import org.geotools.referencing.factory.epsg.FactoryUsingAnsiSQL;
30
// Geotools dependencies
31

  
32

  
33
/**
34
 * Adapts SQL statements for HSQL. The HSQL database engine doesn't understand
35
 * the parenthesis in (INNER JOIN ... ON) statements for the "BursaWolfParameters"
36
 * query. Unfortunatly, those parenthesis are required by MS-Access. We need to
37
 * removes them programmatically here.
38
 *
39
 * @version $Id: FactoryUsingHSQL.java 14624 2005-06-29 02:19:08Z desruisseaux $
40
 * @author Martin Desruisseaux
41
 *
42
 * @since 2.2
43
 */
44
final class FactoryUsingHSQL extends FactoryUsingAnsiSQL {
45
    /**
46
     * The regular expression pattern for searching the "FROM (" clause.
47
     * This is the pattern for the opening parenthesis.
48
     */
49
    private static final Pattern OPENING_PATTERN =
50
            Pattern.compile("\\s+FROM\\s*\\(",
51
            Pattern.CASE_INSENSITIVE);
52

  
53
    /**
54
     * Constructs the factory for the given connection to the HSQL database.
55
     */
56
    public FactoryUsingHSQL(final FactoryGroup factories, final Connection connection) {
57
        super(factories, connection);
58
    }
59

  
60
    /**
61
     * If the query contains a "FROM (" expression, remove the parenthesis.
62
     */
63
    public String adaptSQL(String query) {
64
        query = super.adaptSQL(query);
65
        final Matcher matcher = OPENING_PATTERN.matcher(query);
66
        if (matcher.find()) {
67
            final int opening = matcher.end()-1;
68
            final int length  = query.length();
69
            int closing = opening;
70
            for (int count=0; ; closing++) {
71
                if (closing >= length) {
72
                    // Should never happen with well formed SQL statement.
73
                    // If it happen anyway, don't change anything and let
74
                    // the HSQL driver produces a "syntax error" message.
75
                    return query;
76
                }
77
                switch (query.charAt(closing)) {
78
                    case '(': count++; break;
79
                    case ')': count--; break;
80
                    default : continue;
81
                }
82
                if (count == 0) {
83
                    break;
84
                }
85
            }
86
            query = query.substring(0,         opening) +
87
                    query.substring(opening+1, closing) +
88
                    query.substring(closing+1);
89
        }
90
        return query;
91
    }
92

  
93
    /**
94
     * Shutdown the HSQL database engine.
95
     */
96
    void shutdown(final boolean active) throws SQLException {
97
        if (active) {
98
            final Statement statement = connection.createStatement();
99
            statement.execute("SHUTDOWN");
100
            statement.close();
101
        }
102
//        super.shutdown(active); // FIXME: no tiene este metodo. 
103
    }
104
}
0 105

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/java/es/idr/teledeteccion/connection/iau2000/FactoryUsingHSQL.java
1
/*
2
 *    GeoTools - OpenSource mapping toolkit
3
 *    http://geotools.org
4
 *    (C) 2005-2006, GeoTools Project Managment Committee (PMC)
5
 * 
6
 *    This library is free software; you can redistribute it and/or
7
 *    modify it under the terms of the GNU Lesser General Public
8
 *    License as published by the Free Software Foundation;
9
 *    version 2.1 of the License.
10
 *
11
 *    This library 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 GNU
14
 *    Lesser General Public License for more details.
15
 */
16
package es.idr.teledeteccion.connection.iau2000;
17

  
18
// J2SE dependencies
19

  
20
import java.io.IOException;
21
import java.sql.Connection;
22
import java.sql.PreparedStatement;
23
import java.sql.ResultSet;
24
import java.sql.SQLException;
25
import java.sql.Statement;
26
import java.text.ParseException;
27
import java.util.Hashtable;
28
import java.util.Set;
29

  
30
import org.geotools.metadata.iso.citation.CitationImpl;
31
import org.geotools.referencing.CRS;
32
import org.geotools.referencing.wkt.Parser;
33
import org.gvsig.crs.CrsFactory;
34
import org.hsqldb.jdbc.jdbcDataSource;
35
import org.opengis.metadata.citation.Citation;
36
import org.opengis.referencing.FactoryException;
37
import org.opengis.referencing.IdentifiedObject;
38
import org.opengis.referencing.crs.CRSAuthorityFactory;
39
import org.opengis.referencing.crs.CRSFactory;
40
import org.opengis.referencing.crs.CompoundCRS;
41
import org.opengis.referencing.crs.CoordinateReferenceSystem;
42
import org.opengis.referencing.crs.DerivedCRS;
43
import org.opengis.referencing.crs.EngineeringCRS;
44
import org.opengis.referencing.crs.GeocentricCRS;
45
import org.opengis.referencing.crs.GeographicCRS;
46
import org.opengis.referencing.crs.ImageCRS;
47
import org.opengis.referencing.crs.ProjectedCRS;
48
import org.opengis.referencing.crs.TemporalCRS;
49
import org.opengis.referencing.crs.VerticalCRS;
50
import org.opengis.util.InternationalString;
51

  
52

  
53
public class FactoryUsingHSQL extends jdbcDataSource implements CRSAuthorityFactory {
54
   
55
    /**
56
     * The connection to the EPSG database.
57
     */
58
    protected Connection connection;
59
      
60
    //  object factory
61
    protected CRSFactory crsFactory;
62
    
63
    /** Cache of parsed CoordinateReferenceSystem WKT by IAU2000_NUMBER */
64
    private Hashtable cache = new Hashtable();
65
      
66
    /**
67
     * The database name.
68
     *
69
     * @since 2.3
70
     */
71
    public static final String DATABASE_NAME = "IAU2000";
72
    
73
    public FactoryUsingHSQL() {
74
    	 try {
75
             loadDefault();
76
         }
77
         catch( IOException oops ){
78
             System.err.println("Could not load "+ oops );
79
         }
80
    	//this(FactoryFinder.getCRSFactory(null));
81
    }   
82

  
83
	protected FactoryUsingHSQL(CRSFactory factory) {
84
		this.crsFactory = factory;
85
        try {
86
            loadDefault();
87
        }
88
        catch( IOException oops ){
89
            System.err.println("Could not load "+ oops );
90
        }
91
	}
92
	
93
	protected void loadDefault() throws IOException {
94
		String db = "jdbc:hsqldb:file:" + CrsFactory.getDataBaseFolder().getAbsolutePath() + "/iau2000";
95
		setDatabase(db);
96
		setUser("sa");
97
		try {
98
			connection = super.getConnection();
99
		} catch (SQLException e) {
100
			// TODO Auto-generated catch block
101
			e.printStackTrace();
102
		}
103
        
104
    }
105
	
106
	public CoordinateReferenceSystem createCoordinateReferenceSystem(String code) throws FactoryException {
107
		// TODO Auto-generated method stub
108
		CoordinateReferenceSystem returnValue = null;
109
		String wkt = null;
110
		String IAU2000_NUMBER = code.substring(code.indexOf(":")+1, code.length());
111
		int cod = Integer.parseInt(IAU2000_NUMBER);
112
        
113
		if( cache.contains( IAU2000_NUMBER ) ){
114
            Object value = cache.get( IAU2000_NUMBER );
115
            if( value instanceof Throwable ){
116
                throw new FactoryException( "WKT for "+code+" could not be parsed", (Throwable) value );
117
            }
118
            if( value instanceof CoordinateReferenceSystem){
119
                return (CoordinateReferenceSystem) value;
120
            }            
121
        }
122
		
123
		try {        	
124
        	final PreparedStatement stmt;
125
            /*stmt = connection.prepareStatement("SELECT IAU_WKT"
126
                                          + " FROM IAU2000"
127
                                          + " WHERE IAU_CODE = " + code.substring(code.indexOf(":")+1, code.length()));
128
            ResultSet result = stmt.executeQuery();
129
            */
130
            String sentence = "SELECT IAU_WKT"
131
            + " FROM IAU2000"
132
            + " WHERE IAU_CODE = " + code.substring(code.indexOf(":")+1, code.length());
133
        
134
        	Statement st = null;
135
    		ResultSet result = null;
136
        	st = connection.createStatement();
137
			result = st.executeQuery(sentence);
138
			st.close();        	
139
        	while (result.next()) {
140
                wkt    = result.getString("iau_wkt"); 	
141
            }
142
            result.close();
143
            if( wkt.indexOf( cod ) == -1){
144
            	wkt = wkt.trim();
145
            	wkt = wkt.substring(0, wkt.length()-1 );
146
            	wkt += ",AUTHORITY[\"IAU2000\",\""+cod+"\"]]";
147
            }
148
        } catch (SQLException exception) {
149
            System.out.println(exception);
150
        }
151
        Parser parser = new Parser();
152
        
153
		try {
154
			returnValue = parser.parseCoordinateReferenceSystem(wkt);
155
		} catch (ParseException e) {
156
			// TODO Auto-generated catch block
157
			System.out.println("Cadena WKT no ha podido ser parseada");
158
			e.printStackTrace();
159
		}
160
		
161
        return returnValue;		
162
	}
163

  
164
	public CompoundCRS createCompoundCRS(String arg0) throws FactoryException {
165
		// TODO Auto-generated method stub
166
		return null;
167
	}
168

  
169
	public DerivedCRS createDerivedCRS(String arg0) throws FactoryException {
170
		// TODO Auto-generated method stub
171
		return null;
172
	}
173

  
174
	public EngineeringCRS createEngineeringCRS(String arg0) throws FactoryException {
175
		// TODO Auto-generated method stub
176
		return null;
177
	}
178

  
179
	public GeographicCRS createGeographicCRS(String arg0) throws FactoryException {
180
		// TODO Auto-generated method stub
181
		return null;
182
	}
183

  
184
	public GeocentricCRS createGeocentricCRS(String arg0) throws FactoryException {
185
		// TODO Auto-generated method stub
186
		return null;
187
	}
188

  
189
	public ImageCRS createImageCRS(String arg0) throws FactoryException {
190
		// TODO Auto-generated method stub
191
		return null;
192
	}
193

  
194
	public ProjectedCRS createProjectedCRS(String arg0) throws FactoryException {
195
		// TODO Auto-generated method stub
196
		return null;
197
	}
198

  
199
	public TemporalCRS createTemporalCRS(String arg0) throws FactoryException {
200
		// TODO Auto-generated method stub
201
		return null;
202
	}
203

  
204
	public VerticalCRS createVerticalCRS(String arg0) throws FactoryException {
205
		// TODO Auto-generated method stub
206
		return null;
207
	}
208

  
209
	public Citation getAuthority() {		
210
		Citation citation = CitationImpl.createCitation("IAU2000");
211
		citation.getIdentifiers().add("IAU2000");
212
		return citation;
213
	}
214

  
215
	public Set getAuthorityCodes(Class arg0) throws FactoryException {
216
		// TODO Auto-generated method stub
217
		return null;
218
	}
219

  
220
	public InternationalString getDescriptionText(String arg0) throws FactoryException {
221
		// TODO Auto-generated method stub
222
		return null;
223
	}
224

  
225
	public IdentifiedObject createObject(String code) throws FactoryException {
226
		return createCoordinateReferenceSystem(code);
227
	}
228

  
229
	public Citation getVendor() {
230
		return CitationImpl.createCitation("IAU2000");
231
	}
232
}
0 233

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.264/org.gvsig.projection.jcrs.lib/src/main/java/es/idr/teledeteccion/connection/esri/FactoryUsingHSQL.java
1
/*
2
 *    GeoTools - OpenSource mapping toolkit
3
 *    http://geotools.org
4
 *    (C) 2005-2006, GeoTools Project Managment Committee (PMC)
5
 * 
6
 *    This library is free software; you can redistribute it and/or
7
 *    modify it under the terms of the GNU Lesser General Public
8
 *    License as published by the Free Software Foundation;
9
 *    version 2.1 of the License.
10
 *
11
 *    This library 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 GNU
14
 *    Lesser General Public License for more details.
15
 */
16
package es.idr.teledeteccion.connection.esri;
17

  
18
// J2SE dependencies
19

  
20
import java.io.IOException;
21
import java.sql.Connection;
22
import java.sql.ResultSet;
23
import java.sql.SQLException;
24
import java.sql.Statement;
25
import java.text.ParseException;
26
import java.util.Hashtable;
27
import java.util.Set;
28

  
29
import org.geotools.metadata.iso.citation.CitationImpl;
30
import org.geotools.referencing.CRS;
31
import org.geotools.referencing.wkt.Parser;
32
import org.gvsig.crs.CrsFactory;
33
import org.hsqldb.jdbc.jdbcDataSource;
34
import org.opengis.metadata.citation.Citation;
35
import org.opengis.referencing.FactoryException;
36
import org.opengis.referencing.IdentifiedObject;
37
import org.opengis.referencing.crs.CRSAuthorityFactory;
38
import org.opengis.referencing.crs.CRSFactory;
39
import org.opengis.referencing.crs.CompoundCRS;
40
import org.opengis.referencing.crs.CoordinateReferenceSystem;
41
import org.opengis.referencing.crs.DerivedCRS;
42
import org.opengis.referencing.crs.EngineeringCRS;
43
import org.opengis.referencing.crs.GeocentricCRS;
44
import org.opengis.referencing.crs.GeographicCRS;
45
import org.opengis.referencing.crs.ImageCRS;
46
import org.opengis.referencing.crs.ProjectedCRS;
47
import org.opengis.referencing.crs.TemporalCRS;
48
import org.opengis.referencing.crs.VerticalCRS;
49
import org.opengis.util.InternationalString;
50

  
51

  
52
public class FactoryUsingHSQL extends jdbcDataSource implements CRSAuthorityFactory {
53
   
54

  
55
    
56
    /**
57
     * The connection to the EPSG database.
58
     */
59
    protected Connection connection;
60
      
61
    //  object factory
62
    protected CRSFactory crsFactory;
63
    
64
    /** Cache of parsed CoordinateReferenceSystem WKT by ESRI_NUMBER */
65
    private Hashtable cache = new Hashtable();
66
      
67
    /**
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff