Statistics
| Revision:

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

History | View | Annotate | Download (60.4 KB)

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

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

    
57
import org.cresques.cts.IProjection;
58

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

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

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

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

    
130
        private static int defaultMapUnits = -1;
131

    
132
        private static int defaultDistanceUnits = -1;
133

    
134
        private PropertyChangeSupport change;
135

    
136
        boolean modified = false;
137

    
138
        private String name;
139

    
140
        // private String path;
141
        private String creationDate;
142

    
143
        private String modificationDate;
144

    
145
        private String owner;
146

    
147
        private String comments;
148

    
149
        private Color selectionColor = null;
150

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

    
156
        private ArrayList extents = new ArrayList();
157

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

    
162
        // private int signatureAtStartup;
163
        private IProjection projection;
164

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

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

    
187
        /**
188
         * Creates a new Project object.
189
         */
190
        public Project() {
191
                change = new PropertyChangeSupport(this);
192

    
193
                // change.addPropertyChangeListener(this);
194
                creationDate = DateFormat.getDateInstance().format(new Date());
195
                modificationDate = creationDate;
196
                setSelectionColor(getDefaultSelectionColor());
197
                // signatureAtStartup = computeSignature();
198

    
199
                /*
200
                 * LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
201
                 * .getPluginDirectory() .getAbsolutePath() + File.separator +
202
                 * "drivers");
203
                 */
204
        }
205

    
206
        /**
207
         * Obtiene la fecha de creaci?n del proyecto
208
         * 
209
         * @return
210
         */
211
        public String getCreationDate() {
212
                return creationDate;
213
        }
214

    
215
        /**
216
         * Obtiene el nombre del proyecto
217
         * 
218
         * @return
219
         */
220
        public String getName() {
221
                return name;
222
        }
223

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

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

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

    
259
        // /**
260
        // * establece la ruta completa de donde se encuentra guardado el proyecto
261
        // *
262
        // * @param string
263
        // */
264
        // public void setPath(String string) {
265
        // path = 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
        /**
317
         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
318
         * fue modificado
319
         * 
320
         * @return
321
         */
322
        public boolean isModified() {
323
                if (this.getDocumentsByType(ProjectMapFactory.registerName).size() == 0
324
                                && this.getDocumentsByType(ProjectViewFactory.registerName)
325
                                                .size() == 0
326
                                && this.getDocumentsByType(ProjectTableFactory.registerName)
327
                                                .size() == 0) {
328
                        return false;
329
                }
330
                return true;
331
                // /return modified; TODO El atributo modified solo detecta cuando se
332
                // elimina o a?ade una vista,
333
                // /mapa o tabla pero no cuando se modifican.
334
        }
335

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

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

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

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

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

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

    
396
        /**
397
         * Establece el flag de modificado del proyecto
398
         * 
399
         * @param b
400
         */
401
        public void setModified(boolean b) {
402
                modified = b;
403
        }
404

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

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

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

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

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

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

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

    
482
                return extents.remove(arg0);
483
        }
484

    
485
        /**
486
         * DOCUMENT ME!
487
         * 
488
         * @return DOCUMENT ME!
489
         */
490
        public ProjectExtent[] getExtents() {
491
                return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
492
        }
493

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

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

    
518
                return this.cameras.remove(arg0);
519
        }
520

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

    
530
        /**
531
         * DOCUMENT ME!
532
         * 
533
         * @param arg0
534
         */
535
        public synchronized void addPropertyChangeListener(
536
                        PropertyChangeListener arg0) {
537
                change.addPropertyChangeListener(arg0);
538
        }
539

    
540
        /**
541
         * DOCUMENT ME!
542
         * 
543
         * @deprecated utilizar getDocument(String s);
544
         * @return
545
         */
546
        public ArrayList getMaps() {
547
                return getDocumentsByType(ProjectMapFactory.registerName);
548
        }
549

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

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

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

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

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

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

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

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

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

    
651
                int numExtents = extents.size();
