Revision 335

View differences:

org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.16/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.16/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.16/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.16/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.16/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.16/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.16/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.io.BufferedReader;
23
import java.io.File;
24
import java.io.FileInputStream;
25
import java.io.IOException;
26
import java.io.InputStreamReader;
27
import java.lang.management.ManagementFactory;
28
import java.sql.Connection;
29
import java.sql.ResultSet;
30
import java.sql.SQLException;
31
import java.sql.SQLFeatureNotSupportedException;
32
import java.sql.Statement;
33

  
34
import org.apache.commons.io.FileUtils;
35
import org.geotools.referencing.factory.AbstractAuthorityFactory;
36
import org.geotools.referencing.factory.FactoryGroup;
37
import org.geotools.referencing.factory.epsg.DataSource;
38
import org.geotools.referencing.factory.epsg.FactoryUsingSQL;
39
import org.gvsig.crs.CrsFactory;
40
// HSQL dependencies
41
import org.hsqldb.jdbc.jdbcDataSource;
42
import org.slf4j.Logger;
43
import org.slf4j.LoggerFactory;
44

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

  
71
    // 20090518 cmartinez: Use a different tmp dir for each geotools instance
72
    private static File tmpDir = null;
73

  
74
    private static final Logger logger = LoggerFactory.getLogger(HSQLDataSource.class);
75

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

  
111
    private File getGtTmpDir() {
112
        if ( tmpDir == null ) {
113
            tmpDir = new File(CrsFactory.getDataBaseFolder(), "temp-" + getProcessId());
114
            Runtime.getRuntime().addShutdownHook(new cleanOnShutdown(this));
115
        }
116
        return tmpDir;
117
    }
118

  
119
    private static String getProcessId() {
120
        String fallback = "time" + System.currentTimeMillis();
121

  
122
        // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
123
        final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
124
        final int index = jvmName.indexOf('@');
125
        if ( index < 1 ) {
126
            // part before '@' empty (index = 0) / '@' not found (index = -1)
127
            return fallback;
128
        }
129
        try {
130
            return "pid" + Long.toString(Long.parseLong(jvmName.substring(0, index)));
131
        } catch (NumberFormatException e) {
132
            // ignore
133
        }
134
        return fallback;
135
    }
136

  
137
    public static class cleanOnShutdown extends Thread {
138

  
139
        private HSQLDataSource ds;
140

  
141
        public cleanOnShutdown(HSQLDataSource ds) {
142
            this.ds = ds;
143
        }
144

  
145
        public void run() {
146
            this.shutdown();
147
            this.delete();
148
        }
149

  
150
        private void delete() {
151
            File folder = HSQLDataSource.tmpDir;
152
            if ( folder == null ) {
153
                return;
154
            }
155
            try {
156
                logger.info("Deleting CRS temporary database folder (" + folder.getAbsolutePath() + ").");
157
                FileUtils.deleteDirectory(folder);
158
            } catch (IOException e) {
159
                logger.error("Can't delete CRS temporary database folder (" + folder + ".", e);
160
            }
161
        }
162

  
163
        private void shutdown() {
164
            try {
165
                logger.info("Shutdown the data-base.");
166
                Connection connection = this.ds.getConnection(false);
167
                final Statement statement = connection.createStatement();
168
                statement.execute("SHUTDOWN");
169
                statement.close();
170
                connection.close();
171
            } catch (Exception ex) {
172
                logger.error("Can't shutdown the database.", ex);
173
            }
174
        }
175
    }
176

  
177
    /**
178
     * Returns the priority for this data source. This priority is set to a
179
     * lower value than the {@linkplain AccessDataSource}'s one in order to give
180
     * the priority to the Access-backed database, if presents. Priorities are
181
     * set that way because:
182
     * <ul>
183
     * <li>The MS-Access format is the primary EPSG database format.</li>
184
     * <li>If a user downloads the MS-Access database himself, he probably wants
185
     * to use it.</li>
186
     * </ul>
187
     */
188
    public int getPriority() {
189
        return NORMAL_PRIORITY - 30;
190
    }
191

  
192
    /**
193
     * Returns {@code true} if the database contains data. This method returns
194
     * {@code false} if an empty EPSG database has been automatically created by
195
     * HSQL and not yet populated.
196
     */
197
    private static boolean dataExists(final Connection connection) throws SQLException {
198
        final ResultSet tables = connection.getMetaData().getTables(
199
                null, null, "EPSG_%", new String[]{"TABLE"});
200
        final boolean exists = tables.next();
201
        tables.close();
202
        return exists;
203
    }
204

  
205
    /**
206
     * Opens a connection to the database. If the cached tables are not
207
     * available, they will be created now from the SQL scripts bundled in this
208
     * plugin.
209
     */
210
    public Connection getConnection() throws SQLException {
211
        return getConnection(true);
212
    }
