Statistics
| Revision:

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

History | View | Annotate | Download (58.3 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.Attributes;
98
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
99
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
100
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
101
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
102
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
103
import com.iver.cit.gvsig.project.documents.view.ProjectView;
104
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
105
import com.iver.utiles.IPersistance;
106
import com.iver.utiles.PostProcessSupport;
107
import com.iver.utiles.StringUtilities;
108
import com.iver.utiles.XMLEntity;
109
import com.iver.utiles.extensionPoints.ExtensionPoint;
110
import com.iver.utiles.extensionPoints.ExtensionPoints;
111
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
112

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

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

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

    
131
        private static int defaultMapUnits = -1;
132

    
133
        private static int defaultDistanceUnits = -1;
134

    
135
        private PropertyChangeSupport change;
136

    
137
        private boolean modified = false;
138

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

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

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

    
146
        private String owner = "";
147

    
148
        private String comments = "";
149

    
150
        private Color selectionColor = null;
151

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

    
157
        private ArrayList extents = new ArrayList();
158

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

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

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

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

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

    
197
                // change.addPropertyChangeListener(this);
198
                creationDate = DateFormat.getDateInstance().format(new Date());
199
                modificationDate = creationDate;
200
                setSelectionColor(getDefaultSelectionColor());
201
                // signatureAtStartup = computeSignature();
202

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

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

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

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

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

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

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

    
283
                return null;
284
        }
285

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

    
306
                return null;
307
        }
308

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
486
                return extents.remove(arg0);
487
        }
488

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

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

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

    
522
                return this.cameras.remove(arg0);
523
        }
524

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

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

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

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

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

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

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

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

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

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

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

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

    
655
                int numExtents = extents.size();
656
                xml.putProperty("numExtents", numExtents);
657

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

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

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

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

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

    
721
                saveWindowProperties(xml);
722
                return xml;
723
        }
724

    
725
        private void saveWindowProperties(XMLEntity xml) {
726
                XMLEntity propertyList = new XMLEntity();
727

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

    
731
                boolean projectWindowSaved = false;
732

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

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

    
794
                                                propertyList.addChild(windowProperties);
795
                                        }
796
                                }
797
                        }
798
                }
799

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

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

    
822
                xml.addChild(propertyList);
823
        }
824

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

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

    
858
                this.initialWindowProperties = orderedProperties.values().iterator();
859
        }
860

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

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

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

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

    
908
                if (xml.contains("numViews"))
909
                        childNumb += xml.getIntProperty("numViews");
910

    
911
                if (xml.contains("numMaps"))
912
                        limit = childNumb + xml.getIntProperty("numMaps");
913

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

    
935
                this.initialWindowProperties = windowList.iterator();
936
        }
937

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

    
948
                Iterator propertiesIterator = this.initialWindowProperties;
949
                if (propertiesIterator != null) {
950
                        this.initialWindowProperties = null;
951

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

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

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

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

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

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

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

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

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

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

    
1109
                int childNumber = 0;
1110
                Project p = new Project();
1111

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

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

    
1122
                        // Leemos el ultiom hijo recogido
1123
                        childNumber = numExtents;
1124

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

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

    
1145
                        childNumber += numCameras;
1146

    
1147
                        int numDataSources = xml.getIntProperty("data-source-count");
1148

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

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

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

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

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

    
1199
                        p.setLinkTable();
1200
                        String strProj = xml.getStringProperty("projection");
1201

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

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

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

    
1228
                return p;
1229

    
1230
        }
1231

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

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

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

    
1262
                                                (((ProjectTable) tables.get(i)).getModelo()
1263
                                                                .getRecordset()).addSelectionListener(lsl);
1264

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

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

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

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

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

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

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

    
1359
        public static IProjection getDefaultProjection() {
1360
                return Project.defaultProjection;
1361
        }
1362

    
1363
        /**
1364
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1365
         * pointExtension, este ?ltimo se puede obtener del
1366
         * Project****Factory.registerName.
1367
         *
1368
         * @param name
1369
         *            Nombre del documento
1370
         * @param type
1371
         *            nombre de registro en el extensionPoint
1372
         *
1373
         * @return Documento
1374
         */
1375
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1376
                ArrayList docs = getDocumentsByType(type);
1377
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1378
                        ProjectDocument elem = (ProjectDocument) iter.next();
1379

    
1380
                        if (elem.getName().equals(name)) {
1381
                                return elem;
1382
                        }
1383
                }
1384

    
1385
                return null;
1386
        }
1387

    
1388
        /**
1389
         * DOCUMENT ME!
1390
         *
1391
         * @param name
1392
         *
1393
         * @return
1394
         */
1395
        /*
1396
         * public ProjectTable getTableByName(String name) { ArrayList
1397
         * tables=getDocuments(PluginServices.getText(this,"Tabla")); Object o =
1398
         * getProjectElementByName(name, tables);
1399
         *
1400
         * if (o == null) { return null; }
1401
         *
1402
         * return (ProjectTable) o; }
1403
         */
1404
        /**
1405
         * DOCUMENT ME!
1406
         *
1407
         * @param name
1408
         *
1409
         * @return
1410
         */
1411
        /*
1412
         * public ProjectMap getLayoutByName(String name) { Object o =
1413
         * getProjectElementByName(name, maps);
1414
         *
1415
         * if (o == null) { return null; }
1416
         *
1417
         * return (ProjectMap) o; }
1418
         */
1419
        public SelectableDataSource getDataSourceByLayer(FLayer layer)
1420
                        throws ReadDriverException {
1421
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1422
                SelectableDataSource dataSource = null;
1423
                for (int i = 0; i < tables.size(); i++) {
1424
                        ProjectTable pt = (ProjectTable) tables.get(i);
1425
                        if (pt.getOriginal() == ((AlphanumericData) layer)
1426
                                        .getRecordset()) {
1427
                                dataSource = pt.getModelo().getRecordset();
1428
                                break;
1429
                        } else if (pt.getModelo() == ((AlphanumericData) layer)
1430
                                        .getRecordset()) {
1431
                                        dataSource = pt.getModelo().getRecordset();
1432
                                        break;
1433
                        }
1434
                }
1435

    
1436
                if (dataSource == null) {
1437
                        // No se ha creado la tabla asociada al tema
1438
                        dataSource = ((AlphanumericData) layer).getRecordset();
1439
                }
1440

    
1441
                return dataSource;
1442

    
1443
        }
1444

    
1445
        /**
1446
         * Recorremos las capas y las tablas del proyecto, y creamos una lista con
1447
         * todos los datasources de GDBMS que estamos usando. Luego recorremos los
1448
         * que est?n registrados, y borramos aquellos que no est?n siendo usados, es
1449
         * decir, aquellos que no est?n en nuestra lista (un Hash con clave el
1450
         * nombre del GDBMS)
1451
         *
1452
         */
1453
        private void cleanBadReferences() {
1454
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1455
                Hashtable usedDataSources = new Hashtable();
1456
                // Primero las tablas
1457
                int i, j;
1458
                try {
1459
                        for (i = 0; i < tables.size(); i++) {
1460
                                ProjectTable t = (ProjectTable) tables.get(i);
1461
                                SelectableDataSource ds;
1462

    
1463
                                ds = t.getModelo().getRecordset();
1464

    
1465
                                if (t.getOriginal() != null)
1466
                                        usedDataSources.put(t.getOriginal().getRecordset()
1467
                                                        .getName(), t.getOriginal());
1468
                                usedDataSources.put(ds.getName(), ds);
1469
                        }
1470
                } catch (ReadDriverException e) {
1471
                        e.printStackTrace();
1472
                }
1473
                // Ahora las vistas
1474
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1475
                try {
1476
                        for (i = 0; i < views.size(); i++) {
1477
                                ProjectView pv = (ProjectView) views.get(i);
1478

    
1479
                                FLayers lyrs = pv.getMapContext().getLayers();
1480

    
1481
                                for (j = 0; j < lyrs.getLayersCount(); j++) {
1482
                                        FLayer lyr = lyrs.getLayer(j);
1483
                                        if (lyr instanceof FLyrVect) {
1484
                                                FLyrVect lyrVect = (FLyrVect) lyr;
1485
                                                if (lyrVect.isAvailable())
1486
                                                        usedDataSources.put(lyrVect.getRecordset()
1487
                                                                        .getName(), lyrVect.getSource()
1488
                                                                        .getRecordset());
1489
                                        }
1490
                                }
1491
                                MapContext aux = pv.getMapOverViewContext();
1492
                                if (aux != null) {
1493
                                        FLayers lyrsOverview = aux.getLayers();
1494
                                        for (j = 0; j < lyrsOverview.getLayersCount(); j++) {
1495
                                                FLayer lyr = lyrsOverview.getLayer(j);
1496
                                                if (lyr instanceof FLyrVect) {
1497
                                                        FLyrVect lyrVect = (FLyrVect) lyr;
1498
                                                        usedDataSources.put(lyrVect.getSource()
1499
                                                                        .getRecordset().getName(), lyrVect
1500
                                                                        .getSource().getRecordset());
1501
                                                }
1502
                                        }
1503
                                }
1504

    
1505
                        } // for i
1506
                } catch (ReadDriverException e) {
1507
                        e.printStackTrace();
1508
                }
1509
                // Recorremos los dataSources y los borramos si no
1510
                // los estamos usando.
1511
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1512
                                .getDriverInfos();
1513
                try {
1514
                        for (i = 0; i < infos.length; i++) {
1515
                                if (!usedDataSources.containsKey(infos[i].name)) {
1516
                                        DataSource ds;
1517
                                        ds = LayerFactory.getDataSourceFactory()
1518
                                                        .createRandomDataSource(infos[i].name);
1519
                                        ds.remove();
1520
                                }
1521
                        }
1522
                } catch (DriverLoadException e) {
1523
                        e.printStackTrace();
1524
                } catch (NoSuchTableException e) {
1525
                        e.printStackTrace();
1526
                } catch (ReadDriverException e) {
1527
                        e.printStackTrace();
1528
                } catch (WriteDriverException e) {
1529
                        e.printStackTrace();
1530
                }
1531
        }
1532

    
1533
        /**
1534
         * DOCUMENT ME!
1535
         *
1536
         * @return DOCUMENT ME!
1537
         * @throws SaveException
1538
         * @throws XMLException
1539
         * @throws SaveException
1540
         */
1541
        public XMLEntity getWindowInfoXMLEntity(IWindow window)
1542
                        throws SaveException {
1543
                if (window != null
1544
                                && PluginServices.getMDIManager().getWindowInfo(window) != null) {
1545
                        WindowInfo vi = PluginServices.getMDIManager()
1546
                                        .getWindowInfo(window);
1547
                        XMLEntity xml = new XMLEntity();
1548
                        // xml.putProperty("nameClass", this.getClass().getName());
1549
                        try {
1550
                                xml.setName("ViewInfoProperties");
1551
                                xml.putProperty("className", this.getClass().getName());
1552
                                xml.putProperty("X", vi.getX());
1553
                                xml.putProperty("Y", vi.getY());
1554
                                xml.putProperty("Width", vi.getWidth());
1555
                                xml.putProperty("Height", vi.getHeight());
1556
                                xml.putProperty("isVisible", vi.isVisible());
1557
                                xml.putProperty("isResizable", vi.isResizable());
1558
                                xml.putProperty("isMaximizable", vi.isMaximizable());
1559
                                xml.putProperty("isModal", vi.isModal());
1560
                                xml.putProperty("isModeless", vi.isModeless());
1561
                                xml.putProperty("isClosed", vi.isClosed());
1562
                                if (vi.isMaximized() == true) {
1563
                                        xml.putProperty("isMaximized", vi.isMaximized());
1564
                                        xml.putProperty("normalX", vi.getNormalX());
1565
                                        xml.putProperty("normalY", vi.getNormalY());
1566
                                        xml.putProperty("normalWidth", vi.getNormalWidth());
1567
                                        xml.putProperty("normalHeight", vi.getNormalHeight());
1568
}
1569
                        } catch (Exception e) {
1570
                                throw new SaveException(e, this.getClass().getName());
1571
                        }
1572
                        return xml;
1573
                }
1574
                return null;
1575
        }
1576

    
1577
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1578
                WindowInfo result = new WindowInfo();
1579
                result.setX(xml.getIntProperty("X"));
1580
                result.setY(xml.getIntProperty("Y"));
1581
                result.setHeight(xml.getIntProperty("Height"));
1582
                result.setWidth(xml.getIntProperty("Width"));
1583
                result.setClosed(xml.getBooleanProperty("isClosed"));
1584
                if (xml.contains("isMaximized")) {
1585
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1586
                        result.setMaximized(maximized);
1587
                        if (maximized == true) {
1588
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1589
                                                .getIntProperty("normalY"), xml
1590
                                                .getIntProperty("normalWidth"), xml
1591
                                                .getIntProperty("normalHeight"));
1592
                        } else {
1593
                                result.setNormalBounds(result.getBounds());
1594
                        }
1595
                }
1596

    
1597
                return result;
1598
        }
1599

    
1600
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1601
                XMLEntity child = new XMLEntity();
1602

    
1603
                if (di instanceof ObjectSourceInfo) {
1604
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1605
                        child.putProperty("type", "sameDriverFile");
1606
                        child.putProperty("gdbmsname", driver.name);
1607
                } else if (di instanceof FileSourceInfo) {
1608
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1609
                        child.putProperty("type", "otherDriverFile");
1610
                        child.putProperty("gdbmsname", vfdi.name);
1611
                        child.putProperty("file", vfdi.file);
1612
                        child.putProperty("driverName", vfdi.driverName);
1613
                } else if (di instanceof DBSourceInfo) {
1614
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1615
                        child.putProperty("type", "db");
1616
                        child.putProperty("gdbmsname", dbdi.name);
1617
                        child.putProperty("dbms", dbdi.dbms);
1618
                        child.putProperty("host", dbdi.host);
1619
                        child.putProperty("port", dbdi.port);
1620
                        child.putProperty("user", dbdi.user);
1621
                        child.putProperty("password", dbdi.password);
1622
                        child.putProperty("dbName", dbdi.dbName);
1623
                        child.putProperty("tableName", dbdi.tableName);
1624
                        child.putProperty("driverInfo", dbdi.driverName);
1625
                }
1626

    
1627
                return child;
1628
        }
1629

    
1630
        /**
1631
         * Devuelve un arrayList con todos los documentos del tipo especificado como
1632
         * par?metro.
1633
         *
1634
         * @param registerName
1635
         *            nombre de registro en el extensionPoint
1636
         *
1637
         * @return Documentos del tipo especificado
1638
         */
1639
        public ArrayList getDocumentsByType(String registerName) {
1640
                ArrayList docuArray = new ArrayList();
1641
                for (int i = 0; i < documents.size(); i++) {
1642
                        ProjectDocument projectDocument = (ProjectDocument) documents
1643
                                        .get(i);
1644
                        ProjectDocumentFactory pdf = projectDocument
1645
                                        .getProjectDocumentFactory();
1646
                        if (pdf == null)
1647
                                continue;
1648
                        if (pdf.getRegisterName().equals(registerName)) {
1649
                                docuArray.add(projectDocument);
1650
                        }
1651
                }
1652
                return docuArray;
1653
        }
1654

    
1655
        /**
1656
         * Devuelve un arrayList con todos los documentos.
1657
         *
1658
         * @return Documentos
1659
         */
1660
        public ArrayList getDocuments() {
1661
                ArrayList docuArray = new ArrayList();
1662
                for (int i = 0; i < documents.size(); i++) {
1663
                        ProjectDocument projectDocument = (ProjectDocument) documents
1664
                                        .get(i);
1665
                        docuArray.add(projectDocument);
1666
                }
1667
                return docuArray;
1668
        }
1669

    
1670
        /**
1671
         * Inserta un documento.
1672
         *
1673
         * @param doc
1674
         *            Documento
1675
         */
1676
        public void addDocument(ProjectDocument doc) {
1677
                documents.add(doc);
1678
                doc.addPropertyChangeListener(this);
1679
                //modified = true;
1680
                change.firePropertyChange("", "", null);
1681
                doc.setProject(this, 0);
1682
                doc.afterAdd();
1683

    
1684
        }
1685

    
1686
        /**
1687
         * Borra un documento.
1688
         *
1689
         * @param doc
1690
         *            Documento
1691
         */
1692
        public void delDocument(ProjectDocument doc) {
1693
                documents.remove(doc);
1694
                //modified = true;
1695
                change.firePropertyChange("", null, null);
1696
                doc.afterRemove();
1697
        }
1698

    
1699
        /**
1700
         * Sets the default selection color that will be used in subsequent
1701
         * projects.
1702
         *
1703
         * @param color
1704
         */
1705
        public static void setDefaultSelectionColor(Color color) {
1706
                defaultSelectionColor = color;
1707
        }
1708

    
1709
        /**
1710
         * Returns the current default selection color defined which is the color
1711
         * defined when the user does not define any other one
1712
         *
1713
         * @return java.awt.Color
1714
         */
1715
        public static Color getDefaultSelectionColor() {
1716
                // TODO es millorable?
1717
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1718
                                .getPersistentXML();
1719
                if (xml.contains("DefaultSelectionColor"))
1720
                        defaultSelectionColor = StringUtilities.string2Color(xml
1721
                                        .getStringProperty("DefaultSelectionColor"));
1722
                return defaultSelectionColor;
1723
        }
1724

    
1725
        /**
1726
         * Returns the user's default map units. This is the cartography data
1727
         * distance units.
1728
         *
1729
         * @return int (index of the <b>Attributes.NAMES array</b>)
1730
         */
1731
        public static int getDefaultMapUnits() {
1732
                if (defaultMapUnits == -1) {
1733
                        XMLEntity xml = PluginServices.getPluginServices(
1734
                                        "com.iver.cit.gvsig").getPersistentXML();
1735
                        if (xml.contains("DefaultMapUnits")) {
1736
                                defaultMapUnits = xml.getIntProperty("DefaultMapUnits");
1737
                        } else {
1738
                                // first app run case
1739
                                String[] unitNames = Attributes.NAMES;
1740
                                for (int i = 0; i < unitNames.length; i++) {
1741
                                        // meter is the factory default's map unit
1742
                                        if (unitNames[i].equals(PluginServices.getText(
1743
                                                        Project.class, "Metros"))) {
1744
                                                defaultMapUnits = i;
1745
                                                break;
1746
                                        }
1747
                                }
1748
                        }
1749
                        if (defaultMapUnits == -1)
1750
                                defaultMapUnits = ViewPort.METROS;
1751
                }
1752
                return defaultMapUnits;
1753
        }
1754

    
1755
        /**
1756
         * Returns the user's default view units for measuring distances. This is
1757
         * the units that the user will see in the status bar of the view.
1758
         *
1759
         * @return int (index of the <b>Attributes.NAMES array</b>)
1760
         */
1761
        public static int getDefaultDistanceUnits() {
1762
                if (defaultDistanceUnits == -1) {
1763
                        XMLEntity xml = PluginServices.getPluginServices(
1764
                                        "com.iver.cit.gvsig").getPersistentXML();
1765
                        if (xml.contains("DefaultDistanceUnits")) {
1766
                                defaultDistanceUnits = xml
1767
                                                .getIntProperty("DefaultDistanceUnits");
1768
                        } else {
1769
                                // first app run case
1770
                                String[] unitNames = Attributes.NAMES;
1771
                                for (int i = 0; i < unitNames.length; i++) {
1772
                                        // meter is the factory default's distance unit
1773
                                        if (unitNames[i].equals("Metros")) {
1774
                                                defaultDistanceUnits = i;
1775
                                                break;
1776
                                        }
1777
                                }
1778
                        }
1779
                        if (defaultDistanceUnits == -1)
1780
                                defaultDistanceUnits = ViewPort.METROS;
1781
                }
1782
                return defaultDistanceUnits;
1783
        }
1784

    
1785
        /**
1786
         * Sets the default map unit (the units used by the data).
1787
         *
1788
         * @param mapUnits
1789
         */
1790
        public static void setDefaultMapUnits(int mapUnits) {
1791
                defaultMapUnits = mapUnits;
1792
        }
1793

    
1794
        /**
1795
         * Sets the default distance units (the units shown in the status bar)
1796
         *
1797
         * @param distanceUnits
1798
         */
1799
        public static void setDefaultDistanceUnits(int distanceUnits) {
1800
                defaultDistanceUnits = distanceUnits;
1801
        }
1802

    
1803
        public String exportToXML() throws SaveException {
1804
                XMLEntity xml = this.newExportXMLRootNode();
1805

    
1806
                Iterator iter = this.documents.iterator();
1807
                ProjectDocument document;
1808
                // FIXME: Falta atrapar los errores
1809
                while (iter.hasNext()) {
1810
                        document = (ProjectDocument) iter.next();
1811
                        document.exportToXML(xml, this);
1812
                }
1813

    
1814
                return xml.toString();
1815
        }
1816

    
1817
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1818
                XMLEntity xml = this.newExportXMLRootNode();
1819

    
1820
                for (int i = 0; i < documents.length; i++) {
1821
                        documents[i].exportToXML(xml, this);
1822
                }
1823

    
1824
                return xml.toString();
1825
        }
1826

    
1827
        public void importFromXML(String xml) throws Exception {
1828
                throw new Exception("Not Implemented");
1829
                /*
1830
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1831
                 *
1832
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1833
                 * Exception(e); }
1834
                 *
1835
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1836
                 * Error"); //FIXME: traducir }
1837
                 *
1838
                 * int i;
1839
                 *
1840
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1841
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1842
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1843
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1844
                 * root "+i+ "error"); } documentFactory =
1845
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1846
                 * int j; }
1847
                 */
1848

    
1849
        }
1850

    
1851
        public void importFromXML(String xml, String type) throws Exception {
1852
                // FIXME: EXCEPTIONS!!!!
1853
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1854

    
1855
                if (!checkExportXMLRootNode(xmlEntity)) {
1856
                        throw new Exception();
1857
                }
1858

    
1859
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1860
                if (typeRoot.getChildrenCount() == 0) {
1861
                        return;
1862
                }
1863

    
1864
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1865

    
1866
                Hashtable conflicts = getConflicts(xmlEntity);
1867

    
1868
                if (conflicts.size() != 0) {
1869
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1870
                                        conflicts)) {
1871
                                return;
1872
                        }
1873
                }
1874
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1875
                                "dataSources"));
1876

    
1877
                int i;
1878
                ProjectDocument document;
1879
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1880
                        document = documentFactory.create(this);
1881
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1882
                }
1883

    
1884
        }
1885

    
1886
        private Hashtable getConflicts(XMLEntity xml) {
1887
                int iType;
1888
                Hashtable conflicts = new Hashtable();
1889
                ArrayList elements;
1890
                XMLEntity typeRoot;
1891
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
1892
                        typeRoot = xml.getChild(iType);
1893
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
1894
                        Hashtable conflictsType = new Hashtable();
1895
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
1896
                                XMLEntity child = typeRoot.getChild(iXML);
1897
                                Iterator iter = elements.iterator();
1898
                                while (iter.hasNext()) {
1899
                                        ProjectDocument element = (ProjectDocument) iter.next();
1900
                                        if (element.getName().equalsIgnoreCase(
1901
                                                        child.getStringProperty("name"))) {
1902
                                                conflictsType.put(new Integer(iXML), child);
1903
                                                break;
1904
                                        }
1905

    
1906
                                }
1907
                        }
1908
                        if (conflictsType.size() > 0) {
1909
                                conflicts
1910
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1911
                        }
1912
                }
1913
                return conflicts;
1914
        }
1915

    
1916
        public boolean isValidXMLForImport(String xml) {
1917
                XMLEntity xmlEntity;
1918
                try {
1919
                        xmlEntity = XMLEntity.parse(xml);
1920
                } catch (Exception e) {
1921
                        return false;
1922
                }
1923

    
1924
                return checkExportXMLRootNode(xmlEntity);
1925
        }
1926

    
1927
        public boolean isValidXMLForImport(String xml, String type) {
1928
                XMLEntity xmlEntity;
1929
                try {
1930
                        xmlEntity = XMLEntity.parse(xml);
1931
                } catch (Exception e) {
1932
                        return false;
1933
                }
1934

    
1935
                if (!checkExportXMLRootNode(xmlEntity)) {
1936
                        return false;
1937
                }
1938

    
1939
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1940

    
1941
                if (typeRoot == null) {
1942
                        return false;
1943
                }
1944

    
1945
                return (typeRoot.getChildrenCount() > 0);
1946
        }
1947

    
1948
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1949
                if (!xml.contains("applicationName"))
1950
                        return false;
1951
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1952
                        return false;
1953

    
1954
                if (!xml.contains("version"))
1955
                        return false;
1956
                if (!xml.getStringProperty("version")
1957
                                .equalsIgnoreCase(Version.format()))
1958
                        return false;
1959

    
1960
                return true;
1961
        }
1962

    
1963
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
1964
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
1965
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
1966
                                .getDriverInfo(dataSourceName);
1967
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
1968
        }
1969

    
1970
        private XMLEntity newExportXMLRootNode() {
1971
                XMLEntity xml = new XMLEntity();
1972
                xml.putProperty("applicationName", "gvSIG");
1973
                xml.putProperty("version", Version.format());
1974
                return xml;
1975
        }
1976

    
1977
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
1978
                XMLEntity typeRoot = root.firstChild("type", type);
1979
                if (typeRoot == null) {
1980
                        typeRoot = this.newExportXMLTypeNode(type);
1981
                        root.addChild(typeRoot);
1982
                }
1983
                return typeRoot;
1984
        }
1985

    
1986
        private XMLEntity newExportXMLTypeNode(String type) {
1987
                XMLEntity xmlDataSources = new XMLEntity();
1988
                xmlDataSources.putProperty("type", type);
1989
                return xmlDataSources;
1990
        }
1991

    
1992
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
1993
                String name = xmlDataSource.getStringProperty("gdbmsname");
1994

    
1995
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
1996
                        if (xmlDataSource.getStringProperty("type").equals(
1997
                                        "otherDriverFile")) {
1998
                                LayerFactory.getDataSourceFactory().addFileDataSource(
1999
                                                xmlDataSource.getStringProperty("driverName"), name,
2000
                                                xmlDataSource.getStringProperty("file"));
2001

    
2002
                        } else if (xmlDataSource.getStringProperty("type").equals(
2003
                                        "sameDriverFile")) {
2004

    
2005
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2006
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2007
                                                name, xmlDataSource.getStringProperty("host"),
2008
                                                xmlDataSource.getIntProperty("port"),
2009
                                                xmlDataSource.getStringProperty("user"),
2010
                                                xmlDataSource.getStringProperty("password"),
2011
                                                xmlDataSource.getStringProperty("dbName"),
2012
                                                xmlDataSource.getStringProperty("tableName"),
2013
                                                xmlDataSource.getStringProperty("driverInfo"));
2014
                        } else {
2015
                                return false;
2016
                        }
2017

    
2018
                }
2019
                return true;
2020
        }
2021

    
2022
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2023
                try {
2024
                        int numDataSources = xmlDataSources.getChildrenCount();
2025

    
2026
                        if (numDataSources == 0)
2027
                                return true;
2028
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2029

    
2030
                        for (int i = 0; i < numDataSources; i++) {
2031
                                XMLEntity child = xmlDataSources.getChild(i);
2032
                                if (!this.registerDataSourceFromXML(child)) {
2033
                                        return false;
2034
                                }
2035
                        }
2036

    
2037
                        return true;
2038
                } catch (Exception e) {
2039
                        e.printStackTrace();
2040
                        return false;
2041
                }
2042
        }
2043

    
2044
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2045
                ProjectDocumentFactory pde = null;
2046
                try {
2047
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2048
                                        .getInstance();
2049
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2050
                                        .get("Documents"));
2051
                        try {
2052
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2053
                        } catch (InstantiationException e) {
2054
                                NotificationManager.addError(
2055
                                                "Clase de ProjectDocument no reconocida", e);
2056
                        } catch (IllegalAccessException e) {
2057
                                NotificationManager.addError(
2058
                                                "Clase de ProjectDocument no reconocida", e);
2059
                        }
2060

    
2061
                } catch (Exception e1) {
2062
                        return null;
2063
                }
2064
                return pde;
2065
        }
2066

    
2067
         public boolean hasChanged() {
2068

    
2069
//                 System.out.println(getXMLEntity().toString());
2070
//                 System.err.println("old hash = " +signatureAtStartup+", new hash "+getXMLEntity().hash());
2071
                 return signatureAtStartup != getXMLEntity().hash();
2072

    
2073
         }
2074

    
2075
        public void setSignature(long hash) {
2076
                signatureAtStartup = hash;
2077
//                System.err.println("\n\nHASH = " +hash+"\n\n");
2078
//                System.out.println(getXMLEntity().toString());
2079
        }
2080
}