Statistics
| Revision:

gvsig-raster / org.gvsig.raster.wms / trunk / org.gvsig.raster.wms / org.gvsig.raster.wms.app.wmsclient / src / main / java / org / gvsig / raster / wms / app / wmsclient / wmc / WebMapContext.java @ 4181

History | View | Annotate | Download (35.9 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

    
23
package org.gvsig.raster.wms.app.wmsclient.wmc;
24

    
25
import java.awt.Dimension;
26
import java.awt.geom.Rectangle2D;
27
import java.io.BufferedReader;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.FileReader;
32
import java.io.IOException;
33
import java.net.URI;
34
import java.net.URISyntaxException;
35
import java.util.ArrayList;
36
import java.util.Arrays;
37
import java.util.HashMap;
38
import java.util.HashSet;
39
import java.util.Hashtable;
40
import java.util.List;
41
import java.util.Vector;
42

    
43
import org.cresques.cts.ICoordTrans;
44
import org.cresques.cts.IProjection;
45

    
46
import org.gvsig.app.ApplicationLocator;
47
import org.gvsig.app.project.documents.view.DefaultViewDocument;
48
import org.gvsig.fmap.crs.CRSFactory;
49
import org.gvsig.fmap.dal.coverage.exception.ImportMapContextException;
50
import org.gvsig.fmap.mapcontext.exceptions.UnsupportedVersionLayerException;
51
import org.gvsig.fmap.mapcontext.layers.FLayer;
52
import org.gvsig.fmap.mapcontext.layers.FLayers;
53
import org.gvsig.i18n.Messages;
54
import org.gvsig.raster.wms.app.wmsclient.layer.FLyrWMS;
55
import org.gvsig.raster.wms.io.RemoteWMSStyle;
56
import org.gvsig.raster.wms.io.WMSDataParameters;
57
import org.gvsig.raster.wms.io.WMSDataParametersImpl;
58

    
59
import org.kxml2.io.KXmlParser;
60
import org.slf4j.Logger;
61
import org.slf4j.LoggerFactory;
62
import org.xmlpull.v1.XmlPullParserException;
63

    
64

    
65
/**
66
 * Class that loads and produces WebMapContext files and holds its attributes.
67
 *
68
 * You can create a blank WebMapContext instance using the default constructor
69
 * or an already initialized instance by specifying a source file. In the last
70
 * case the file will be readed and the values loaded an holded by the instance.
71
 *
72
 * You can get the equivalent WebMapContext XML document by calling the method
73
 * getXML() supplying the ProjectView that you want to export and depending on
74
 * the value of the fileVersion field (currently you can use "1.1.0" (default),
75
 * "1.0.0" or "0.4.1" to specify the destination document version.
76
 *
77
 * @author jaume dominguez faus - jaume.dominguez@iver.es
78
 */
79
public class WebMapContext {
80
        public final static String FILE_EXTENSION = ".cml";
81
        private Logger  log = LoggerFactory.getLogger(WebMapContext.class);
82
        static final ArrayList<String> supportedVersions = new ArrayList<String>();
83
        static public final ArrayList<String> exportVersions    = new ArrayList<String>();
84
        static private HashSet supportedLayers = new HashSet();
85
        private File mapContextFile;
86
        private String encoding = "UTF-8";
87
        private String WMC_START_TAG;
88

    
89
        // MapContext stuff
90
        public String fileVersion = null;
91
        public Dimension windowSize = null;
92
        public String srs = null;
93
        public Rectangle2D bBox = null;
94
        public String title = null;
95
        public String id = null;
96
        public String xmlns = null;
97
        public String xmlns_xlink = null;
98
        public String xmlns_xsi = null;;
99
        public String xsi_schemaLocation = null;
100
        public String _abstract = null;
101
        public List<String> keywordList = null;
102
        public Dimension logoURLSize = null;
103
        public String logoURLFormat = null;
104
        public String logoURL = null;
105
        public String descriptionURLFormat = null;
106
        public String descriptionURL = null;
107
        public boolean contactInfo = false;
108
        public String contactPerson = null;
109
        public String contactOrganization = null;
110
        public String contactPosition = null;
111
        public String address = null;
112
        public String city = null;
113
        public String stateOrProvince = null;
114
        public String postCode = null;
115
        public String country = null;
116
        public String telephone = null;
117
        public String fax = null;
118
        public String email = null;
119

    
120
        private StringBuffer errorMessages;
121

    
122
        List<FLyrWMS>            layerList  = null;
123
        List<WMSDataParameters>  paramsList = null;
124

    
125
        Hashtable<Object, String[]>  srsList = null;
126

    
127
        /**
128
         * key: server URL (URL)
129
         * value: server title (String)
130
         */
131
        Hashtable<String, String> serverTitles = null;
132

    
133
        /**
134
         * key: layer FLyrWMS
135
         * value: layer abstract (String)
136
         */
137
        Hashtable layerAbstracts = null;
138

    
139
        /**
140
         * key: layer FLyrWMS
141
         * value: layer formats (String[])
142
         */
143
        Hashtable layerFormats = null;
144

    
145
        /**
146
         * key: layer FLyrWMS
147
         * value: styles (FMapWMSStyle[])
148
         */
149
        Hashtable layerStyles = null;
150

    
151

    
152
        static {
153
                supportedVersions.add("1.1.0");
154
                supportedVersions.add("1.0.0");
155
                supportedVersions.add("0.1.4");
156
        }
157

    
158
        static {
159
                exportVersions.add("1.1.0");
160
                exportVersions.add("1.0.0");
161
                exportVersions.add("0.1.4");
162
        }
163

    
164
        static {
165
                supportedLayers.add(FLyrWMS.class);
166
        }
167

    
168

    
169
        /**
170
         * Initializes the WebMapContext properties from the values in the WebMapContext (.cml)
171
         * file passed in the argument.
172
         * @param file
173
         * @throws UnsupportedVersionLayerException
174
         * @throws ImportMapContextException
175
         */
176
        public void readFile(File file) throws UnsupportedVersionLayerException, ImportMapContextException {
177
                this.mapContextFile = file;
178
                errorMessages = new StringBuffer();
179
                if (getVersion() != null) {
180
                        if (supportedVersions.contains(getVersion())) {
181
                                WMC_START_TAG = WebMapContextTags.VIEW_CONTEXT;
182
                                if (getVersion().equals("0.1.4")) {
183
                                        WMC_START_TAG = WebMapContextTags.VIEW_CONTEXT_0_1_4;
184
                                        parse1_1_0(file);
185
                                } else if (getVersion().equals("1.1.0")) {
186
                                        parse1_1_0(file);
187
                                } else if (getVersion().equals("1.0.0")) {
188
                                        parse1_1_0(file);
189
                                } else {
190
                                        parseDefaultVersion(file);
191
                                }
192

    
193
                                // Once parsed, check errors
194
                                if (errorMessages.length() > 0) {
195
                                        throw new ImportMapContextException(errorMessages.toString(), false);
196
                                }
197
                        } else {
198
                                throw new UnsupportedVersionLayerException(file.getName(), null);
199
                        }
200
                }
201
        }
202

    
203

    
204
        /**
205
         * If no version was recognized then will parse the default one which is supposed
206
         * to be the best available.
207
         * @param file
208
         * @throws ImportMapContextException
209
         */
210
        private void parseDefaultVersion(File file) throws ImportMapContextException {
211
                parse1_1_0(file);
212
        }
213

    
214
        /**
215
         * Reads the header of the Weg Map Context file and determines which version
216
         * it belongs to.
217
         * @return String.
218
         */
219
        private String getVersion() {
220
                if (fileVersion == null) {
221
                        String v = null;
222
                        try {
223
                                FileReader fr = new FileReader(mapContextFile);
224
                                KXmlParser parser = new KXmlParser();
225
                                parser.setInput(fr);
226
                                parser.nextTag();
227
                            if ( parser.getEventType() != KXmlParser.END_DOCUMENT )        {
228
                                    if ((parser.getName().compareTo(WebMapContextTags.VIEW_CONTEXT) == 0) ||
229
                                             parser.getName().compareTo(WebMapContextTags.VIEW_CONTEXT_0_1_4) == 0) {
230
                                            v = parser.getAttributeValue("", WebMapContextTags.VERSION);
231
                                    }
232
                            }
233
                        } catch (FileNotFoundException fnfEx) {
234
                        } catch (XmlPullParserException xmlEx) {
235
                                xmlEx.printStackTrace();
236
                        } catch (IOException e) {
237
                        }
238
                        fileVersion = v;
239
                }
240
                return fileVersion;
241
        }
242

    
243
        private void readEnconding(File file) {
244
                FileReader fr = null;
245
                try {
246
                        fr = new FileReader(file);
247
                    BufferedReader br = new BufferedReader(fr);
248
                    char[] buffer = new char[100];
249
                    br.read(buffer);
250
                    StringBuffer st = new StringBuffer(new String(buffer));
251
                    String searchText = "encoding=\"";
252
                    int index = st.indexOf(searchText);
253
                    if (index>-1) {
254
                            st.delete(0, index+searchText.length());
255
                            encoding = st.substring(0, st.indexOf("\""));
256
                    }
257
                    br.close();
258
                    fr.close();
259
            } catch(FileNotFoundException ex)        {
260
                    log.info("Error reading the encoding", ex);
261
            } catch (IOException e) {
262
                    log.info("Error reading the encoding", e);
263
                }
264
        }
265

    
266
        /**
267
         * Reads a Web Map Context version 1.1.0. As far as v1.0.0 is a subset of
268
         * v1.1.0 it can be used to read files belonging to 1.0.0 as well.
269
         * @param file, the web map context file.
270
         */
271
        private void parse1_1_0(File file) throws ImportMapContextException {
272
                try {
273
                        readEnconding(file);
274

    
275
                        KXmlParser parser = new KXmlParser();
276
                        parser.setInput(new FileInputStream(file), encoding);
277
                        int tag = parser.nextTag();
278
                        if ( parser.getEventType() != KXmlParser.END_DOCUMENT ) {
279
                                parser.require(KXmlParser.START_TAG, null, WMC_START_TAG);
280
                                while(tag != KXmlParser.END_DOCUMENT) {
281
                                        switch(tag) {
282
                                                case KXmlParser.START_TAG:
283
                                                        if (parser.getName().compareTo(WMC_START_TAG) == 0) {
284
                                                                id = parser.getAttributeValue("", WebMapContextTags.ID);
285
                                                                xmlns = parser.getAttributeValue("", WebMapContextTags.XMLNS);
286
                                                                xmlns_xlink = parser.getAttributeValue("", WebMapContextTags.XMLNS_XLINK);
287
                                                                xmlns_xsi = parser.getAttributeValue("", WebMapContextTags.XMLNS_XSI);
288
                                                                xsi_schemaLocation = parser.getAttributeValue("", WebMapContextTags.XSI_SCHEMA_LOCATION) ;
289
                                                        } else if (parser.getName().compareTo(WebMapContextTags.GENERAL) == 0) {
290
                                                                parseGeneral1_1_0(parser);
291
                                                        } else if (parser.getName().compareTo(WebMapContextTags.LAYER_LIST) == 0) {
292
                                                                int layerListTag = parser.nextTag();
293
                                                                boolean bLayerListEnd = false;
294
                                                                layerList = new ArrayList<FLyrWMS>();
295
                                                                paramsList = new ArrayList<WMSDataParameters>();
296
                                                                while (!bLayerListEnd) {
297
                                                                        switch(layerListTag) {
298
                                                                        case KXmlParser.START_TAG:
299
                                                                                if (parser.getName().compareTo(WebMapContextTags.LAYER) == 0) {
300
                                                                                        FLyrWMS layer = new FLyrWMS();
301
                                                                                        WMSDataParameters dataParameters = new WMSDataParametersImpl();
302
                                                                                        dataParameters.setSRS(srs);
303
                                                                                        parseLayer1_1_0(parser, layer, dataParameters);
304
                                                                                        // will use the mapcontext's bounding box as layer's fullextent
305
                                                                                        IProjection proj =  CRSFactory.getCRS(srs);
306
                                                                                        if (proj == null) {
307
                                                                                                // non supported srs, and cannot continue
308
                                                                                                String msg = Messages.getText("unsupported_crs") + " (" + srs + ")";
309
                                                                                                throw new ImportMapContextException(msg, true);
310
                                                                                        }
311
                                                                                        /*String[] availableSRS = dataParameters.getSRSCode().split(",");
312
                                                                                        ICoordTrans ct = null;
313
                                                                                        String mySRS = null;
314
                                                                                        for (int i = 0; i < availableSRS.length; i++) {
315
                                                                                                mySRS = availableSRS[i];
316
                                                                                                IProjection dstProj = CRSFactory.getCRS(mySRS);
317
                                                                                                if (dstProj != null) {
318
                                                                                                        try{
319
                                                                                                                        ct = proj.getCT(dstProj);
320
                                                                                                                } catch(Exception e) {
321
                                                                                                                        ct = null;
322
                                                                                                                } catch (Error e) {
323
                                                                                                                        ct = null;
324
                                                                                                                }
325
                                                                                                        if (mySRS.equals(srs)) {
326
                                                                                                                break;
327
                                                                                                        }
328
                                                                                                }
329
                                                                                        }
330

331
                                                                                        if (ct != null) {
332
                                                                                                dataParameters.setSRS(mySRS);
333
                                                                                        } else {
334
                                                                                                // can't reproject
335
                                                                                                errorMessages.append("[").
336
                                                                                                                      append(Messages.getText("layer")).
337
                                                                                                                      append(" ").
338
                                                                                                                      append(layer.getName()).
339
                                                                                                                      append("] ").
340
                                                                                                                          append(Messages.getText("cant_reproject_from_any_of")).
341
                                                                                                                          append(" [").append(dataParameters.getSRSCode()).append("] ").
342
                                                                                                                          append(Messages.getText("to")).
343
                                                                                                                          append(srs).
344
                                                                                                                          append("\n");
345
                                                                                                dataParameters.setSRS(srs);
346
                                                                                        }*/
347

    
348
                                                                                        dataParameters.setWmsTransparency(true);
349
                                                                                        layerList.add(layer);
350
                                                                                        paramsList.add(dataParameters);
351
                                                                                } else {
352
                                                                                        log.info("Unrecognized "+ parser.getName());
353
                                                                                }
354
                                                                                break;
355
                                                                        case KXmlParser.END_TAG:
356
                                                                                if (parser.getName().compareTo(WebMapContextTags.LAYER_LIST) == 0) {
357
                                                                                        bLayerListEnd = true;
358
                                                                                }
359
                                                                                break;
360
                                                                        case KXmlParser.TEXT:
361
                                                                                break;
362
                                                                        }
363
                                                                        layerListTag = parser.next();
364
                                                                }
365
                                                        } else if (parser.getName().compareTo(WebMapContextTags.DIMENSION_LIST) == 0) {
366
                                                                log.info("WebMapContext's Dimension not yet implemented");
367
                                                        } else {
368
                                                                log.info("Unrecognized " + parser.getName());
369
                                                        }
370
                                                        break;
371
                                                case KXmlParser.END_TAG:
372
                                                        break;
373
                                                case KXmlParser.TEXT:
374
                                                        break;
375
                                        }
376
                                        tag = parser.next();
377
                                }
378
                                parser.require(KXmlParser.END_DOCUMENT, null, null);
379
                        }
380
                } catch (ImportMapContextException e){
381
                        throw e;
382
                } catch (Exception e) {
383
                        log.debug(Messages.getText("map_context_file_error"), e);
384
                }
385
        }
386

    
387
        /**
388
         * Parses the General tag of a web map context 1.1.0 (and 1.0.0) file
389
         * @param parser
390
         * @throws XmlPullParserException
391
         * @throws IOException
392
         */
393
        private void parseGeneral1_1_0(KXmlParser parser) throws XmlPullParserException, IOException {
394
                boolean end = false;
395
            int tag = parser.next();
396
            while (!end) {
397
                    switch(tag) {
398
                        case KXmlParser.START_TAG:
399
                                if (parser.getName().compareTo(WebMapContextTags.WINDOW) == 0) {
400
                                        if (windowSize == null) {
401
                                                        windowSize = new Dimension();
402
                                                }
403
                                                windowSize.setSize(Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.WIDTH)),
404
                                                                                   Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.HEIGHT)));
405
                                } else if (parser.getName().compareTo(WebMapContextTags.BOUNDING_BOX) == 0) {
406
                                        srs = parser.getAttributeValue("", WebMapContextTags.SRS);
407
                                        double minx = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.X_MIN));
