Statistics
| Revision:

root / trunk / extensions / extWMS / src / com / iver / cit / gvsig / wmc / WebMapContext.java @ 10627

History | View | Annotate | Download (36.6 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41

    
42
/* CVS MESSAGES:
43
*
44
* $Id: WebMapContext.java 10627 2007-03-06 17:10:21Z caballero $
45
* $Log$
46
* Revision 1.9  2007-03-06 17:06:43  caballero
47
* Exceptions
48
*
49
* Revision 1.8  2007/01/08 07:57:34  jaume
50
* *** empty log message ***
51
*
52
* Revision 1.7  2006/09/26 14:41:48  jaume
53
* *** empty log message ***
54
*
55
* Revision 1.6  2006/09/25 10:23:26  caballero
56
* Projection
57
*
58
* Revision 1.5  2006/09/15 10:44:24  caballero
59
* extensibilidad de documentos
60
*
61
* Revision 1.4  2006/07/21 10:31:05  jaume
62
* *** empty log message ***
63
*
64
* Revision 1.3  2006/05/24 16:36:28  jaume
65
* *** empty log message ***
66
*
67
* Revision 1.2  2006/05/12 07:47:39  jaume
68
* removed unnecessary imports
69
*
70
* Revision 1.1  2006/05/03 07:51:21  jaume
71
* *** empty log message ***
72
*
73
* Revision 1.10  2006/05/02 15:57:44  jaume
74
* Few better javadoc
75
*
76
* Revision 1.9  2006/04/25 11:40:56  jaume
77
* *** empty log message ***
78
*
79
* Revision 1.8  2006/04/25 10:01:56  jaume
80
* fixed extend bug when importing
81
*
82
* Revision 1.7  2006/04/21 12:46:53  jaume
83
* *** empty log message ***
84
*
85
* Revision 1.6  2006/04/21 11:53:50  jaume
86
* *** empty log message ***
87
*
88
* Revision 1.5  2006/04/21 11:02:25  jaume
89
* few translations
90
*
91
* Revision 1.4  2006/04/21 10:27:32  jaume
92
* exporting now supported
93
*
94
* Revision 1.3  2006/04/20 17:11:54  jaume
95
* Attempting to export
96
*
97
* Revision 1.2  2006/04/19 16:34:29  jaume
98
* *** empty log message ***
99
*
100
* Revision 1.1  2006/04/19 07:57:29  jaume
101
* *** empty log message ***
102
*
103
* Revision 1.1  2006/04/12 17:10:53  jaume
104
* *** empty log message ***
105
*
106
*
107
*/
108
package com.iver.cit.gvsig.wmc;
109

    
110
import java.awt.Dimension;
111
import java.awt.geom.Rectangle2D;
112
import java.io.BufferedReader;
113
import java.io.File;
114
import java.io.FileInputStream;
115
import java.io.FileNotFoundException;
116
import java.io.FileReader;
117
import java.io.IOException;
118
import java.net.URL;
119
import java.util.ArrayList;
120
import java.util.HashMap;
121
import java.util.HashSet;
122
import java.util.Hashtable;
123
import java.util.Vector;
124

    
125
import org.cresques.cts.ICoordTrans;
126
import org.cresques.cts.IProjection;
127
import org.kxml2.io.KXmlParser;
128
import org.xmlpull.v1.XmlPullParserException;
129

    
130
import com.iver.andami.PluginServices;
131
import com.iver.andami.messages.NotificationManager;
132
import com.iver.cit.gvsig.exceptions.layers.UnsupportedVersionLayerException;
133
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
134
import com.iver.cit.gvsig.fmap.exceptions.ImportMapContextException;
135
import com.iver.cit.gvsig.fmap.layers.FLayer;
136
import com.iver.cit.gvsig.fmap.layers.FLayers;
137
import com.iver.cit.gvsig.fmap.layers.FLyrWMS;
138
import com.iver.cit.gvsig.fmap.layers.WMSLayerNode;
139
import com.iver.cit.gvsig.fmap.layers.WMSLayerNode.FMapWMSStyle;
140
import com.iver.cit.gvsig.fmap.rendering.XmlBuilder;
141
import com.iver.cit.gvsig.project.Project;
142
import com.iver.cit.gvsig.project.documents.view.ProjectView;
143

    
144
/**
145
 * Class that loads and produces WebMapContext files and holds its attributes.
146
 *
147
 * You can create a blank WebMapContext instance using the default constructor
148
 * or an already initialized instance by specifying a source file. In the last
149
 * case the file will be readed and the values loaded an holded by the instance.
150
 *
151
 * You can get the equivalent WebMapContext XML document by calling the method
152
 * getXML() supplying the ProjectView that you want to export and depending on
153
 * the value of the fileVersion field (currently you can use "1.1.0" (default),
154
 * "1.0.0" or "0.4.1" to specify the destination document version.
155
 *
156
 * @author jaume dominguez faus - jaume.dominguez@iver.es
157
 */
158
public class WebMapContext {
159
        public final static String FILE_EXTENSION = ".cml";
160

    
161
        static final ArrayList supportedVersions = new ArrayList();
162
        static public final ArrayList exportVersions    = new ArrayList();
163
        static private HashSet supportedLayers = new HashSet();
164
        private File mapContextFile;
165
        private String encoding = "UTF-8";
166
        private String WMC_START_TAG;
167

    
168
        // MapContext stuff
169
        public String fileVersion = null;
170
        public Dimension windowSize = null;
171
        public String srs = null;
172
        public Rectangle2D bBox = null;
173
        public String title = null;
174
        public String id = null;
175
        public String xmlns = null;
176
        public String xmlns_xlink = null;
177
        public String xmlns_xsi = null;;
178
        public String xsi_schemaLocation = null;
179
        public String _abstract = null;
180
        public ArrayList keywordList = null;
181
        public Dimension logoURLSize = null;
182
        public String logoURLFormat = null;
183
        public String logoURL = null;
184
        public String descriptionURLFormat = null;
185
        public String descriptionURL = null;
186
        public boolean contactInfo = false;
187
        public String contactPerson = null;
188
        public String contactOrganization = null;
189
        public String contactPosition = null;
190
        public String address = null;
191
        public String city = null;
192
        public String stateOrProvince = null;
193
        public String postCode = null;
194
        public String country = null;
195
        public String telephone = null;
196
        public String fax = null;
197
        public String email = null;
198

    
199
        private StringBuffer errorMessages;
200

    
201
        /**
202
         * list of FLyrWMS.
203
         */
204
        ArrayList layerList = null;
205

    
206
        /**
207
         * key: server URL (URL)
208
         * value: server title (String)
209
         */
210
        Hashtable serverTitles = null;
211

    
212
        /**
213
         * key: layer FLyrWMS
214
         * value: layer abstract (String)
215
         */
216
        Hashtable layerAbstracts = null;
217

    
218
        /**
219
         * key: layer FLyrWMS
220
         * value: layer formats (String[])
221
         */
222
        Hashtable layerFormats = null;
223

    
224
        /**
225
         * key: layer FLyrWMS
226
         * value: styles (FMapWMSStyle[])
227
         */
228
        Hashtable layerStyles = null;
229

    
230

    
231
        static {
232
                supportedVersions.add("1.1.0");
233
                supportedVersions.add("1.0.0");
234
                supportedVersions.add("0.1.4");
235
        }
236

    
237
        static {
238
                exportVersions.add("1.1.0");
239
                exportVersions.add("1.0.0");
240
                exportVersions.add("0.1.4");
241
        }
242

    
243
        static {
244
                supportedLayers.add(FLyrWMS.class);
245
        }
246

    
247

    
248
        /**
249
         * Initializes the WebMapContext properties from the values in the WebMapContext (.cml)
250
         * file passed in the argument.
251
         * @param file
252
         * @throws UnsupportedVersionLayerException
253
         * @throws ImportMapContextException
254
         */
255
        public void readFile(File file) throws UnsupportedVersionLayerException, ImportMapContextException {
256
                this.mapContextFile = file;
257
                errorMessages = new StringBuffer();
258
                if (getVersion()!=null) {
259
                        if (supportedVersions.contains(getVersion())) {
260
                                WMC_START_TAG = WebMapContextTags.VIEW_CONTEXT;
261
                                if (getVersion().equals("0.1.4")) {
262
                                        WMC_START_TAG = WebMapContextTags.VIEW_CONTEXT_0_1_4;
263
                                        parse1_1_0(file);
264
                                } else if (getVersion().equals("1.1.0")) {
265
                                        parse1_1_0(file);
266
                                } else if (getVersion().equals("1.0.0")) {
267
                                        parse1_1_0(file);
268
                                } else {
269
                                        parseDefaultVersion(file);
270
                                }
271

    
272
                                // Once parsed, check errors
273
                                if (errorMessages.length()>0)
274
                                        throw new ImportMapContextException(errorMessages.toString(), false);
275
                        } else throw new UnsupportedVersionLayerException(file.getName(),null);
276
                }
277
        }
278

    
279

    
280
        /**
281
         * If no version was recognized then will parse the default one which is supposed
282
         * to be the best available.
283
         * @param file
284
         */
285
        private void parseDefaultVersion(File file) {
286
                parse1_1_0(file);
287
        }
288

    
289
        /**
290
         * Reads the header of the Weg Map Context file and determines which version
291
         * it belongs to.
292
         * @return String.
293
         */
294
        private String getVersion() {
295
                if (fileVersion == null) {
296
                        String v = null;
297
                        try {
298
                                FileReader fr = new FileReader(mapContextFile);
299
                                KXmlParser parser = new KXmlParser();
300
                                parser.setInput(fr);
301
                                parser.nextTag();
302
                            if ( parser.getEventType() != KXmlParser.END_DOCUMENT )        {
303
                                    if ((parser.getName().compareTo(WebMapContextTags.VIEW_CONTEXT) == 0) ||
304
                                             parser.getName().compareTo(WebMapContextTags.VIEW_CONTEXT_0_1_4) == 0) {
305
                                            v = parser.getAttributeValue("", WebMapContextTags.VERSION);
306
                                    }
307
                            }
308
                        } catch (FileNotFoundException fnfEx) {
309
                        } catch (XmlPullParserException xmlEx) {
310
                                xmlEx.printStackTrace();
311
                        } catch (IOException e) {
312
                        }
313
                        fileVersion = v;
314
                }
315
                return fileVersion;
316
        }
317

    
318
        /**
319
         * Reads a Web Map Context version 1.1.0. As far as v1.0.0 is a subset of
320
         * v1.1.0 it can be used to read files belonging to 1.0.0 as well.
321
         * @param file, the web map context file.
322
         */
323
        private void parse1_1_0(File file) {
324
                try {
325
                        FileReader fr;
326
                        try
327
                    {
328
                                fr = new FileReader(file);
329
                            BufferedReader br = new BufferedReader(fr);
330
                            char[] buffer = new char[100];
331
                            br.read(buffer);
332
                            StringBuffer st = new StringBuffer(new String(buffer));
333
                            String searchText = "encoding=\"";
334
                            int index = st.indexOf(searchText);
335
                            if (index>-1) {
336
                                    st.delete(0, index+searchText.length());
337
                                    encoding = st.substring(0, st.indexOf("\""));
338
                            }
339
                    } catch(FileNotFoundException ex)        {
340
                            ex.printStackTrace();
341
                    } catch (IOException e) {
342
                                e.printStackTrace();
343
                        }
344

    
345
                        fr = new FileReader(file);
346
                        KXmlParser parser = new KXmlParser();
347
                        parser.setInput(new FileInputStream(file), encoding);
348
                        int tag = parser.nextTag();
349
                        if ( parser.getEventType() != KXmlParser.END_DOCUMENT )
350
                        {
351
                                parser.require(KXmlParser.START_TAG, null, WMC_START_TAG);
352
                                while(tag != KXmlParser.END_DOCUMENT) {
353
                                        switch(tag) {
354
                                                case KXmlParser.START_TAG:
355
                                                        if (parser.getName().compareTo(WMC_START_TAG) == 0) {
356
                                                                id = parser.getAttributeValue("", WebMapContextTags.ID);
357
                                                                xmlns = parser.getAttributeValue("", WebMapContextTags.XMLNS);
358
                                                                xmlns_xlink = parser.getAttributeValue("", WebMapContextTags.XMLNS_XLINK);
359
                                                                xmlns_xsi = parser.getAttributeValue("", WebMapContextTags.XMLNS_XSI);
360
                                                                xsi_schemaLocation = parser.getAttributeValue("", WebMapContextTags.XSI_SCHEMA_LOCATION) ;
361
                                                        } else if (parser.getName().compareTo(WebMapContextTags.GENERAL) == 0) {
362
                                                                parseGeneral1_1_0(parser);
363
                                                        } else if (parser.getName().compareTo(WebMapContextTags.LAYER_LIST) == 0) {
364
                                                                int layerListTag = parser.nextTag();
365
                                                                boolean bLayerListEnd = false;
366
                                                                layerList = new ArrayList();
367
                                                                while (!bLayerListEnd) {
368
                                                                        switch(layerListTag) {
369
                                                                        case KXmlParser.START_TAG:
370
                                                                                if (parser.getName().compareTo(WebMapContextTags.LAYER) == 0) {
371
                                                                                        FLyrWMS layer = parseLayer1_1_0(parser);
372
                                                                                        // will use the mapcontext's bounding box as layer's fullextent
373
                                                                                        IProjection proj =  CRSFactory.getCRS(srs);
374
                                                                                        if (proj == null) {
375
                                                                                                // non supported srs, and cannot continue
376
                                                                                                String msg = PluginServices.getText(this, "unsupported_crs") +
377
                                                                                                                         " (" + srs + ")";
378
                                                                                                throw new ImportMapContextException(msg, true);
379
                                                                                        }
380
                                                                                        String[] availableSRS = layer.getSRS().split(",");
381
                                                                                        ICoordTrans ct = null;
382
                                                                                        String mySRS = null;
383
                                                                                        for (int i = 0; i < availableSRS.length; i++) {
384
                                                                                                mySRS = availableSRS[i];
385
                                                                                                IProjection dstProj = CRSFactory.getCRS(mySRS);
386
                                                                                                if (dstProj != null) {
387
                                                                                                        ct = proj.getCT(dstProj);
388
                                                                                                        if (mySRS.equals(srs)) {
389
                                                                                                                // this is the most suitable SRS,
390
                                                                                                                break;
391
                                                                                                        }
392
                                                                                                }
393
                                                                                        }
394

    
395
                                                                                        if (ct != null) {
396
                                                                                                // I've found a supported projection
397
                                                                                                layer.setFullExtent(ct.convert(bBox));
398
                                                                                                layer.setSRS(mySRS);
399
                                                                                        } else {
400
                                                                                                // can't reproject
401
                                                                                                errorMessages.append("[").
402
                                                                                                                      append(PluginServices.getText(this, "layer")).
403
                                                                                                                      append(" ").
404
                                                                                                                      append(layer.getName()).
405
                                                                                                                      append("] ").
406
                                                                                                                          append(PluginServices.getText(this, "cant_reproject_from_any_of")).
407
                                                                                                                          append(" [").append(layer.getSRS()).append("] ").
408
                                                                                                                          append(PluginServices.getText(this, "to")).
409
                                                                                                                          append(srs).
410
                                                                                                                          append("\n");
411

    
412
                                                                                                /*
413
                                                                                                 * will use view's projection and bounding box
414
                                                                                                 * strictly this is incorrect but, at least it allows
415
                                                                                                 * the user to recover by changin layer properties.
416
                                                                                                 */
417
                                                                                                layer.setFullExtent(bBox);
418
                                                                                                layer.setSRS(srs);
419
                                                                                        }
420

    
421
                                                                                        layer.setWmsTransparency(true);
422
                                                                                        layerList.add(layer);
423
                                                                                } else {
424
                                                                    System.out.println("Unrecognized "+parser.getName());
425
                                                                                }
426
                                                                                break;
427
                                                                        case KXmlParser.END_TAG:
428
                                                                                if (parser.getName().compareTo(WebMapContextTags.LAYER_LIST) == 0)
429
                                                                                        bLayerListEnd = true;
430
                                                                                break;
431
                                                                        case KXmlParser.TEXT:
432
                                                                                //System.out.println("[TEXT]["+kxmlParser.getText()+"]");
433
                                                                                break;
434
                                                                        }
435
                                                                        layerListTag = parser.next();
436
                                                                }
437
                                                        } else if (parser.getName().compareTo(WebMapContextTags.DIMENSION_LIST) == 0) {
438
                                                                // TODO
439
                                                                System.out.println("WebMapContext's Dimension not yet implemented");
440
                                                        } else {
441
                                            System.out.println("Unrecognized "+parser.getName());
442
                                                        }
443
                                                        break;
444
                                                case KXmlParser.END_TAG:
445
                                                        break;
446
                                                case KXmlParser.TEXT:
447
                                                        //System.out.println("[TEXT]["+kxmlParser.getText()+"]");
448
                                                        break;
449
                                        }
450
                                        tag = parser.next();
451
                                }
452
                                parser.require(KXmlParser.END_DOCUMENT, null, null);
453
                        }
454
                } catch (Exception e) {
455
                        NotificationManager.addError(PluginServices.getText(this, "map_context_file_error"),e);
456
                        e.printStackTrace();
457
                }
458

    
459
        }
460

    
461
        /**
462
         * Parses the General tag of a web map context 1.1.0 (and 1.0.0) file
463
         * @param parser
464
         * @throws XmlPullParserException
465
         * @throws IOException
466
         */
467
        private void parseGeneral1_1_0(KXmlParser parser) throws XmlPullParserException, IOException {
468
                boolean end = false;
469
            int tag = parser.next();
470
            while (!end) {
471
                    switch(tag) {
472
                        case KXmlParser.START_TAG:
473
                                if (parser.getName().compareTo(WebMapContextTags.WINDOW) == 0) {
474
                                        if (windowSize == null) windowSize = new Dimension();
475
                                                windowSize.setSize(Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.WIDTH)),
476
                                                                                   Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.HEIGHT)));
477
                                } else if (parser.getName().compareTo(WebMapContextTags.BOUNDING_BOX) == 0) {
478
                                        srs = parser.getAttributeValue("", WebMapContextTags.SRS);
479
                                        double minx = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.X_MIN));