652
                xml.putProperty("numExtents", numExtents);
653

    
654
                for (int i = 0; i < numExtents; i++) {
655
                        xml.addChild(((ProjectExtent) extents.get(i)).getXMLEntity());
656
                }
657

    
658
                // Guardando propiedades de las camaras
659
                int numCameras = this.cameras.size();
660
                xml.putProperty("numCameras", numCameras);
661

    
662
                for (int i = 0; i < numCameras; i++) {
663
                        xml.addChild(((IPersistance) this.cameras.get(i)).getXMLEntity());
664
                }
665

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

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

    
719
                saveWindowProperties(xml);
720
                return xml;
721
        }
722

    
723
        private void saveWindowProperties(XMLEntity xml) {
724
                XMLEntity propertyList = new XMLEntity();
725

    
726
                propertyList.setName("AndamiPersistence");
727
                propertyList.putProperty("className", Project.class.getName());
728

    
729
                boolean projectWindowSaved = false;
730

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

    
793
                if (projectWindowSaved == false) {
794
                        // If the Project Manager was closed, it was not in the
795
                        // previous window list. Save it now
796
                        ProjectExtension pe = (ProjectExtension) PluginServices
797
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
798

    
799
                        if (pe != null) {
800
                                IWindow projectWindow = pe.getProjectWindow();
801
                                wi = PluginServices.getMDIManager()
802
                                                .getWindowInfo(projectWindow);
803
                                if (wi != null && wi.checkPersistence()) {
804
                                        windowProperties = wi.getXMLEntity();
805
                                        if (windowProperties != null) {
806
                                                windowProperties
807
                                                                .putProperty("className",
808
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
809
                                                propertyList.addChild(windowProperties);
810
                                        }
811
                                }
812
                        }
813
                }
814

    
815
                xml.addChild(propertyList);
816
        }
817

    
818
        /**
819
         * Store the initial window properties, to later restore the window sizes
820
         * and positions
821
         */
822
        private void storeInitialWindowProperties(XMLEntity xml) {
823
                XMLEntity child;
824
                int childNumb;
825

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

    
851
                this.initialWindowProperties = orderedProperties.values().iterator();
852
        }
853

    
854
        /**
855
         * Store the initial window properties, to later restore the window sizes
856
         * and positions
857
         */
858
        private void storeInitialWindowProperties061(XMLEntity xml) {
859
                XMLEntity child;
860
                int childNumb = 0;
861
                ArrayList windowList = new ArrayList();
862

    
863
                child = xml.getChild(xml.getChildrenCount() - 1);
864
                if (child.contains("className")
865
                                && child.getStringProperty("className").equals(
866
                                                "com.iver.cit.gvsig.project.Project")
867
                                && child.contains("name")
868
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
869
                        child.putProperty("className",
870
                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
871
                        windowList.add(child);
872
                }
873

    
874
                // try to open the views
875
                if (xml.contains("numExtents"))
876
                        childNumb += xml.getIntProperty("numExtents");
877
                if (xml.contains("data-source-count"))
878
                        childNumb += xml.getIntProperty("data-source-count");
879
                int limit = 0;
880
                if (xml.contains("numViews"))
881
                        limit = xml.getIntProperty("numViews")+childNumb;
882

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

    
901
                if (xml.contains("numViews"))
902
                        childNumb += xml.getIntProperty("numViews");
903

    
904
                if (xml.contains("numMaps"))
905
                        limit = childNumb + xml.getIntProperty("numMaps");
906

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

    
928
                this.initialWindowProperties = windowList.iterator();
929
        }
930

    
931
        /**
932
         * Restores the size, position and order of the windows, according to
933
         * variable initialWindowProperties. If this variable is null, the method
934
         * just opens the project manager window.
935
         * 
936
         */
937
        public void restoreWindowProperties() {
938
                boolean projectWindowRestored = false;
939
                XMLEntity child;
940

    
941
                Iterator propertiesIterator = this.initialWindowProperties;
942
                if (propertiesIterator != null) {
943
                        this.initialWindowProperties = null;
944

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

    
1005
                if (!projectWindowRestored) { // if the project window was not stored
1006
                        // in the project, open it now
1007
                        ProjectExtension pe = (ProjectExtension) PluginServices
1008
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1009

    
1010
                        if (pe != null) {
1011
                                pe.setProject(this);
1012
                                pe.showProjectWindow();
1013
                        }
1014
                }
1015
        }
1016

    
1017
        /**
1018
         * DOCUMENT ME!
1019
         * 
1020
         * @param xml
1021
         *            DOCUMENT ME!
1022
         * 
1023
         * @return DOCUMENT ME!
1024
         * @throws XMLException
1025
         * @throws DriverException
1026
         * @throws DriverIOException
1027
         * @throws OpenException
1028
         */
1029
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1030
                Project p = new Project();
1031
                try {
1032
                        p.comments = xml.getStringProperty("comments");
1033
                        p.creationDate = xml.getStringProperty("creationDate");
1034

    
1035
                        int numExtents = xml.getIntProperty("numExtents");
1036
                        for (int i = 0; i < numExtents; i++) {
1037
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1038
                                                .getChild(i));
1039
                                p.extents.add(pe);
1040
                        }
1041

    
1042
                        int numDocuments = 0;
1043
                        if (xml.contains("numDocuments")) {
1044
                                numDocuments = xml.getIntProperty("numDocuments");
1045
                        } else {
1046
                                int numViews = xml.getIntProperty("numViews");
1047
                                int numMaps = xml.getIntProperty("numMaps");
1048
                                int numTables = xml.getIntProperty("numTables");
1049
                                numDocuments = numViews + numMaps + numTables;
1050
                        }
1051
                        for (int i = numExtents; i < numDocuments + numExtents; i++) {
1052
                                ProjectDocument pD = ProjectDocument.createFromXML03(xml
1053
                                                .getChild(i), p);
1054
                                p.addDocument(pD);
1055
                                p.sortedDocuments.put(pD, new Integer(i));
1056
                        }
1057
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1058
                                        .keySet().toArray(new ProjectDocument[0]);
1059
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1060
                                        .toArray(new Integer[0]);
1061

    
1062
                        int i = 0;
1063
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1064
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1065
                                                .intValue()));
1066
                                i++;
1067
                        }