408
                                        double miny = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.Y_MIN));
409
                                        double maxx = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.X_MAX));
410
                                        double maxy = Double.parseDouble(parser.getAttributeValue("", WebMapContextTags.Y_MAX));
411
                                        bBox = new Rectangle2D.Double(minx, miny, maxx-minx, maxy-miny);
412
                            } else if (parser.getName().compareTo(WebMapContextTags.TITLE) == 0) {
413
                                        title = parser.nextText();
414
                                } else if (parser.getName().compareTo(WebMapContextTags.ABSTRACT) == 0) {
415
                                        _abstract = parser.nextText();
416
                                } else if (parser.getName().compareTo(WebMapContextTags.KEYWORD_LIST) == 0) {
417
                                        keywordList = new ArrayList<String>();
418
                                        boolean keywordEnd = false;
419
                                    int keywordTag = parser.next();
420
                                    while (!keywordEnd) {
421
                                            switch(keywordTag) {
422
                                                case KXmlParser.START_TAG:
423
                                                        if (parser.getName().compareTo(WebMapContextTags.KEYWORD) == 0) {
424
                                                                keywordList.add(parser.nextText());
425
                                                        } else {
426
                                                    System.out.println("Unrecognized "+parser.getName());
427
                                                                }
428
                                                                break;
429
                                                 case KXmlParser.END_TAG:
430
                                                        if (parser.getName().compareTo(WebMapContextTags.KEYWORD_LIST) == 0) {
431
                                                                                keywordEnd = true;
432
                                                                        }
433
                                                        break;
434
                                                case KXmlParser.TEXT:
435
                                                        if (parser.getName()!=null) {
436
                                                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
437
                                                                        }
438
                                                        break;
439
                                            }
440
                                            keywordTag = parser.next();
441
                                    }
442
                                } else if (parser.getName().compareTo(WebMapContextTags.LOGO_URL) == 0) {
443
                                        logoURLSize = new Dimension(Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.WIDTH)),