480
                                        double miny = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.Y_MIN));
481
                                        double maxx = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.X_MAX));
482
                                        double maxy = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.Y_MAX));
483
                                        bBox = new Rectangle2D.Double(minx, miny, maxx-minx, maxy-miny);
484
                            } else if (parser.getName().compareTo(WebMapContextTags.TITLE) == 0) {
485
                                        title = parser.nextText();
486
                                } else if (parser.getName().compareTo(WebMapContextTags.ABSTRACT) == 0) {
487
                                        _abstract = parser.nextText();
488
                                } else if (parser.getName().compareTo(WebMapContextTags.KEYWORD_LIST) == 0) {
489
                                        keywordList = new ArrayList();
490
                                        boolean keywordEnd = false;
491
                                    int keywordTag = parser.next();
492
                                    while (!keywordEnd) {
493
                                            switch(keywordTag) {
494
                                                case KXmlParser.START_TAG:
495
                                                        if (parser.getName().compareTo(WebMapContextTags.KEYWORD) == 0) {
496
                                                                keywordList.add(parser.nextText());
497
                                                        } else {
498
                                                    System.out.println("Unrecognized "+parser.getName());
499
                                                                }
500
                                                                break;
501
                                                 case KXmlParser.END_TAG:
502
                                                        if (parser.getName().compareTo(WebMapContextTags.KEYWORD_LIST) == 0)
503
                                                                keywordEnd = true;
504
                                                        break;
505
                                                case KXmlParser.TEXT:
506
                                                        if (parser.getName()!=null)
507
                                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
508
                                                        break;
509
                                            }
510
                                            keywordTag = parser.next();
511
                                    }
512
                                } else if (parser.getName().compareTo(WebMapContextTags.LOGO_URL) == 0) {
513
                                        logoURLSize = new Dimension(Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.WIDTH)),