1068

    
1069
                        p.modificationDate = xml.getStringProperty("modificationDate");
1070
                        p.modified = xml.getBooleanProperty("modified");
1071
                        p.name = xml.getStringProperty("name");
1072
                        p.owner = xml.getStringProperty("owner");
1073
                        p.selectionColor = StringUtilities.string2Color(xml
1074
                                        .getStringProperty("selectionColor"));
1075

    
1076
                        String strProj = xml.getStringProperty("projection");
1077
                        if (strProj != null)
1078
                                p.setProjection(CRSFactory.getCRS(strProj));
1079
                } catch (Exception e) {
1080
                        throw new OpenException(e, p.getClass().getName());
1081
                }
1082
                return p;
1083
        }
1084

    
1085
        /**
1086
         * DOCUMENT ME!
1087
         * 
1088
         * @param xml
1089
         *            DOCUMENT ME!
1090
         * 
1091
         * @return DOCUMENT ME!
1092
         * 
1093
         * @throws XMLException
1094
         * @throws DriverException
1095
         * @throws DriverIOException
1096
         * @throws OpenException
1097
         * @throws VersionException
1098
         */
1099
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1100

    
1101
                int childNumber = 0;
1102
                Project p = new Project();
1103
                try {
1104
                        p.comments = xml.getStringProperty("comments");
1105
                        p.creationDate = xml.getStringProperty("creationDate");
1106
                        int numExtents = xml.getIntProperty("numExtents");
1107

    
1108
                        for (int i = 0; i < numExtents; i++) {
1109
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1110
                                p.extents.add(pe);
1111
                        }
1112

    
1113
                        // Leemos el ultiom hijo recogido
1114
                        childNumber = numExtents;
1115

    
1116
                        // Recogiendo el numero de cameras
1117
                        int numCameras = 0;
1118
                        if (xml.contains("numCameras"))
1119
                                numCameras = xml.getIntProperty("numCameras");
1120

    
1121
                        // Recogiendo todo las camaras
1122
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1123
                                XMLEntity xmlProp = xml.getChild(i);
1124
                                try {
1125
                                        String className = xmlProp.getStringProperty("className");
1126
                                        Class classProp = Class.forName(className);
1127
                                        Object obj = classProp.newInstance();
1128
                                        IPersistance objPersist = (IPersistance) obj;
1129
                                        objPersist.setXMLEntity(xmlProp);
1130
                                        p.cameras.add(obj);
1131
                                } catch (Exception e) {
1132
                                        continue;
1133
                                }
1134
                        }
1135

    
1136
                        childNumber += numCameras;
1137

    
1138
                        int numDataSources = xml.getIntProperty("data-source-count");
1139

    
1140
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1141
                                XMLEntity child = xml.getChild(i);
1142
                                registerDataSourceFromXML(child);
1143
                        }
1144

    
1145
                        childNumber += numDataSources;
1146
                        int numDocuments = 0;
1147
                        if (xml.contains("numDocuments")) {
1148
                                numDocuments = xml.getIntProperty("numDocuments");
1149
                        } else {
1150
                                int numViews = xml.getIntProperty("numViews");
1151
                                int numMaps = xml.getIntProperty("numMaps");
1152
                                int numTables = xml.getIntProperty("numTables");
1153
                                numDocuments = numViews + numMaps + numTables;
1154
                        }
1155

    
1156
                        for (int i = childNumber; i < (numDocuments + childNumber); i++) {
1157
                                try {
1158
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1159
                                                        .getChild(i), p);
1160
                                        p.addDocument(pD);
1161
                                        p.sortedDocuments.put(pD, new Integer(i));
1162
                                } catch (OpenException e) {
1163
                                        e.showError();
1164
                                }
1165
                        }
1166
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1167
                                        .keySet().toArray(new ProjectDocument[0]);
1168
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1169
                                        .toArray(new Integer[0]);
1170

    
1171
                        int i = 0;
1172
                        for (int k = childNumber; k < (numDocuments + childNumber); k++) {
1173
                                try {
1174
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1175
                                                        .intValue()));
1176
                                } catch (OpenException e) {
1177
                                        e.showError();
1178
                                }
1179
                                i++;
1180
                        }
1181
                        childNumber += numDocuments;
1182

    
1183
                        p.modificationDate = xml.getStringProperty("modificationDate");
1184
                        p.modified = xml.getBooleanProperty("modified");
1185
                        p.name = xml.getStringProperty("name");
1186
                        p.owner = xml.getStringProperty("owner");
1187
                        p.selectionColor = StringUtilities.string2Color(xml
1188
                                        .getStringProperty("selectionColor"));
1189

    
1190
                        p.setLinkTable();
1191
                        String strProj = xml.getStringProperty("projection");
1192

    
1193
                        if (strProj != null) {
1194
                                p.setProjection(CRSFactory.getCRS(strProj));
1195
                        }
1196

    
1197
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1198
                                // of the windows
1199
                                XMLEntity child = xml.getChild(childNumber);
1200
                                if (child.contains("name")
1201
                                                && child.getStringProperty("name").equals(
1202
                                                                "AndamiPersistence")) {
1203
                                        p.storeInitialWindowProperties(child);
1204
                                } else if (child.contains("className")
1205
                                                && child.getStringProperty("className").equals(
1206
                                                                "com.iver.cit.gvsig.project.Project")
1207
                                                && child.contains("name")
1208
                                                && child.getStringProperty("name").equals(
1209
                                                                "ViewInfoProperties")) {
1210
                                        p.storeInitialWindowProperties061(xml);
1211
                                }
1212
                        }
1213

    
1214
                        PostProcessSupport.executeCalls();
1215
                } catch (Exception e) {
1216
                        throw new OpenException(e, p.getClass().getName());
1217
                }
1218
                // p.setSignature( p.hashCode());
1219
                return p;
1220

    
1221
        }
1222

    
1223
        // private void setSignature(int signature) {
1224
        // this.signatureAtStartup = computeSignature();
1225
        // }
1226

    
1227
        /**
1228
         * Reestablece los link que ten?a cada tabla con las dem?s.
1229
         */
1230
        public void setLinkTable() {
1231
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1232

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

    
1250
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1251
                                                                .get(i)).getModelo().getRecordset(),
1252
                                                                ((ProjectTable) tables.get(j)).getModelo()
1253
                                                                                .getRecordset(), ((ProjectTable) tables
1254
                                                                                .get(i)).getField1(),
1255
                                                                ((ProjectTable) tables.get(i)).getField2());
1256

    
1257
                                                (((ProjectTable) tables.get(i)).getModelo()
1258
                                                                .getRecordset()).addSelectionListener(lsl);
1259

    
1260
                                        }
1261
                                } catch (DriverLoadException e) {
1262
                                        e.printStackTrace();
1263
                                }
1264
                        }
1265
                }
1266
        }
1267

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

    
1289
                throw new RuntimeException("The layer is not in a view");
1290
        }
1291

    
1292
        public boolean isView(FLayers layers, FLayer layer) {
1293
                for (int i = 0; i < layers.getLayersCount(); i++) {
1294
                        if (layers.getLayer(i) instanceof FLayers) {
1295
                                return isView((FLayers) layers.getLayer(i), layer);
1296
                        }
1297
                        if (layers.getLayer(i) == layer) {
1298
                                return true;
1299
                        }
1300
                }
1301
                return false;
1302
        }
1303

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

    
1334
        /**
1335
         * DOCUMENT ME!
1336
         * 
1337
         * @param defaultProjection
1338
         *            DOCUMENT ME!
1339
         */
1340
        public void setProjection(IProjection projection) {
1341
                this.projection = projection;
1342
        }
1343

    
1344
        /**
1345
         * Sets the projection used when no projection is defined
1346
         * 
1347
         * @param defaultProjection
1348
         *            DOCUMENT ME!
1349
         */
1350
        public static void setDefaultProjection(IProjection defaultProjection) {
1351
                Project.defaultProjection = defaultProjection;
1352
        }
1353

    
1354
        public static IProjection getDefaultProjection() {
1355
                return Project.defaultProjection;
1356
        }
1357

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

    
1375
                        if (elem.getName().equals(name)) {
1376
                                return elem;
1377
                        }
1378
                }
1379

    
1380
                return null;
1381
        }
1382

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

    
1428
                                        dataSource = pt.getModelo().getRecordset();
1429

    
1430
                                        break;
1431
                                }
1432
                        }
1433
                } catch (DriverLoadException e) {
1434
                        e.printStackTrace();
1435
                }
1436

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

    
1442
                return dataSource;
1443

    
1444
        }
1445

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

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

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

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

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

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

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

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

    
1598
                return result;
1599
        }
1600

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

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

    
1628
                return child;
1629
        }
1630

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

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

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

    
1685
        }
1686

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

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

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

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

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

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

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

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

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

    
1815
                return xml.toString();
1816
        }
1817

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

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

    
1825
                return xml.toString();
1826
        }
1827

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

    
1850
        }
1851

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

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

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

    
1865
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1866

    
1867
                Hashtable conflicts = getConflicts(xmlEntity);
1868

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

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

    
1885
        }
1886

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

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

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

    
1925
                return checkExportXMLRootNode(xmlEntity);
1926
        }
1927

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

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

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

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

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

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

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

    
1961
                return true;
1962
        }
1963

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

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

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

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

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

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

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

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

    
2019
                }
2020
                return true;
2021
        }
2022

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

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

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

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

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

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

    
2068
        // public boolean hasChanged() {
2069
        // return signatureAtStartup != computeSignature();
2070
        // }
2071

    
2072
        // public int computeSignature() {
2073
        //
2074
        // // /* TODO method also present in ProjectMap, ProjectTable,
2075
        // // * ProjectView and ProjectExtent
2076
        // // */
2077
        // int result = 17;
2078
        // //
2079
        // // Class clazz = getClass();
2080
        // // Field[] fields = clazz.getDeclaredFields();
2081
        // // for (int i = 0; i < fields.length; i++) {
2082
        // // try {
2083
        // // // don't compute following fields
2084
        // // if (fields[i].getName().equals("modificationDate")
2085
        // // || fields[i].getName().equals("creationDate")
2086
        // // || fields[i].getName().equals("signatureAtStartup")
2087
        // // || fields[i].getName().equals("change")
2088
        // // || Modifier.isStatic(fields[i].getModifiers()))
2089
        // // continue;
2090
        // //
2091
        // //
2092
        // // String type = fields[i].getType().getName();
2093
        // // if (type.equals("boolean")) {
2094
        // // result += 37 + ((fields[i].getBoolean(this)) ? 1 : 0);
2095
        // // } else if (type.equals("java.lang.String")) {
2096
        // // Object v = fields[i].get(this);
2097
        // // if (v == null) {
2098
        // // result += 37;
2099
        // // continue;
2100
        // // }
2101
        // // char[] chars = ((String) v).toCharArray();
2102
        // // for (int j = 0; j < chars.length; j++) {
2103
        // // result += 37 + (int) chars[i];
2104
        // // }
2105
        // // } else if (type.equals("byte")) {
2106
        // // result += 37 + (int) fields[i].getByte(this);
2107
        // // } else if (type.equals("char")) {
2108
        // // result += 37 + (int) fields[i].getChar(this);
2109
        // // } else if (type.equals("short")) {
2110
        // // result += 37 + (int) fields[i].getShort(this);
2111
        // // } else if (type.equals("int")) {
2112
        // // result += 37 + fields[i].getInt(this);
2113
        // // } else if (type.equals("long")) {
2114
        // // long f = fields[i].getLong(this) ;
2115
        // // result += 37 + (f ^ (f >>> 32));
2116
        // // } else if (type.equals("float")) {
2117
        // // result += 37 + Float.floatToIntBits(fields[i].getFloat(this));
2118
        // // } else if (type.equals("double")) {
2119
        // // long f = Double.doubleToLongBits(fields[i].getDouble(this));
2120
        // // result += 37 + (f ^ (f >>> 32));
2121
        // // } else {
2122
        // //// Object obj = fields[i].get(this);
2123
        // //// result += 37 + ((obj != null)? obj.hashCode() : 0);
2124
        // // }
2125
        // // } catch (Exception e) { e.printStackTrace(); }
2126
        // //
2127
        // // }
2128
        // //
2129
        // // for (int i = 0; i < views.size(); i++) {
2130
        // // ProjectView e = (ProjectView) views.get(i);
2131
        // // result += 37 + e.computeSignature();
2132
        // // }
2133
        // //
2134
        // // for (int i = 0; i < tables.size(); i++) {
2135
        // // ProjectTable e = (ProjectTable) tables.get(i);
2136
        // // result += 37 + e.computeSignature();
2137
        // // }
2138
        // //
2139
        // // for (int i = 0; i < maps.size(); i++) {
2140
        // // ProjectMap e = (ProjectMap) maps.get(i);
2141
        // // result += 37 + e.computeSignature();
2142
        // // }
2143
        // //
2144
        // // for (int i = 0; i < extents.size(); i++) {
2145
        // // ProjectExtent e = (ProjectExtent) extents.get(i);
2146
        // // result += 37 + e.computeSignature();
2147
        // // }
2148
        //
2149
        //
2150
        // return result;
2151
        // }
2152

    
2153
}