444
                                                                                                Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.HEIGHT)));
445
                                        logoURLFormat = parser.getAttributeValue("", WebMapContextTags.FORMAT.toLowerCase());
446
                                        parser.nextTag();
447
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0) {
448
                                                logoURL = parser.getAttributeValue("", WebMapContextTags.XLINK_HREF);
449
                                        } else {
450
                                System.out.println("Unrecognized "+parser.getName());
451
                                            }
452
                                } else if (parser.getName().compareTo(WebMapContextTags.DESCRIPTION_URL) == 0) {
453
                                        descriptionURLFormat = parser.getAttributeValue("", WebMapContextTags.FORMAT.toLowerCase());
454
                                        parser.nextTag();
455
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0) {
456
                                                descriptionURL = parser.getAttributeValue("", WebMapContextTags.XLINK_HREF);
457
                                        } else {
458
                                System.out.println("Unrecognized "+parser.getName());
459
                                            }
460
                                } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_INFORMATION) == 0) {
461
                                        boolean contactInfoEnd = false;
462
                                    int contactInfoTag = parser.next();
463
                                    while (!contactInfoEnd) {
464
                                            switch(contactInfoTag) {
465
                                                case KXmlParser.START_TAG:
466
                                                        if (parser.getName().compareTo(WebMapContextTags.CONTACT_PERSON) == 0) {
467
                                                                contactPerson = parser.nextText();
468
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_ORGANIZATION) == 0) {
469
                                                                contactOrganization = parser.nextText();
470
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_POSITION) == 0) {
471
                                                                contactPosition = parser.nextText();
472
                                                        } else if (parser.getName().compareTo(WebMapContextTags.ADDRESS) == 0) {
473
                                                                address = parser.nextText();
474
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CITY) == 0) {
475
                                                                city = parser.nextText();
476
                                                        } else if (parser.getName().compareTo(WebMapContextTags.STATE_OR_PROVINCE) == 0) {
477
                                                                stateOrProvince = parser.nextText();
478
                                                        } else if (parser.getName().compareTo(WebMapContextTags.POSTCODE) == 0) {
479
                                                                postCode = parser.nextText();
480
                                                        } else if (parser.getName().compareTo(WebMapContextTags.COUNTRY) == 0) {
481
                                                                country = parser.nextText();
482
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_VOICE_TELEPHONE) == 0) {
483
                                                                telephone = parser.nextText();
484
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_FACSIMILE_TELEPHONE) == 0) {
485
                                                                fax = parser.nextText();
486
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_ELECTRONIC_MAIL_ADDRESS) == 0) {
487
                                                                email = parser.nextText();
488
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_PERSON_PRIMARY) == 0) {
489
                                                                // DO NOTHING
490
                                                        } else if (parser.getName().compareTo(WebMapContextTags.CONTACT_ADDRESS) == 0) {
491
                                                                // DO NOTHING
492
                                                        } else {
493
                                                    System.out.println("Unrecognized "+parser.getName());
494
                                                                }