514
                                                                                                Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.HEIGHT)));
515
                                        logoURLFormat = parser.getAttributeValue("", WebMapContextTags.FORMAT.toLowerCase());
516
                                        parser.nextTag();
517
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0) {
518
                                                logoURL = parser.getAttributeValue("", WebMapContextTags.XLINK_HREF);
519
                                        } else {
520
                                System.out.println("Unrecognized "+parser.getName());
521
                                            }
522
                                } else if (parser.getName().compareTo(WebMapContextTags.DESCRIPTION_URL) == 0) {
523
                                        descriptionURLFormat = parser.getAttributeValue("", WebMapContextTags.FORMAT.toLowerCase());
524
                                        parser.nextTag();
525
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0) {
526
                                                descriptionURL = parser.getAttributeValue("", WebMapContextTags.XLINK_HREF);
527
                                        } else {
528
                                System.out.println("Unrecognized "+parser.getName());
529
                                            }
530
                                } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_INFORMATION) == 0) {
531
                                        boolean contactInfoEnd = false;
532
                                    int contactInfoTag = parser.next();
533
                                    while (!contactInfoEnd) {
534
                                            switch(contactInfoTag) {
535
                                                case KXmlParser.START_TAG:
536
                                                        if (parser.getName().compareTo(WebMapContextTags.CONTACT_PERSON) == 0) {
537
                                                                contactPerson = parser.nextText();
538
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_ORGANIZATION) == 0) {
539
                                                                contactOrganization = parser.nextText();
540
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_POSITION) == 0) {
541
                                                                contactPosition = parser.nextText();
542
                                                        } else if (parser.getName().compareTo(WebMapContextTags.ADDRESS) == 0) {
543
                                                                address = parser.nextText();
544
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CITY) == 0) {
545
                                                                city = parser.nextText();
546
                                                        } else if (parser.getName().compareTo(WebMapContextTags.STATE_OR_PROVINCE) == 0) {
547
                                                                stateOrProvince = parser.nextText();
548
                                                        } else if (parser.getName().compareTo(WebMapContextTags.POSTCODE) == 0) {
549
                                                                postCode = parser.nextText();
550
                                                        } else if (parser.getName().compareTo(WebMapContextTags.COUNTRY) == 0) {
551
                                                                country = parser.nextText();
552
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_VOICE_TELEPHONE) == 0) {
553
                                                                telephone = parser.nextText();
554
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_FACSIMILE_TELEPHONE) == 0) {
555
                                                                fax = parser.nextText();
556
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_ELECTRONIC_MAIL_ADDRESS) == 0) {
557
                                                                email = parser.nextText();
558
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_PERSON_PRIMARY) == 0) {
559
                                                                // DO NOTHING
560
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_ADDRESS) == 0) {
561
                                                                // DO NOTHING
562
                                                        } else {
563
                                                    System.out.println("Unrecognized "+parser.getName());
564
                                                                }
