Statistics
| Revision:

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

History | View | Annotate | Download (9.18 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.StringTokenizer;
12

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

    
23
import com.sun.xml.xsom.parser.XSOMParser;
24

    
25
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
26
 *
27
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
28
 *
29
 * This program is free software; you can redistribute it and/or
30
 * modify it under the terms of the GNU General Public License
31
 * as published by the Free Software Foundation; either version 2
32
 * of the License, or (at your option) any later version.
33
 *
34
 * This program is distributed in the hope that it will be useful,
35
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37
 * GNU General Public License for more details.
38
 *
39
 * You should have received a copy of the GNU General Public License
40
 * along with this program; if not, write to the Free Software
41
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
42
 *
43
 * For more information, contact:
44
 *
45
 *  Generalitat Valenciana
46
 *   Conselleria d'Infraestructures i Transport
47
 *   Av. Blasco Ib??ez, 50
48
 *   46010 VALENCIA
49
 *   SPAIN
50
 *
51
 *      +34 963862235
52
 *   gvsig@gva.es
53
 *      www.gvsig.gva.es
54
 *
55
 *    or
56
 *
57
 *   IVER T.I. S.A
58
 *   Salamanca 50
59
 *   46005 Valencia
60
 *   Spain
61
 *
62
 *   +34 963163400
63
 *   dac@iver.es
64
 */
65
/* CVS MESSAGES:
66
 *
67
 * $Id: GPEGmlParser.java 11265 2007-04-19 11:56:03Z csanchez $
68
 * $Log$
69
 * Revision 1.4  2007-04-19 11:51:43  csanchez
70
 * Actualizacion protoripo libGPE
71
 *
72
 * Revision 1.1  2007/04/18 12:54:45  csanchez
73
 * Actualizacion protoripo libGPE
74
 *
75
 *
76
 */
77
/**
78
 * @author Carlos S?nchez Peri??n (sanchez_carper@gva.es)
79
 */
80
public class GPEGmlParser extends GPEXmlParser{
81

    
82
        private XSOMParser schemaParser = null;
83
        private XmlPullParser fileParser = null;
84
        private String mainTag = null;
85
        private File mainFile = null;
86
        private File schemaFile = null;
87
        private int no_schema = 1;
88
        
89
        public GPEGmlParser() {
90
                //First, it gets the file parser.
91
                fileParser = getParser();
92
                // TODO Ap?ndice de constructor generado autom?ticamente
93
        }
94
        
95
        /*
96
         * (non-Javadoc)
97
         * @see org.gvsig.gpe.GPEParser#getFormats()
98
         */
99
        public String[] getFormats() {
100
                String[] formats = new String[2];
101
                formats[0] = "GML";
102
                formats[1] = "XML";
103
                return formats;
104
        }
105

    
106
        public boolean accept(File file) {
107
                this.mainFile = file;
108
                if ((file.getName().toUpperCase().endsWith("GML"))
109
                                || (file.getName().toUpperCase().endsWith("XML"))) {
110
                        return true;
111
                }
112
                return false;
113
        }
114

    
115
        protected InputStream createInputStream(File file) throws FileNotFoundException {
116
                // TODO Ap?ndice de m?todo generado autom?ticamente
117
                return new FileInputStream(file);
118
        }
119
        /** 
120
         * 
121
         * AQUI SE IMPLEMENTA LA BASE PARA PODER PARSEAR CUALQUIER FICHERO GML:
122
         * -PARTIMOS DE QUE TENEMOS EL FICHERO ABIERTO EN MODO LECTURA Y UN FILE PARSER
123
         * -
124
         * -ABRIR EN MODO LECTURA CON LA CODIFICACI?N CORRECTA
125
         * -CREAR EL PARSER DE XML ?"XSOM"?
126
         * -DETECTAR FORMATO FICHERO Y VERSI?N ?"EST? REGISTRADO"?
127
         * -SI EXISTE, LLAMADA AL PARSER DEL FORMATO CONCRETO
128
         *
129
         **/
130
        protected void initParse() {
131
                //First of all it has to parse the head 
132
                parseHead();
133
        }
134
        /*
135
         * (non-Javadoc)
136
         * @see org.gvsig.gpe.GPEParser#getWriter(java.lang.String)
137
         */
138
        public GPEWriterHandler getWriter(String format) {
139
                return new GPEGmlWriterHandler();
140
        }
141

    
142
        public String[] getVersions() {
143
                // TODO Ap?ndice de m?todo generado autom?ticamente
144
                return null;
145
        }
146
        private void parseHead(){
147
                //nextTag() --> Method from KXML library to get next full tag
148
                try {
149
                        fileParser.nextTag();
150
                } catch (XmlPullParserException e) {
151
                        // TODO Bloque catch generado autom?ticamente
152
                        System.out.println("Error en XmlPullParser al intentar obtener la siguiente etiqueta: "+e.getMessage());
153
                        
154
                } catch (IOException e) {
155
                        // TODO Bloque catch generado autom?ticamente
156
                        System.out.println("Error al leer la siguiente etiqueta en XmlPullParser: "+e.getMessage());
157
                        
158
                }
159
                //It keeps the name of the start tag to compare with the close tag later
160
                mainTag = fileParser.getName();
161
                //If it has namespace before the ":" we keep the maintag without namespace 
162
                int pos = mainTag.indexOf(":");
163
                if (pos > 0){
164
                        mainTag = mainTag.substring(mainTag.indexOf(":") + 1,mainTag.length());
165
                }
166
                //It start to get all the attributes and values from the header tag
167
                for (int i = 0 ; i < fileParser.getAttributeCount() ; i++){
168
                        String attName = fileParser.getAttributeName(i);
169
                        String attValue = fileParser.getAttributeValue(i);
170
                        
171
                                                
172
                        //it splits the attributes names at the both sides from ":"
173
                        String[] ns = attName.split(":");
174
                        
175
                        //If it founds the 'xmlns' is a new namespace declaration and it has to parse it
176
                        if ((ns.length>1) && (ns[0].compareTo(GMLTags.XML_NAMESPACE)==0)){
177
                                parseNameSpace(ns[1],attValue);
178
                        }
179
                        
180
                        //If its the "SCHEMA LOCATION" attribute, it means that there are schema and it tries to parse it
181
                        if ((ns.length>1) && (ns[1].compareTo(GMLTags.XML_SCHEMA_LOCATION)==0)){
182
                                no_schema=0;
183
                                parseSchemaLocation(ns[0],attValue);
184
                        }
185
                }
186
                if (no_schema==1){
187
                        //Alert that th GML File hasn't schema but it tries to parse
188
                        //warnings.setElement(new GMLWarningNoSchema());
189
                }
190
        }
191
        /**
192
         * It downloads the schema's file and parse it
193
         * @param xmlnsName : Alias
194
         * @param xmlnsValue: URI 
195
         */
196
        private void parseSchemaLocation(String schemaAlias, String schemaURI){
197
                //It take the name of the schemas file to open or downlad 
198
                StringTokenizer tokenizer = new StringTokenizer(schemaURI, " \t");
199
        while (tokenizer.hasMoreTokens()){
200
            String URI = tokenizer.nextToken();
201
            if (!tokenizer.hasMoreTokens()){
202
                            //If it hasn't the name of the schemas file or dont find it,
203
                            //it exits, and tries to parse without schema
204
                            //warnings.setElement(new GMLWarningNotFound(null,null));
205
                            System.out.println("Error, esquema no encontrado.PARSEO SIN ESQUEMA ");
206
                            
207
            }
208
            else
209
            {
210
                            String schemaLocation = tokenizer.nextToken();
211
                            //It add the schemaLocation to the hashtable
212
                            try {
213
                                        XMLSchemasFactory.addSchemaLocation(schemaAlias,URI,schemaLocation);
214
                                } 
215
                                catch (BaseException e) {
216
                                        // TODO Auto-generated catch block
217
                                        //warnings.setElement(new GMLWarningMalformed());
218
                                        System.out.println("Error al a?adir el esquema o esquema mal formado: "+e.getMessage());
219
                                }
220
                                //It downloads the schema if it's a remote schema
221
                                schemaFile = getSchemaFile(schemaLocation);
222
                            //It parses the schema.
223
                                schemaParser = new XSOMParser();
224
                                try {
225
                                        schemaParser.parse(schemaFile);
226
                                } catch (SAXException e) {
227
                                        // TODO Bloque catch generado autom?ticamente
228
                                        System.out.println("Error al parsear el Schema: "+e.getMessage());
229
                                } catch (IOException e) {
230
                                        // TODO Bloque catch generado autom?ticamente
231
                                        System.out.println("Error de lectura/escritura del esquema: "+e.getMessage());
232
                                }
233
            }
234
        }
235
        }
236
        /**
237
         * It adds an XML namespace tag to the hashtable
238
         * @param xmlnsName : Namespace
239
         * @param xmlnsValue: URI 
240
         */
241
        private void parseNameSpace(String xmlnsName,String xmlnsValue){
242
                XMLSchemasFactory.addType(xmlnsName,xmlnsValue);                
243
        }
244
        /**
245
         * It downloads the schema if it's a remote schema
246
         * else it tries to open a local file and return if it's succesfull
247
         * @param String : schemaLocation
248
         */
249
        private File getSchemaFile(String schemaLocation){
250
                File f = null;
251
                
252
                //If it is a local file, it has to construct the absolute route
253
                if (schemaLocation.indexOf("http://") != 0){
254
                        f = new File(schemaLocation);
255
                        if (!(f.isAbsolute())){
256
                                schemaLocation = mainFile.getParentFile().getAbsolutePath() + File.separator +  schemaLocation;
257
                                f = new File(schemaLocation);
258
                        }
259
                        return f;
260
                }
261
                //Else it is an URL direction and it has to download it.
262
                else {
263
                        URL url;
264
                
265
                        try {
266
                                url = new URL(schemaLocation);
267
                                //Download the schema without cancel option.
268
                                f = Utilities.downloadFile(url,"gml_schmema.xsd");                                
269
                        } catch (MalformedURLException e) {
270
                                // TODO Bloque catch generado autom?ticamente
271
                                System.out.println("Error, URL del esquema mal formada: "+e.getMessage());
272
                        } catch (ConnectException e) {
273
                                // TODO Bloque catch generado autom?ticamente
274
                                System.out.println("Error al descargar esquema, Imposible conectar: "+e.getMessage());
275
                        } catch (UnknownHostException e) {
276
                                // TODO Bloque catch generado autom?ticamente
277
                                System.out.println("Error al descargar esquema, Host desconocido: "+e.getMessage());
278
                        } catch (IOException e) {
279
                                // TODO Bloque catch generado autom?ticamente
280
                                System.out.println("Erroral descargar esquema, Fallo de lectura/escritura: "+e.getMessage());
281
                        }
282
                        return f;        
283
                }
284
        }
285
}