Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / Project.java @ 11704

History | View | Annotate | Download (58.6 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 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
package com.iver.cit.gvsig.project;
42

    
43
import java.awt.Color;
44
import java.beans.PropertyChangeEvent;
45
import java.beans.PropertyChangeListener;
46
import java.beans.PropertyChangeSupport;
47
import java.io.Serializable;
48
import java.text.DateFormat;
49
import java.util.ArrayList;
50
import java.util.Comparator;
51
import java.util.Date;
52
import java.util.Hashtable;
53
import java.util.Iterator;
54
import java.util.List;
55
import java.util.TreeMap;
56

    
57
import org.cresques.cts.IProjection;
58

    
59
import com.hardcode.driverManager.DriverLoadException;
60
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
61
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
62
import com.hardcode.gdbms.engine.data.DataSource;
63
import com.hardcode.gdbms.engine.data.DataSourceFactory;
64
import com.hardcode.gdbms.engine.data.NoSuchTableException;
65
import com.hardcode.gdbms.engine.data.SourceInfo;
66
import com.hardcode.gdbms.engine.data.db.DBSourceInfo;
67
import com.hardcode.gdbms.engine.data.db.DBTableSourceInfo;
68
import com.hardcode.gdbms.engine.data.file.FileSourceInfo;
69
import com.hardcode.gdbms.engine.data.object.ObjectSourceInfo;
70
import com.iver.andami.PluginServices;
71
import com.iver.andami.messages.NotificationManager;
72
import com.iver.andami.ui.mdiManager.IWindow;
73
import com.iver.andami.ui.mdiManager.SingletonWindow;
74
import com.iver.andami.ui.mdiManager.WindowInfo;
75
import com.iver.cit.gvsig.ProjectExtension;
76
import com.iver.cit.gvsig.Version;
77
import com.iver.cit.gvsig.fmap.MapContext;
78
import com.iver.cit.gvsig.fmap.ViewPort;
79
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
80
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
81
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
82
import com.iver.cit.gvsig.fmap.layers.FLayer;
83
import com.iver.cit.gvsig.fmap.layers.FLayers;
84
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
85
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
86
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
87
import com.iver.cit.gvsig.fmap.layers.XMLException;
88
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
89
import com.iver.cit.gvsig.fmap.operations.selection.LinkSelectionListener;
90
import com.iver.cit.gvsig.project.documents.ProjectDocument;
91
import com.iver.cit.gvsig.project.documents.ProjectDocumentFactory;
92
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
93
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
94
import com.iver.cit.gvsig.project.documents.gui.IDocumentWindow;
95
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
96
import com.iver.cit.gvsig.project.documents.gui.WindowData;
97
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
98
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
99
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
100
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
101
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
102
import com.iver.cit.gvsig.project.documents.view.ProjectView;
103
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
104
import com.iver.utiles.IPersistance;
105
import com.iver.utiles.PostProcessSupport;
106
import com.iver.utiles.StringUtilities;
107
import com.iver.utiles.XMLEntity;
108
import com.iver.utiles.extensionPoints.ExtensionPoint;
109
import com.iver.utiles.extensionPoints.ExtensionPoints;
110
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
111

    
112
/**
113
 * Clase que representa un proyecto de openSIG
114
 *
115
 * @author Fernando Gonz?lez Cort?s
116
 */
117
public class Project implements Serializable, PropertyChangeListener {
118
        public static String VERSION = Version.format();
119

    
120
        static private IProjection defaultProjection = null;
121

    
122
        static private IProjection defaultFactoryProjection = CRSFactory
123
                        .getCRS("EPSG:23030");
124

    
125
        /*
126
         * distiguishing between a static field "defaultSelectionColor" and a
127
         * selectionColor field will allow to define default color in a multiple
128
         * project scenario
129
         */
130
        static private Color defaultSelectionColor = Color.YELLOW;
131

    
132
        private static int defaultMapUnits = -1;
133

    
134
        private static int defaultDistanceUnits = -1;
135

    
136
        private PropertyChangeSupport change;
137

    
138
        private boolean modified = false;
139

    
140
        private String name = PluginServices.getText(this, "untitled");
141

    
142
        // private String path;
143
        private String creationDate = new Date().toGMTString();
144

    
145
        private String modificationDate = new Date().toGMTString();
146

    
147
        private String owner = "";
148

    
149
        private String comments = "";
150

    
151
        private Color selectionColor = null;
152

    
153
        // private ArrayList views = new ArrayList();
154
        // private ArrayList tables = new ArrayList();
155
        // private ArrayList maps = new ArrayList();
156
        private ArrayList documents = new ArrayList();
157

    
158
        private ArrayList extents = new ArrayList();
159

    
160
        // Lista de objetos del tipo camera. Necesarios para almacenar la posicion
161
        // del usuario haciendo uso de los marcadores
162
        private List cameras = new ArrayList();
163

    
164
        /**
165
         * this is a runtime-calculated value, do NOT persist it!
166
         */
167
        private long signatureAtStartup;
168
        private IProjection projection;
169

    
170
        /**
171
         * Stores the initial properties of the windows, to be restored just after
172
         * the project is loaded. It's an ordered iterator of XMLEntity objects,
173
         * each containing a XML version of a WindowInfo object.
174
         */
175
        private Iterator initialWindowProperties = null;
176

    
177
        private TreeMap sortedDocuments = new TreeMap(new Comparator() {
178
                public int compare(Object o1, Object o2) {
179
                        if ((o1 != null) && (o2 != null)) {
180
                                int priority1 = ((ProjectDocument) o1)
181
                                                .getProjectDocumentFactory().getPriority();
182
                                int priority2 = ((ProjectDocument) o2)
183
                                                .getProjectDocumentFactory().getPriority();
184
                                if (priority1 >= priority2)
185
                                        return 1;
186
                                return -1;
187
                        }
188
                        return 0;
189
                }
190
        }); // Para poder ordenar
191

    
192
        /**
193
         * Creates a new Project object.
194
         */
195
        public Project() {
196
                change = new PropertyChangeSupport(this);
197

    
198
                // change.addPropertyChangeListener(this);
199
                creationDate = DateFormat.getDateInstance().format(new Date());
200
                modificationDate = creationDate;
201
                setSelectionColor(getDefaultSelectionColor());
202
                getDefaultProjection(); //For initialize it
203
                // signatureAtStartup = computeSignature();
204

    
205
                /*
206
                 * LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
207
                 * .getPluginDirectory() .getAbsolutePath() + File.separator +
208
                 * "drivers");
209
                 */
210
        }
211

    
212
        /**
213
         * Obtiene la fecha de creaci?n del proyecto
214
         *
215
         * @return
216
         */
217
        public String getCreationDate() {
218
                return creationDate;
219
        }
220

    
221
        /**
222
         * Obtiene el nombre del proyecto
223
         *
224
         * @return
225
         */
226
        public String getName() {
227
                return name;
228
        }
229

    
230
        // /**
231
        // * Obtiene la ruta completa del fichero donde se guardo por ?ltima vez el
232
        // * proyecto
233
        // *
234
        // * @return
235
        // */
236
        // public String getPath() {
237
        // return path;
238
        // }
239

    
240
        /**
241
         * Asigna la fecha de creaci?n del proyecto. Este m?todo tiene sentido s?lo
242
         * por que al recuperar la fecha del XML hay que asignarla al objeto
243
         * proyecto de alguna manera. La fecha se asigna en el constructor y no se
244
         * deber?a de modificar nunca
245
         *
246
         * @param string
247
         */
248
        public void setCreationDate(String string) {
249
                creationDate = string;
250
                //modified = true;
251
                change.firePropertyChange("", null, null);
252
        }
253

    
254
        /**
255
         * Establece el nombre del proyecto
256
         *
257
         * @param string
258
         */
259
        public void setName(String string) {
260
                name = string;
261
                //modified = true;
262
                change.firePropertyChange("", null, null);
263
        }
264

    
265
        /**
266
         * Devuelve a partir de la capa la tabla asociada.
267
         *
268
         * @param co
269
         *            Capa.
270
         *
271
         * @return ProjectTable de la tabla asociada.
272
         */
273
        public ProjectTable getTable(AlphanumericData co) {
274
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
275
                /**
276
                 * Como las tablas se pueden a?adir cuando se pincha en "ver tabla" de
277
                 * una capa, se puede intentar a?adir dos veces la misma tabla
278
                 */
279
                for (int i = 0; i < tables.size(); i++) {
280
                        if (((ProjectTable) tables.get(i)).getAssociatedTable() == co) {
281
                                return (ProjectTable) tables.get(i);
282
                        }
283
                }
284

    
285
                return null;
286
        }
287

    
288
        /**
289
         * Devuelve a partir del nombre la tabla asociada.
290
         *
291
         * @param name
292
         *            Nombre.
293
         * @deprecated utilizar getProjectDocumentByName(...);
294
         * @return ProjectTable de la tabla asociada.
295
         */
296
        public ProjectTable getTable(String name) {
297
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
298
                /**
299
                 * Como las tablas se pueden a?adir cuando se pincha en "ver tabla" de
300
                 * una capa, se puede intentar a?adir dos veces la misma tabla
301
                 */
302
                for (int i = 0; i < tables.size(); i++) {
303
                        if (((ProjectTable) tables.get(i)).getName().equals(name)) {
304
                                return (ProjectTable) tables.get(i);
305
                        }
306
                }
307

    
308
                return null;
309
        }
310

    
311
        private boolean isModifiedDocuments() {
312
                ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
313
                for (int i=0;i<documents.length;i++) {
314
                        if (documents[i].isModified()) {
315
                                return true;
316
                        }
317
                }
318
                return false;
319
        }
320
//        /**
321
//         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
322
//         * fue modificado
323
//         *
324
//         * @return
325
//         */
326
//        public boolean isModified() {
327
//                if ((this.getDocuments().size() == 0) && !modified && !isModifiedDocuments()) {
328
//                        return false;
329
//                }
330
//                return true;
331
//                // /return modified; TODO El atributo modified solo detecta cuando se
332
//                // elimina o a?ade una vista,
333
//                // /mapa o tabla pero no cuando se modifican.
334
//        }
335

    
336
        /**
337
         * Obtiene los comentarios
338
         *
339
         * @return
340
         */
341
        public String getComments() {
342
                return comments;
343
        }
344

    
345
        /**
346
         * Obtiene la fecha de la ?ltima modificaci?n
347
         *
348
         * @return
349
         */
350
        public String getModificationDate() {
351
                return modificationDate;
352
        }
353

    
354
        /**
355
         * Obtiene el propietario del proyecto
356
         *
357
         * @return
358
         */
359
        public String getOwner() {
360
                return owner;
361
        }
362

    
363
        /**
364
         * Establece una cadena como comentarios al proyecto
365
         *
366
         * @param string
367
         */
368
        public void setComments(String string) {
369
                comments = string;
370
                //modified = true;
371
                change.firePropertyChange("", null, null);
372
        }
373

    
374
        /**
375
         * Establece la fecha de la ?ltima modificaci?n
376
         *
377
         * @param string
378
         */
379
        public void setModificationDate(String string) {
380
                modificationDate = string;
381
                //modified = true;
382
                change.firePropertyChange("", null, null);
383
        }
384

    
385
        /**
386
         * Establece el propietario del proyecto
387
         *
388
         * @param string
389
         */
390
        public void setOwner(String string) {
391
                owner = string;
392
                //modified = true;
393
                change.firePropertyChange("", null, null);
394
        }
395

    
396
        /**
397
         * Establece el flag de modificado del proyecto
398
         *
399
         * @param b
400
         */
401
        public void setModified(boolean b) {
402
                modified = b;
403
                if (modified==false) {
404
                        ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
405
                        for (int i=0;i<documents.length;i++) {
406
                                documents[i].setModified(false);
407
                        }
408
                }
409
        }
410

    
411
        /**
412
         * Obtiene el color de selecci?n que se usar? en el proyecto
413
         *
414
         * @return
415
         */
416
        public Color getSelectionColor() {
417
                if (selectionColor == null) {
418
                        selectionColor = defaultSelectionColor;
419
                }
420
                return selectionColor;
421
        }
422

    
423
        /**
424
         * Establece el color de selecci?n
425
         *
426
         * @param color
427
         */
428
        public void setSelectionColor(Color color) {
429
                selectionColor = color;
430
                FSymbol.setSelectionColor(color);
431
                //modified = true;
432
                change.firePropertyChange("selectionColor", null, color);
433
        }
434

    
435
        /**
436
         * Obtiene el color como un entero para su serializaci?n a XML
437
         *
438
         * @return
439
         */
440
        public String getColor() {
441
                return StringUtilities.color2String(selectionColor);
442
        }
443

    
444
        /**
445
         * M?todo invocado al recuperar de XML para establecer el color de seleccion
446
         * del proyecto
447
         *
448
         * @param color
449
         *            Entero que representa un color
450
         */
451
        public void setColor(String color) {
452
                //modified = true;
453
                selectionColor = StringUtilities.string2Color(color);
454
        }
455

    
456
        /*
457
         * (non-Javadoc)
458
         *
459
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
460
         */
461
        public void propertyChange(PropertyChangeEvent evt) {
462
                //this.modified = true;
463
                change.firePropertyChange(evt);
464
        }
465

    
466
        /**
467
         * DOCUMENT ME!
468
         *
469
         * @param arg1
470
         */
471
        public void addExtent(ProjectExtent arg1) {
472
                extents.add(arg1);
473
                //modified = true;
474
                change.firePropertyChange("addExtent", null, null);
475
        }
476

    
477
        /**
478
         * DOCUMENT ME!
479
         *
480
         * @param arg0
481
         *
482
         * @return
483
         */
484
        public Object removeExtent(int arg0) {
485
                //modified = true;
486
                change.firePropertyChange("delExtent", null, null);
487

    
488
                return extents.remove(arg0);
489
        }
490

    
491
        /**
492
         * DOCUMENT ME!
493
         *
494
         * @return DOCUMENT ME!
495
         */
496
        public ProjectExtent[] getExtents() {
497
                return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
498
        }
499

    
500
        /**
501
         * Metodo que a?ade una nueva camera a la lista de cameras
502
         *
503
         * @param arg1
504
         *            camera introducida
505
         */
506
        public void addCamera(Object arg1) {
507
                this.cameras.add(arg1);
508
                //modified = true;
509
                change.firePropertyChange("addCamera", null, null);
510
        }
511

    
512
        /**
513
         * Metodo que borra de la lisat un elemento seleccionado
514
         *
515
         * @param arg0
516
         *            indice del elemento que se va a borrar
517
         *
518
         * @return resultado de la operacion de borrado
519
         */
520
        public Object removeCamera(int arg0) {
521
                //modified = true;
522
                change.firePropertyChange("delCamera", null, null);
523

    
524
                return this.cameras.remove(arg0);
525
        }
526

    
527
        /**
528
         * Metodo que devuelve la lista de cameras
529
         *
530
         * @return lista de objetos de tipo camera
531
         */
532
        public Object[] getCameras() {
533
                return (Object[]) this.cameras.toArray(new Object[0]);
534
        }
535

    
536
        /**
537
         * DOCUMENT ME!
538
         *
539
         * @param arg0
540
         */
541
        public synchronized void addPropertyChangeListener(
542
                        PropertyChangeListener arg0) {
543
                change.addPropertyChangeListener(arg0);
544
        }
545

    
546
        /**
547
         * DOCUMENT ME!
548
         *
549
         * @deprecated utilizar getDocument(String s);
550
         * @return
551
         */
552
        public ArrayList getMaps() {
553
                return getDocumentsByType(ProjectMapFactory.registerName);
554
        }
555

    
556
        /**
557
         * DOCUMENT ME!
558
         *
559
         * @deprecated utilizar getDocument(String s);
560
         * @return
561
         */
562
        public ArrayList getTables() {
563
                return getDocumentsByType(ProjectTableFactory.registerName);
564
        }
565

    
566
        /**
567
         * DOCUMENT ME!
568
         *
569
         * @deprecated utilizar getDocument(String s);
570
         * @return
571
         */
572
        public ArrayList getViews() {
573
                return getDocumentsByType(ProjectViewFactory.registerName);
574
        }
575

    
576
        /**
577
         * A?ade un mapa al proyecto
578
         *
579
         * @deprecated utilizar addDocument(ProjectDocument pD);
580
         * @param m
581
         */
582
        public void addMap(ProjectMap m) {
583
                addDocument(m);
584
        }
585

    
586
        /**
587
         * Elimina un mapa del proyecto
588
         *
589
         * @deprecated utilizar delDocument(ProjectDocument pD);
590
         * @param i
591
         *            indice del mapa
592
         */
593
        public void delMap(int i) {
594
                ArrayList list = getDocumentsByType(ProjectMapFactory.registerName);
595
                delDocument((ProjectDocument) list.get(i));
596
        }
597

    
598
        /**
599
         * A?ade una tabla al proyecto
600
         *
601
         * @deprecated utilizar addDocument(ProjectDocument pD);
602
         * @param t
603
         */
604
        public void addTable(ProjectTable t) {
605
                addDocument(t);
606
        }
607

    
608
        /**
609
         * Elimina una tabla del proyecto
610
         *
611
         * @deprecated utilizar delDocument(ProjectDocument pD);
612
         * @param i
613
         *            indice de la tabla
614
         */
615
        public void delTable(int i) {
616
                ArrayList list = getDocumentsByType(ProjectTableFactory.registerName);
617
                delDocument((ProjectDocument) list.get(i));
618
        }
619

    
620
        /**
621
         * A?ade una vista al proyecto
622
         *
623
         * @deprecated utilizar addDocument(ProjectDocument pD);
624
         * @param v
625
         */
626
        public void addView(ProjectView v) {
627
                addDocument(v);
628
        }
629

    
630
        /**
631
         * Elimina una tabla del proyecto
632
         *
633
         * @deprecated utilizar delDocument(ProjectDocument pD);
634
         * @param i
635
         *            indice del proyecto
636
         */
637
        public void delView(int i) {
638
                ArrayList list = getDocumentsByType(ProjectViewFactory.registerName);
639
                delDocument((ProjectDocument) list.get(i));
640
        }
641

    
642
        /**
643
         * DOCUMENT ME!
644
         *
645
         * @return DOCUMENT ME!
646
         *
647
         * @throws DriverException
648
         * @throws XMLException
649
         */
650
        public XMLEntity getXMLEntity() {
651
                XMLEntity xml = new XMLEntity();
652
                xml.putProperty("className", this.getClass().getName());
653
                xml.putProperty("VERSION", VERSION);
654
                xml.putProperty("comments", getComments());
655
                xml.putProperty("creationDate", creationDate);
656

    
657
                int numExtents = extents.size();
658
                xml.putProperty("numExtents", numExtents);
659

    
660
                for (int i = 0; i < numExtents; i++) {
661
                        xml.addChild(((ProjectExtent) extents.get(i)).getXMLEntity());
662
                }
663

    
664
                // Guardando propiedades de las camaras
665
                int numCameras = this.cameras.size();
666
                xml.putProperty("numCameras", numCameras);
667

    
668
                for (int i = 0; i < numCameras; i++) {
669
                        xml.addChild(((IPersistance) this.cameras.get(i)).getXMLEntity());
670
                }
671

    
672
                // NUEVO: ESTO ESTA EN PRUEBAS. SIRVE PARA
673
                // BORRAR LAS REFERENCIAS A DATASOURCES QUE HEMOS
674
                // BORRADO. Hay que probar a borrarlos cuando se
675
                // borra una tabla y cuando se borra una capa.
676
                cleanBadReferences();
677
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
678
                                .getDriverInfos();
679
                xml.putProperty("data-source-count", infos.length);
680

    
681
                for (int i = 0; i < infos.length; i++) {
682
                        SourceInfo di = infos[i];
683
                        XMLEntity child = this.getSourceInfoXMLEntity(di);
684
                        xml.addChild(child);
685
                }
686
                int numDocuments = 0;
687
                for (int i = 0; i < documents.size(); i++) {
688
                        try {
689
                                XMLEntity xmlchild = ((ProjectDocument) documents.get(i))
690
                                                .getXMLEntity();
691
                                xml.addChild(xmlchild);
692
                                numDocuments++;
693
                        } catch (SaveException e) {
694
                                e.showError();
695
                        }
696
                }
697
                xml.putProperty("numDocuments", numDocuments);
698
                /*
699
                 * int numViews=0; for (int i = 0; i < views.size(); i++) { try {
700
                 * XMLEntity xmlchild=((ProjectView) views.get(i)).getXMLEntity();
701
                 * xml.addChild(xmlchild); numViews++; } catch (SaveException e) {
702
                 * e.showError(); } } xml.putProperty("numViews", numViews);
703
                 *
704
                 * int numMaps=0; for (int i = 0; i < maps.size(); i++) { try {
705
                 * XMLEntity xmlchild=((ProjectMap) maps.get(i)).getXMLEntity();
706
                 * xml.addChild(xmlchild); numMaps++; } catch (SaveException e) {
707
                 * e.showError(); } } xml.putProperty("numMaps", numMaps);
708
                 */
709
                xml.putProperty("modificationDate", modificationDate);
710
                xml.putProperty("name", name, false);
711
                xml.putProperty("owner", owner);
712
                xml.putProperty("selectionColor", StringUtilities
713
                                .color2String(selectionColor));
714
                /*
715
                 * int numTables=0; for (int i = 0; i < tables.size(); i++) { try {
716
                 * XMLEntity xmlchild=((ProjectTable) tables.get(i)).getXMLEntity();
717
                 * xml.addChild(xmlchild); numTables++; } catch (SaveException e) {
718
                 *
719
                 * e.showError(); } } xml.putProperty("numTables", numTables);
720
                 */
721
                xml.putProperty("projection", defaultProjection.getAbrev());
722

    
723
                saveWindowProperties(xml);
724
                return xml;
725
        }
726

    
727
        private void saveWindowProperties(XMLEntity xml) {
728
                XMLEntity propertyList = new XMLEntity();
729

    
730
                propertyList.setName("AndamiPersistence");
731
                propertyList.putProperty("className", Project.class.getName(), false);
732

    
733
                boolean projectWindowSaved = false;
734

    
735
                IWindow[] windowList = PluginServices.getMDIManager()
736
                                .getOrderedWindows();
737
                WindowInfo wi;
738
                XMLEntity windowProperties;
739
                for (int winIndex = windowList.length - 1; winIndex >= 0; winIndex--) {
740
                        wi = PluginServices.getMDIManager().getWindowInfo(
741
                                        windowList[winIndex]);
742
                        if (wi != null && wi.checkPersistence()) {
743
                                if (windowList[winIndex] instanceof Layout) { // for the
744
                                        // moment we
745
                                        // can't do this
746
                                        // for Maps
747
                                        // because they
748
                                        // don't have a
749
                                        // standard
750
                                        // model
751
                                        Layout layoutWindow = (Layout) windowList[winIndex];
752
                                        windowProperties = wi.getXMLEntity();
753
                                        windowProperties.putProperty("documentType",
754
                                                        ProjectMapFactory.registerName, false);
755
                                        windowProperties.putProperty("documentName", layoutWindow
756
                                                        .getName(), false);
757
                                        windowProperties.putProperty("zPosition", winIndex, false);
758
                                        propertyList.addChild(windowProperties);
759
                                } else if (windowList[winIndex] instanceof ProjectWindow) {
760
                                        projectWindowSaved = true;
761
                                        windowProperties = wi.getXMLEntity();
762
                                        windowProperties
763
                                                        .putProperty("className",
764
                                                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow", false);
765
                                        windowProperties.putProperty("zPosition", winIndex, false);
766
                                        propertyList.addChild(windowProperties);
767
                                } else if (windowList[winIndex] instanceof SingletonWindow) { // for
768
                                        // table,
769
                                        // view
770
                                        // and
771
                                        // maybe
772
                                        // other
773
                                        // documents
774
                                        SingletonWindow viewWindow = (SingletonWindow) windowList[winIndex];
775
                                        if (viewWindow.getWindowModel() instanceof ProjectDocument) {
776
                                                ProjectDocument doc = (ProjectDocument) viewWindow
777
                                                                .getWindowModel();
778
                                                windowProperties = wi.getXMLEntity();
779
                                                windowProperties.putProperty("documentType", doc
780
                                                                .getProjectDocumentFactory().getRegisterName(), false);
781
                                                windowProperties.putProperty("documentName",
782
                                                                ((ProjectDocument) viewWindow.getWindowModel())
783
                                                                                .getName(), false);
784
                                                windowProperties.putProperty("zPosition", winIndex, false);
785

    
786
                                                // TODO this will be generalized to all ProjectDocuments as soon as possible
787
//                                                if (viewWindow instanceof BaseView) {
788
//                                                        BaseView win = (BaseView) viewWindow;
789
//                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
790
//                                                }
791
                                                if (viewWindow instanceof IDocumentWindow) {
792
                                                        IDocumentWindow win = (IDocumentWindow) viewWindow;
793
                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
794
                                                }
795

    
796
                                                propertyList.addChild(windowProperties);
797
                                        }
798
                                }
799
                        }
800
                }
801

    
802
                if (projectWindowSaved == false) {
803
                        // If the Project Manager was closed, it was not in the
804
                        // previous window list. Save it now
805
                        ProjectExtension pe = (ProjectExtension) PluginServices
806
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
807

    
808
                        if (pe != null) {
809
                                IWindow projectWindow = pe.getProjectWindow();
810
                                wi = PluginServices.getMDIManager()
811
                                                .getWindowInfo(projectWindow);
812
                                if (wi != null && wi.checkPersistence()) {
813
                                        windowProperties = wi.getXMLEntity();
814
                                        if (windowProperties != null) {
815
                                                windowProperties
816
                                                                .putProperty("className",
817
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow", false);
818
                                                propertyList.addChild(windowProperties);
819
                                        }
820
                                }
821
                        }
822
                }
823

    
824
                xml.addChild(propertyList);
825
        }
826

    
827
        /**
828
         * Store the initial window properties, to later restore the window sizes
829
         * and positions
830
         */
831
        private void storeInitialWindowProperties(XMLEntity xml) {
832
                XMLEntity child;
833
                int childNumb;
834

    
835
                // order the window properties before restoring them, so that we also
836
                // restore the zPosition
837
                TreeMap orderedProperties = new TreeMap();
838
                int maximum = 1;
839
                for (childNumb = xml.getChildrenCount() - 1; childNumb >= 0; childNumb--) {
840
                        child = xml.getChild(childNumb);
841
                        if (child.contains("zPosition")) {
842
                                orderedProperties.put(new Integer(-child
843
                                                .getIntProperty("zPosition")), child); // reverse the
844
                                // order, so
845
                                // that we add
846
                                // the back
847
                                // windows first
848
                        } else {
849
                                orderedProperties.put(new Integer(maximum++), child); // the
850
                                // windows
851
                                // without
852
                                // zPosition
853
                                // will
854
                                // be on
855
                                // the
856
                                // fore
857
                        }
858
                }
859

    
860
                this.initialWindowProperties = orderedProperties.values().iterator();
861
        }
862

    
863
        /**
864
         * Store the initial window properties, to later restore the window sizes
865
         * and positions
866
         */
867
        private void storeInitialWindowProperties061(XMLEntity xml) {
868
                XMLEntity child;
869
                int childNumb = 0;
870
                ArrayList windowList = new ArrayList();
871

    
872
                child = xml.getChild(xml.getChildrenCount() - 1);
873
                if (child.contains("className")
874
                                && child.getStringProperty("className").equals(
875
                                                "com.iver.cit.gvsig.project.Project")
876
                                && child.contains("name")
877
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
878
                        child.putProperty("className",
879
                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
880
                        windowList.add(child);
881
                }
882

    
883
                // try to open the views
884
                if (xml.contains("numExtents"))
885
                        childNumb += xml.getIntProperty("numExtents");
886
                if (xml.contains("data-source-count"))
887
                        childNumb += xml.getIntProperty("data-source-count");
888
                int limit = 0;
889
                if (xml.contains("numViews"))
890
                        limit = xml.getIntProperty("numViews")+childNumb;
891

    
892
                XMLEntity view;
893
                for (int i = childNumb; i < limit; i++) {
894
                        view = xml.getChild(i);
895
                        child = view.getChild(view.getChildrenCount() - 1);
896
                        if (child.contains("className")
897
                                        && child.getStringProperty("className").equals(
898
                                                        "com.iver.cit.gvsig.project.ProjectView")
899
                                        && child.contains("name")
900
                                        && child.getStringProperty("name").equals(
901
                                                        "ViewInfoProperties")) {
902
                                child.putProperty("documentName", view
903
                                                .getStringProperty("name"));
904
                                child.putProperty("documentType",
905
                                                ProjectViewFactory.registerName);
906
                                windowList.add(child);
907
                        }
908
                }
909

    
910
                if (xml.contains("numViews"))
911
                        childNumb += xml.getIntProperty("numViews");
912

    
913
                if (xml.contains("numMaps"))
914
                        limit = childNumb + xml.getIntProperty("numMaps");
915

    
916
                // try to open the maps
917
                XMLEntity map;
918
                for (int i = childNumb; i < limit; i++) {
919
                        map = xml.getChild(i);
920
                        for (int j = 0; j < map.getChildrenCount(); j++) {
921
                                child = map.getChild(j);
922
                                if (child.contains("className")
923
                                                && child.getStringProperty("className").equals(
924
                                                                "com.iver.cit.gvsig.project.ProjectMap")
925
                                                && child.contains("name")
926
                                                && child.getStringProperty("name").equals(
927
                                                                "ViewInfoProperties")) {
928
                                        child.putProperty("documentName", map
929
                                                        .getStringProperty("name"));
930
                                        child.putProperty("documentType",
931
                                                        ProjectMapFactory.registerName);
932
                                        windowList.add(child);
933
                                }
934
                        }
935
                }
936

    
937
                this.initialWindowProperties = windowList.iterator();
938
        }
939

    
940
        /**
941
         * Restores the size, position and order of the windows, according to
942
         * variable initialWindowProperties. If this variable is null, the method
943
         * just opens the project manager window.
944
         *
945
         */
946
        public void restoreWindowProperties() {
947
                boolean projectWindowRestored = false;
948
                XMLEntity child;
949

    
950
                Iterator propertiesIterator = this.initialWindowProperties;
951
                if (propertiesIterator != null) {
952
                        this.initialWindowProperties = null;
953

    
954
                        while (propertiesIterator.hasNext()) {
955
                                child = (XMLEntity) propertiesIterator.next();
956
                                if (child.contains("name") // restore the position of the
957
                                                // document windows
958
                                                && child.getStringProperty("name").equals(
959
                                                                "ViewInfoProperties")
960
                                                && child.contains("documentType")) {
961
                                        boolean isClosed = true;
962
                                        if (child.contains("isClosed"))
963
                                                isClosed = child.getBooleanProperty("isClosed");
964
                                        if (isClosed == false) {
965
                                                WindowInfo windowProps = WindowInfo
966
                                                                .createFromXMLEntity(child);
967
                                                String documentName = child
968
                                                                .getStringProperty("documentName");
969
                                                String documentType = child
970
                                                                .getStringProperty("documentType");
971
                                                ProjectDocument pd = this.getProjectDocumentByName(
972
                                                                documentName, documentType);
973
                                                if (pd==null) continue;
974
                                                IWindow win = null;
975
                                                if (pd instanceof ProjectDocument
976
                                                                && child.getChildrenCount()>0
977
                                                                && child.getChild(0).getName().equals("windowData")) {
978
                                                        // this will be generalized to all ProjectDocuments as soon as possible
979
                                                        WindowData windowData = new WindowData();
980
                                                        windowData.setXMLEntity(child.getChild(0));
981
                                                        pd.storeWindowData(windowData);
982
                                                        win = ((ProjectDocument)pd).createWindow();
983
                                                } else {
984
                                                        win = pd.createWindow();
985
                                                }
986
                                                PluginServices.getMDIManager().addWindow(win);
987
                                                PluginServices.getMDIManager().changeWindowInfo(win,
988
                                                                windowProps);
989
                                        }
990
                                } else if (child.contains("className") // restore the position
991
                                                // of the project
992
                                                // manager window
993
                                                && child
994
                                                                .getStringProperty("className")
995
                                                                .equals(
996
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow")
997
                                                && child.contains("name")
998
                                                && child.getStringProperty("name").equals(
999
                                                                "ViewInfoProperties")) {
1000
                                        WindowInfo wi = WindowInfo.createFromXMLEntity(child);
1001
                                        // don't restore size for ProjectManager window, as it's not resizable
1002
                                        wi.setHeight(-1);
1003
                                        wi.setWidth(-1);
1004
                                        ProjectExtension pe = (ProjectExtension) PluginServices
1005
                                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1006
                                        if (pe != null) {
1007
                                                pe.setProject(this);
1008
                                                pe.showProjectWindow(wi);
1009
                                        }
1010
                                        projectWindowRestored = true;
1011
                                }
1012
                        }
1013
                }
1014

    
1015
                if (!projectWindowRestored) { // if the project window was not stored
1016
                        // in the project, open it now
1017
                        ProjectExtension pe = (ProjectExtension) PluginServices
1018
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1019

    
1020
                        if (pe != null) {
1021
                                pe.setProject(this);
1022
                                pe.showProjectWindow();
1023
                        }
1024
                }
1025
        }
1026

    
1027
        /**
1028
         * DOCUMENT ME!
1029
         *
1030
         * @param xml
1031
         *            DOCUMENT ME!
1032
         *
1033
         * @return DOCUMENT ME!
1034
         * @throws XMLException
1035
         * @throws DriverException
1036
         * @throws DriverIOException
1037
         * @throws OpenException
1038
         */
1039
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1040
                Project p = new Project();
1041
                try {
1042
                        p.comments = xml.getStringProperty("comments");
1043
                        p.creationDate = xml.getStringProperty("creationDate");
1044

    
1045
                        int numExtents = xml.getIntProperty("numExtents");
1046
                        for (int i = 0; i < numExtents; i++) {
1047
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1048
                                                .getChild(i));
1049
                                p.extents.add(pe);
1050
                        }
1051

    
1052
                        int numDocuments = 0;
1053
                        if (xml.contains("numDocuments")) {
1054
                                numDocuments = xml.getIntProperty("numDocuments");
1055
                        } else {
1056
                                int numViews = xml.getIntProperty("numViews");
1057
                                int numMaps = xml.getIntProperty("numMaps");
1058
                                int numTables = xml.getIntProperty("numTables");
1059
                                numDocuments = numViews + numMaps + numTables;
1060
                        }
1061
                        for (int i = numExtents; i < numDocuments + numExtents; i++) {
1062
                                ProjectDocument pD = ProjectDocument.createFromXML03(xml
1063
                                                .getChild(i), p);
1064
                                p.addDocument(pD);
1065
                                p.sortedDocuments.put(pD, new Integer(i));
1066
                        }
1067
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1068
                                        .keySet().toArray(new ProjectDocument[0]);
1069
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1070
                                        .toArray(new Integer[0]);
1071

    
1072
                        int i = 0;
1073
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1074
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1075
                                                .intValue()));
1076
                                i++;
1077
                        }
1078

    
1079
                        p.modificationDate = xml.getStringProperty("modificationDate");
1080
                        //p.modified = xml.getBooleanProperty("modified");
1081
                        p.name = xml.getStringProperty("name");
1082
                        p.owner = xml.getStringProperty("owner");
1083
                        p.selectionColor = StringUtilities.string2Color(xml
1084
                                        .getStringProperty("selectionColor"));
1085

    
1086
                        String strProj = xml.getStringProperty("projection");
1087
                        if (strProj != null)
1088
                                p.setProjection(CRSFactory.getCRS(strProj));
1089
                } catch (Exception e) {
1090
                        throw new OpenException(e, p.getClass().getName());
1091
                }
1092
                return p;
1093
        }
1094

    
1095
        /**
1096
         * DOCUMENT ME!
1097
         *
1098
         * @param xml
1099
         *            DOCUMENT ME!
1100
         *
1101
         * @return DOCUMENT ME!
1102
         *
1103
         * @throws XMLException
1104
         * @throws DriverException
1105
         * @throws DriverIOException
1106
         * @throws OpenException
1107
         * @throws VersionException
1108
         */
1109
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1110

    
1111
                int childNumber = 0;
1112
                Project p = new Project();
1113

    
1114
                try {
1115
                        p.comments = xml.getStringProperty("comments");
1116
                        p.creationDate = xml.getStringProperty("creationDate");
1117
                        int numExtents = xml.getIntProperty("numExtents");
1118

    
1119
                        for (int i = 0; i < numExtents; i++) {
1120
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1121
                                p.extents.add(pe);
1122
                        }
1123

    
1124
                        // Leemos el ultiom hijo recogido
1125
                        childNumber = numExtents;
1126

    
1127
                        // Recogiendo el numero de cameras
1128
                        int numCameras = 0;
1129
                        if (xml.contains("numCameras"))
1130
                                numCameras = xml.getIntProperty("numCameras");
1131

    
1132
                        // Recogiendo todo las camaras
1133
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1134
                                XMLEntity xmlProp = xml.getChild(i);
1135
                                try {
1136
                                        String className = xmlProp.getStringProperty("className");
1137
                                        Class classProp = Class.forName(className);
1138
                                        Object obj = classProp.newInstance();
1139
                                        IPersistance objPersist = (IPersistance) obj;
1140
                                        objPersist.setXMLEntity(xmlProp);
1141
                                        p.cameras.add(obj);
1142
                                } catch (Exception e) {
1143
                                        continue;
1144
                                }
1145
                        }
1146

    
1147
                        childNumber += numCameras;
1148

    
1149
                        int numDataSources = xml.getIntProperty("data-source-count");
1150

    
1151
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1152
                                XMLEntity child = xml.getChild(i);
1153
                                registerDataSourceFromXML(child);
1154
                        }
1155

    
1156
                        childNumber += numDataSources;
1157
                        int numDocuments = 0;
1158
                        if (xml.contains("numDocuments")) {
1159
                                numDocuments = xml.getIntProperty("numDocuments");
1160
                        } else {
1161
                                int numViews = xml.getIntProperty("numViews");
1162
                                int numMaps = xml.getIntProperty("numMaps");
1163
                                int numTables = xml.getIntProperty("numTables");
1164
                                numDocuments = numViews + numMaps + numTables;
1165
                        }
1166

    
1167
                        for (int i = childNumber; i < (numDocuments + childNumber); i++) {
1168
                                try {
1169
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1170
                                                        .getChild(i), p);
1171
                                        p.addDocument(pD);
1172
                                        p.sortedDocuments.put(pD, new Integer(i));
1173
                                } catch (OpenException e) {
1174
                                        e.showError();
1175
                                }
1176
                        }
1177
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1178
                                        .keySet().toArray(new ProjectDocument[0]);
1179
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1180
                                        .toArray(new Integer[0]);
1181

    
1182
                        int i = 0;
1183
                        for (int k = childNumber; k < (numDocuments + childNumber); k++) {
1184
                                try {
1185
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1186
                                                        .intValue()));
1187
                                } catch (OpenException e) {
1188
                                        e.showError();
1189
                                }
1190
                                i++;
1191
                        }
1192
                        childNumber += numDocuments;
1193

    
1194
                        p.modificationDate = xml.getStringProperty("modificationDate");
1195
                        //p.modified = xml.getBooleanProperty("modified");
1196
                        p.name = xml.getStringProperty("name");
1197
                        p.owner = xml.getStringProperty("owner");
1198
                        p.selectionColor = StringUtilities.string2Color(xml
1199
                                        .getStringProperty("selectionColor"));
1200

    
1201
                        p.setLinkTable();
1202
                        String strProj = xml.getStringProperty("projection");
1203

    
1204
                        if (strProj != null) {
1205
                                p.setProjection(CRSFactory.getCRS(strProj));
1206
                        }
1207

    
1208
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1209
                                // of the windows
1210
                                XMLEntity child = xml.getChild(childNumber);
1211
                                if (child.contains("name")
1212
                                                && child.getStringProperty("name").equals(
1213
                                                                "AndamiPersistence")) {
1214
                                        p.storeInitialWindowProperties(child);
1215
                                } else if (child.contains("className")
1216
                                                && child.getStringProperty("className").equals(
1217
                                                                "com.iver.cit.gvsig.project.Project")
1218
                                                && child.contains("name")
1219
                                                && child.getStringProperty("name").equals(
1220
                                                                "ViewInfoProperties")) {
1221
                                        p.storeInitialWindowProperties061(xml);
1222
                                }
1223
                        }
1224

    
1225
                        PostProcessSupport.executeCalls();
1226
                } catch (Exception e) {
1227
                        throw new OpenException(e, p.getClass().getName());
1228
                }
1229

    
1230
                return p;
1231

    
1232
        }
1233

    
1234
        /**
1235
         * Reestablece los link que ten?a cada tabla con las dem?s.
1236
         */
1237
        public void setLinkTable() {
1238
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1239

    
1240
                for (int i = 0; i < tables.size(); i++) {
1241
                        for (int j = 0; j < tables.size(); j++) {
1242
                                /*
1243
                                 * System.out.println("name = " + ((ProjectTable)
1244
                                 * tables.get(j)).getModelo().getName());
1245
                                 * System.out.println("linktable = " + ((ProjectTable)
1246
                                 * tables.get(i)).getLinkTable());
1247
                                 */
1248
                                try {
1249
                                        if ((((ProjectTable) tables.get(i)).getLinkTable() != null)
1250
                                                        && ((ProjectTable) tables.get(i)).getLinkTable()
1251
                                                        .equals(
1252
                                                                        ((ProjectTable) tables.get(j))
1253
                                                                        .getModelo().getRecordset()
1254
                                                                        .getName())) {
1255
                                                LinkSelectionListener lsl;
1256

    
1257
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1258
                                                                .get(i)).getModelo().getRecordset(),
1259
                                                                ((ProjectTable) tables.get(j)).getModelo()
1260
                                                                .getRecordset(), ((ProjectTable) tables
1261
                                                                                .get(i)).getField1(),
1262
                                                                                ((ProjectTable) tables.get(i)).getField2());
1263

    
1264
                                                (((ProjectTable) tables.get(i)).getModelo()
1265
                                                                .getRecordset()).addSelectionListener(lsl);
1266

    
1267
                                        }
1268
                                } catch (ReadDriverException e) {
1269
                                        e.printStackTrace();
1270
                                }
1271
                        }
1272
                }
1273
        }
1274

    
1275
        /**
1276
         * Obtiene la vista que contiene a la capa que se pasa como par?metro
1277
         *
1278
         * @param layer
1279
         *            Capa cuya vista se quiere obtener
1280
         *
1281
         * @return
1282
         *
1283
         * @throws RuntimeException
1284
         *             Si la capa que se pasa como par?metro no se encuentra en
1285
         *             ninguna vista
1286
         */
1287
        public String getView(FLayer layer) {
1288
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1289
                for (int v = 0; v < views.size(); v++) {
1290
                        ProjectView pView = (ProjectView) views.get(v);
1291
                        FLayers layers = pView.getMapContext().getLayers();
1292
                        if (isView(layers, layer))
1293
                                return pView.getName();
1294
                }
1295

    
1296
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1297
        }
1298

    
1299
        public boolean isView(FLayers layers, FLayer layer) {
1300
                for (int i = 0; i < layers.getLayersCount(); i++) {
1301
                        if (layers.getLayer(i) instanceof FLayers) {
1302
                                return isView((FLayers) layers.getLayer(i), layer);
1303
                        }
1304
                        if (layers.getLayer(i) == layer) {
1305
                                return true;
1306
                        }
1307
                }
1308
                return false;
1309
        }
1310

    
1311
        /**
1312
         * Devuelve la vista cuyo nombre coincide (sensible a mayusculas) con el que
1313
         * se pasa como par?metro. Devuelve null si no hay ninguna vista con ese
1314
         * nombre
1315
         *
1316
         * @param viewName
1317
         *            Nombre de la vista que se quiere obtener
1318
         *
1319
         * @return DOCUMENT ME!
1320
         */
1321
        /*
1322
         * public ProjectView getViewByName(String viewName) { ArrayList
1323
         * views=getDocuments(PluginServices.getText(this,"Vista")); Object o =
1324
         * getProjectDocumentByName(viewName, PluginServices.getText(this,"Vista"));
1325
         *
1326
         * if (o == null) { return null; }
1327
         *
1328
         * return (ProjectView) o; }
1329
         */
1330
        /**
1331
         * DOCUMENT ME!
1332
         *
1333
         * @return DOCUMENT ME!
1334
         */
1335
        public IProjection getProjection() {
1336
                if (projection == null)
1337
                        projection = Project.defaultProjection;
1338
                return projection;
1339
        }
1340

    
1341
        /**
1342
         * DOCUMENT ME!
1343
         *
1344
         * @param defaultProjection
1345
         *            DOCUMENT ME!
1346
         */
1347
        public void setProjection(IProjection projection) {
1348
                this.projection = projection;
1349
        }
1350

    
1351
        /**
1352
         * Sets the projection used when no projection is defined
1353
         *
1354
         * @param defaultProjection
1355
         *            DOCUMENT ME!
1356
         */
1357
        public static void setDefaultProjection(IProjection defaultProjection) {
1358
                Project.defaultProjection = defaultProjection;
1359
        }
1360

    
1361
        public static IProjection getDefaultProjection() {
1362
                if (defaultProjection == null){
1363
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1364
                        .getPersistentXML();
1365

    
1366
                        // Default Projection
1367
                        String projCode = null;
1368
                        if (xml.contains("DefaultProjection")) {
1369
                                projCode = xml.getStringProperty("DefaultProjection");
1370
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1371
                        } else {
1372
                                Project.setDefaultProjection(defaultFactoryProjection);
1373
                        }
1374

    
1375
                }
1376
                return Project.defaultProjection;
1377
        }
1378

    
1379
        /**
1380
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1381
         * pointExtension, este ?ltimo se puede obtener del
1382
         * Project****Factory.registerName.
1383
         *
1384
         * @param name
1385
         *            Nombre del documento
1386
         * @param type
1387
         *            nombre de registro en el extensionPoint
1388
         *
1389
         * @return Documento
1390
         */
1391
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1392
                ArrayList docs = getDocumentsByType(type);
1393
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1394
                        ProjectDocument elem = (ProjectDocument) iter.next();
1395

    
1396
                        if (elem.getName().equals(name)) {
1397
                                return elem;
1398
                        }
1399
                }
1400

    
1401
                return null;
1402
        }
1403

    
1404
        /**
1405
         * DOCUMENT ME!
1406
         *
1407
         * @param name
1408
         *
1409
         * @return
1410
         */
1411
        /*
1412
         * public ProjectTable getTableByName(String name) { ArrayList
1413
         * tables=getDocuments(PluginServices.getText(this,"Tabla")); Object o =
1414
         * getProjectElementByName(name, tables);
1415
         *
1416
         * if (o == null) { return null; }
1417
         *
1418
         * return (ProjectTable) o; }
1419
         */
1420
        /**
1421
         * DOCUMENT ME!
1422
         *
1423
         * @param name
1424
         *
1425
         * @return
1426
         */
1427
        /*
1428
         * public ProjectMap getLayoutByName(String name) { Object o =
1429
         * getProjectElementByName(name, maps);
1430
         *
1431
         * if (o == null) { return null; }
1432
         *
1433
         * return (ProjectMap) o; }
1434
         */
1435
        public SelectableDataSource getDataSourceByLayer(FLayer layer)
1436
                        throws ReadDriverException {
1437
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1438
                SelectableDataSource dataSource = null;
1439
                for (int i = 0; i < tables.size(); i++) {
1440
                        ProjectTable pt = (ProjectTable) tables.get(i);
1441
                        if (pt.getOriginal() == ((AlphanumericData) layer)
1442
                                        .getRecordset()) {
1443
                                dataSource = pt.getModelo().getRecordset();
1444
                                break;
1445
                        } else if (pt.getModelo() == ((AlphanumericData) layer)
1446
                                        .getRecordset()) {
1447
                                        dataSource = pt.getModelo().getRecordset();
1448
                                        break;
1449
                        }
1450
                }
1451

    
1452
                if (dataSource == null) {
1453
                        // No se ha creado la tabla asociada al tema
1454
                        dataSource = ((AlphanumericData) layer).getRecordset();
1455
                }
1456

    
1457
                return dataSource;
1458

    
1459
        }
1460

    
1461
        /**
1462
         * Recorremos las capas y las tablas del proyecto, y creamos una lista con
1463
         * todos los datasources de GDBMS que estamos usando. Luego recorremos los
1464
         * que est?n registrados, y borramos aquellos que no est?n siendo usados, es
1465
         * decir, aquellos que no est?n en nuestra lista (un Hash con clave el
1466
         * nombre del GDBMS)
1467
         *
1468
         */
1469
        private void cleanBadReferences() {
1470
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1471
                Hashtable usedDataSources = new Hashtable();
1472
                // Primero las tablas
1473
                int i, j;
1474
                try {
1475
                        for (i = 0; i < tables.size(); i++) {
1476
                                ProjectTable t = (ProjectTable) tables.get(i);
1477
                                SelectableDataSource ds;
1478

    
1479
                                ds = t.getModelo().getRecordset();
1480

    
1481
                                if (t.getOriginal() != null)
1482
                                        usedDataSources.put(t.getOriginal().getRecordset()
1483
                                                        .getName(), t.getOriginal());
1484
                                usedDataSources.put(ds.getName(), ds);
1485
                        }
1486
                } catch (ReadDriverException e) {
1487
                        e.printStackTrace();
1488
                }
1489
                // Ahora las vistas
1490
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1491
                try {
1492
                        for (i = 0; i < views.size(); i++) {
1493
                                ProjectView pv = (ProjectView) views.get(i);
1494

    
1495
                                FLayers lyrs = pv.getMapContext().getLayers();
1496

    
1497
                                for (j = 0; j < lyrs.getLayersCount(); j++) {
1498
                                        FLayer lyr = lyrs.getLayer(j);
1499
                                        if (lyr instanceof FLyrVect) {
1500
                                                FLyrVect lyrVect = (FLyrVect) lyr;
1501
                                                if (lyrVect.isAvailable())
1502
                                                        usedDataSources.put(lyrVect.getRecordset()
1503
                                                                        .getName(), lyrVect.getSource()
1504
                                                                        .getRecordset());
1505
                                        }
1506
                                }
1507
                                MapContext aux = pv.getMapOverViewContext();
1508
                                if (aux != null) {
1509
                                        FLayers lyrsOverview = aux.getLayers();
1510
                                        for (j = 0; j < lyrsOverview.getLayersCount(); j++) {
1511
                                                FLayer lyr = lyrsOverview.getLayer(j);
1512
                                                if (lyr instanceof FLyrVect) {
1513
                                                        FLyrVect lyrVect = (FLyrVect) lyr;
1514
                                                        usedDataSources.put(lyrVect.getSource()
1515
                                                                        .getRecordset().getName(), lyrVect
1516
                                                                        .getSource().getRecordset());
1517
                                                }
1518
                                        }
1519
                                }
1520

    
1521
                        } // for i
1522
                } catch (ReadDriverException e) {
1523
                        e.printStackTrace();
1524
                }
1525

    
1526
                // Recorremos los dataSources y los borramos si no
1527
                // los estamos usando.
1528
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1529
                                .getDriverInfos();
1530
                try {
1531
                        for (i = 0; i < infos.length; i++) {
1532
                                if (!usedDataSources.containsKey(infos[i].name)) {
1533
                                        DataSource ds;
1534
                                        ds = LayerFactory.getDataSourceFactory()
1535
                                                        .createRandomDataSource(infos[i].name);
1536
                                        ds.remove();
1537
                                }
1538
                        }
1539
                } catch (DriverLoadException e) {
1540
                        e.printStackTrace();
1541
                } catch (NoSuchTableException e) {
1542
                        e.printStackTrace();
1543
                } catch (ReadDriverException e) {
1544
                        e.printStackTrace();
1545
                } catch (WriteDriverException e) {
1546
                        e.printStackTrace();
1547
                }
1548
        }
1549

    
1550
        /**
1551
         * DOCUMENT ME!
1552
         *
1553
         * @return DOCUMENT ME!
1554
         * @throws SaveException
1555
         * @throws XMLException
1556
         * @throws SaveException
1557
         */
1558
        public XMLEntity getWindowInfoXMLEntity(IWindow window)