565
                                                        break;
566
                                                 case KXmlParser.END_TAG:
567
                                                        if (parser.getName().compareTo(WebMapContextTags.CONTACT_INFORMATION) == 0)
568
                                                                contactInfoEnd = true;
569
                                                        break;
570
                                                case KXmlParser.TEXT:
571
                                                        if (parser.getName()!=null)
572
                                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
573
                                                        break;
574
                                            }
575
                                            contactInfoTag = parser.next();
576
                                    }
577
                            } else {
578
                            System.out.println("Unrecognized "+parser.getName());
579
                                        }
580
                                        break;
581
                         case KXmlParser.END_TAG:
582
                                if (parser.getName().compareTo(WebMapContextTags.GENERAL) == 0)
583
                                        end = true;
584
                                break;
585
                        case KXmlParser.TEXT:
586
                                if (parser.getName()!=null)
587
                                        System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
588
                                break;
589
                    }
590
                    tag = parser.next();
591
            }
592
        }
593

    
594
        private FLyrWMS parseLayer1_1_0(KXmlParser parser) throws XmlPullParserException, IOException {
595
                boolean end = false;
596
                FLyrWMS layer = new FLyrWMS();
597

    
598
                String queryable = parser.getAttributeValue("", WebMapContextTags.QUERYABLE);
599
                layer.setQueryable(queryable!=null && (queryable.equals("1") || queryable.toLowerCase().equals("true")));
600

    
601
                String hidden = parser.getAttributeValue("", WebMapContextTags.HIDDEN);
602
                layer.setVisible(hidden==null || !hidden.equals("1") || !hidden.toLowerCase().equals("true"));
603
            int tag = parser.next();
604
            while (!end) {
605
                    switch(tag) {
606
                        case KXmlParser.START_TAG:
607
                                if (parser.getName().compareTo(WebMapContextTags.SERVER) == 0) {
608
                                        String serverTitle = parser.getAttributeValue("", WebMapContextTags.TITLE.toLowerCase());
609
                                        parser.nextTag();
610
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0) {
611
                                                layer.setHost(new URL(parser.getAttributeValue("", WebMapContextTags.XLINK_HREF)));
612
                                                if (serverTitles == null)
613
                                                    serverTitles = new Hashtable();
614
                                            serverTitles.put(parser.getAttributeValue("", WebMapContextTags.XLINK_HREF), serverTitle);
615
                                        }
616
                                } else if (parser.getName().compareTo(WebMapContextTags.TITLE) == 0) {
617
                                        layer.setName(parser.nextText());
618
                                } else if (parser.getName().compareTo(WebMapContextTags.NAME) == 0) {
619
                                        layer.setLayerQuery(parser.nextText());
620
                                /* //TODO This case would handle nested layer definitions.
621
                                 *
622
                                 } else if (parser.getName().compareTo(WebMapContextTags.LAYER) == 0) {
623
                                        FLyrWMS sonLayer = parseLayer1_1_0(parser);
624
                                        String q = layer.getLayerQuery();
625
                                        if (q == null) q = "";
626
                                        else q += ",";
627
                                        layer.setLayerQuery( q + sonLayer.getLayerQuery());
628
                                 *
629
                                 */
630
                                } else if (parser.getName().compareTo(WebMapContextTags.ABSTRACT) == 0) {
631
                                        if (layerAbstracts == null)
632
                                                layerAbstracts = new Hashtable();
633
                                        layerAbstracts.put(layer, parser.nextText());
634
                                } else if (parser.getName().compareTo(WebMapContextTags.SRS) == 0) {
635
                                        layer.setSRS(parser.nextText());
636
                                } else if (parser.getName().compareTo(WebMapContextTags.FORMAT_LIST) == 0) {
637
                                        int formatsTag = parser.nextTag();
638
                                        boolean bFormatsEnd = false;
639
                                        ArrayList formats = new ArrayList();
640
                                        while (!bFormatsEnd) {
641
                                                switch (formatsTag) {
642
                                                case KXmlParser.START_TAG:
643
                                                        if (parser.getName().compareTo(WebMapContextTags.FORMAT) == 0) {
644
                                                                String current = parser.getAttributeValue("", WebMapContextTags.CURRENT);
645
                                                                String format = parser.nextText();
646
                                                                if (current!=null && current.equals("1"))
647
                                                                        layer.setFormat(format);
648
                                                                formats.add(format);
649
                                                        } else {
650
                                                                System.out.println("Unrecognized "+parser.getName());
651
                                                        }
652
                                                        break;
653
                                                case KXmlParser.END_TAG:
654
                                                        if (parser.getName().compareTo(WebMapContextTags.FORMAT_LIST) == 0)
655
                                                                bFormatsEnd = true;
656
                                                        break;
657
                                                case KXmlParser.TEXT:
658
                                                        if (parser.getName()!=null)
659
                                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
660
                                                        break;
661
                                                }
662
                                                formatsTag = parser.next();
663
                                        }
664
                                        if (layerFormats == null)
665
                                                layerFormats = new Hashtable();
666
                                        layerFormats.put(layer, formats.toArray(new String[0]));
667

    
668
                                } else if (parser.getName().compareTo(WebMapContextTags.STYLE_LIST) == 0) {
669
                                        int stylesTag = parser.nextTag();
670
                                        boolean bStylesEnd = false;
671
                                        ArrayList styles = new ArrayList();
672
                                        while (!bStylesEnd) {
673
                                                switch (stylesTag) {
674
                                                case KXmlParser.START_TAG:
675
                                                        if (parser.getName().compareTo(WebMapContextTags.STYLE) == 0) {
676
                                                                String current = parser.getAttributeValue("", WebMapContextTags.CURRENT);
677
                                                                FMapWMSStyle style = parseStyle1_1_0(parser);
678
                                                                if (current!=null && current.equals("1")) {
679
                                                                        Vector v = new Vector();
680
                                                                        v.add(style.name);
681
                                                                        layer.setStyles(v);
682
                                                                }
683
                                                                styles.add(style);
684
                                                        } else {
685
                                                                System.out.println("Unrecognized "+parser.getName());
686
                                                        }
687
                                                        break;
688
                                                case KXmlParser.END_TAG:
689
                                                        if (parser.getName().compareTo(WebMapContextTags.STYLE_LIST) == 0)
690
                                                                bStylesEnd = true;
691
                                                        break;
692
                                                case KXmlParser.TEXT:
693
                                                        if (parser.getName()!=null)
694
                                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
695
                                                        break;
696
                                                }
697
                                                stylesTag = parser.next();
698
                                        }
699
                                        if (layerStyles == null)
700
                                                layerStyles = new Hashtable();
701

    
702
                                        layerStyles.put(layer, styles.toArray(new FMapWMSStyle[0]));
703
                                } else {
704
                                        System.out.println("Unrecognized "+parser.getName());
705
                                }
706
                                break;
707
                        case KXmlParser.END_TAG:
708
                                if (parser.getName().compareTo(WebMapContextTags.LAYER) == 0)
709
                                        end = true;
710
                                break;
711
                        case KXmlParser.TEXT:
712
                                if (parser.getName()!=null)
713
                                        System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
714
                                break;
715
                    }
716
                    tag = parser.next();
717
            }
718
            return layer;
719
        }
720

    
721
        private FMapWMSStyle parseStyle1_1_0(KXmlParser parser) throws XmlPullParserException, IOException {
722
                boolean end = false;
723
                String styleName = null;
724
                String styleAbstract = null;
725
                String styleTitle = null;
726
                int legendWidth = -1;
727
                int legendHeight = -1;
728
                String legendType = null;
729
                String legendHref = null;
730

    
731
            int tag = parser.next();
732
            while (!end) {
733
                    switch(tag) {
734
                        case KXmlParser.START_TAG:
735
                                if (parser.getName().compareTo(WebMapContextTags.NAME) == 0) {
736
                                        styleName = parser.nextText();
737
                                } else if (parser.getName().compareTo(WebMapContextTags.ABSTRACT) == 0) {
738
                                        styleAbstract = parser.nextText();
739
                                } else if (parser.getName().compareTo(WebMapContextTags.TITLE) == 0) {
740
                                        styleTitle = parser.nextText();
741
                                } else if (parser.getName().compareTo(WebMapContextTags.LEGEND_URL) == 0){
742
                                        legendWidth = Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.WIDTH));
743
                                        legendHeight = Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.HEIGHT));
744
                                        parser.nextTag();
745
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0 ) {
746
                                                        legendType = parser.getAttributeValue("", WebMapContextTags.XLINK_TYPE);
747
                                                        legendHref = parser.getAttributeValue("", WebMapContextTags.XLINK_HREF);
748
                                        }
749
                                } else {
750
                            System.out.println("Unrecognized "+parser.getName());
751
                                        }
752
                                break;
753
                         case KXmlParser.END_TAG:
754
                                if (parser.getName().compareTo(WebMapContextTags.STYLE) == 0)
755
                                        end = true;
756
                                break;
757
                        case KXmlParser.TEXT:
758
                                if (parser.getName()!=null)
759
                                        System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
760
                                break;
761
                    }
762
                    tag = parser.next();
763
            }
764
            WMSLayerNode n = new WMSLayerNode();
765
            FMapWMSStyle sty = n.new FMapWMSStyle();
766
            sty.name = styleName;
767
            sty.title = styleTitle;
768
            sty.styleAbstract = styleAbstract;
769
            sty.legendWidth = legendWidth;
770
            sty.legendHeight = legendHeight;
771
            sty.type = legendType;
772
            sty.href = legendHref;
773
            sty.parent = null;
774
            return sty;
775
        }
776

    
777
        /**
778
         * Creates the Web Map Context (WMC) XML according on the version 1.1.0. Since Web
779
         * WMC 1.0.0 is a subset of WMC 1.1.0 and this method does not produce tags for
780
         * unset values, it can be used to produce WMC 1.0.0, or even to produce
781
         * the deprecated (but still alive) WMC 0.1.4.
782
         * @param v
783
         * @return
784
         */
785
        private String createMapContext1_1_0(ProjectView v) {
786
                ArrayList layersToExport = getExportableLayers(v);
787

    
788
                XmlBuilder xml = new XmlBuilder();
789
                HashMap xmlAttrs = new HashMap();
790
                xml.setEncoding("ISO-8859-1"); // TODO make it customizable???
791
                xml.writeHeader();
792

    
793
                // <ViewContext>
794
                String viewContextTag;
795
                if (fileVersion.equals("0.1.4"))
796
                        viewContextTag = WebMapContextTags.VIEW_CONTEXT_0_1_4;
797
                else
798
                        viewContextTag = WebMapContextTags.VIEW_CONTEXT;
799

    
800
                xml.writeRaw("<!-- "+PluginServices.getText(this, "created_with")+" gvSIG "+Project.VERSION+" -->");
801

    
802
                xmlAttrs.put(WebMapContextTags.VERSION, fileVersion);
803
                xmlAttrs.put(WebMapContextTags.ID, id);
804
                xmlAttrs.put(WebMapContextTags.XMLNS, WebMapContextTags.XMLNS_VALUE);
805
                xmlAttrs.put(WebMapContextTags.XMLNS_XLINK, WebMapContextTags.XMLNS_XLINK_VALUE);
806
                xmlAttrs.put(WebMapContextTags.XMLNS_XSI, WebMapContextTags.XMLNS_XSI_VALUE);
807
                xmlAttrs.put(WebMapContextTags.XSI_SCHEMA_LOCATION, WebMapContextTags.XSI_SCHEMA_LOCATION_VALUE);
808
                xml.openTag(viewContextTag,  xmlAttrs);
809
                xmlAttrs.clear();
810

    
811
                        // <General>
812
                        xml.openTag(WebMapContextTags.GENERAL);
813

    
814
                                // <Window>
815
                                if (windowSize!=null) {
816
                                        xmlAttrs.put(WebMapContextTags.WIDTH, ((int) windowSize.getWidth())+"");
817
                                        xmlAttrs.put(WebMapContextTags.HEIGHT, ((int) windowSize.getHeight())+"");
818
                                        xml.writeTag(WebMapContextTags.WINDOW, xmlAttrs);
819
                                        xmlAttrs.clear();
820
                                }
821
                                // </Window>
822

    
823
                                // <BoundingBox>
824
                                xmlAttrs.put(WebMapContextTags.SRS, v.getProjection().getAbrev());
825
                                xmlAttrs.put(WebMapContextTags.X_MIN, bBox.getMinX()+"");
826
                                xmlAttrs.put(WebMapContextTags.Y_MIN, bBox.getMinY()+"");
827
                                xmlAttrs.put(WebMapContextTags.X_MAX, bBox.getMaxX()+"");
828
                                xmlAttrs.put(WebMapContextTags.Y_MAX, bBox.getMaxY()+"");
829
                                xml.writeTag(WebMapContextTags.BOUNDING_BOX, xmlAttrs);
830
                                xmlAttrs.clear();
831
                                // </BoundingBox>
832

    
833
                                // <Title>
834
                                xml.writeTag(WebMapContextTags.TITLE, title.trim());
835
                                // </Title>
836

    
837
                                // <Abstract>
838
                                if (_abstract != null)
839
                                        xml.writeTag(WebMapContextTags.ABSTRACT, _abstract.trim());
840
                                // </Abstract>
841

    
842
                                // <LogoURL>
843
                                if (logoURL != null)
844
                                        xml.writeTag(WebMapContextTags.LOGO_URL, logoURL.trim());
845
                                // </LogoURL>
846

    
847
                                // <DescriptionURL>
848
                                if (descriptionURL != null)
849
                                        xml.writeTag(WebMapContextTags.DESCRIPTION_URL, descriptionURL.trim());
850
                                // </DescriptionURL>
851

    
852
                                if (contactInfo) {
853

    
854
                                        // <ContactInformation>
855
                                        xml.openTag(WebMapContextTags.CONTACT_INFORMATION);
856
                                        if (contactPerson != null || contactOrganization != null) {
857

    
858
                                                // <ContactPersonPrimary>
859
                                                xml.openTag(WebMapContextTags.CONTACT_PERSON_PRIMARY);
860

    
861
                                                        // <ContactPerson>
862
                                                        if (contactPerson != null)
863
                                                                xml.writeTag(WebMapContextTags.CONTACT_PERSON, contactPerson.trim());
864
                                                        // </ContactPerson>
865

    
866
                                                        // <ContactOrganization>
867
                                                        if (contactOrganization != null)
868
                                                                xml.writeTag(WebMapContextTags.CONTACT_ORGANIZATION, contactOrganization.trim());
869
                                                        // </ContactOrganization>
870

    
871
                                                xml.closeTag();
872
                                                // </ContactPersonPrimary>
873
                                        }
874
                                        xml.closeTag();
875
                                        // </ContactInformation>
876

    
877
                                        // <ContactPosition>
878
                                        if (contactPosition != null)
879
                                                xml.writeTag(WebMapContextTags.CONTACT_POSITION, contactPosition.trim());
880
                                        // </ContactPosition>
881

    
882
                                        // <ContactAddress>
883
                                        if (address != null || city != null || stateOrProvince != null || postCode != null || country != null) {
884
                                                xml.openTag(WebMapContextTags.CONTACT_ADDRESS);
885

    
886
                                                        // <AddressType>
887
                                                        xml.writeTag(WebMapContextTags.ADDRESS_TYPE, "Postal");
888
                                                        // </AddressType>
889

    
890
                                                        // <Address>
891
                                                        if (address != null)
892
                                                                xml.writeTag(WebMapContextTags.ADDRESS, address.trim());
893
                                                        // </Address>
894

    
895
                                                        // <City>
896
                                                        if (city != null)
897
                                                                xml.writeTag(WebMapContextTags.CITY, city.trim());
898
                                                        // </City>
899

    
900
                                                        // <StateOrProvince>
901
                                                        if (stateOrProvince != null)
902
                                                                xml.writeTag(WebMapContextTags.STATE_OR_PROVINCE, stateOrProvince.trim());
903
                                                        // </StateOrProvince>
904

    
905
                                                        // <PostCode>
906
                                                        if (postCode != null)
907
                                                                xml.writeTag(WebMapContextTags.POSTCODE, postCode.trim());
908
                                                        // </PostCode>
909

    
910
                                                        // <Country>
911
                                                        if (country != null)
912
                                                                xml.writeTag(WebMapContextTags.COUNTRY, country.trim());
913
                                                        // </Country>
914
                                                xml.closeTag();
915
                                        }
916
                                        // </ContactAddress>
917

    
918
                                        // <ContactVoiceTelephone>
919
                                        if (telephone != null)
920
                                                xml.writeTag(WebMapContextTags.CONTACT_VOICE_TELEPHONE, telephone.trim());
921
                                        // </ContactVoiceTelephone>
922

    
923
                                        // <ContactFacsimileTelephone>
924
                                        if (fax != null)
925
                                                xml.writeTag(WebMapContextTags.CONTACT_FACSIMILE_TELEPHONE, fax.trim());
926
                                        // </ContactFacsimileTelephone>
927

    
928
                                        // <ContactElectronicMailAddress>
929
                                        if (email != null)
930
                                                xml.writeTag(WebMapContextTags.CONTACT_ELECTRONIC_MAIL_ADDRESS, email.trim());
931
                                        // </ContactElectronicMailAddress>
932
                                }
933
                                // <KeywordList>
934
                                xml.openTag(WebMapContextTags.KEYWORD_LIST);
935
                                if (keywordList != null) {
936
                                        for (int i = 0; i < keywordList.size(); i++) {
937
                                                xml.writeTag(WebMapContextTags.KEYWORD, ((String) keywordList.get(i)).trim());
938
                                        }
939
                                } else {
940
                                        xml.writeTag(WebMapContextTags.KEYWORD, "");
941
                                }
942
                                xml.closeTag();
943

    
944
                                // </KeywordList>
945
                        xml.closeTag();
946
                        // </General>
947

    
948
                        // <LayerList>
949
                        xml.openTag(WebMapContextTags.LAYER_LIST);
950
                        for (int i = 0; i < layersToExport.size(); i++) {
951
                                xml.writeRaw(((FLyrWMS) layersToExport.get(i)).toMapContext(fileVersion));
952
                        }
953
                        xml.closeTag();
954
                        // </LayerList>
955
                xml.closeTag();
956
                // </ViewContext>
957

    
958
                return xml.getXML();
959
        }
