Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / Project.java @ 14704

History | View | Annotate | Download (59.8 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.Map;
56
import java.util.TreeMap;
57

    
58
import org.cresques.cts.IProjection;
59

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

    
117
/**
118
 * Clase que representa un proyecto de openSIG
119
 *
120
 * @author Fernando Gonz�lez Cort�s
121
 */
122
public class Project implements Serializable, PropertyChangeListener {
123
        public static String VERSION = Version.format();
124

    
125
        static private IProjection defaultProjection = null;
126

    
127
        static private IProjection defaultFactoryProjection = CRSFactory
128
                        .getCRS("EPSG:23030");
129

    
130
        /*
131
         * distiguishing between a static field "defaultSelectionColor" and a
132
         * selectionColor field will allow to define default color in a multiple
133
         * project scenario
134
         */
135
        static private Color defaultSelectionColor = Color.YELLOW;
136

    
137
        private static int defaultMapUnits = -1;
138

    
139
        private static int defaultDistanceUnits = -1;
140

    
141
        private PropertyChangeSupport change;
142

    
143
        private boolean modified = false;
144

    
145
        private String name = PluginServices.getText(this, "untitled");
146

    
147
        // private String path;
148
        private String creationDate = new Date().toGMTString();
149

    
150
        private String modificationDate = new Date().toGMTString();
151

    
152
        private String owner = "";
153

    
154
        private String comments = "";
155

    
156
        private Color selectionColor = null;
157

    
158
        // private ArrayList views = new ArrayList();
159
        // private ArrayList tables = new ArrayList();
160
        // private ArrayList maps = new ArrayList();
161
        private ArrayList documents = new ArrayList();
162

    
163
        private ArrayList extents = new ArrayList();
164

    
165
        // Lista de objetos del tipo camera. Necesarios para almacenar la posicion
166
        // del usuario haciendo uso de los marcadores
167
        private List cameras = new ArrayList();
168

    
169
        /**
170
         * this is a runtime-calculated value, do NOT persist it!
171
         */
172
        private long signatureAtStartup;
173
        private IProjection projection;
174

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

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

    
197
        /**
198
         * Creates a new Project object.
199
         */
200
        public Project() {
201
                change = new PropertyChangeSupport(this);
202

    
203
                // change.addPropertyChangeListener(this);
204
                creationDate = DateFormat.getDateInstance().format(new Date());
205
                modificationDate = creationDate;
206
                setSelectionColor(getDefaultSelectionColor());
207
                getDefaultProjection(); //For initialize it
208
                // signatureAtStartup = computeSignature();
209

    
210
                /*
211
                 * LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
212
                 * .getPluginDirectory() .getAbsolutePath() + File.separator +
213
                 * "drivers");
214
                 */
215
        }
216

    
217
        /**
218
         * Obtiene la fecha de creaci�n del proyecto
219
         *
220
         * @return
221
         */
222
        public String getCreationDate() {
223
                return creationDate;
224
        }
225

    
226
        /**
227
         * Obtiene el nombre del proyecto
228
         *
229
         * @return
230
         */
231
        public String getName() {
232
                return name;
233
        }
234

    
235
        // /**
236
        // * Obtiene la ruta completa del fichero donde se guardo por �ltima vez el
237
        // * proyecto
238
        // *
239
        // * @return
240
        // */
241
        // public String getPath() {
242
        // return path;
243
        // }
244

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

    
259
        /**
260
         * Establece el nombre del proyecto
261
         *
262
         * @param string
263
         */
264
        public void setName(String string) {
265
                name = string;
266
                //modified = true;
267
                change.firePropertyChange("", null, null);
268
        }
269

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

    
290
                return null;
291
        }
292

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

    
313
                return null;
314
        }
315

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

    
341
        /**
342
         * Obtiene los comentarios
343
         *
344
         * @return
345
         */
346
        public String getComments() {
347
                return comments;
348
        }
349

    
350
        /**
351
         * Obtiene la fecha de la �ltima modificaci�n
352
         *
353
         * @return
354
         */
355
        public String getModificationDate() {
356
                return modificationDate;
357
        }
358

    
359
        /**
360
         * Obtiene el propietario del proyecto
361
         *
362
         * @return
363
         */
364
        public String getOwner() {
365
                return owner;
366
        }
367

    
368
        /**
369
         * Establece una cadena como comentarios al proyecto
370
         *
371
         * @param string
372
         */
373
        public void setComments(String string) {
374
                comments = string;
375
                //modified = true;
376
                change.firePropertyChange("", null, null);
377
        }
378

    
379
        /**
380
         * Establece la fecha de la �ltima modificaci�n
381
         *
382
         * @param string
383
         */
384
        public void setModificationDate(String string) {
385
                modificationDate = string;
386
                //modified = true;
387
                change.firePropertyChange("", null, null);
388
        }
389

    
390
        /**
391
         * Establece el propietario del proyecto
392
         *
393
         * @param string
394
         */
395
        public void setOwner(String string) {
396
                owner = string;
397
                //modified = true;
398
                change.firePropertyChange("", null, null);
399
        }
400

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

    
416
        /**
417
         * Obtiene el color de selecci�n que se usar� en el proyecto
418
         *
419
         * @return
420
         */
421
        public Color getSelectionColor() {
422
                if (selectionColor == null) {
423
                        selectionColor = defaultSelectionColor;
424
                }
425
                return selectionColor;
426
        }
427

    
428
        /**
429
         * Establece el color de selecci�n
430
         *
431
         * @param color
432
         */
433
        public void setSelectionColor(Color color) {
434
                selectionColor = color;
435
                MapContext.setSelectionColor(color);
436
                //modified = true;
437
                change.firePropertyChange("selectionColor", null, color);
438
        }
439

    
440
        /**
441
         * Obtiene el color como un entero para su serializaci�n a XML
442
         *
443
         * @return
444
         */
445
        public String getColor() {
446
                return StringUtilities.color2String(selectionColor);
447
        }
448

    
449
        /**
450
         * M�todo invocado al recuperar de XML para establecer el color de seleccion
451
         * del proyecto
452
         *
453
         * @param color
454
         *            Entero que representa un color
455
         */
456
        public void setColor(String color) {
457
                //modified = true;
458
                selectionColor = StringUtilities.string2Color(color);
459
        }
460

    
461
        /*
462
         * (non-Javadoc)
463
         *
464
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
465
         */
466
        public void propertyChange(PropertyChangeEvent evt) {
467
                //this.modified = true;
468
                change.firePropertyChange(evt);
469
        }
470

    
471
        /**
472
         * DOCUMENT ME!
473
         *
474
         * @param arg1
475
         */
476
        public void addExtent(ProjectExtent arg1) {
477
                extents.add(arg1);
478
                //modified = true;
479
                change.firePropertyChange("addExtent", null, null);
480
        }
481

    
482
        /**
483
         * DOCUMENT ME!
484
         *
485
         * @param arg0
486
         *
487
         * @return
488
         */
489
        public Object removeExtent(int arg0) {
490
                //modified = true;
491
                change.firePropertyChange("delExtent", null, null);
492

    
493
                return extents.remove(arg0);
494
        }
495

    
496
        /**
497
         * DOCUMENT ME!
498
         *
499
         * @return DOCUMENT ME!
500
         */
501
        public ProjectExtent[] getExtents() {
502
                return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
503
        }
504

    
505
        /**
506
         * Metodo que a�ade una nueva camera a la lista de cameras
507
         *
508
         * @param arg1
509
         *            camera introducida
510
         */
511
        public void addCamera(Object arg1) {
512
                this.cameras.add(arg1);
513
                //modified = true;
514
                change.firePropertyChange("addCamera", null, null);
515
        }
516

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

    
529
                return this.cameras.remove(arg0);
530
        }
531

    
532
        /**
533
         * Metodo que devuelve la lista de cameras
534
         *
535
         * @return lista de objetos de tipo camera
536
         */
537
        public Object[] getCameras() {
538
                return (Object[]) this.cameras.toArray(new Object[0]);
539
        }
540

    
541
        /**
542
         * DOCUMENT ME!
543
         *
544
         * @param arg0
545
         */
546
        public synchronized void addPropertyChangeListener(
547
                        PropertyChangeListener arg0) {
548
                change.addPropertyChangeListener(arg0);
549
        }
550

    
551
        /**
552
         * DOCUMENT ME!
553
         *
554
         * @deprecated utilizar getDocument(String s);
555
         * @return
556
         */
557
        public ArrayList getMaps() {
558
                return getDocumentsByType(ProjectMapFactory.registerName);
559
        }
560

    
561
        /**
562
         * DOCUMENT ME!
563
         *
564
         * @deprecated utilizar getDocument(String s);
565
         * @return
566
         */
567
        public ArrayList getTables() {
568
                return getDocumentsByType(ProjectTableFactory.registerName);
569
        }
570

    
571
        /**
572
         * DOCUMENT ME!
573
         *
574
         * @deprecated utilizar getDocument(String s);
575
         * @return
576
         */
577
        public ArrayList getViews() {
578
                return getDocumentsByType(ProjectViewFactory.registerName);
579
        }
580

    
581
        /**
582
         * A�ade un mapa al proyecto
583
         *
584
         * @deprecated utilizar addDocument(ProjectDocument pD);
585
         * @param m
586
         */
587
        public void addMap(ProjectMap m) {
588
                addDocument(m);
589
        }
590

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

    
603
        /**
604
         * A�ade una tabla al proyecto
605
         *
606
         * @deprecated utilizar addDocument(ProjectDocument pD);
607
         * @param t
608
         */
609
        public void addTable(ProjectTable t) {
610
                addDocument(t);
611
        }
612

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

    
625
        /**
626
         * A�ade una vista al proyecto
627
         *
628
         * @deprecated utilizar addDocument(ProjectDocument pD);
629
         * @param v
630
         */
631
        public void addView(ProjectView v) {
632
                addDocument(v);
633
        }
634

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

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

    
662
                int numExtents = extents.size();
663
                xml.putProperty("numExtents", numExtents);
664

    
665
                for (int i = 0; i < numExtents; i++) {
666
                        xml.addChild(((ProjectExtent) extents.get(i)).getXMLEntity());
667
                }
668

    
669
                // Guardando propiedades de las camaras
670
                int numCameras = this.cameras.size();
671
                xml.putProperty("numCameras", numCameras);
672

    
673
                for (int i = 0; i < numCameras; i++) {
674
                        xml.addChild(((IPersistence) this.cameras.get(i)).getXMLEntity());
675
                }
676

    
677
                // NUEVO: ESTO ESTA EN PRUEBAS. SIRVE PARA
678
                // BORRAR LAS REFERENCIAS A DATASOURCES QUE HEMOS
679
                // BORRADO. Hay que probar a borrarlos cuando se
680
                // borra una tabla y cuando se borra una capa.
681
                try {
682
                        cleanBadReferences();
683
                }catch (Exception e) {
684
                        NotificationManager.addError("clean_bad_references",e);
685
                }
686
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
687
                                .getDriverInfos();
688
                xml.putProperty("data-source-count", infos.length);
689

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

    
732
                saveWindowProperties(xml);
733
                return xml;
734
        }
735

    
736
        private void saveWindowProperties(XMLEntity xml) {
737
                XMLEntity propertyList = new XMLEntity();
738

    
739
                propertyList.setName("AndamiPersistence");
740
                propertyList.putProperty("className", Project.class.getName(), false);
741

    
742
                boolean projectWindowSaved = false;
743

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

    
795
                                                // TODO this will be generalized to all ProjectDocuments as soon as possible
796
//                                                if (viewWindow instanceof BaseView) {
797
//                                                        BaseView win = (BaseView) viewWindow;
798
//                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
799
//                                                }
800
                                                if (viewWindow instanceof IDocumentWindow) {
801
                                                        IDocumentWindow win = (IDocumentWindow) viewWindow;
802
                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
803
                                                }
804

    
805
                                                propertyList.addChild(windowProperties);
806
                                        }
807
                                }
808
                        }
809
                }
810

    
811
                if (projectWindowSaved == false) {
812
                        // If the Project Manager was closed, it was not in the
813
                        // previous window list. Save it now
814
                        ProjectExtension pe = (ProjectExtension) PluginServices
815
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
816

    
817
                        if (pe != null) {
818
                                IWindow projectWindow = pe.getProjectWindow();
819
                                wi = PluginServices.getMDIManager()
820
                                                .getWindowInfo(projectWindow);
821
                                if (wi != null && wi.checkPersistence()) {
822
                                        windowProperties = wi.getXMLEntity();
823
                                        if (windowProperties != null) {
824
                                                windowProperties
825
                                                                .putProperty("className",
826
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow", false);
827
                                                propertyList.addChild(windowProperties);
828
                                        }
829
                                }
830
                        }
831
                }
832

    
833
                xml.addChild(propertyList);
834
        }
835

    
836
        /**
837
         * Store the initial window properties, to later restore the window sizes
838
         * and positions
839
         */
840
        private void storeInitialWindowProperties(XMLEntity xml) {
841
                XMLEntity child;
842
                int childNumb;
843

    
844
                // order the window properties before restoring them, so that we also
845
                // restore the zPosition
846
                TreeMap orderedProperties = new TreeMap();
847
                int maximum = 1;
848
                for (childNumb = xml.getChildrenCount() - 1; childNumb >= 0; childNumb--) {
849
                        child = xml.getChild(childNumb);
850
                        if (child.contains("zPosition")) {
851
                                orderedProperties.put(new Integer(-child
852
                                                .getIntProperty("zPosition")), child); // reverse the
853
                                // order, so
854
                                // that we add
855
                                // the back
856
                                // windows first
857
                        } else {
858
                                orderedProperties.put(new Integer(maximum++), child); // the
859
                                // windows
860
                                // without
861
                                // zPosition
862
                                // will
863
                                // be on
864
                                // the
865
                                // fore
866
                        }
867
                }
868

    
869
                this.initialWindowProperties = orderedProperties.values().iterator();
870
        }
871

    
872
        /**
873
         * Store the initial window properties, to later restore the window sizes
874
         * and positions
875
         */
876
        private void storeInitialWindowProperties061(XMLEntity xml) {
877
                XMLEntity child;
878
                int childNumb = 0;
879
                ArrayList windowList = new ArrayList();
880

    
881
                child = xml.getChild(xml.getChildrenCount() - 1);
882
                if (child.contains("className")
883
                                && child.getStringProperty("className").equals(
884
                                                "com.iver.cit.gvsig.project.Project")
885
                                && child.contains("name")
886
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
887
                        child.putProperty("className",
888
                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
889
                        windowList.add(child);
890
                }
891

    
892
                // try to open the views
893
                if (xml.contains("numExtents"))
894
                        childNumb += xml.getIntProperty("numExtents");
895
                if (xml.contains("data-source-count"))
896
                        childNumb += xml.getIntProperty("data-source-count");
897
                int limit = 0;
898
                if (xml.contains("numViews"))
899
                        limit = xml.getIntProperty("numViews")+childNumb;
900

    
901
                XMLEntity view;
902
                for (int i = childNumb; i < limit; i++) {
903
                        view = xml.getChild(i);
904
                        child = view.getChild(view.getChildrenCount() - 1);
905
                        if (child.contains("className")
906
                                        && child.getStringProperty("className").equals(
907
                                                        "com.iver.cit.gvsig.project.ProjectView")
908
                                        && child.contains("name")
909
                                        && child.getStringProperty("name").equals(
910
                                                        "ViewInfoProperties")) {
911
                                child.putProperty("documentName", view
912
                                                .getStringProperty("name"));
913
                                child.putProperty("documentType",
914
                                                ProjectViewFactory.registerName);
915
                                windowList.add(child);
916
                        }
917
                }
918

    
919
                if (xml.contains("numViews"))
920
                        childNumb += xml.getIntProperty("numViews");
921

    
922
                if (xml.contains("numMaps"))
923
                        limit = childNumb + xml.getIntProperty("numMaps");
924

    
925
                // try to open the maps
926
                XMLEntity map;
927
                for (int i = childNumb; i < limit; i++) {
928
                        map = xml.getChild(i);
929
                        for (int j = 0; j < map.getChildrenCount(); j++) {
930
                                child = map.getChild(j);
931
                                if (child.contains("className")
932
                                                && child.getStringProperty("className").equals(
933
                                                                "com.iver.cit.gvsig.project.ProjectMap")
934
                                                && child.contains("name")
935
                                                && child.getStringProperty("name").equals(
936
                                                                "ViewInfoProperties")) {
937
                                        child.putProperty("documentName", map
938
                                                        .getStringProperty("name"));
939
                                        child.putProperty("documentType",
940
                                                        ProjectMapFactory.registerName);
941
                                        windowList.add(child);
942
                                }
943
                        }
944
                }
945

    
946
                this.initialWindowProperties = windowList.iterator();
947
        }
948

    
949
        /**
950
         * Restores the size, position and order of the windows, according to
951
         * variable initialWindowProperties. If this variable is null, the method
952
         * just opens the project manager window.
953
         *
954
         */
955
        public void restoreWindowProperties() {
956
                boolean projectWindowRestored = false;
957
                XMLEntity child;
958

    
959
                Iterator propertiesIterator = this.initialWindowProperties;
960
                if (propertiesIterator != null) {
961
                        this.initialWindowProperties = null;
962

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

    
1024
                if (!projectWindowRestored) { // if the project window was not stored
1025
                        // in the project, open it now
1026
                        ProjectExtension pe = (ProjectExtension) PluginServices
1027
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1028

    
1029
                        if (pe != null) {
1030
                                pe.setProject(this);
1031
                                pe.showProjectWindow();
1032
                        }
1033
                }
1034
        }
1035

    
1036
        /**
1037
         * DOCUMENT ME!
1038
         *
1039
         * @param xml
1040
         *            DOCUMENT ME!
1041
         *
1042
         * @return DOCUMENT ME!
1043
         * @throws XMLException
1044
         * @throws DriverException
1045
         * @throws DriverIOException
1046
         * @throws OpenException
1047
         */
1048
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1049
                Project p = new Project();
1050
                try {
1051
                        p.comments = xml.getStringProperty("comments");
1052
                        p.creationDate = xml.getStringProperty("creationDate");
1053

    
1054
                        int numExtents = xml.getIntProperty("numExtents");
1055
                        for (int i = 0; i < numExtents; i++) {
1056
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1057
                                                .getChild(i));
1058
                                p.extents.add(pe);
1059
                        }
1060

    
1061
                        int numDocuments = 0;
1062
                        if (xml.contains("numDocuments")) {
1063
                                numDocuments = xml.getIntProperty("numDocuments");
1064
                        } else {
1065
                                int numViews = xml.getIntProperty("numViews");
1066
                                int numMaps = xml.getIntProperty("numMaps");
1067
                                int numTables = xml.getIntProperty("numTables");
1068
                                numDocuments = numViews + numMaps + numTables;
1069
                        }
1070
                        for (int i = numExtents; i < numDocuments + numExtents; i++) {
1071
                                ProjectDocument pD = ProjectDocument.createFromXML03(xml
1072
                                                .getChild(i), p);
1073
                                p.addDocument(pD);
1074
                                p.sortedDocuments.put(pD, new Integer(i));
1075
                        }
1076
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1077
                                        .keySet().toArray(new ProjectDocument[0]);
1078
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1079
                                        .toArray(new Integer[0]);
1080

    
1081
                        int i = 0;
1082
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1083
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1084
                                                .intValue()));
1085
                                i++;
1086
                        }
1087

    
1088
                        p.modificationDate = xml.getStringProperty("modificationDate");
1089
                        //p.modified = xml.getBooleanProperty("modified");
1090
                        p.name = xml.getStringProperty("name");
1091
                        p.owner = xml.getStringProperty("owner");
1092
                        p.selectionColor = StringUtilities.string2Color(xml
1093
                                        .getStringProperty("selectionColor"));
1094

    
1095
                        String strProj = xml.getStringProperty("projection");
1096
                        if (strProj != null)
1097
                                p.setProjection(CRSFactory.getCRS(strProj));
1098
                } catch (Exception e) {
1099
                        throw new OpenException(e, p.getClass().getName());
1100
                }
1101
                return p;
1102
        }
1103

    
1104
        /**
1105
         * DOCUMENT ME!
1106
         *
1107
         * @param xml
1108
         *            DOCUMENT ME!
1109
         *
1110
         * @return DOCUMENT ME!
1111
         *
1112
         * @throws XMLException
1113
         * @throws DriverException
1114
         * @throws DriverIOException
1115
         * @throws OpenException
1116
         * @throws VersionException
1117
         */
1118
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1119

    
1120
                int childNumber = 0;
1121
                Project p = new Project();
1122

    
1123
                try {
1124
                        p.comments = xml.getStringProperty("comments");
1125
                        p.creationDate = xml.getStringProperty("creationDate");
1126
                        int numExtents = xml.getIntProperty("numExtents");
1127

    
1128
                        for (int i = 0; i < numExtents; i++) {
1129
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1130
                                p.extents.add(pe);
1131
                        }
1132

    
1133
                        // Leemos el ultiom hijo recogido
1134
                        childNumber = numExtents;
1135

    
1136
                        // Recogiendo el numero de cameras
1137
                        int numCameras = 0;
1138
                        if (xml.contains("numCameras"))
1139
                                numCameras = xml.getIntProperty("numCameras");
1140

    
1141
                        // Recogiendo todo las camaras
1142
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1143
                                XMLEntity xmlProp = xml.getChild(i);
1144
                                try {
1145
                                        String className = xmlProp.getStringProperty("className");
1146
                                        Class classProp = Class.forName(className);
1147
                                        Object obj = classProp.newInstance();
1148
                                        IPersistence objPersist = (IPersistence) obj;
1149
                                        objPersist.setXMLEntity(xmlProp);
1150
                                        p.cameras.add(obj);
1151
                                } catch (Exception e) {
1152
                                        continue;
1153
                                }
1154
                        }
1155

    
1156
                        childNumber += numCameras;
1157

    
1158
                        int numDataSources = xml.getIntProperty("data-source-count");
1159

    
1160
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1161
                                XMLEntity child = xml.getChild(i);
1162
                                registerDataSourceFromXML(child);
1163
                        }
1164

    
1165
                        childNumber += numDataSources;
1166
                        int numDocuments = 0;
1167
                        if (xml.contains("numDocuments")) {
1168
                                numDocuments = xml.getIntProperty("numDocuments");
1169
                        } else {
1170
                                int numViews = xml.getIntProperty("numViews");
1171
                                int numMaps = xml.getIntProperty("numMaps");
1172
                                int numTables = xml.getIntProperty("numTables");
1173
                                numDocuments = numViews + numMaps + numTables;
1174
                        }
1175

    
1176
                        for (int i = childNumber; i < (numDocuments + childNumber); i++) {
1177
                                try {
1178
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1179
                                                        .getChild(i), p);
1180
                                        p.addDocument(pD);
1181
                                        p.sortedDocuments.put(pD, new Integer(i));
1182
                                } catch (OpenException e) {
1183
                                        e.showError();
1184
                                }
1185
                        }
1186
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1187
                                        .keySet().toArray(new ProjectDocument[0]);
1188
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1189
                                        .toArray(new Integer[0]);
1190

    
1191
                        int i = 0;
1192
                        for (int k = childNumber; k < (numDocuments + childNumber); k++) {
1193
                                try {
1194
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1195
                                                        .intValue()));
1196
                                } catch (OpenException e) {
1197
                                        e.showError();
1198
                                }
1199
                                i++;
1200
                        }
1201
                        childNumber += numDocuments;
1202

    
1203
                        p.modificationDate = xml.getStringProperty("modificationDate");
1204
                        //p.modified = xml.getBooleanProperty("modified");
1205
                        p.name = xml.getStringProperty("name");
1206
                        p.owner = xml.getStringProperty("owner");
1207
                        p.selectionColor = StringUtilities.string2Color(xml
1208
                                        .getStringProperty("selectionColor"));
1209

    
1210
                        p.setLinkTable();
1211
                        String strProj = xml.getStringProperty("projection");
1212

    
1213
                        if (strProj != null) {
1214
                                p.setProjection(CRSFactory.getCRS(strProj));
1215
                        }
1216

    
1217
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1218
                                // of the windows
1219
                                XMLEntity child = xml.getChild(childNumber);
1220
                                if (child.contains("name")
1221
                                                && child.getStringProperty("name").equals(
1222
                                                                "AndamiPersistence")) {
1223
                                        p.storeInitialWindowProperties(child);
1224
                                } else if (child.contains("className")
1225
                                                && child.getStringProperty("className").equals(
1226
                                                                "com.iver.cit.gvsig.project.Project")
1227
                                                && child.contains("name")
1228
                                                && child.getStringProperty("name").equals(
1229
                                                                "ViewInfoProperties")) {
1230
                                        p.storeInitialWindowProperties061(xml);
1231
                                }
1232
                        }
1233

    
1234
                        PostProcessSupport.executeCalls();
1235
                } catch (Exception e) {
1236
                        throw new OpenException(e, p.getClass().getName());
1237
                }
1238

    
1239
                return p;
1240

    
1241
        }
1242

    
1243
        /**
1244
         * Reestablece los link que ten�a cada tabla con las dem�s.
1245
         */
1246
        public void setLinkTable() {
1247
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1248

    
1249
                for (int i = 0; i < tables.size(); i++) {
1250
                        for (int j = 0; j < tables.size(); j++) {
1251
                                /*
1252
                                 * System.out.println("name = " + ((ProjectTable)
1253
                                 * tables.get(j)).getModelo().getName());
1254
                                 * System.out.println("linktable = " + ((ProjectTable)
1255
                                 * tables.get(i)).getLinkTable());
1256
                                 */
1257
                                try {
1258
                                        if ((((ProjectTable) tables.get(i)).getLinkTable() != null)
1259
                                                        && ((ProjectTable) tables.get(i)).getLinkTable()
1260
                                                        .equals(
1261
                                                                        ((ProjectTable) tables.get(j))
1262
                                                                        .getModelo().getRecordset()
1263
                                                                        .getName())) {
1264
                                                LinkSelectionListener lsl;
1265

    
1266
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1267
                                                                .get(i)).getModelo().getRecordset(),
1268
                                                                ((ProjectTable) tables.get(j)).getModelo()
1269
                                                                .getRecordset(), ((ProjectTable) tables
1270
                                                                                .get(i)).getField1(),
1271
                                                                                ((ProjectTable) tables.get(i)).getField2());
1272

    
1273
                                                (((ProjectTable) tables.get(i)).getModelo()
1274
                                                                .getRecordset()).addSelectionListener(lsl);
1275

    
1276
                                        }
1277
                                } catch (ReadDriverException e) {
1278
                                        e.printStackTrace();
1279
                                }
1280
                        }
1281
                }
1282
        }
1283

    
1284
        /**
1285
         * Obtiene la vista que contiene a la capa que se pasa como par�metro
1286
         *
1287
         * @param layer
1288
         *            Capa cuya vista se quiere obtener
1289
         *
1290
         * @return
1291
         *
1292
         * @throws RuntimeException
1293
         *             Si la capa que se pasa como par�metro no se encuentra en
1294
         *             ninguna vista
1295
         */
1296
        public String getView(FLayer layer) {
1297
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1298
                for (int v = 0; v < views.size(); v++) {
1299
                        ProjectView pView = (ProjectView) views.get(v);
1300
                        FLayers layers = pView.getMapContext().getLayers();
1301
                        if (isView(layers, layer))
1302
                                return pView.getName();
1303
                }
1304

    
1305
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1306
        }
1307

    
1308
        public boolean isView(FLayers layers, FLayer layer) {
1309
                for (int i = 0; i < layers.getLayersCount(); i++) {
1310
                        if (layers.getLayer(i) instanceof FLayers) {
1311
                                return isView((FLayers) layers.getLayer(i), layer);
1312
                        }
1313
                        if (layers.getLayer(i) == layer) {
1314
                                return true;
1315
                        }
1316
                }
1317
                return false;
1318
        }
1319

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

    
1350
        /**
1351
         * DOCUMENT ME!
1352
         *
1353
         * @param defaultProjection
1354
         *            DOCUMENT ME!
1355
         */
1356
        public void setProjection(IProjection projection) {
1357
                this.projection = projection;
1358
        }
1359

    
1360
        /**
1361
         * Sets the projection used when no projection is defined
1362
         *
1363
         * @param defaultProjection
1364
         *            DOCUMENT ME!
1365
         */
1366
        public static void setDefaultProjection(IProjection defaultProjection) {
1367
                Project.defaultProjection = defaultProjection;
1368
        }
1369

    
1370
        public static IProjection getDefaultProjection() {
1371
                if (defaultProjection == null){
1372
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1373
                        .getPersistentXML();
1374

    
1375
                        // Default Projection
1376
                        String projCode = null;
1377
                        if (xml.contains("DefaultProjection")) {
1378
                                projCode = xml.getStringProperty("DefaultProjection");
1379
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1380
                        } else {
1381
                                Project.setDefaultProjection(defaultFactoryProjection);
1382
                        }
1383

    
1384
                }
1385
                return Project.defaultProjection;
1386
        }
1387

    
1388
        /**
1389
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1390
         * pointExtension, este �ltimo se puede obtener del
1391
         * Project****Factory.registerName.
1392
         *
1393
         * @param name
1394
         *            Nombre del documento
1395
         * @param type
1396
         *            nombre de registro en el extensionPoint
1397
         *
1398
         * @return Documento
1399
         */
1400
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1401
                ArrayList docs = getDocumentsByType(type);
1402
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1403
                        ProjectDocument elem = (ProjectDocument) iter.next();
1404

    
1405
                        if (elem.getName().equals(name)) {
1406
                                return elem;
1407
                        }
1408
                }
1409

    
1410
                return null;
1411
        }
1412

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

    
1461
                if (dataSource == null) {
1462
                        // No se ha creado la tabla asociada al tema
1463
                        dataSource = ((AlphanumericData) layer).getRecordset();
1464
                }
1465

    
1466
                return dataSource;
1467

    
1468
        }
1469

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

    
1488
                                ds = t.getModelo().getRecordset();
1489

    
1490
                                if (t.getOriginal() != null)
1491
                                        usedDataSources.put(t.getOriginal().getRecordset()
1492
                                                        .getName(), t.getOriginal());
1493
                                usedDataSources.put(ds.getName(), ds);
1494
                        }
1495
                } catch (ReadDriverException e) {
1496
                        e.printStackTrace();
1497
                }
1498
                // Ahora las vistas
1499
                ProjectView pv;
1500
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1501
                try {
1502
                        for (i = 0; i < views.size(); i++) {
1503
                                pv = (ProjectView) views.get(i);
1504
                                this.findLayersVectDataSorces(pv.getMapContext(), usedDataSources);
1505

    
1506
                                MapContext aux = pv.getMapOverViewContext();
1507
                                if (aux != null) {
1508
                                        this.findLayersVectDataSorces(aux, usedDataSources);
1509
                                }
1510

    
1511
                        } // for i
1512

    
1513
                } catch (ReadDriverException e) {
1514
                        e.printStackTrace();
1515
                }
1516

    
1517
                // Ahora los mapas
1518
                ArrayList maps = getDocumentsByType(ProjectMapFactory.registerName);
1519
                ProjectMap pm;
1520
                LayoutContext lContext;
1521
                IFFrame[] fframes;
1522
                try {
1523
                        for (i = 0; i < maps.size(); i++) {
1524
                                pm = (ProjectMap) maps.get(i);
1525
                                fframes = pm.getModel().getLayoutContext().getFFrames();
1526
                                for (j=0;j < fframes.length; j++){
1527
                                        if (!(fframes[j] instanceof FFrameView)){
1528
                                                continue;
1529
                                        }
1530
                                        this.findLayersVectDataSorces(((FFrameView)fframes[i]).getMapContext(), usedDataSources);
1531
                                } //for j
1532

    
1533
                        } // for i
1534

    
1535
                } catch (ReadDriverException e) {
1536
                        e.printStackTrace();
1537
                }
1538

    
1539

    
1540
                // Recorremos los dataSources y los borramos si no
1541
                // los estamos usando.
1542
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1543
                                .getDriverInfos();
1544
                try {
1545
                        for (i = 0; i < infos.length; i++) {
1546
                                if (!usedDataSources.containsKey(infos[i].name)) {
1547
                                        DataSource ds;
1548
                                        ds = LayerFactory.getDataSourceFactory()
1549
                                                        .createRandomDataSource(infos[i].name);
1550
                                        ds.remove();
1551
                                }
1552
                        }
1553
                } catch (DriverLoadException e) {
1554
                        e.printStackTrace();
1555
                } catch (NoSuchTableException e) {
1556
                        e.printStackTrace();
1557
                } catch (ReadDriverException e) {
1558
                        e.printStackTrace();
1559
                } catch (WriteDriverException e) {
1560
                        e.printStackTrace();
1561
                }
1562
        }
1563

    
1564
        private void findLayersVectDataSorces(MapContext mapContext,Map dataSourcesMap) throws ReadDriverException{
1565
                LayersIterator iter = new LayersIterator(mapContext.getLayers()){
1566

    
1567
                        //@Override
1568
                        public boolean evaluate(FLayer layer) {
1569
                                if (!(layer instanceof FLyrVect))
1570
                                        return false;
1571
                                return super.evaluate(layer);
1572
                        }
1573

    
1574
                };
1575
                FLyrVect layer;
1576
                while (iter.hasNext()){
1577
                        layer = (FLyrVect)iter.nextLayer();
1578
                        dataSourcesMap.put(layer.getRecordset().getName(), layer.getRecordset());
1579
                        if (layer.isJoined()){
1580
                                dataSourcesMap.put(layer.getSource().getRecordset().getName(),layer.getSource().getRecordset());
1581
                        }
1582

    
1583
                }
1584
        }
1585

    
1586
        /**
1587
         * DOCUMENT ME!
1588
         *
1589
         * @return DOCUMENT ME!
1590
         * @throws SaveException
1591
         * @throws XMLException
1592
         * @throws SaveException
1593
         */
1594
        public XMLEntity getWindowInfoXMLEntity(IWindow window)
1595
                        throws SaveException {
1596
                if (window != null
1597
                                && PluginServices.getMDIManager().getWindowInfo(window) != null) {
1598
                        WindowInfo vi = PluginServices.getMDIManager()
1599
                                        .getWindowInfo(window);
1600
                        XMLEntity xml = new XMLEntity();
1601
                        // xml.putProperty("nameClass", this.getClass().getName());
1602
                        try {
1603
                                xml.setName("ViewInfoProperties");
1604
                                xml.putProperty("className", this.getClass().getName());
1605
                                xml.putProperty("X", vi.getX());
1606
                                xml.putProperty("Y", vi.getY());
1607
                                xml.putProperty("Width", vi.getWidth());
1608
                                xml.putProperty("Height", vi.getHeight());
1609
                                xml.putProperty("isVisible", vi.isVisible());
1610
                                xml.putProperty("isResizable", vi.isResizable());
1611
                                xml.putProperty("isMaximizable", vi.isMaximizable());
1612
                                xml.putProperty("isModal", vi.isModal());
1613
                                xml.putProperty("isModeless", vi.isModeless());
1614
                                xml.putProperty("isClosed", vi.isClosed());
1615
                                if (vi.isMaximized() == true) {
1616
                                        xml.putProperty("isMaximized", vi.isMaximized());
1617
                                        xml.putProperty("normalX", vi.getNormalX());
1618
                                        xml.putProperty("normalY", vi.getNormalY());
1619
                                        xml.putProperty("normalWidth", vi.getNormalWidth());
1620
                                        xml.putProperty("normalHeight", vi.getNormalHeight());
1621
}
1622
                        } catch (Exception e) {
1623
                                throw new SaveException(e, this.getClass().getName());
1624
                        }
1625
                        return xml;
1626
                }
1627
                return null;
1628
        }
1629

    
1630
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1631
                WindowInfo result = new WindowInfo();
1632
                result.setX(xml.getIntProperty("X"));
1633
                result.setY(xml.getIntProperty("Y"));
1634
                result.setHeight(xml.getIntProperty("Height"));
1635
                result.setWidth(xml.getIntProperty("Width"));
1636
                result.setClosed(xml.getBooleanProperty("isClosed"));
1637
                if (xml.contains("isMaximized")) {
1638
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1639
                        result.setMaximized(maximized);
1640
                        if (maximized == true) {
1641
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1642
                                                .getIntProperty("normalY"), xml
1643
                                                .getIntProperty("normalWidth"), xml
1644
                                                .getIntProperty("normalHeight"));
1645
                        } else {
1646
                                result.setNormalBounds(result.getBounds());
1647
                        }
1648
                }
1649

    
1650
                return result;
1651
        }
1652

    
1653
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1654
                XMLEntity child = new XMLEntity();
1655

    
1656
                if (di instanceof ObjectSourceInfo) {
1657
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1658
                        child.putProperty("type", "sameDriverFile");
1659
                        child.putProperty("gdbmsname", driver.name);
1660
                } else if (di instanceof FileSourceInfo) {
1661
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1662
                        child.putProperty("type", "otherDriverFile");
1663
                        child.putProperty("gdbmsname", vfdi.name);
1664
                        child.putProperty("file", vfdi.file);
1665
                        child.putProperty("driverName", vfdi.driverName);
1666
                } else if (di instanceof DBSourceInfo) {
1667
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1668
                        child.putProperty("type", "db");
1669
                        child.putProperty("gdbmsname", dbdi.name);
1670
                        child.putProperty("dbms", dbdi.dbms);
1671
                        child.putProperty("host", dbdi.host);
1672
                        child.putProperty("port", dbdi.port);
1673
                        child.putProperty("user", dbdi.user);
1674
                        child.putProperty("password", dbdi.password);
1675
                        child.putProperty("dbName", dbdi.dbName);
1676
                        child.putProperty("tableName", dbdi.tableName);
1677
                        child.putProperty("driverInfo", dbdi.driverName);
1678
                }
1679

    
1680
                return child;
1681
        }
1682

    
1683
        /**
1684
         * Devuelve un arrayList con todos los documentos del tipo especificado como
1685
         * par�metro.
1686
         *
1687
         * @param registerName
1688
         *            nombre de registro en el extensionPoint
1689
         *
1690
         * @return Documentos del tipo especificado
1691
         */
1692
        public ArrayList getDocumentsByType(String registerName) {
1693
                ArrayList docuArray = new ArrayList();
1694
                for (int i = 0; i < documents.size(); i++) {
1695
                        ProjectDocument projectDocument = (ProjectDocument) documents
1696
                                        .get(i);
1697
                        ProjectDocumentFactory pdf = projectDocument
1698
                                        .getProjectDocumentFactory();
1699
                        if (pdf == null)
1700
                                continue;
1701
                        if (pdf.getRegisterName().equals(registerName)) {
1702
                                docuArray.add(projectDocument);
1703
                        }
1704
                }
1705
                return docuArray;
1706
        }
1707

    
1708
        /**
1709
         * Devuelve un arrayList con todos los documentos.
1710
         *
1711
         * @return Documentos
1712
         */
1713
        public ArrayList getDocuments() {
1714
                ArrayList docuArray = new ArrayList();
1715
                for (int i = 0; i < documents.size(); i++) {
1716
                        ProjectDocument projectDocument = (ProjectDocument) documents
1717
                                        .get(i);
1718
                        docuArray.add(projectDocument);
1719
                }
1720
                return docuArray;
1721
        }
1722

    
1723
        /**
1724
         * Inserta un documento.
1725
         *
1726
         * @param doc
1727
         *            Documento
1728
         */
1729
        public void addDocument(ProjectDocument doc) {
1730
                documents.add(doc);
1731
                doc.addPropertyChangeListener(this);
1732
                //modified = true;
1733
                change.firePropertyChange("", "", null);
1734
                doc.setProject(this, 0);
1735
                doc.afterAdd();
1736

    
1737
        }
1738

    
1739
        /**
1740
         * Borra un documento.
1741
         *
1742
         * @param doc
1743
         *            Documento
1744
         */
1745
        public void delDocument(ProjectDocument doc) {
1746
                documents.remove(doc);
1747
                //modified = true;
1748
                change.firePropertyChange("", null, null);
1749
                doc.afterRemove();
1750
        }
1751

    
1752
        /**
1753
         * Sets the default selection color that will be used in subsequent
1754
         * projects.
1755
         *
1756
         * @param color
1757
         */
1758
        public static void setDefaultSelectionColor(Color color) {
1759
                defaultSelectionColor = color;
1760
        }
1761

    
1762
        /**
1763
         * Returns the current default selection color defined which is the color
1764
         * defined when the user does not define any other one
1765
         *
1766
         * @return java.awt.Color
1767
         */
1768
        public static Color getDefaultSelectionColor() {
1769
                // TODO es millorable?
1770
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1771
                                .getPersistentXML();
1772
                if (xml.contains("DefaultSelectionColor"))
1773
                        defaultSelectionColor = StringUtilities.string2Color(xml
1774
                                        .getStringProperty("DefaultSelectionColor"));
1775
                return defaultSelectionColor;
1776
        }
1777

    
1778
        /**
1779
         * Returns the user's default map units. This is the cartography data
1780
         * distance units.
1781
         *
1782
         * @return int (index of the <b>Attributes.NAMES array</b>)
1783
         */
1784
        public static int getDefaultMapUnits() {
1785
                if (defaultMapUnits == -1) {
1786
                        XMLEntity xml = PluginServices.getPluginServices(
1787
                                        "com.iver.cit.gvsig").getPersistentXML();
1788
                        if (xml.contains("DefaultMapUnits")) {
1789
                                defaultMapUnits = xml.getIntProperty("DefaultMapUnits");
1790
                        } else {
1791
                                // first app run case
1792
                                String[] unitNames = MapContext.NAMES;
1793
                                for (int i = 0; i < unitNames.length; i++) {
1794
                                        // meter is the factory default's map unit
1795
                                        if (unitNames[i].equals(PluginServices.getText(
1796
                                                        Project.class, "Metros"))) {
1797
                                                defaultMapUnits = i;
1798
                                                break;
1799
                                        }
1800
                                }
1801
                        }
1802
                        if (defaultMapUnits == -1)
1803
                                defaultMapUnits = ViewPort.METROS;
1804
                }
1805
                return defaultMapUnits;
1806
        }
1807

    
1808
        /**
1809
         * Returns the user's default view units for measuring distances. This is
1810
         * the units that the user will see in the status bar of the view.
1811
         *
1812
         * @return int (index of the <b>Attributes.NAMES array</b>)
1813
         */
1814
        public static int getDefaultDistanceUnits() {
1815
                if (defaultDistanceUnits == -1) {
1816
                        XMLEntity xml = PluginServices.getPluginServices(
1817
                                        "com.iver.cit.gvsig").getPersistentXML();
1818
                        if (xml.contains("DefaultDistanceUnits")) {
1819
                                defaultDistanceUnits = xml
1820
                                                .getIntProperty("DefaultDistanceUnits");
1821
                        } else {
1822
                                // first app run case
1823
                                String[] unitNames = MapContext.NAMES;
1824
                                for (int i = 0; i < unitNames.length; i++) {
1825
                                        // meter is the factory default's distance unit
1826
                                        if (unitNames[i].equals("Metros")) {
1827
                                                defaultDistanceUnits = i;
1828
                                                break;
1829
                                        }
1830
                                }
1831
                        }
1832
                        if (defaultDistanceUnits == -1)
1833
                                defaultDistanceUnits = ViewPort.METROS;
1834
                }
1835
                return defaultDistanceUnits;
1836
        }
1837

    
1838
        /**
1839
         * Sets the default map unit (the units used by the data).
1840
         *
1841
         * @param mapUnits
1842
         */
1843
        public static void setDefaultMapUnits(int mapUnits) {
1844
                defaultMapUnits = mapUnits;
1845
        }
1846

    
1847
        /**
1848
         * Sets the default distance units (the units shown in the status bar)
1849
         *
1850
         * @param distanceUnits
1851
         */
1852
        public static void setDefaultDistanceUnits(int distanceUnits) {
1853
                defaultDistanceUnits = distanceUnits;
1854
        }
1855

    
1856
        public String exportToXML() throws SaveException {
1857
                XMLEntity xml = this.newExportXMLRootNode();
1858

    
1859
                Iterator iter = this.documents.iterator();
1860
                ProjectDocument document;
1861
                // FIXME: Falta atrapar los errores
1862
                while (iter.hasNext()) {
1863
                        document = (ProjectDocument) iter.next();
1864
                        document.exportToXML(xml, this);
1865
                }
1866

    
1867
                return xml.toString();
1868
        }
1869

    
1870
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1871
                XMLEntity xml = this.newExportXMLRootNode();
1872

    
1873
                for (int i = 0; i < documents.length; i++) {
1874
                        documents[i].exportToXML(xml, this);
1875
                }
1876

    
1877
                return xml.toString();
1878
        }
1879

    
1880
        public void importFromXML(String xml) throws Exception {
1881
                throw new Exception("Not Implemented");
1882
                /*
1883
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1884
                 *
1885
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1886
                 * Exception(e); }
1887
                 *
1888
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1889
                 * Error"); //FIXME: traducir }
1890
                 *
1891
                 * int i;
1892
                 *
1893
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1894
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1895
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1896
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1897
                 * root "+i+ "error"); } documentFactory =
1898
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1899
                 * int j; }
1900
                 */
1901

    
1902
        }
1903

    
1904
        public void importFromXML(String xml, String type) throws Exception {
1905
                // FIXME: EXCEPTIONS!!!!
1906
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1907

    
1908
                if (!checkExportXMLRootNode(xmlEntity)) {
1909
                        throw new Exception();
1910
                }
1911

    
1912
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1913
                if (typeRoot.getChildrenCount() == 0) {
1914
                        return;
1915
                }
1916

    
1917
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1918

    
1919
                Hashtable conflicts = getConflicts(xmlEntity);
1920

    
1921
                if (conflicts.size() != 0) {
1922
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1923
                                        conflicts)) {
1924
                                return;
1925
                        }
1926
                }
1927
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1928
                                "dataSources"));
1929

    
1930
                int i;
1931
                ProjectDocument document;
1932
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1933
                        document = documentFactory.create(this);
1934
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1935
                }
1936

    
1937
        }
1938

    
1939
        private Hashtable getConflicts(XMLEntity xml) {
1940
                int iType;
1941
                Hashtable conflicts = new Hashtable();
1942
                ArrayList elements;
1943
                XMLEntity typeRoot;
1944
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
1945
                        typeRoot = xml.getChild(iType);
1946
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
1947
                        Hashtable conflictsType = new Hashtable();
1948
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
1949
                                XMLEntity child = typeRoot.getChild(iXML);
1950
                                Iterator iter = elements.iterator();
1951
                                while (iter.hasNext()) {
1952
                                        ProjectDocument element = (ProjectDocument) iter.next();
1953
                                        if (element.getName().equalsIgnoreCase(
1954
                                                        child.getStringProperty("name"))) {
1955
                                                conflictsType.put(new Integer(iXML), child);
1956
                                                break;
1957
                                        }
1958

    
1959
                                }
1960
                        }
1961
                        if (conflictsType.size() > 0) {
1962
                                conflicts
1963
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1964
                        }
1965
                }
1966
                return conflicts;
1967
        }
1968

    
1969
        public boolean isValidXMLForImport(String xml) {
1970
                XMLEntity xmlEntity;
1971
                try {
1972
                        xmlEntity = XMLEntity.parse(xml);
1973
                } catch (Exception e) {
1974
                        return false;
1975
                }
1976

    
1977
                return checkExportXMLRootNode(xmlEntity);
1978
        }
1979

    
1980
        public boolean isValidXMLForImport(String xml, String type) {
1981
                XMLEntity xmlEntity;
1982
                try {
1983
                        xmlEntity = XMLEntity.parse(xml);
1984
                } catch (Exception e) {
1985
                        return false;
1986
                }
1987

    
1988
                if (!checkExportXMLRootNode(xmlEntity)) {
1989
                        return false;
1990
                }
1991

    
1992
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1993

    
1994
                if (typeRoot == null) {
1995
                        return false;
1996
                }
1997

    
1998
                return (typeRoot.getChildrenCount() > 0);
1999
        }
2000

    
2001
        private boolean checkExportXMLRootNode(XMLEntity xml) {
2002
                if (!xml.contains("applicationName"))
2003
                        return false;
2004
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
2005
                        return false;
2006

    
2007
                if (!xml.contains("version"))
2008
                        return false;
2009
                if (!xml.getStringProperty("version")
2010
                                .equalsIgnoreCase(Version.format()))
2011
                        return false;
2012

    
2013
                return true;
2014
        }
2015

    
2016
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
2017
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
2018
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
2019
                                .getDriverInfo(dataSourceName);
2020
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
2021
        }
2022

    
2023
        private XMLEntity newExportXMLRootNode() {
2024
                XMLEntity xml = new XMLEntity();
2025
                xml.putProperty("applicationName", "gvSIG");
2026
                xml.putProperty("version", Version.format());
2027
                return xml;
2028
        }
2029

    
2030
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
2031
                XMLEntity typeRoot = root.firstChild("type", type);
2032
                if (typeRoot == null) {
2033
                        typeRoot = this.newExportXMLTypeNode(type);
2034
                        root.addChild(typeRoot);
2035
                }
2036
                return typeRoot;
2037
        }
2038

    
2039
        private XMLEntity newExportXMLTypeNode(String type) {
2040
                XMLEntity xmlDataSources = new XMLEntity();
2041
                xmlDataSources.putProperty("type", type);
2042
                return xmlDataSources;
2043
        }
2044

    
2045
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2046
                String name = xmlDataSource.getStringProperty("gdbmsname");
2047

    
2048
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2049
                        if (xmlDataSource.getStringProperty("type").equals(
2050
                                        "otherDriverFile")) {
2051
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2052
                                                xmlDataSource.getStringProperty("driverName"), name,
2053
                                                xmlDataSource.getStringProperty("file"));
2054

    
2055
                        } else if (xmlDataSource.getStringProperty("type").equals(
2056
                                        "sameDriverFile")) {
2057

    
2058
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2059
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2060
                                                name, xmlDataSource.getStringProperty("host"),
2061
                                                xmlDataSource.getIntProperty("port"),
2062
                                                xmlDataSource.getStringProperty("user"),
2063
                                                xmlDataSource.getStringProperty("password"),
2064
                                                xmlDataSource.getStringProperty("dbName"),
2065
                                                xmlDataSource.getStringProperty("tableName"),
2066
                                                xmlDataSource.getStringProperty("driverInfo"));
2067
                        } else {
2068
                                return false;
2069
                        }
2070

    
2071
                }
2072
                return true;
2073
        }
2074

    
2075
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2076
                try {
2077
                        int numDataSources = xmlDataSources.getChildrenCount();
2078

    
2079
                        if (numDataSources == 0)
2080
                                return true;
2081
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2082

    
2083
                        for (int i = 0; i < numDataSources; i++) {
2084
                                XMLEntity child = xmlDataSources.getChild(i);
2085
                                if (!this.registerDataSourceFromXML(child)) {
2086
                                        return false;
2087
                                }
2088
                        }
2089

    
2090
                        return true;
2091
                } catch (Exception e) {
2092
                        e.printStackTrace();
2093
                        return false;
2094
                }
2095
        }
2096

    
2097
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2098
                ProjectDocumentFactory pde = null;
2099
                try {
2100
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2101
                                        .getInstance();
2102
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2103
                                        .get("Documents"));
2104
                        try {
2105
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2106
                        } catch (InstantiationException e) {
2107
                                NotificationManager.addError(
2108
                                                "Clase de ProjectDocument no reconocida", e);
2109
                        } catch (IllegalAccessException e) {
2110
                                NotificationManager.addError(
2111
                                                "Clase de ProjectDocument no reconocida", e);
2112
                        }
2113

    
2114
                } catch (Exception e1) {
2115
                        return null;
2116
                }
2117
                return pde;
2118
        }
2119

    
2120
         public boolean hasChanged() {
2121
                 // we return true if the project is not empty (until we have a better method...)
2122
                 if ((this.getDocuments().size() != 0) || modified) {
2123
                         return true;
2124
                 }
2125
                 return false;
2126
//                 return signatureAtStartup != getXMLEntity().hash();
2127
         }
2128

    
2129
        public void setSignature(long hash) {
2130
                signatureAtStartup = hash;
2131
        }
2132
}