1559
                        throws SaveException {
1560
                if (window != null
1561
                                && PluginServices.getMDIManager().getWindowInfo(window) != null) {
1562
                        WindowInfo vi = PluginServices.getMDIManager()
1563
                                        .getWindowInfo(window);
1564
                        XMLEntity xml = new XMLEntity();
1565
                        // xml.putProperty("nameClass", this.getClass().getName());
1566
                        try {
1567
                                xml.setName("ViewInfoProperties");
1568
                                xml.putProperty("className", this.getClass().getName());
1569
                                xml.putProperty("X", vi.getX());
1570
                                xml.putProperty("Y", vi.getY());
1571
                                xml.putProperty("Width", vi.getWidth());
1572
                                xml.putProperty("Height", vi.getHeight());
1573
                                xml.putProperty("isVisible", vi.isVisible());
1574
                                xml.putProperty("isResizable", vi.isResizable());
1575
                                xml.putProperty("isMaximizable", vi.isMaximizable());
1576
                                xml.putProperty("isModal", vi.isModal());
1577
                                xml.putProperty("isModeless", vi.isModeless());
1578
                                xml.putProperty("isClosed", vi.isClosed());
1579
                                if (vi.isMaximized() == true) {
1580
                                        xml.putProperty("isMaximized", vi.isMaximized());
1581
                                        xml.putProperty("normalX", vi.getNormalX());
1582
                                        xml.putProperty("normalY", vi.getNormalY());
1583
                                        xml.putProperty("normalWidth", vi.getNormalWidth());
1584
                                        xml.putProperty("normalHeight", vi.getNormalHeight());
1585
}
1586
                        } catch (Exception e) {
1587
                                throw new SaveException(e, this.getClass().getName());
1588
                        }
1589
                        return xml;
1590
                }
1591
                return null;
1592
        }
1593

    
1594
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1595
                WindowInfo result = new WindowInfo();
1596
                result.setX(xml.getIntProperty("X"));
1597
                result.setY(xml.getIntProperty("Y"));
1598
                result.setHeight(xml.getIntProperty("Height"));
1599
                result.setWidth(xml.getIntProperty("Width"));
1600
                result.setClosed(xml.getBooleanProperty("isClosed"));
1601
                if (xml.contains("isMaximized")) {
1602
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1603
                        result.setMaximized(maximized);
1604
                        if (maximized == true) {
1605
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1606
                                                .getIntProperty("normalY"), xml
1607
                                                .getIntProperty("normalWidth"), xml
1608
                                                .getIntProperty("normalHeight"));
1609
                        } else {
1610
                                result.setNormalBounds(result.getBounds());
1611
                        }
1612
                }
1613

    
1614
                return result;
1615
        }
1616

    
1617
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1618
                XMLEntity child = new XMLEntity();
1619

    
1620
                if (di instanceof ObjectSourceInfo) {
1621
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1622
                        child.putProperty("type", "sameDriverFile");
1623
                        child.putProperty("gdbmsname", driver.name);
1624
                } else if (di instanceof FileSourceInfo) {
1625
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1626
                        child.putProperty("type", "otherDriverFile");
1627
                        child.putProperty("gdbmsname", vfdi.name);
1628
                        child.putProperty("file", vfdi.file);
1629
                        child.putProperty("driverName", vfdi.driverName);
1630
                } else if (di instanceof DBSourceInfo) {
1631
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1632
                        child.putProperty("type", "db");
1633
                        child.putProperty("gdbmsname", dbdi.name);
1634
                        child.putProperty("dbms", dbdi.dbms);
1635
                        child.putProperty("host", dbdi.host);
1636
                        child.putProperty("port", dbdi.port);
1637
                        child.putProperty("user", dbdi.user);
1638
                        child.putProperty("password", dbdi.password);
1639
                        child.putProperty("dbName", dbdi.dbName);
1640
                        child.putProperty("tableName", dbdi.tableName);
1641
                        child.putProperty("driverInfo", dbdi.driverName);
1642
                }
1643

    
1644
                return child;
1645
        }
1646

    
1647
        /**
1648
         * Devuelve un arrayList con todos los documentos del tipo especificado como
1649
         * par?metro.
1650
         *
1651
         * @param registerName
1652
         *            nombre de registro en el extensionPoint
1653
         *
1654
         * @return Documentos del tipo especificado
1655
         */
1656
        public ArrayList getDocumentsByType(String registerName) {
1657
                ArrayList docuArray = new ArrayList();
1658
                for (int i = 0; i < documents.size(); i++) {
1659
                        ProjectDocument projectDocument = (ProjectDocument) documents
1660
                                        .get(i);
1661
                        ProjectDocumentFactory pdf = projectDocument
1662
                                        .getProjectDocumentFactory();
1663
                        if (pdf == null)
1664
                                continue;
1665
                        if (pdf.getRegisterName().equals(registerName)) {
1666
                                docuArray.add(projectDocument);
1667
                        }
1668
                }
1669
                return docuArray;
1670
        }
1671

    
1672
        /**
1673
         * Devuelve un arrayList con todos los documentos.
1674
         *
1675
         * @return Documentos
1676
         */
1677
        public ArrayList getDocuments() {
1678
                ArrayList docuArray = new ArrayList();
1679
                for (int i = 0; i < documents.size(); i++) {
1680
                        ProjectDocument projectDocument = (ProjectDocument) documents
1681
                                        .get(i);
1682
                        docuArray.add(projectDocument);
1683
                }
1684
                return docuArray;
1685
        }
1686

    
1687
        /**
1688
         * Inserta un documento.
1689
         *
1690
         * @param doc
1691
         *            Documento
1692
         */
1693
        public void addDocument(ProjectDocument doc) {
1694
                documents.add(doc);
1695
                doc.addPropertyChangeListener(this);
1696
                //modified = true;
1697
                change.firePropertyChange("", "", null);
1698
                doc.setProject(this, 0);
1699
                doc.afterAdd();
1700

    
1701
        }
1702

    
1703
        /**
1704
         * Borra un documento.
1705
         *
1706
         * @param doc
1707
         *            Documento
1708
         */
1709
        public void delDocument(ProjectDocument doc) {
1710
                documents.remove(doc);
1711
                //modified = true;
1712
                change.firePropertyChange("", null, null);
1713
                doc.afterRemove();
1714
        }
1715

    
1716
        /**
1717
         * Sets the default selection color that will be used in subsequent
1718
         * projects.
1719
         *
1720
         * @param color
1721
         */
1722
        public static void setDefaultSelectionColor(Color color) {
1723
                defaultSelectionColor = color;
1724
        }
1725

    
1726
        /**
1727
         * Returns the current default selection color defined which is the color
1728
         * defined when the user does not define any other one
1729
         *
1730
         * @return java.awt.Color
1731
         */
1732
        public static Color getDefaultSelectionColor() {
1733
                // TODO es millorable?
1734
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1735
                                .getPersistentXML();
1736
                if (xml.contains("DefaultSelectionColor"))
1737
                        defaultSelectionColor = StringUtilities.string2Color(xml
1738
                                        .getStringProperty("DefaultSelectionColor"));
1739
                return defaultSelectionColor;
1740
        }
1741

    
1742
        /**
1743
         * Returns the user's default map units. This is the cartography data
1744
         * distance units.
1745
         *
1746
         * @return int (index of the <b>Attributes.NAMES array</b>)
1747
         */
1748
        public static int getDefaultMapUnits() {
1749
                if (defaultMapUnits == -1) {
1750
                        XMLEntity xml = PluginServices.getPluginServices(
1751
                                        "com.iver.cit.gvsig").getPersistentXML();
1752
                        if (xml.contains("DefaultMapUnits")) {
1753
                                defaultMapUnits = xml.getIntProperty("DefaultMapUnits");
1754
                        } else {
1755
                                // first app run case
1756
                                String[] unitNames = MapContext.NAMES;
1757
                                for (int i = 0; i < unitNames.length; i++) {
1758
                                        // meter is the factory default's map unit
1759
                                        if (unitNames[i].equals(PluginServices.getText(
1760
                                                        Project.class, "Metros"))) {
1761
                                                defaultMapUnits = i;
1762
                                                break;
1763
                                        }
1764
                                }
1765
                        }
1766
                        if (defaultMapUnits == -1)
1767
                                defaultMapUnits = ViewPort.METROS;
1768
                }
1769
                return defaultMapUnits;
1770
        }
1771

    
1772
        /**
1773
         * Returns the user's default view units for measuring distances. This is
1774
         * the units that the user will see in the status bar of the view.
1775
         *
1776
         * @return int (index of the <b>Attributes.NAMES array</b>)
1777
         */
1778
        public static int getDefaultDistanceUnits() {
1779
                if (defaultDistanceUnits == -1) {
1780
                        XMLEntity xml = PluginServices.getPluginServices(
1781
                                        "com.iver.cit.gvsig").getPersistentXML();
1782
                        if (xml.contains("DefaultDistanceUnits")) {
1783
                                defaultDistanceUnits = xml
1784
                                                .getIntProperty("DefaultDistanceUnits");
1785
                        } else {
1786
                                // first app run case
1787
                                String[] unitNames = MapContext.NAMES;
1788
                                for (int i = 0; i < unitNames.length; i++) {
1789
                                        // meter is the factory default's distance unit
1790
                                        if (unitNames[i].equals("Metros")) {
1791
                                                defaultDistanceUnits = i;
1792
                                                break;
1793
                                        }
1794
                                }
1795
                        }
1796
                        if (defaultDistanceUnits == -1)
1797
                                defaultDistanceUnits = ViewPort.METROS;
1798
                }
1799
                return defaultDistanceUnits;
1800
        }