213

  
214
    public Connection getConnection(boolean initialize) throws SQLException {
215
        final String database = getDatabase();
216
        if ( database == null || database.trim().length() == 0 ) {
217
            /*
218
             * The 'database' attribute is unset if the constructor has been unable
219
             * to locate the temporary directory, or to create the subdirectory.
220
             */
221
            throw new SQLException("Can't write to the temporary directory.");
222
        }
223
        Connection connection = super.getConnection();
224
        if ( !initialize ) {
225
            return connection;
226
        }
227
        if ( !dataExists(connection) ) {
228
            /*
229
             * HSQL has created automatically an empty database. We need to populate it.
230
             * Executes the SQL scripts bundled in the JAR. In theory, each line contains
231
             * a full SQL statement. For this plugin however, we have compressed "INSERT
232
             * INTO" statements using Compactor class in this package.
233
             */
234
            logger.info("Creating temporary cached EPSG database in '"
235
                    + getGtTmpDir().getAbsolutePath()
236
                    + "' from '"
237
                    + CrsFactory.getEpsgDatabaseFile()
238
                    + "'."
239
            );
240
            final Statement statement = connection.createStatement();
241
            try {
242
                FileInputStream sqlInputStream = new FileInputStream(CrsFactory.getEpsgDatabaseFile());
243
                final BufferedReader in = new BufferedReader(new InputStreamReader(
244
                        sqlInputStream, "ISO-8859-1"));
245
                StringBuffer insertStatement = null;
246
                String line;
247
                while ( (line = in.readLine()) != null ) {
248
                    line = line.trim();
249
                    if( line.startsWith("-- " ) ) {
250
                        continue;
251
                    }
252
                    final int length = line.length();
253
                    if ( length != 0 ) {
254
                        if ( line.startsWith("INSERT INTO") ) {
255
                            /*
256
                             * We are about to insert many rows into a single table.
257
                             * The row values appear in next lines; the current line
258
                             * should stop right after the VALUES keyword.
259
                             */
260
                            insertStatement = new StringBuffer(line);
261
                            continue;
262
                        }
263
                        if ( insertStatement != null ) {
264
                            /*
265
                             * We are about to insert a row. Prepend the "INSERT INTO"
266
                             * statement and check if we will have more rows to insert
267
                             * after this one.
268
                             */
269
                            final int values = insertStatement.length();
270
                            insertStatement.append(line);
271
                            final boolean hasMore = (line.charAt(length - 1) == ',');
272
                            if ( hasMore ) {
273
                                insertStatement.setLength(insertStatement.length() - 1);
274
                            }
275
                            line = insertStatement.toString();
276
                            insertStatement.setLength(values);
277
                            if ( !hasMore ) {
278
                                insertStatement = null;
279
                            }
280
                        }
281
                        statement.execute(line);
282
                    }
283
                }
284
                in.close();
285
            } catch (IOException exception) {
286
                statement.close();
287
                SQLException e = new SQLException("Can't read the SQL script.");
288
                e.initCause(exception);
289
                throw e;
290
            }
291
            statement.close();
292
            connection.close();
293
            connection = super.getConnection();
294
            assert dataExists(connection);
295
        }
296
        return connection;
297
    }
298

  
299
    /**
300
     * Open a connection and creates an
301
     * {@linkplain FactoryUsingSQL EPSG factory} for it.
302
     *
303
     * @param factories The low-level factories to use for CRS creation.
304
     * @return The EPSG factory using HSQLDB SQL syntax.
305
     * @throws SQLException if connection to the database failed.
306
     */
307
    public AbstractAuthorityFactory createFactory(final FactoryGroup factories) throws SQLException {
308
        return new FactoryUsingHSQL(factories, getConnection());
309
    }
310

  
311
    public java.util.logging.Logger getParentLogger()
312
            throws SQLFeatureNotSupportedException {
313
        // TODO Auto-generated method stub
314
        return null;
315
    }
316

  
317
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
318
        // TODO Auto-generated method stub
319
        return false;
320
    }
321

  
322
    public <T> T unwrap(Class<T> iface) throws SQLException {
323
        // TODO Auto-generated method stub
324
        return null;
325
    }
326
}
0 327

  
org.gvsig.projection.jcrs/tags/org.gvsig.projection.jcrs-2.1.16/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.16/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.16/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
    /**
68
     * The database name.
69
     *
70
     * @since 2.3
71
     */
72
    public static final String DATABASE_NAME = "ESRI";
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() + "/esri";
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
		CoordinateReferenceSystem returnValue = null;
109
		String wkt = null;
110
		String ESRI_NUMBER = code.substring(code.indexOf(":")+1, code.length());
111
		int cod = Integer.parseInt(ESRI_NUMBER);
112
        
113
		if( cache.contains( ESRI_NUMBER ) ){
114
            Object value = cache.get( ESRI_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
        	 
125
            String sentence = "SELECT ESRI_WKT"
126
            + " FROM ESRI"
127
            + " WHERE ESRI_CODE = " + code.substring(code.indexOf(":")+1, code.length());
128
        
129
        	Statement st = null;
130
    		ResultSet result = null;
131
        	st = connection.createStatement();
132
			result = st.executeQuery(sentence);
133
			st.close();
134
        	while (result.next()) {
135
                wkt    = result.getString("esri_wkt"); 	
136
            }
137
            result.close();
138
            if( wkt.indexOf( cod ) == -1){
139
            	wkt = wkt.trim();
140
            	wkt = wkt.substring(0, wkt.length()-1 );
141
            	wkt += ",AUTHORITY[\"ESRI\",\""+cod+"\"]]";
142
            }
143
        } catch (SQLException exception) {
144
            System.out.println(exception);
145
        }
146
        Parser parser = new Parser();
147
        
148
		try {
149
			returnValue = parser.parseCoordinateReferenceSystem(wkt);
150
		} catch (ParseException e) {
151
			// TODO Auto-generated catch block
152
			System.out.println("Cadena WKT no ha podido ser parseada");
153
			e.printStackTrace();
154
		}
155
		
156
        return returnValue;			
157
	}
158

  
159
	public CompoundCRS createCompoundCRS(String arg0) throws FactoryException {
160
		// TODO Auto-generated method stub
161
		return null;
162
	}
163

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

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

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

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

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

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

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

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

  
204
	public Citation getAuthority() {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff