Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libGPE-GML / src / org / gvsig / gpe / gml / GPEGmlParser.java @ 11622

History | View | Annotate | Download (15.4 KB)

1
package org.gvsig.gpe.gml;
2
import java.io.File;
3
import java.io.FileInputStream;
4
import java.io.FileNotFoundException;
5
import java.io.IOException;
6
import java.io.InputStream;
7
import java.net.ConnectException;
8
import java.net.MalformedURLException;
9
import java.net.URI;
10
import java.net.URL;
11
import java.net.UnknownHostException;
12
import java.util.Iterator;
13
import java.util.StringTokenizer;
14

    
15
import org.gvsig.exceptions.BaseException;
16
import org.gvsig.gpe.gml.bindings.FeatureMemberTypeBinding;
17
import org.gvsig.gpe.gml.bindings.FeatureTypeBinding;
18
import org.gvsig.gpe.gml.bindings.geometries.LinearRingTypeBinding;
19
import org.gvsig.gpe.gml.factories.XMLSchemasFactory;
20
import org.gvsig.gpe.gml.utils.CompareUtils;
21
import org.gvsig.gpe.gml.utils.Utilities;
22
import org.gvsig.gpe.gml.writer.GPEGmlWriterHandler;
23
import org.gvsig.gpe.writers.GPEWriterHandler;
24
import org.gvsig.gpe.xml.GPEXmlParser;
25
import org.kxml2.io.KXmlParser;
26
import org.xml.sax.SAXException;
27
import org.xml.sax.helpers.ParserFactory;
28
import org.xmlpull.v1.XmlPullParser;
29
import org.xmlpull.v1.XmlPullParserException;
30

    
31
import com.sun.xml.xsom.XSElementDecl;
32
import com.sun.xml.xsom.XSSchema;
33
import com.sun.xml.xsom.XSSchemaSet;
34
import com.sun.xml.xsom.XSType;
35
import com.sun.xml.xsom.parser.XSOMParser;
36

    
37
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
38
 *
39
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
40
 *
41
 * This program is free software; you can redistribute it and/or
42
 * modify it under the terms of the GNU General Public License
43
 * as published by the Free Software Foundation; either version 2
44
 * of the License, or (at your option) any later version.
45
 *
46
 * This program is distributed in the hope that it will be useful,
47
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
49
 * GNU General Public License for more details.
50
 *
51
 * You should have received a copy of the GNU General Public License
52
 * along with this program; if not, write to the Free Software
53
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
54
 *
55
 * For more information, contact:
56
 *
57
 *  Generalitat Valenciana
58
 *   Conselleria d'Infraestructures i Transport
59
 *   Av. Blasco Ib??ez, 50
60
 *   46010 VALENCIA
61
 *   SPAIN
62
 *
63
 *      +34 963862235
64
 *   gvsig@gva.es
65
 *      www.gvsig.gva.es
66
 *
67
 *    or
68
 *
69
 *   IVER T.I. S.A
70
 *   Salamanca 50
71
 *   46005 Valencia
72
 *   Spain
73
 *
74
 *   +34 963163400
75
 *   dac@iver.es
76
 */
77
/* CVS MESSAGES:
78
 *
79
 * $Id: GPEGmlParser.java 11622 2007-05-14 11:23:12Z jorpiell $
80
 * $Log$
81
 * Revision 1.10  2007-05-14 11:23:12  jorpiell
82
 * ProjectionFactory updated
83
 *
84
 * Revision 1.9  2007/05/14 09:52:26  jorpiell
85
 * Tupes separator tag updated
86
 *
87
 * Revision 1.8  2007/05/09 06:54:25  jorpiell
88
 * Change the File by URI
89
 *
90
 * Revision 1.7  2007/05/07 07:06:46  jorpiell
91
 * Add a constructor with the name and the description fields
92
 *
93
 * Revision 1.6  2007/04/25 11:08:38  csanchez
94
 * Parseo correcto con XSOM de esquemas, EntityResolver para los imports
95
 *
96
 * Revision 1.5  2007/04/20 12:04:10  csanchez
97
 * Actualizacion protoripo libGPE, A?adidos test para el parser, parseo con XSOM
98
 *
99
 * Revision 1.4  2007/04/19 11:51:43  csanchez
100
 * Actualizacion protoripo libGPE
101
 *
102
 * Revision 1.1  2007/04/18 12:54:45  csanchez
103
 * Actualizacion protoripo libGPE
104
 *
105
 *
106
 */