1801

    
1802
        /**
1803
         * Sets the default map unit (the units used by the data).
1804
         *
1805
         * @param mapUnits
1806
         */
1807
        public static void setDefaultMapUnits(int mapUnits) {
1808
                defaultMapUnits = mapUnits;
1809
        }
1810

    
1811
        /**
1812
         * Sets the default distance units (the units shown in the status bar)
1813
         *
1814
         * @param distanceUnits
1815
         */
1816
        public static void setDefaultDistanceUnits(int distanceUnits) {
1817
                defaultDistanceUnits = distanceUnits;
1818
        }
1819

    
1820
        public String exportToXML() throws SaveException {
1821
                XMLEntity xml = this.newExportXMLRootNode();
1822

    
1823
                Iterator iter = this.documents.iterator();
1824
                ProjectDocument document;
1825
                // FIXME: Falta atrapar los errores
1826
                while (iter.hasNext()) {
1827
                        document = (ProjectDocument) iter.next();
1828
                        document.exportToXML(xml, this);
1829
                }
1830

    
1831
                return xml.toString();
1832
        }
1833

    
1834
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1835
                XMLEntity xml = this.newExportXMLRootNode();
1836

    
1837
                for (int i = 0; i < documents.length; i++) {
1838
                        documents[i].exportToXML(xml, this);
1839
                }
1840

    
1841
                return xml.toString();
1842
        }
1843

    
1844
        public void importFromXML(String xml) throws Exception {
1845
                throw new Exception("Not Implemented");
1846
                /*
1847
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1848
                 *
1849
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1850
                 * Exception(e); }
1851
                 *
1852
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1853
                 * Error"); //FIXME: traducir }
1854
                 *
1855
                 * int i;
1856
                 *
1857
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1858
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1859
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1860
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1861
                 * root "+i+ "error"); } documentFactory =
1862
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1863
                 * int j; }
1864
                 */
1865

    
1866
        }
1867

    
1868
        public void importFromXML(String xml, String type) throws Exception {
1869
                // FIXME: EXCEPTIONS!!!!
1870
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1871

    
1872
                if (!checkExportXMLRootNode(xmlEntity)) {
1873
                        throw new Exception();
1874
                }
1875

    
1876
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1877
                if (typeRoot.getChildrenCount() == 0) {
1878
                        return;
1879
                }
1880

    
1881
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1882

    
1883
                Hashtable conflicts = getConflicts(xmlEntity);
1884

    
1885
                if (conflicts.size() != 0) {
1886
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1887
                                        conflicts)) {
1888
                                return;
1889
                        }
1890
                }
1891
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1892
                                "dataSources"));
1893

    
1894
                int i;
1895
                ProjectDocument document;
1896
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1897
                        document = documentFactory.create(this);
1898
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1899
                }
1900

    
1901
        }
1902

    
1903
        private Hashtable getConflicts(XMLEntity xml) {
1904
                int iType;
1905
                Hashtable conflicts = new Hashtable();
1906
                ArrayList elements;
1907
                XMLEntity typeRoot;
1908
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
1909
                        typeRoot = xml.getChild(iType);
1910
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
1911
                        Hashtable conflictsType = new Hashtable();
1912
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
1913
                                XMLEntity child = typeRoot.getChild(iXML);
1914
                                Iterator iter = elements.iterator();
1915
                                while (iter.hasNext()) {
1916
                                        ProjectDocument element = (ProjectDocument) iter.next();
1917
                                        if (element.getName().equalsIgnoreCase(
1918
                                                        child.getStringProperty("name"))) {
1919
                                                conflictsType.put(new Integer(iXML), child);
1920
                                                break;
1921
                                        }
1922

    
1923
                                }
1924
                        }
1925
                        if (conflictsType.size() > 0) {
1926
                                conflicts
1927
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1928
                        }
1929
                }
1930
                return conflicts;
1931
        }
1932

    
1933
        public boolean isValidXMLForImport(String xml) {
1934
                XMLEntity xmlEntity;
1935
                try {
1936
                        xmlEntity = XMLEntity.parse(xml);
1937
                } catch (Exception e) {
1938
                        return false;
1939
                }
1940

    
1941
                return checkExportXMLRootNode(xmlEntity);
1942
        }
1943

    
1944
        public boolean isValidXMLForImport(String xml, String type) {
1945
                XMLEntity xmlEntity;
1946
                try {
1947
                        xmlEntity = XMLEntity.parse(xml);
1948
                } catch (Exception e) {
1949
                        return false;
1950
                }
1951

    
1952
                if (!checkExportXMLRootNode(xmlEntity)) {
1953
                        return false;
1954
                }
1955

    
1956
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1957

    
1958
                if (typeRoot == null) {
1959
                        return false;
1960
                }
1961

    
1962
                return (typeRoot.getChildrenCount() > 0);
1963
        }
1964

    
1965
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1966
                if (!xml.contains("applicationName"))
1967
                        return false;
1968
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1969
                        return false;
1970

    
1971
                if (!xml.contains("version"))
1972
                        return false;
1973
                if (!xml.getStringProperty("version")
1974
                                .equalsIgnoreCase(Version.format()))
1975
                        return false;
1976

    
1977
                return true;
1978
        }
1979

    
1980
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
1981
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
1982
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
1983
                                .getDriverInfo(dataSourceName);
1984
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
1985
        }
1986

    
1987
        private XMLEntity newExportXMLRootNode() {
1988
                XMLEntity xml = new XMLEntity();
1989
                xml.putProperty("applicationName", "gvSIG");
1990
                xml.putProperty("version", Version.format());
1991
                return xml;
1992
        }
1993

    
1994
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
1995
                XMLEntity typeRoot = root.firstChild("type", type);
1996
                if (typeRoot == null) {
1997
                        typeRoot = this.newExportXMLTypeNode(type);
1998
                        root.addChild(typeRoot);
1999
                }
2000
                return typeRoot;
2001
        }
2002

    
2003
        private XMLEntity newExportXMLTypeNode(String type) {
2004
                XMLEntity xmlDataSources = new XMLEntity();
2005
                xmlDataSources.putProperty("type", type);
2006
                return xmlDataSources;
2007
        }
2008

    
2009
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2010
                String name = xmlDataSource.getStringProperty("gdbmsname");
2011

    
2012
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2013
                        if (xmlDataSource.getStringProperty("type").equals(
2014
                                        "otherDriverFile")) {
2015
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2016
                                                xmlDataSource.getStringProperty("driverName"), name,
2017
                                                xmlDataSource.getStringProperty("file"));
2018

    
2019
                        } else if (xmlDataSource.getStringProperty("type").equals(
2020
                                        "sameDriverFile")) {
2021

    
2022
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2023
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2024
                                                name, xmlDataSource.getStringProperty("host"),
2025
                                                xmlDataSource.getIntProperty("port"),
2026
                                                xmlDataSource.getStringProperty("user"),
2027
                                                xmlDataSource.getStringProperty("password"),
2028
                                                xmlDataSource.getStringProperty("dbName"),
2029
                                                xmlDataSource.getStringProperty("tableName"),
2030
                                                xmlDataSource.getStringProperty("driverInfo"));
2031
                        } else {
2032
                                return false;
2033
                        }
2034

    
2035
                }
2036
                return true;
2037
        }
2038

    
2039
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2040
                try {
2041
                        int numDataSources = xmlDataSources.getChildrenCount();
2042

    
2043
                        if (numDataSources == 0)
2044
                                return true;
2045
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2046

    
2047
                        for (int i = 0; i < numDataSources; i++) {
2048
                                XMLEntity child = xmlDataSources.getChild(i);
2049
                                if (!this.registerDataSourceFromXML(child)) {
2050
                                        return false;
2051
                                }
2052
                        }
2053

    
2054
                        return true;
2055
                } catch (Exception e) {
2056
                        e.printStackTrace();
2057
                        return false;
2058
                }
2059
        }
2060

    
2061
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2062
                ProjectDocumentFactory pde = null;
2063
                try {
2064
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2065
                                        .getInstance();
2066
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2067
                                        .get("Documents"));
2068
                        try {
2069
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2070
                        } catch (InstantiationException e) {
2071
                                NotificationManager.addError(
2072
                                                "Clase de ProjectDocument no reconocida", e);
2073
                        } catch (IllegalAccessException e) {
2074
                                NotificationManager.addError(
2075
                                                "Clase de ProjectDocument no reconocida", e);
2076
                        }
2077

    
2078
                } catch (Exception e1) {
2079
                        return null;
2080
                }
2081
                return pde;
2082
        }
2083

    
2084
         public boolean hasChanged() {
2085
                 return true;
2086
//                 return signatureAtStartup != getXMLEntity().hash();
2087
         }
2088

    
2089
        public void setSignature(long hash) {
2090
                signatureAtStartup = hash;
2091
        }
2092
}