960

    
961
        /**
962
         * Exports the ProjectView passed as parameter to Web Map Context XML compliant
963
         * with the defined specifications for the version set in the fileVersion field.
964
         * @param ProjectView to be exported
965
         * @return String containing the XML
966
         */
967
        public String toXML(ProjectView v) {
968
                if (fileVersion.equals("1.1.0") ||
969
                                fileVersion.equals("1.0.0") ||
970
                                fileVersion.equals("0.1.4")) {
971
                        return createMapContext1_1_0(v);
972
                }
973
                return null;
974
        }
975

    
976

    
977
        public static ArrayList getExportableLayers(ProjectView v) {
978
                ArrayList list = new ArrayList();
979
                FLayers lyrs = v.getMapContext().getLayers();
980
                list.addAll(_getExportableLayers(lyrs));
981
                return list;
982
        }
983

    
984
        private static ArrayList _getExportableLayers(FLayer lyr) {
985
                ArrayList list = new ArrayList();
986
                if (checkType(lyr)) {
987
                        list.add(lyr);
988
                } else {
989
                        if (lyr instanceof FLayers) {
990
                                FLayers lyrs = (FLayers) lyr;
991
                                for (int i = 0; i < lyrs.getLayersCount(); i++) {
992
                                        list.addAll(_getExportableLayers(lyrs.getLayer(i)));
993
                                }
994
                        }
995
                }
996
                return list;
997
        }
998

    
999
        /**
1000
         * Checks if the layer is supported by the WebMapContext
1001
         * @param lyr
1002
         * @return
1003
         */
1004
        private static boolean checkType(FLayer lyr) {
1005
                return supportedLayers.contains(lyr.getClass());
1006
        }
1007

    
1008
        /**
1009
         * Searches in the layer tree of the TOC for an ocurrence of any
1010
         * exportable layer and returns true if so, or false otherwise.
1011
         * @param layer
1012
         * @return
1013
         */
1014
        public static boolean containsExportableLayers(FLayer layer) {
1015
                if (checkType(layer))
1016
                        return true;
1017

    
1018
                if (layer instanceof FLayers) {
1019
                        FLayers layers = (FLayers) layer;
1020
                        for (int i = 0; i < layers.getLayersCount(); i++) {
1021
                                FLayer lyr = layers.getLayer(i);
1022
                                if (containsExportableLayers(lyr))
1023
                                        return true;
1024

    
1025
                        }
1026
                }
1027
                return false;
1028
        }
1029
}