495
                                                        break;
496
                                                 case KXmlParser.END_TAG:
497
                                                        if (parser.getName().compareTo(WebMapContextTags.CONTACT_INFORMATION) == 0) {
498
                                                                                contactInfoEnd = true;
499
                                                                        }
500
                                                        break;
501
                                                case KXmlParser.TEXT:
502
                                                        if (parser.getName()!=null) {
503
                                                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
504
                                                                        }
505
                                                        break;
506
                                            }
507
                                            contactInfoTag = parser.next();
508
                                    }
509
                            } else {
510
                            System.out.println("Unrecognized "+parser.getName());
511
                                        }
512
                                        break;
513
                         case KXmlParser.END_TAG:
514
                                if (parser.getName().compareTo(WebMapContextTags.GENERAL) == 0) {
515
                                                end = true;
516
                                        }
517
                                break;
518
                        case KXmlParser.TEXT:
519
                                if (parser.getName()!=null) {
520
                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
521
                                        }
522
                                break;
523
                    }
524
                    tag = parser.next();
525
            }
526
        }
527

    
528
        @SuppressWarnings("unchecked")
529
        private void parseLayer1_1_0(KXmlParser parser, FLyrWMS layer, WMSDataParameters dataParameters) throws XmlPullParserException, IOException {
530
                boolean end = false;
531

    
532
                String queryable = parser.getAttributeValue("", WebMapContextTags.QUERYABLE);
533
                dataParameters.setQueryable(queryable!=null && (queryable.equals("1") || queryable.toLowerCase().equals("true")));
534
                List<RemoteWMSStyle> styles = new ArrayList<RemoteWMSStyle>();
535

    
536
                String hidden = parser.getAttributeValue("", WebMapContextTags.HIDDEN);
537
                layer.setVisible(hidden == null || !hidden.equals("1") || !hidden.toLowerCase().equals("true"));
538
            int tag = parser.next();
539
            while (!end) {
540
                    switch(tag) {
541
                        case KXmlParser.START_TAG:
542
                                if (parser.getName().compareTo(WebMapContextTags.SERVER) == 0) {
543
                                        String serverTitle = parser.getAttributeValue("", WebMapContextTags.TITLE.toLowerCase());
544
                                        parser.nextTag();
545
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0) {
546
                                            URI uri;
547
                            String uriStr = parser.getAttributeValue("", WebMapContextTags.XLINK_HREF);
548
                            try {
549
                                uri = new URI(uriStr);
550
                            } catch (URISyntaxException e) {
551
                                throw new IOException("Can't create URI from "+uriStr, e);
552
                            }
553

    
554
                                                dataParameters.setURI(uri);
555
                                                if (serverTitles == null) {
556
                                                                serverTitles = new Hashtable<String, String>();
557
                                                        }
558
                                            serverTitles.put(uriStr, serverTitle);
559
                                        }
560
                                } else if (parser.getName().compareTo(WebMapContextTags.TITLE) == 0) {
561
                                        layer.setName(parser.nextText());
562
                                } else if (parser.getName().compareTo(WebMapContextTags.NAME) == 0) {
563
                                        dataParameters.setLayerQuery(parser.nextText());
564
                                /* //TODO This case would handle nested layer definitions.
565
                                 *
566
                                 } else if (parser.getName().compareTo(WebMapContextTags.LAYER) == 0) {
567
                                        FLyrWMS sonLayer = parseLayer1_1_0(parser);
568
                                        String q = layer.getLayerQuery();
569
                                        if (q == null) q = "";
570
                                        else q += ",";
571
                                        layer.setLayerQuery( q + sonLayer.getLayerQuery());
572
                                 *
573
                                 */
574
                                } else if (parser.getName().compareTo(WebMapContextTags.ABSTRACT) == 0) {
575
                                        if (layerAbstracts == null) {
576
                                                        layerAbstracts = new Hashtable();
577
                                                }
578
                                        layerAbstracts.put(layer, parser.nextText());
579
                                } else if (parser.getName().compareTo(WebMapContextTags.SRS) == 0) {
580
                                        String[] srss = parseEPSGList(parser.nextText());
581
                                        if (srsList == null) {
582
                                                srsList = new Hashtable<Object, String[]>();
583
                                                }
584
                                        srsList.put(layer, srss);
585
                                } else if (parser.getName().compareTo(WebMapContextTags.FORMAT_LIST) == 0) {
586
                                        int formatsTag = parser.nextTag();
587
                                        boolean bFormatsEnd = false;
588
                                        ArrayList formats = new ArrayList();
589
                                        while (!bFormatsEnd) {
590
                                                switch (formatsTag) {
591
                                                case KXmlParser.START_TAG:
592
                                                        if (parser.getName().compareTo(WebMapContextTags.FORMAT) == 0) {
593
                                                                String current = parser.getAttributeValue("", WebMapContextTags.CURRENT);
594
                                                                String format = parser.nextText();
595
                                                                if (current!=null && current.equals("1")) {
596
                                                                        dataParameters.setFormat(format);
597
                                                                        }
598
                                                                formats.add(format);
599
                                                        } else {
600
                                                                log.info("Unrecognized " + parser.getName());
601
                                                        }
602
                                                        break;
603
                                                case KXmlParser.END_TAG:
604
                                                        if (parser.getName().compareTo(WebMapContextTags.FORMAT_LIST) == 0) {
605
                                                                        bFormatsEnd = true;
606
                                                                }
607
                                                        break;
608
                                                case KXmlParser.TEXT:
609
                                                        if (parser.getName()!=null) {
610
                                                                log.info("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
611
                                                                }
612
                                                        break;
613
                                                }
614
                                                formatsTag = parser.next();
615
                                        }
616
                                        if (layerFormats == null) {
617
                                                        layerFormats = new Hashtable();
618
                                                }
619
                                        layerFormats.put(layer, formats.toArray(new String[0]));
620

    
621
                                } else if (parser.getName().compareTo(WebMapContextTags.STYLE_LIST) == 0) {
622
                                        int stylesTag = parser.nextTag();
623
                                        boolean bStylesEnd = false;
624
                                        while (!bStylesEnd) {
625
                                                switch (stylesTag) {
626
                                                case KXmlParser.START_TAG:
627
                                                        if (parser.getName().compareTo(WebMapContextTags.STYLE) == 0) {
628
                                                                String current = parser.getAttributeValue("", WebMapContextTags.CURRENT);
629
                                                                RemoteWMSStyle style = parseStyle1_1_0(parser);
630

    
631
                                                                if (current!=null && current.equals("1") && !style.getName().equals("default")) {
632
                                                                        style.setName("default");
633
                                                                }
634
                                                                styles.add(style);
635
                                                        } else {
636
                                                                System.out.println("Unrecognized "+parser.getName());
637
                                                        }
638
                                                        break;
639
                                                case KXmlParser.END_TAG:
640
                                                        if (parser.getName().compareTo(WebMapContextTags.STYLE_LIST) == 0) {
641
                                                                        bStylesEnd = true;
642
                                                                }
643
                                                        break;
644
                                                case KXmlParser.TEXT:
645
                                                        if (parser.getName()!=null) {
646
                                                                        System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
647
                                                                }
648
                                                        break;
649
                                                }
650
                                                stylesTag = parser.next();
651
                                        }
652
                                        if (layerStyles == null) {
653
                                                        layerStyles = new Hashtable();
654
                                                }
655

    
656
                                        layerStyles.put(layer, styles.toArray(new RemoteWMSStyle[0]));
657
                                } else {
658
                                        log.info("Unrecognized " + parser.getName());
659
                                }
660
                                break;
661
                        case KXmlParser.END_TAG:
662
                                if (parser.getName().compareTo(WebMapContextTags.LAYER) == 0) {
663
                                                end = true;
664
                                        }
665
                                break;
666
                        case KXmlParser.TEXT:
667
                                if (parser.getName()!=null) {
668
                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
669
                                        }
670
                                break;
671
                    }
672
                    tag = parser.next();
673
            }
674
            dataParameters.setStyles(styles);
675
        }
676

    
677
        private String[] parseEPSGList(String nextText) {
678
                String[] epsglist = nextText.split(",");
679
                return epsglist;//Arrays.asList(epsglist);
680
        }
681

    
682

    
683
        private RemoteWMSStyle parseStyle1_1_0(KXmlParser parser) throws XmlPullParserException, IOException {
684
                boolean end = false;
685
                String styleName = null;
686
                String styleAbstract = null;
687
                String styleTitle = null;
688
                int legendWidth = -1;
689
                int legendHeight = -1;
690
                String legendType = null;
691
                String legendHref = null;
692

    
693
            int tag = parser.next();
694
            while (!end) {
695
                    switch(tag) {
696
                        case KXmlParser.START_TAG:
697
                                if (parser.getName().compareTo(WebMapContextTags.NAME) == 0) {
698
                                        styleName = parser.nextText();
699
                                } else if (parser.getName().compareTo(WebMapContextTags.ABSTRACT) == 0) {
700
                                        styleAbstract = parser.nextText();
701
                                } else if (parser.getName().compareTo(WebMapContextTags.TITLE) == 0) {
702
                                        styleTitle = parser.nextText();
703
                                } else if (parser.getName().compareTo(WebMapContextTags.LEGEND_URL) == 0){
704
                                        legendWidth = Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.WIDTH));
705
                                        legendHeight = Integer.parseInt(parser.getAttributeValue("", WebMapContextTags.HEIGHT));
706
                                        parser.nextTag();
707
                                        if (parser.getName().compareTo(WebMapContextTags.ONLINE_RESOURCE) == 0 ) {
708
                                                        legendType = parser.getAttributeValue("", WebMapContextTags.XLINK_TYPE);
709
                                                        legendHref = parser.getAttributeValue("", WebMapContextTags.XLINK_HREF);
710
                                        }
711
                                } else {
712
                            System.out.println("Unrecognized "+parser.getName());
713
                                        }
714
                                break;
715
                         case KXmlParser.END_TAG:
716
                                if (parser.getName().compareTo(WebMapContextTags.STYLE) == 0) {
717
                                                end = true;
718
                                        }
719
                                break;
720
                        case KXmlParser.TEXT:
721
                                if (parser.getName()!=null) {
722
                                                System.out.println("[TAG]["+parser.getName()+"]\n[TEXT]["+parser.getText().trim()+"]");
723
                                        }
724
                                break;
725
                    }
726
                    tag = parser.next();
727
            }
728

    
729
            RemoteWMSStyle sty = new RemoteWMSStyle();
730
            sty.setName(styleName);
731
            sty.setTitle(styleTitle);
732
            sty.setStyleAbstract(styleAbstract);
733
            sty.setLegendWidth(legendWidth);
734
            sty.setLegendHeight(legendHeight);
735
            sty.setType(legendType);
736
            sty.setHref(legendHref);
737
            sty.setParent(null);
738
            return sty;
739
        }
740

    
741
        /**
742
         * Creates the Web Map Context (WMC) XML according on the version 1.1.0. Since Web
743
         * WMC 1.0.0 is a subset of WMC 1.1.0 and this method does not produce tags for
744
         * unset values, it can be used to produce WMC 1.0.0, or even to produce
745
         * the deprecated (but still alive) WMC 0.1.4.
746
         * @param v
747
         * @return
748
         */
749
        private String createMapContext1_1_0(DefaultViewDocument v) {
750
                ArrayList layersToExport = getExportableLayers(v);
751

    
752
                XmlBuilder xml = new XmlBuilder();
753
                HashMap<Object, String> xmlAttrs = new HashMap<Object, String>();
754
                xml.setEncoding("ISO-8859-1"); // TODO make it customizable???
755
                xml.writeHeader();
756

    
757
                // <ViewContext>
758
                String viewContextTag;
759
                if (fileVersion.equals("0.1.4")) {
760
                        viewContextTag = WebMapContextTags.VIEW_CONTEXT_0_1_4;
761
                } else {
762
                        viewContextTag = WebMapContextTags.VIEW_CONTEXT;
763
                }
764

    
765
                xml.writeRaw("<!-- " + Messages.getText("created_with") + " gvSIG " + ApplicationLocator.getManager().getVersion() + " -->");
766

    
767
                xmlAttrs.put(WebMapContextTags.VERSION, fileVersion);
768
                xmlAttrs.put(WebMapContextTags.ID, id);
769
                xmlAttrs.put(WebMapContextTags.XMLNS, WebMapContextTags.XMLNS_VALUE);
770
                xmlAttrs.put(WebMapContextTags.XMLNS_XLINK, WebMapContextTags.XMLNS_XLINK_VALUE);
771
                xmlAttrs.put(WebMapContextTags.XMLNS_XSI, WebMapContextTags.XMLNS_XSI_VALUE);
772
                xmlAttrs.put(WebMapContextTags.XSI_SCHEMA_LOCATION, WebMapContextTags.XSI_SCHEMA_LOCATION_VALUE);
773
                xml.openTag(viewContextTag,  xmlAttrs);
774
                xmlAttrs.clear();
775

    
776
                // <General>
777
                xml.openTag(WebMapContextTags.GENERAL);
778

    
779
                // <Window>
780
                if (windowSize!=null) {
781
                        xmlAttrs.put(WebMapContextTags.WIDTH, ((int) windowSize.getWidth())+"");
782
                        xmlAttrs.put(WebMapContextTags.HEIGHT, ((int) windowSize.getHeight())+"");
783
                        xml.writeTag(WebMapContextTags.WINDOW, xmlAttrs);
784
                        xmlAttrs.clear();
785
                }
786
                // </Window>
787

    
788
                // <BoundingBox>
789
                xmlAttrs.put(WebMapContextTags.SRS, v.getProjection().getAbrev());
790
                xmlAttrs.put(WebMapContextTags.X_MIN, bBox.getMinX()+"");
791
                xmlAttrs.put(WebMapContextTags.Y_MIN, bBox.getMinY()+"");
792
                xmlAttrs.put(WebMapContextTags.X_MAX, bBox.getMaxX()+"");
793
                xmlAttrs.put(WebMapContextTags.Y_MAX, bBox.getMaxY()+"");
794
                xml.writeTag(WebMapContextTags.BOUNDING_BOX, xmlAttrs);
795
                xmlAttrs.clear();
796
                // </BoundingBox>
797

    
798
                // <Title>
799
                xml.writeTag(WebMapContextTags.TITLE, title.trim());
800
                // </Title>
801

    
802
                // <Abstract>
803
                if (_abstract != null) {
804
                        xml.writeTag(WebMapContextTags.ABSTRACT, _abstract.trim());
805
                        // </Abstract>
806
                }
807

    
808
                // <LogoURL>
809
                if (logoURL != null) {
810
                        xml.writeTag(WebMapContextTags.LOGO_URL, logoURL.trim());
811
                        // </LogoURL>
812
                }
813

    
814
                // <DescriptionURL>
815
                if (descriptionURL != null) {
816
                        xml.writeTag(WebMapContextTags.DESCRIPTION_URL, descriptionURL.trim());
817
                        // </DescriptionURL>
818
                }
819

    
820
                if (contactInfo) {
821

    
822
                        // <ContactInformation>
823
                        xml.openTag(WebMapContextTags.CONTACT_INFORMATION);
824
                        if (contactPerson != null || contactOrganization != null) {
825

    
826
                                // <ContactPersonPrimary>
827
                                xml.openTag(WebMapContextTags.CONTACT_PERSON_PRIMARY);
828

    
829
                                // <ContactPerson>
830
                                if (contactPerson != null) {
831
                                        xml.writeTag(WebMapContextTags.CONTACT_PERSON, contactPerson.trim());
832
                                        // </ContactPerson>
833
                                }
834

    
835
                                // <ContactOrganization>
836
                                if (contactOrganization != null) {
837
                                        xml.writeTag(WebMapContextTags.CONTACT_ORGANIZATION, contactOrganization.trim());
838
                                        // </ContactOrganization>
839
                                }
840

    
841
                                xml.closeTag();
842
                                // </ContactPersonPrimary>
843
                        }
844
                        xml.closeTag();
845
                        // </ContactInformation>
846

    
847
                        // <ContactPosition>
848
                        if (contactPosition != null) {
849
                                xml.writeTag(WebMapContextTags.CONTACT_POSITION, contactPosition.trim());
850
                                // </ContactPosition>
851
                        }
852

    
853
                        // <ContactAddress>
854
                        if (address != null || city != null || stateOrProvince != null || postCode != null || country != null) {
855
                                xml.openTag(WebMapContextTags.CONTACT_ADDRESS);
856

    
857
                                // <AddressType>
858
                                xml.writeTag(WebMapContextTags.ADDRESS_TYPE, "Postal");
859
                                // </AddressType>
860

    
861
                                // <Address>
862
                                if (address != null) {
863
                                        xml.writeTag(WebMapContextTags.ADDRESS, address.trim());
864
                                        // </Address>
865
                                }
866

    
867
                                // <City>
868
                                if (city != null) {
869
                                        xml.writeTag(WebMapContextTags.CITY, city.trim());
870
                                        // </City>
871
                                }
872

    
873
                                // <StateOrProvince>
874
                                if (stateOrProvince != null) {
875
                                        xml.writeTag(WebMapContextTags.STATE_OR_PROVINCE, stateOrProvince.trim());
876
                                        // </StateOrProvince>
877
                                }
878

    
879
                                // <PostCode>
880
                                if (postCode != null) {
881
                                        xml.writeTag(WebMapContextTags.POSTCODE, postCode.trim());
882
                                        // </PostCode>
883
                                }
884

    
885
                                // <Country>
886
                                if (country != null) {
887
                                        xml.writeTag(WebMapContextTags.COUNTRY, country.trim());
888
                                }
889
                                // </Country>
890
                                xml.closeTag();
891
                        }
892
                        // </ContactAddress>
893

    
894
                        // <ContactVoiceTelephone>
895
                        if (telephone != null) {
896
                                xml.writeTag(WebMapContextTags.CONTACT_VOICE_TELEPHONE, telephone.trim());
897
                                // </ContactVoiceTelephone>
898
                        }
899

    
900
                        // <ContactFacsimileTelephone>
901
                        if (fax != null) {
902
                                xml.writeTag(WebMapContextTags.CONTACT_FACSIMILE_TELEPHONE, fax.trim());
903
                                // </ContactFacsimileTelephone>
904
                        }
905

    
906
                        // <ContactElectronicMailAddress>
907
                        if (email != null) {
908
                                xml.writeTag(WebMapContextTags.CONTACT_ELECTRONIC_MAIL_ADDRESS, email.trim());
909
                                // </ContactElectronicMailAddress>
910
                        }
911
                }
912
                // <KeywordList>
913
                xml.openTag(WebMapContextTags.KEYWORD_LIST);
914
                if (keywordList != null) {
915
                        for (int i = 0; i < keywordList.size(); i++) {
916
                                xml.writeTag(WebMapContextTags.KEYWORD, ((String) keywordList.get(i)).trim());
917
                        }
918
                } else {
919
                        xml.writeTag(WebMapContextTags.KEYWORD, "");
920
                }
921
                xml.closeTag();
922

    
923
                // </KeywordList>
924
                xml.closeTag();
925
                // </General>
926

    
927
                // <LayerList>
928
                xml.openTag(WebMapContextTags.LAYER_LIST);
929
                for (int i = 0; i < layersToExport.size(); i++) {
930
                        xml.writeRaw(((FLyrWMS) layersToExport.get(i)).toMapContext(fileVersion));
931
                }
932
                xml.closeTag();
933
                // </LayerList>
934
                xml.closeTag();
935
                // </ViewContext>
936

    
937
                return xml.getXML();
938
        }
939

    
940
        /**
941
         * Exports the ProjectView passed as parameter to Web Map Context XML compliant
942
         * with the defined specifications for the version set in the fileVersion field.
943
         * @param DefaultViewDocument to be exported
944
         * @return String containing the XML
945
         */
946
        public String toXML(DefaultViewDocument v) {
947
                if (fileVersion.equals("1.1.0") ||
948
                                fileVersion.equals("1.0.0") ||
949
                                fileVersion.equals("0.1.4")) {
950
                        return createMapContext1_1_0(v);
951
                }
952
                return null;
953
        }
954

    
955

    
956
        public static ArrayList getExportableLayers(DefaultViewDocument v) {
957
                ArrayList list = new ArrayList();
958
                FLayers lyrs = v.getMapContext().getLayers();
959
                list.addAll(_getExportableLayers(lyrs));
960
                return list;
961
        }
962

    
963
        private static ArrayList _getExportableLayers(FLayer lyr) {
964
                ArrayList list = new ArrayList();
965
                if (checkType(lyr)) {
966
                        list.add(lyr);
967
                } else {
968
                        if (lyr instanceof FLayers) {
969
                                FLayers lyrs = (FLayers) lyr;
970
                                for (int i = 0; i < lyrs.getLayersCount(); i++) {
971
                                        list.addAll(_getExportableLayers(lyrs.getLayer(i)));
972
                                }
973
                        }
974
                }
975
                return list;
976
        }
977

    
978
        /**
979
         * Checks if the layer is supported by the WebMapContext
980
         * @param lyr
981
         * @return
982
         */
983
        private static boolean checkType(FLayer lyr) {
984
                return supportedLayers.contains(lyr.getClass());
985
        }
986

    
987
        /**
988
         * Searches in the layer tree of the TOC for an ocurrence of any
989
         * exportable layer and returns true if so, or false otherwise.
990
         * @param layer
991
         * @return
992
         */
993
        public static boolean containsExportableLayers(FLayer layer) {
994
                if (checkType(layer)) {
995
                        return true;
996
                }
997

    
998
                if (layer instanceof FLayers) {
999
                        FLayers layers = (FLayers) layer;
1000
                        for (int i = 0; i < layers.getLayersCount(); i++) {
1001
                                FLayer lyr = layers.getLayer(i);
1002
                                if (containsExportableLayers(lyr)) {
1003
                                        return true;
1004
                                }
1005

    
1006
                        }
1007
                }
1008
                return false;
1009
        }
1010
}