Statistics
| Revision:

root / trunk / libraries / libGPE-GML / src / org / gvsig / gpe / gml / GPEGmlParser.java @ 11464

History | View | Annotate | Download (14.9 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.URL;
10
import java.net.UnknownHostException;
11
import java.util.Iterator;
12
import java.util.StringTokenizer;
13

    
14
import org.gvsig.exceptions.BaseException;
15
import org.gvsig.gpe.gml.factories.XMLSchemasFactory;
16
import org.gvsig.gpe.gml.utils.Utilities;
17
import org.gvsig.gpe.gml.writer.GPEGmlWriterHandler;
18
import org.gvsig.gpe.writers.GPEWriterHandler;
19
import org.gvsig.gpe.xml.GPEXmlParser;
20
import org.xml.sax.SAXException;
21
import org.xmlpull.v1.XmlPullParser;
22
import org.xmlpull.v1.XmlPullParserException;
23

    
24
import com.sun.xml.xsom.XSElementDecl;
25
import com.sun.xml.xsom.XSSchema;
26
import com.sun.xml.xsom.XSSchemaSet;
27
import com.sun.xml.xsom.XSType;
28
import com.sun.xml.xsom.parser.XSOMParser;
29

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

    
95
public class GPEGmlParser extends GPEXmlParser{
96

    
97
        private XSOMParser schemaParser = null;
98
        private XmlPullParser fileParser = null;
99
        private String mainTag = null;
100
        private File schemaFile = null;
101
        private int no_schema = 1;
102
        
103
        /*********************
104
         * <GPEGmlParser> 
105
         * Constructor Method
106
         *********************/
107
        public GPEGmlParser(String name, String description) {
108
                super(name, description);
109
        }
110
        
111
        /**************************************************************
112
         * <getFormats>
113
         * Returns the file extensions that are accepted to GML Parser
114
         * @return String[] Accepted Extensions
115
         **************************************************************/
116
        public String[] getFormats() {
117
                String[] formats = new String[2];
118
                formats[0] = "GML";
119
                formats[1] = "XML";
120
                return formats;
121
        }
122
        
123
        /************************************************************************
124
         * <accept>
125
         * Returns true if the file is a gml file and the parser has to parse it
126
         * @param File file
127
         * @return boolean 
128
         ************************************************************************/
129
        public boolean accept(File file) {
130
                if ((file.getName().toUpperCase().endsWith("GML"))
131
                                || (file.getName().toUpperCase().endsWith("XML"))) {
132
                        return true;
133
                }
134
                return false;
135
        }
136

    
137
        /**********************************************
138
         * <getVersions>
139
         * Returns the gml versions that are supported
140
         * @return String[] Accepted Versions
141
         **********************************************/
142
        public String[] getVersions() {
143
                // TODO Ap?ndice de m?todo generado autom?ticamente
144
                return null;
145
        }
146
        
147
        /*************************************
148
         * <createInputStream>
149
         * Creates an InputStream from a file.
150
         * @param File file
151
         * @return FileInputStream
152
         *************************************/
153
        protected InputStream createInputStream(File file) throws FileNotFoundException {
154
                // TODO Ap?ndice de m?todo generado autom?ticamente
155
                return new FileInputStream(file);
156
        }
157
        
158
        /****************************
159
         * <initParse>
160
         * Starts to parse the file.
161
         ****************************/
162
        protected void initParse() {
163
                //First, it gets the file parser.
164
                fileParser = getParser();
165
                //it has to parse the head 
166
                parseHead();
167
        }
168

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

    
291
        /************************************************
292
         * <parseNamespace>
293
         * It adds an XML namespace tag to the hashtable
294
         * @param xmlnsName : Namespace
295
         * @param xmlnsValue: URI 
296
         ************************************************/
297
        private void parseNameSpace(String xmlnsName,String xmlnsValue){
298
                XMLSchemasFactory.addType(xmlnsName,xmlnsValue);                
299
        }
300

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