107
/**
108
 * @author Carlos S?nchez Peri??n (sanchez_carper@gva.es)
109
 **/
110

    
111
public class GPEGmlParser extends GPEXmlParser{
112

    
113
        private XSOMParser schemaParser = null;
114
        private XmlPullParser fileParser = null;
115
        private String mainTag = null;
116
        private File schemaFile = null;
117
        private int no_schema = 1;
118
        
119
        /*********************
120
         * <GPEGmlParser> 
121
         * Constructor Method
122
         *********************/
123
        public GPEGmlParser(String name, String description) {
124
                super(name, description);
125
        }
126
        
127
        /**************************************************************
128
         * <getFormats>
129
         * Returns the file extensions that are accepted to GML Parser
130
         * @return String[] Accepted Extensions
131
         **************************************************************/
132
        public String[] getFormats() {
133
                String[] formats = new String[2];
134
                formats[0] = "GML";
135
                formats[1] = "XML";
136
                return formats;
137
        }
138
        
139
        /************************************************************************
140
         * <accept>
141
         * Returns true if the file is a gml file and the parser has to parse it
142
         * @param URI uri
143
         * @return boolean 
144
         ************************************************************************/
145
        public boolean accept(URI uri) {
146
                if ((uri.getPath().toUpperCase().endsWith("GML"))
147
                                || (uri.getPath().toUpperCase().endsWith("XML"))) {
148
                        return true;
149
                }
150
                return false;
151
        }
152

    
153
        /**********************************************
154
         * <getVersions>
155
         * Returns the gml versions that are supported
156
         * @return String[] Accepted Versions
157
         **********************************************/
158
        public String[] getVersions() {
159
                // TODO Ap?ndice de m?todo generado autom?ticamente
160
                return null;
161
        }
162
        
163
        /*************************************
164
         * <createInputStream>
165
         * Creates an InputStream from a file.
166
         * @param File file
167
         * @return FileInputStream
168
         *************************************/
169
        protected InputStream createInputStream(File file) throws FileNotFoundException {
170
                // TODO Ap?ndice de m?todo generado autom?ticamente
171
                return new FileInputStream(file);
172
        }
173
        
174
        /****************************
175
         * <initParse>
176
         * Starts to parse the file.
177
         ****************************/
178
        protected void initParse() {
179
                //First, it gets the file parser.
180
                fileParser = getParser();
181
                //it has to parse the head 
182
                parseHead();                
183
        }        
184

    
185
        /************************************************************************
186
         * <parseHead>
187
         * parses the head of the gml file, it contains the URI of 
188
         * the remoteschema and namespaces, normally its a FeatureCollection Tag 
189
         ************************************************************************/
190
        private void parseHead(){
191
                //nextTag() --> Method from KXML library to get next full tag
192
                try {
193
                        fileParser.nextTag();
194
                } catch (XmlPullParserException e) {
195
                        // TODO Bloque catch generado autom?ticamente
196
                        System.out.println("Error en XmlPullParser al intentar obtener la siguiente etiqueta: "+e.getMessage());
197
                        
198
                } catch (IOException e) {
199
                        // TODO Bloque catch generado autom?ticamente
200
                        System.out.println("Error al leer la siguiente etiqueta en XmlPullParser: "+e.getMessage());
201
                        
202
                }
203
                //It keeps the name of the start tag to compare with the close tag later
204
                mainTag = fileParser.getName();
205
                //If it has namespace before the ":" we keep the maintag without namespace 
206
                int pos = mainTag.indexOf(":");
207
                if (pos > 0){
208
                        mainTag = mainTag.substring(mainTag.indexOf(":") + 1,mainTag.length());
209
                }
210
                //It start to get all the attributes and values from the header tag
211
                for (int i = 0 ; i < fileParser.getAttributeCount() ; i++){
212
                        String attName = fileParser.getAttributeName(i);
213
                        String attValue = fileParser.getAttributeValue(i);
214
                        
215
                                                
216
                        //it splits the attributes names at the both sides from ":"
217
                        String[] ns = attName.split(":");
218
                        
219
                        //If it founds the 'xmlns' is a new namespace declaration and it has to parse it
220
                        if ((ns.length>1) && (ns[0].compareTo(GMLTags.XML_NAMESPACE)==0)){
221
                                parseNameSpace(ns[1],attValue);
222
                        }
223
                        
224
                        //If its the "SCHEMA LOCATION" attribute, it means that there are schema and it tries to parse it
225
                        if ((ns.length>1) && (ns[1].compareTo(GMLTags.XML_SCHEMA_LOCATION)==0)){
226
                                no_schema=0;
227
                                parseSchemaLocation(ns[0],attValue);
228
                        }
229
                }
230
                if (no_schema==1){
231
                        //Alert that th GML File hasn't schema but it tries to parse
232
                        //warnings.setElement(new GMLWarningNoSchema());
233
                }
234
        }
235
        
236
        /***********************************************
237
         * <parseSchemaLocation>
238
         * It downloads the schema's file and parse it
239
         * @param xmlnsName : Alias
240
         * @param xmlnsValue: URI 
241
         ***********************************************/
242
        private void parseSchemaLocation(String schemaAlias, String schemaURI){
243
                //It take the name of the schemas file to open or downlad 
244
                StringTokenizer tokenizer = new StringTokenizer(schemaURI, " \t");
245
        while (tokenizer.hasMoreTokens()){
246
            String URI = tokenizer.nextToken();
247
            if (!tokenizer.hasMoreTokens()){
248
                            //If it hasn't the name of the schemas file or dont find it,
249
                            //it exits, and tries to parse without schema
250
                            //warnings.setElement(new GMLWarningNotFound(null,null));
251
                            System.out.println("Error, esquema no encontrado.PARSEO SIN ESQUEMA ");
252
                            
253
            }
254
            else
255
            {
256
                            String schemaLocation = tokenizer.nextToken();
257
                            //It add the schemaLocation to the hashtable
258
                            try {
259
                                        XMLSchemasFactory.addSchemaLocation(schemaAlias,URI,schemaLocation);
260
                                } 
261
                                catch (BaseException e) {
262
                                        // TODO Auto-generated catch block
263
                                        //warnings.setElement(new GMLWarningMalformed());
264
                                        System.out.println("Error al a?adir el esquema o esquema mal formado: "+e.getMessage());
265
                                }
266
                                //It downloads the schema if it's a remote schema
267
                                schemaFile = getSchemaFile(schemaLocation);
268
                            initSchemaParser();
269
                                try {
270
                                        //It parses the schema.
271
                                        schemaParser.parse(schemaFile);
272
                                } catch (SAXException e) {
273
                                        // TODO Bloque catch generado autom?ticamente
274
                                        System.out.println("Error al parsear el Schema: "+e.getMessage());
275
                                } catch (IOException e) {
276
                                        // TODO Bloque catch generado autom?ticamente
277
                                        System.out.println("Error de lectura/escritura del esquema: "+e.getMessage());
278
                                }
279
                                try {
280
//                                Iterator itr = schemaParser.getResult().iterateSchema();
281
                                        showSchemaInfo();
282
                                } catch (SAXException e) {
283
                                        // TODO Bloque catch generado autom?ticamente
284
                                        System.out.println("Excepci?n del parser SAX: "+e.getMessage());
285
                                }
286
            }
287
        }
288
        }
289
        
290
        /*******************************
291
         * <initSchemaParser>
292
         * initializes the XSOM parser
293
         *******************************/
294
        private void initSchemaParser() {
295
                //initialize the XSOMParser.
296
                if (schemaParser==null){
297
                        schemaParser = new XSOMParser();
298
                        GMLSchemaEntityResolver schemaResolver = new GMLSchemaEntityResolver();
299
                         // Crearemos un EntityResolver() para los imports e includes 
300
                         // que nos convenga almacenar localmente para un parseo r?pido
301
                         // o configurar una ruta local para la b?squeda por defecto.
302
                        schemaParser.setEntityResolver(schemaResolver);
303
                        
304
                }
305
        }
306

    
307
        /************************************************
308
         * <parseNamespace>
309
         * It adds an XML namespace tag to the hashtable
310
         * @param xmlnsName : Namespace
311
         * @param xmlnsValue: URI 
312
         ************************************************/
313
        private void parseNameSpace(String xmlnsName,String xmlnsValue){
314
                XMLSchemasFactory.addType(xmlnsName,xmlnsValue);                
315
        }
316

    
317
        /****************************************************************************
318
         * <getSchemaFile>
319
         * It downloads the schema if it's a remote schema
320
         * else it tries to open a local file and return if it's succesfull
321
         * @param String schema location
322
         * @return File local (if is a remote file then first it has to download it)
323
         ****************************************************************************/
324
        private File getSchemaFile(String schemaLocation){
325
                File f = null;
326
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
327
                //If it is a local file, it has to construct the absolute route
328
                if (schemaLocation.indexOf("http://") != 0){
329
                        f = new File(schemaLocation);
330
                        if (!(f.isAbsolute())){
331
                                schemaLocation = new File(getMainFile()).getParentFile().getAbsolutePath() + File.separator +  schemaLocation;
332
                                f = new File(schemaLocation);
333
                        }
334
                        return f;
335
                }
336
                //Else it is an URL direction and it has to download it.
337
                else {
338
                        URL url;
339
                
340
                        try {
341
                                url = new URL(schemaLocation);
342
                                //Download the schema without cancel option.
343
                                f = Utilities.downloadFile(url,"gml_schmema.xsd");                                
344
                        } catch (MalformedURLException e) {
345
                                // TODO Bloque catch generado autom?ticamente
346
                                System.out.println("Error, URL del esquema mal formada: "+e.getMessage());
347
                        } catch (ConnectException e) {
348
                                // TODO Bloque catch generado autom?ticamente
349
                                System.out.println("Error al descargar esquema, Imposible conectar: "+e.getMessage());
350
                        } catch (UnknownHostException e) {
351
                                // TODO Bloque catch generado autom?ticamente
352
                                System.out.println("Error al descargar esquema, Host desconocido: "+e.getMessage());
353
                        } catch (IOException e) {
354
                                // TODO Bloque catch generado autom?ticamente
355
                                System.out.println("Erroral descargar esquema, Fallo de lectura/escritura: "+e.getMessage());
356
                        }
357
                        return f;        
358
                }
359
        }
360
        
361
        /**********************************
362
         * <showSchemaInfo>
363
         * Shows the XSSchema Information 
364
         **********************************/
365
        public void showSchemaInfo() throws SAXException{
366
                Iterator itr = schemaParser.getResult().iterateSchema();
367
                while( itr.hasNext() ) {
368
                          XSSchema s = (XSSchema)itr.next();
369
                          System.out.println("Target namespace: "+s.getTargetNamespace());
370
                          
371
                          Iterator jtr = s.iterateElementDecls();
372
                          while( jtr.hasNext() ) {
373
                                  XSElementDecl e = (XSElementDecl)jtr.next();
374
                            
375
                                  System.out.print("ELEMENT:" + e.getName() );
376
                                  if (e.getAnnotation() != null){
377
                                          System.out.print(" ANOTATION: " + e.getAnnotation().getAnnotation());
378
                                  }
379
                                  XSType type = e.getType();
380
                                  if (type.getAnnotation() != null){
381
                                          System.out.print(" ANOTATION TYPE: " + type.getAnnotation().getLocator().toString());
382
                                  }
383
                                  if( e.isAbstract() ){
384
                                          System.out.print(" (abstract)");
385
                                  }
386
                                  System.out.println();
387
                          }
388
                } 
389
                schemaParser.getResult().iterateSchema();
390
                while( itr.hasNext() ) {
391
                        XSSchema s = (XSSchema)itr.next();
392
                        System.out.println("Target namespace: "+s.getTargetNamespace());
393
                  
394
                        Iterator jtr = s.iterateElementDecls();
395
                        while( jtr.hasNext() ) {
396
                                XSElementDecl e = (XSElementDecl)jtr.next();
397
                    
398
                                System.out.print( e.getName() );
399
                                if( e.isAbstract() )
400
                                        System.out.print(" (abstract)");
401
                                System.out.println();
402
                        }
403
                }
404
        }
405
}