Statistics
| Revision:

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

History | View | Annotate | Download (59.6 KB)

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

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

    
57
import org.cresques.cts.IProjection;
58

    
59
import com.hardcode.driverManager.DriverLoadException;
60
import com.hardcode.gdbms.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.layout.ProjectMap;
97
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
98
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
99
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
100
import com.iver.cit.gvsig.project.documents.view.ProjectView;
101
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
102
import com.iver.utiles.IPersistance;
103
import com.iver.utiles.PostProcessSupport;
104
import com.iver.utiles.StringUtilities;
105
import com.iver.utiles.XMLEntity;
106
import com.iver.utiles.extensionPoints.ExtensionPoint;
107
import com.iver.utiles.extensionPoints.ExtensionPoints;
108
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
109

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

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

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

    
128
        private static int defaultMapUnits = -1;
129

    
130
        private static int defaultDistanceUnits = -1;
131

    
132
        private PropertyChangeSupport change;
133

    
134
        boolean modified = false;
135

    
136
        private String name;
137

    
138
        // private String path;
139
        private String creationDate;
140

    
141
        private String modificationDate;
142

    
143
        private String owner;
144

    
145
        private String comments;
146

    
147
        private Color selectionColor = null;
148

    
149
        // private ArrayList views = new ArrayList();
150
        // private ArrayList tables = new ArrayList();
151
        // private ArrayList maps = new ArrayList();
152
        private ArrayList documents = new ArrayList();
153

    
154
        private ArrayList extents = new ArrayList();
155

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

    
160
        // private int signatureAtStartup;
161
        private IProjection projection;
162

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

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

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

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

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

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

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

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

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

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

    
257
        // /**
258
        // * establece la ruta completa de donde se encuentra guardado el proyecto
259
        // *
260
        // * @param string
261
        // */
262
        // public void setPath(String string) {
263
        // path = string;
264
        // modified = true;
265
        // change.firePropertyChange("", null, null);
266
        // }
267

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

    
288
                return null;
289
        }
290

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

    
311
                return null;
312
        }
313

    
314
        /**
315
         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
316
         * fue modificado
317
         * 
318
         * @return
319
         */
320
        public boolean isModified() {
321
                if (this.getDocumentsByType(ProjectMapFactory.registerName).size() == 0
322
                                && this.getDocumentsByType(ProjectViewFactory.registerName)
323
                                                .size() == 0
324
                                && this.getDocumentsByType(ProjectTableFactory.registerName)
325
                                                .size() == 0) {
326
                        return false;
327
                }
328
                return true;
329
                // /return modified; TODO El atributo modified solo detecta cuando se
330
                // elimina o a?ade una vista,
331
                // /mapa o tabla pero no cuando se modifican.
332
        }
333

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
480
                return extents.remove(arg0);
481
        }
482

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

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

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

    
516
                return this.cameras.remove(arg0);
517
        }
518

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

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

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

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

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

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

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

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

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

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

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

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

    
649
                int numExtents = extents.size();
650
                xml.putProperty("numExtents", numExtents);
651

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

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

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

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

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

    
717
                saveWindowProperties(xml);
718
                return xml;
719
        }
720

    
721
        private void saveWindowProperties(XMLEntity xml) {
722
                XMLEntity propertyList = new XMLEntity();
723

    
724
                propertyList.setName("AndamiPersistence");
725
                propertyList.putProperty("className", Project.class.getName());
726

    
727
                boolean projectWindowSaved = false;
728

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

    
785
                if (projectWindowSaved == false) {
786
                        // If the Project Manager was closed, it was not in the
787
                        // previous window list. Save it now
788
                        ProjectExtension pe = (ProjectExtension) PluginServices
789
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
790

    
791
                        if (pe != null) {
792
                                IWindow projectWindow = pe.getProjectWindow();
793
                                wi = PluginServices.getMDIManager()
794
                                                .getWindowInfo(projectWindow);
795
                                if (wi != null && wi.checkPersistence()) {
796
                                        windowProperties = wi.getXMLEntity();
797
                                        if (windowProperties != null) {
798
                                                windowProperties
799
                                                                .putProperty("className",
800
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
801
                                                propertyList.addChild(windowProperties);
802
                                        }
803
                                }
804
                        }
805
                }
806

    
807
                xml.addChild(propertyList);
808
        }
809

    
810
        /**
811
         * Store the initial window properties, to later restore the window sizes
812
         * and positions
813
         */
814
        private void storeInitialWindowProperties(XMLEntity xml) {
815
                XMLEntity child;
816
                int childNumb;
817

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

    
843
                this.initialWindowProperties = orderedProperties.values().iterator();
844
        }
845

    
846
        /**
847
         * Store the initial window properties, to later restore the window sizes
848
         * and positions
849
         */
850
        private void storeInitialWindowProperties061(XMLEntity xml) {
851
                XMLEntity child;
852
                int childNumb = 0;
853
                ArrayList windowList = new ArrayList();
854

    
855
                child = xml.getChild(xml.getChildrenCount() - 1);
856
                if (child.contains("className")
857
                                && child.getStringProperty("className").equals(
858
                                                "com.iver.cit.gvsig.project.Project")
859
                                && child.contains("name")
860
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
861
                        child.putProperty("className",
862
                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
863
                        windowList.add(child);
864
                }
865

    
866
                // try to open the views
867
                if (xml.contains("numExtents"))
868
                        childNumb += xml.getIntProperty("numExtents");
869
                if (xml.contains("data-source-count"))
870
                        childNumb += xml.getIntProperty("data-source-count");
871
                int limit = 0;
872
                if (xml.contains("numViews"))
873
                        limit = xml.getIntProperty("numViews")+childNumb;
874

    
875
                XMLEntity view;
876
                for (int i = childNumb; i < limit; i++) {
877
                        view = xml.getChild(i);
878
                        child = view.getChild(view.getChildrenCount() - 1);
879
                        if (child.contains("className")
880
                                        && child.getStringProperty("className").equals(
881
                                                        "com.iver.cit.gvsig.project.ProjectView")
882
                                        && child.contains("name")
883
                                        && child.getStringProperty("name").equals(
884
                                                        "ViewInfoProperties")) {
885
                                child.putProperty("documentName", view
886
                                                .getStringProperty("name"));
887
                                child.putProperty("documentType",
888
                                                ProjectViewFactory.registerName);
889
                                windowList.add(child);
890
                        }
891
                }
892

    
893
                if (xml.contains("numViews"))
894
                        childNumb += xml.getIntProperty("numViews");
895

    
896
                if (xml.contains("numMaps"))
897
                        limit = childNumb + xml.getIntProperty("numMaps");
898

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

    
920
                this.initialWindowProperties = windowList.iterator();
921
        }
922

    
923
        /**
924
         * Restores the size, position and order of the windows, according to
925
         * variable initialWindowProperties. If this variable is null, the method
926
         * just opens the project manager window.
927
         * 
928
         */
929
        public void restoreWindowProperties() {
930
                boolean projectWindowRestored = false;
931
                XMLEntity child;
932

    
933
                Iterator propertiesIterator = this.initialWindowProperties;
934
                if (propertiesIterator != null) {
935
                        this.initialWindowProperties = null;
936

    
937
                        while (propertiesIterator.hasNext()) {
938
                                child = (XMLEntity) propertiesIterator.next();
939
                                if (child.contains("name") // restore the position of the
940
                                                // document windows
941
                                                && child.getStringProperty("name").equals(
942
                                                                "ViewInfoProperties")
943
                                                && child.contains("documentType")) {
944
                                        boolean isClosed = true;
945
                                        if (child.contains("isClosed"))
946
                                                isClosed = child.getBooleanProperty("isClosed");
947
                                        if (isClosed == false) {
948
                                                WindowInfo windowProps = WindowInfo
949
                                                                .createFromXMLEntity(child);
950
                                                String documentName = child
951
                                                                .getStringProperty("documentName");
952
                                                String documentType = child
953
                                                                .getStringProperty("documentType");
954
                                                ProjectDocument pd = this.getProjectDocumentByName(
955
                                                                documentName, documentType);
956
                                                IWindow win = pd.createWindow();
957
                                                PluginServices.getMDIManager().addWindow(win);
958
                                                PluginServices.getMDIManager().changeWindowInfo(win,
959
                                                                windowProps);
960
                                        }
961
                                } else if (child.contains("className") // restore the position
962
                                                // of the project
963
                                                // manager window
964
                                                && child
965
                                                                .getStringProperty("className")
966
                                                                .equals(
967
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow")
968
                                                && child.contains("name")
969
                                                && child.getStringProperty("name").equals(
970
                                                                "ViewInfoProperties")) {
971
                                        WindowInfo wi = WindowInfo.createFromXMLEntity(child);
972
                                        // don't restore size for ProjectManager window, as it's not resizable
973
                                        wi.setHeight(-1);
974
                                        wi.setWidth(-1);
975
                                        ProjectExtension pe = (ProjectExtension) PluginServices
976
                                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
977
                                        if (pe != null) {
978
                                                pe.setProject(this);
979
                                                pe.showProjectWindow(wi);
980
                                        }
981
                                        projectWindowRestored = true;
982
                                }
983
                        }
984
                }
985

    
986
                if (!projectWindowRestored) { // if the project window was not stored
987
                        // in the project, open it now
988
                        ProjectExtension pe = (ProjectExtension) PluginServices
989
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
990

    
991
                        if (pe != null) {
992
                                pe.setProject(this);
993
                                pe.showProjectWindow();
994
                        }
995
                }
996
        }
997

    
998
        /**
999
         * DOCUMENT ME!
1000
         * 
1001
         * @param xml
1002
         *            DOCUMENT ME!
1003
         * 
1004
         * @return DOCUMENT ME!
1005
         * @throws XMLException
1006
         * @throws DriverException
1007
         * @throws DriverIOException
1008
         * @throws OpenException
1009
         */
1010
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1011
                Project p = new Project();
1012
                try {
1013
                        p.comments = xml.getStringProperty("comments");
1014
                        p.creationDate = xml.getStringProperty("creationDate");
1015

    
1016
                        int numExtents = xml.getIntProperty("numExtents");
1017
                        for (int i = 0; i < numExtents; i++) {
1018
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1019
                                                .getChild(i));
1020
                                p.extents.add(pe);
1021
                        }
1022

    
1023
                        int numDocuments = 0;
1024
                        if (xml.contains("numDocuments")) {
1025
                                numDocuments = xml.getIntProperty("numDocuments");
1026
                        } else {
1027
                                int numViews = xml.getIntProperty("numViews");
1028
                                int numMaps = xml.getIntProperty("numMaps");
1029
                                int numTables = xml.getIntProperty("numTables");
1030
                                numDocuments = numViews + numMaps + numTables;
1031
                        }
1032
                        for (int i = numExtents; i < numDocuments + numExtents; i++) {
1033
                                ProjectDocument pD = ProjectDocument.createFromXML03(xml
1034
                                                .getChild(i), p);
1035
                                p.addDocument(pD);
1036
                                p.sortedDocuments.put(pD, new Integer(i));
1037
                        }
1038
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1039
                                        .keySet().toArray(new ProjectDocument[0]);
1040
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1041
                                        .toArray(new Integer[0]);
1042

    
1043
                        int i = 0;
1044
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1045
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1046
                                                .intValue()));
1047
                                i++;
1048
                        }
1049

    
1050
                        p.modificationDate = xml.getStringProperty("modificationDate");
1051
                        p.modified = xml.getBooleanProperty("modified");
1052
                        p.name = xml.getStringProperty("name");
1053
                        p.owner = xml.getStringProperty("owner");
1054
                        p.selectionColor = StringUtilities.string2Color(xml
1055
                                        .getStringProperty("selectionColor"));
1056

    
1057
                        String strProj = xml.getStringProperty("projection");
1058
                        if (strProj != null)
1059
                                p.setProjection(CRSFactory.getCRS(strProj));
1060
                } catch (Exception e) {
1061
                        throw new OpenException(e, p.getClass().getName());
1062
                }
1063
                return p;
1064
        }
1065

    
1066
        /**
1067
         * DOCUMENT ME!
1068
         * 
1069
         * @param xml
1070
         *            DOCUMENT ME!
1071
         * 
1072
         * @return DOCUMENT ME!
1073
         * 
1074
         * @throws XMLException
1075
         * @throws DriverException
1076
         * @throws DriverIOException
1077
         * @throws OpenException
1078
         * @throws VersionException
1079
         */
1080
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1081

    
1082
                int childNumber = 0;
1083
                Project p = new Project();
1084
                try {
1085
                        p.comments = xml.getStringProperty("comments");
1086
                        p.creationDate = xml.getStringProperty("creationDate");
1087
                        int numExtents = xml.getIntProperty("numExtents");
1088

    
1089
                        for (int i = 0; i < numExtents; i++) {
1090
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1091
                                p.extents.add(pe);
1092
                        }
1093

    
1094
                        // Leemos el ultiom hijo recogido
1095
                        childNumber = numExtents;
1096

    
1097
                        // Recogiendo el numero de cameras
1098
                        int numCameras = 0;
1099
                        if (xml.contains("numCameras"))
1100
                                numCameras = xml.getIntProperty("numCameras");
1101

    
1102
                        // Recogiendo todo las camaras
1103
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1104
                                XMLEntity xmlProp = xml.getChild(i);
1105
                                try {
1106
                                        String className = xmlProp.getStringProperty("className");
1107
                                        Class classProp = Class.forName(className);
1108
                                        Object obj = classProp.newInstance();
1109
                                        IPersistance objPersist = (IPersistance) obj;
1110
                                        objPersist.setXMLEntity(xmlProp);
1111
                                        p.cameras.add(obj);
1112
                                } catch (Exception e) {
1113
                                        continue;
1114
                                }
1115
                        }
1116

    
1117
                        childNumber += numCameras;
1118

    
1119
                        int numDataSources = xml.getIntProperty("data-source-count");
1120

    
1121
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1122
                                XMLEntity child = xml.getChild(i);
1123
                                registerDataSourceFromXML(child);
1124
                        }
1125

    
1126
                        childNumber += numDataSources;
1127
                        int numDocuments = 0;
1128
                        if (xml.contains("numDocuments")) {
1129
                                numDocuments = xml.getIntProperty("numDocuments");
1130
                        } else {
1131
                                int numViews = xml.getIntProperty("numViews");
1132
                                int numMaps = xml.getIntProperty("numMaps");
1133
                                int numTables = xml.getIntProperty("numTables");
1134
                                numDocuments = numViews + numMaps + numTables;
1135
                        }
1136

    
1137
                        for (int i = childNumber; i < (numDocuments + childNumber); i++) {
1138
                                try {
1139
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1140
                                                        .getChild(i), p);
1141
                                        p.addDocument(pD);
1142
                                        p.sortedDocuments.put(pD, new Integer(i));
1143
                                } catch (OpenException e) {
1144
                                        e.showError();
1145
                                }
1146
                        }
1147
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1148
                                        .keySet().toArray(new ProjectDocument[0]);
1149
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1150
                                        .toArray(new Integer[0]);
1151

    
1152
                        int i = 0;
1153
                        for (int k = childNumber; k < (numDocuments + childNumber); k++) {
1154
                                try {
1155
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1156
                                                        .intValue()));
1157
                                } catch (OpenException e) {
1158
                                        e.showError();
1159
                                }
1160
                                i++;
1161
                        }
1162
                        childNumber += numDocuments;
1163

    
1164
                        p.modificationDate = xml.getStringProperty("modificationDate");
1165
                        p.modified = xml.getBooleanProperty("modified");
1166
                        p.name = xml.getStringProperty("name");
1167
                        p.owner = xml.getStringProperty("owner");
1168
                        p.selectionColor = StringUtilities.string2Color(xml
1169
                                        .getStringProperty("selectionColor"));
1170

    
1171
                        p.setLinkTable();
1172
                        String strProj = xml.getStringProperty("projection");
1173

    
1174
                        if (strProj != null) {
1175
                                p.setProjection(CRSFactory.getCRS(strProj));
1176
                        }
1177

    
1178
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1179
                                // of the windows
1180
                                XMLEntity child = xml.getChild(childNumber);
1181
                                if (child.contains("name")
1182
                                                && child.getStringProperty("name").equals(
1183
                                                                "AndamiPersistence")) {
1184
                                        p.storeInitialWindowProperties(child);
1185
                                } else if (child.contains("className")
1186
                                                && child.getStringProperty("className").equals(
1187
                                                                "com.iver.cit.gvsig.project.Project")
1188
                                                && child.contains("name")
1189
                                                && child.getStringProperty("name").equals(
1190
                                                                "ViewInfoProperties")) {
1191
                                        p.storeInitialWindowProperties061(xml);
1192
                                }
1193
                        }
1194

    
1195
                        PostProcessSupport.executeCalls();
1196
                } catch (Exception e) {
1197
                        throw new OpenException(e, p.getClass().getName());
1198
                }
1199
                // p.setSignature( p.hashCode());
1200
                return p;
1201

    
1202
        }
1203

    
1204
        // private void setSignature(int signature) {
1205
        // this.signatureAtStartup = computeSignature();
1206
        // }
1207

    
1208
        /**
1209
         * Reestablece los link que ten?a cada tabla con las dem?s.
1210
         */
1211
        public void setLinkTable() {
1212
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1213

    
1214
                for (int i = 0; i < tables.size(); i++) {
1215
                        for (int j = 0; j < tables.size(); j++) {
1216
                                /*
1217
                                 * System.out.println("name = " + ((ProjectTable)
1218
                                 * tables.get(j)).getModelo().getName());
1219
                                 * System.out.println("linktable = " + ((ProjectTable)
1220
                                 * tables.get(i)).getLinkTable());
1221
                                 */
1222
                                try {
1223
                                        if ((((ProjectTable) tables.get(i)).getLinkTable() != null)
1224
                                                        && ((ProjectTable) tables.get(i)).getLinkTable()
1225
                                                                        .equals(
1226
                                                                                        ((ProjectTable) tables.get(j))
1227
                                                                                                        .getModelo().getRecordset()
1228
                                                                                                        .getName())) {
1229
                                                LinkSelectionListener lsl;
1230

    
1231
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1232
                                                                .get(i)).getModelo().getRecordset(),
1233
                                                                ((ProjectTable) tables.get(j)).getModelo()
1234
                                                                                .getRecordset(), ((ProjectTable) tables
1235
                                                                                .get(i)).getField1(),
1236
                                                                ((ProjectTable) tables.get(i)).getField2());
1237

    
1238
                                                (((ProjectTable) tables.get(i)).getModelo()
1239
                                                                .getRecordset()).addSelectionListener(lsl);
1240

    
1241
                                        }
1242
                                } catch (DriverLoadException e) {
1243
                                        e.printStackTrace();
1244
                                }
1245
                        }
1246
                }
1247
        }
1248

    
1249
        /**
1250
         * Obtiene la vista que contiene a la capa que se pasa como par?metro
1251
         * 
1252
         * @param layer
1253
         *            Capa cuya vista se quiere obtener
1254
         * 
1255
         * @return
1256
         * 
1257
         * @throws RuntimeException
1258
         *             Si la capa que se pasa como par?metro no se encuentra en
1259
         *             ninguna vista
1260
         */
1261
        public String getView(FLayer layer) {
1262
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1263
                for (int v = 0; v < views.size(); v++) {
1264
                        ProjectView pView = (ProjectView) views.get(v);
1265
                        FLayers layers = pView.getMapContext().getLayers();
1266
                        if (isView(layers, layer))
1267
                                return pView.getName();
1268
                }
1269

    
1270
                throw new RuntimeException("The layer is not in a view");
1271
        }
1272

    
1273
        public boolean isView(FLayers layers, FLayer layer) {
1274
                for (int i = 0; i < layers.getLayersCount(); i++) {
1275
                        if (layers.getLayer(i) instanceof FLayers) {
1276
                                return isView((FLayers) layers.getLayer(i), layer);
1277
                        }
1278
                        if (layers.getLayer(i) == layer) {
1279
                                return true;
1280
                        }
1281
                }
1282
                return false;
1283
        }
1284

    
1285
        /**
1286
         * Devuelve la vista cuyo nombre coincide (sensible a mayusculas) con el que
1287
         * se pasa como par?metro. Devuelve null si no hay ninguna vista con ese
1288
         * nombre
1289
         * 
1290
         * @param viewName
1291
         *            Nombre de la vista que se quiere obtener
1292
         * 
1293
         * @return DOCUMENT ME!
1294
         */
1295
        /*
1296
         * public ProjectView getViewByName(String viewName) { ArrayList
1297
         * views=getDocuments(PluginServices.getText(this,"Vista")); Object o =
1298
         * getProjectDocumentByName(viewName, PluginServices.getText(this,"Vista"));
1299
         * 
1300
         * if (o == null) { return null; }
1301
         * 
1302
         * return (ProjectView) o; }
1303
         */
1304
        /**
1305
         * DOCUMENT ME!
1306
         * 
1307
         * @return DOCUMENT ME!
1308
         */
1309
        public IProjection getProjection() {
1310
                if (projection == null)
1311
                        projection = Project.defaultProjection;
1312
                return projection;
1313
        }
1314

    
1315
        /**
1316
         * DOCUMENT ME!
1317
         * 
1318
         * @param defaultProjection
1319
         *            DOCUMENT ME!
1320
         */
1321
        public void setProjection(IProjection projection) {
1322
                this.projection = projection;
1323
        }
1324

    
1325
        /**
1326
         * Sets the projection used when no projection is defined
1327
         * 
1328
         * @param defaultProjection
1329
         *            DOCUMENT ME!
1330
         */
1331
        public static void setDefaultProjection(IProjection defaultProjection) {
1332
                Project.defaultProjection = defaultProjection;
1333
        }
1334

    
1335
        public static IProjection getDefaultProjection() {
1336
                return Project.defaultProjection;
1337
        }
1338

    
1339
        /**
1340
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1341
         * pointExtension, este ?ltimo se puede obtener del
1342
         * Project****Factory.registerName.
1343
         * 
1344
         * @param name
1345
         *            Nombre del documento
1346
         * @param type
1347
         *            nombre de registro en el extensionPoint
1348
         * 
1349
         * @return Documento
1350
         */
1351
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1352
                ArrayList docs = getDocumentsByType(type);
1353
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1354
                        ProjectDocument elem = (ProjectDocument) iter.next();
1355

    
1356
                        if (elem.getName().equals(name)) {
1357
                                return elem;
1358
                        }
1359
                }
1360

    
1361
                return null;
1362
        }
1363

    
1364
        /**
1365
         * DOCUMENT ME!
1366
         * 
1367
         * @param name
1368
         * 
1369
         * @return
1370
         */
1371
        /*
1372
         * public ProjectTable getTableByName(String name) { ArrayList
1373
         * tables=getDocuments(PluginServices.getText(this,"Tabla")); Object o =
1374
         * getProjectElementByName(name, tables);
1375
         * 
1376
         * if (o == null) { return null; }
1377
         * 
1378
         * return (ProjectTable) o; }
1379
         */
1380
        /**
1381
         * DOCUMENT ME!
1382
         * 
1383
         * @param name
1384
         * 
1385
         * @return
1386
         */
1387
        /*
1388
         * public ProjectMap getLayoutByName(String name) { Object o =
1389
         * getProjectElementByName(name, maps);
1390
         * 
1391
         * if (o == null) { return null; }
1392
         * 
1393
         * return (ProjectMap) o; }
1394
         */
1395
        public SelectableDataSource getDataSourceByLayer(FLayer layer)
1396
                        throws DriverException {
1397
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1398
                SelectableDataSource dataSource = null;
1399
                try {
1400
                        for (int i = 0; i < tables.size(); i++) {
1401
                                ProjectTable pt = (ProjectTable) tables.get(i);
1402
                                if (pt.getOriginal() == ((AlphanumericData) layer)
1403
                                                .getRecordset()) {
1404
                                        dataSource = pt.getModelo().getRecordset();
1405
                                        break;
1406
                                } else if (pt.getModelo() == ((AlphanumericData) layer)
1407
                                                .getRecordset()) {
1408

    
1409
                                        dataSource = pt.getModelo().getRecordset();
1410

    
1411
                                        break;
1412
                                }
1413
                        }
1414
                } catch (DriverLoadException e) {
1415
                        e.printStackTrace();
1416
                }
1417

    
1418
                if (dataSource == null) {
1419
                        // No se ha creado la tabla asociada al tema
1420
                        dataSource = ((AlphanumericData) layer).getRecordset();
1421
                }
1422

    
1423
                return dataSource;
1424

    
1425
        }
1426

    
1427
        /**
1428
         * Recorremos las capas y las tablas del proyecto, y creamos una lista con
1429
         * todos los datasources de GDBMS que estamos usando. Luego recorremos los
1430
         * que est?n registrados, y borramos aquellos que no est?n siendo usados, es
1431
         * decir, aquellos que no est?n en nuestra lista (un Hash con clave el
1432
         * nombre del GDBMS)
1433
         * 
1434
         */
1435
        private void cleanBadReferences() {
1436
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1437
                Hashtable usedDataSources = new Hashtable();
1438
                // Primero las tablas
1439
                int i, j;
1440
                try {
1441
                        for (i = 0; i < tables.size(); i++) {
1442
                                ProjectTable t = (ProjectTable) tables.get(i);
1443
                                SelectableDataSource ds;
1444

    
1445
                                ds = t.getModelo().getRecordset();
1446

    
1447
                                if (t.getOriginal() != null)
1448
                                        usedDataSources.put(t.getOriginal().getRecordset()
1449
                                                        .getName(), t.getOriginal());
1450
                                usedDataSources.put(ds.getName(), ds);
1451
                        }
1452
                } catch (DriverLoadException e) {
1453
                        e.printStackTrace();
1454
                }
1455
                // Ahora las vistas
1456
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1457
                try {
1458
                        for (i = 0; i < views.size(); i++) {
1459
                                ProjectView pv = (ProjectView) views.get(i);
1460

    
1461
                                FLayers lyrs = pv.getMapContext().getLayers();
1462

    
1463
                                for (j = 0; j < lyrs.getLayersCount(); j++) {
1464
                                        FLayer lyr = lyrs.getLayer(j);
1465
                                        if (lyr instanceof FLyrVect) {
1466
                                                FLyrVect lyrVect = (FLyrVect) lyr;
1467
                                                if (lyrVect.isAvailable())
1468
                                                        usedDataSources.put(lyrVect.getRecordset()
1469
                                                                        .getName(), lyrVect.getSource()
1470
                                                                        .getRecordset());
1471
                                        }
1472
                                }
1473
                                MapContext aux = pv.getMapOverViewContext();
1474
                                if (aux != null) {
1475
                                        FLayers lyrsOverview = aux.getLayers();
1476
                                        for (j = 0; j < lyrsOverview.getLayersCount(); j++) {
1477
                                                FLayer lyr = lyrsOverview.getLayer(j);
1478
                                                if (lyr instanceof FLyrVect) {
1479
                                                        FLyrVect lyrVect = (FLyrVect) lyr;
1480
                                                        usedDataSources.put(lyrVect.getSource()
1481
                                                                        .getRecordset().getName(), lyrVect
1482
                                                                        .getSource().getRecordset());
1483
                                                }
1484
                                        }
1485
                                }
1486

    
1487
                        } // for i
1488
                } catch (DriverLoadException e) {
1489
                        e.printStackTrace();
1490
                } catch (DriverException e) {
1491
                        e.printStackTrace();
1492
                }
1493
                // Recorremos los dataSources y los borramos si no
1494
                // los estamos usando.
1495
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1496
                                .getDriverInfos();
1497
                try {
1498
                        for (i = 0; i < infos.length; i++) {
1499
                                if (!usedDataSources.containsKey(infos[i].name)) {
1500
                                        DataSource ds;
1501
                                        ds = LayerFactory.getDataSourceFactory()
1502
                                                        .createRandomDataSource(infos[i].name);
1503
                                        ds.remove();
1504
                                }
1505
                        }
1506
                } catch (DriverLoadException e) {
1507
                        e.printStackTrace();
1508
                } catch (NoSuchTableException e) {
1509
                        e.printStackTrace();
1510
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1511
                        e.printStackTrace();
1512
                }
1513
        }
1514

    
1515
        /**
1516
         * DOCUMENT ME!
1517
         * 
1518
         * @return DOCUMENT ME!
1519
         * @throws SaveException
1520
         * @throws XMLException
1521
         * @throws SaveException
1522
         */
1523
        public XMLEntity getWindowInfoXMLEntity(IWindow window)
1524
                        throws SaveException {
1525
                if (window != null
1526
                                && PluginServices.getMDIManager().getWindowInfo(window) != null) {
1527
                        WindowInfo vi = PluginServices.getMDIManager()
1528
                                        .getWindowInfo(window);
1529
                        XMLEntity xml = new XMLEntity();
1530
                        // xml.putProperty("nameClass", this.getClass().getName());
1531
                        try {
1532
                                xml.setName("ViewInfoProperties");
1533
                                xml.putProperty("className", this.getClass().getName());
1534
                                xml.putProperty("X", vi.getX());
1535
                                xml.putProperty("Y", vi.getY());
1536
                                xml.putProperty("Width", vi.getWidth());
1537
                                xml.putProperty("Height", vi.getHeight());
1538
                                xml.putProperty("isVisible", vi.isVisible());
1539
                                xml.putProperty("isResizable", vi.isResizable());
1540
                                xml.putProperty("isMaximizable", vi.isMaximizable());
1541
                                xml.putProperty("isModal", vi.isModal());
1542
                                xml.putProperty("isModeless", vi.isModeless());
1543
                                xml.putProperty("isClosed", vi.isClosed());
1544
                                if (vi.isMaximized() == true) {
1545
                                        xml.putProperty("isMaximized", vi.isMaximized());
1546
                                        xml.putProperty("normalX", vi.getNormalX());
1547
                                        xml.putProperty("normalY", vi.getNormalY());
1548
                                        xml.putProperty("normalWidth", vi.getNormalWidth());
1549
                                        xml.putProperty("normalHeight", vi.getNormalHeight());
1550
                                }
1551
                        } catch (Exception e) {
1552
                                throw new SaveException(e, this.getClass().getName());
1553
                        }
1554
                        return xml;
1555
                }
1556
                return null;
1557
        }
1558

    
1559
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1560
                WindowInfo result = new WindowInfo();
1561
                result.setX(xml.getIntProperty("X"));
1562
                result.setY(xml.getIntProperty("Y"));
1563
                result.setHeight(xml.getIntProperty("Height"));
1564
                result.setWidth(xml.getIntProperty("Width"));
1565
                result.setClosed(xml.getBooleanProperty("isClosed"));
1566
                if (xml.contains("isMaximized")) {
1567
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1568
                        result.setMaximized(maximized);
1569
                        if (maximized == true) {
1570
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1571
                                                .getIntProperty("normalY"), xml
1572
                                                .getIntProperty("normalWidth"), xml
1573
                                                .getIntProperty("normalHeight"));
1574
                        } else {
1575
                                result.setNormalBounds(result.getBounds());
1576
                        }
1577
                }
1578

    
1579
                return result;
1580
        }
1581

    
1582
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1583
                XMLEntity child = new XMLEntity();
1584

    
1585
                if (di instanceof ObjectSourceInfo) {
1586
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1587
                        child.putProperty("type", "sameDriverFile");
1588
                        child.putProperty("gdbmsname", driver.name);
1589
                } else if (di instanceof FileSourceInfo) {
1590
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1591
                        child.putProperty("type", "otherDriverFile");
1592
                        child.putProperty("gdbmsname", vfdi.name);
1593
                        child.putProperty("file", vfdi.file);
1594
                        child.putProperty("driverName", vfdi.driverName);
1595
                } else if (di instanceof DBSourceInfo) {
1596
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1597
                        child.putProperty("type", "db");
1598
                        child.putProperty("gdbmsname", dbdi.name);
1599
                        child.putProperty("dbms", dbdi.dbms);
1600
                        child.putProperty("host", dbdi.host);
1601
                        child.putProperty("port", dbdi.port);
1602
                        child.putProperty("user", dbdi.user);
1603
                        child.putProperty("password", dbdi.password);
1604
                        child.putProperty("dbName", dbdi.dbName);
1605
                        child.putProperty("tableName", dbdi.tableName);
1606
                        child.putProperty("driverInfo", dbdi.driverName);
1607
                }
1608

    
1609
                return child;
1610
        }
1611

    
1612
        /**
1613
         * Devuelve un arrayList con todos los documentos del tipo especificado como
1614
         * par?metro.
1615
         * 
1616
         * @param registerName
1617
         *            nombre de registro en el extensionPoint
1618
         * 
1619
         * @return Documentos del tipo especificado
1620
         */
1621
        public ArrayList getDocumentsByType(String registerName) {
1622
                ArrayList docuArray = new ArrayList();
1623
                for (int i = 0; i < documents.size(); i++) {
1624
                        ProjectDocument projectDocument = (ProjectDocument) documents
1625
                                        .get(i);
1626
                        ProjectDocumentFactory pdf = projectDocument
1627
                                        .getProjectDocumentFactory();
1628
                        if (pdf == null)
1629
                                continue;
1630
                        if (pdf.getRegisterName().equals(registerName)) {
1631
                                docuArray.add(projectDocument);
1632
                        }
1633
                }
1634
                return docuArray;
1635
        }
1636

    
1637
        /**
1638
         * Devuelve un arrayList con todos los documentos.
1639
         * 
1640
         * @return Documentos
1641
         */
1642
        public ArrayList getDocuments() {
1643
                ArrayList docuArray = new ArrayList();
1644
                for (int i = 0; i < documents.size(); i++) {
1645
                        ProjectDocument projectDocument = (ProjectDocument) documents
1646
                                        .get(i);
1647
                        docuArray.add(projectDocument);
1648
                }
1649
                return docuArray;
1650
        }
1651

    
1652
        /**
1653
         * Inserta un documento.
1654
         * 
1655
         * @param doc
1656
         *            Documento
1657
         */
1658
        public void addDocument(ProjectDocument doc) {
1659
                documents.add(doc);
1660
                doc.addPropertyChangeListener(this);
1661
                modified = true;
1662
                change.firePropertyChange("", "", null);
1663
                doc.setProject(this, 0);
1664
                doc.afterAdd();
1665

    
1666
        }
1667

    
1668
        /**
1669
         * Borra un documento.
1670
         * 
1671
         * @param doc
1672
         *            Documento
1673
         */
1674
        public void delDocument(ProjectDocument doc) {
1675
                documents.remove(doc);
1676
                modified = true;
1677
                change.firePropertyChange("", null, null);
1678
                doc.afterRemove();
1679
        }
1680

    
1681
        /**
1682
         * Sets the default selection color that will be used in subsequent
1683
         * projects.
1684
         * 
1685
         * @param color
1686
         */
1687
        public static void setDefaultSelectionColor(Color color) {
1688
                defaultSelectionColor = color;
1689
        }
1690

    
1691
        /**
1692
         * Returns the current default selection color defined which is the color
1693
         * defined when the user does not define any other one
1694
         * 
1695
         * @return java.awt.Color
1696
         */
1697
        public static Color getDefaultSelectionColor() {
1698
                // TODO es millorable?
1699
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1700
                                .getPersistentXML();
1701
                if (xml.contains("DefaultSelectionColor"))
1702
                        defaultSelectionColor = StringUtilities.string2Color(xml
1703
                                        .getStringProperty("DefaultSelectionColor"));
1704
                return defaultSelectionColor;
1705
        }
1706

    
1707
        /**
1708
         * Returns the user's default map units. This is the cartography data
1709
         * distance units.
1710
         * 
1711
         * @return int (index of the <b>Attributes.NAMES array</b>)
1712
         */
1713
        public static int getDefaultMapUnits() {
1714
                if (defaultMapUnits == -1) {
1715
                        XMLEntity xml = PluginServices.getPluginServices(
1716
                                        "com.iver.cit.gvsig").getPersistentXML();
1717
                        if (xml.contains("DefaultMapUnits")) {
1718
                                defaultMapUnits = xml.getIntProperty("DefaultMapUnits");
1719
                        } else {
1720
                                // first app run case
1721
                                String[] unitNames = Attributes.NAMES;
1722
                                for (int i = 0; i < unitNames.length; i++) {
1723
                                        // meter is the factory default's map unit
1724
                                        if (unitNames[i].equals(PluginServices.getText(
1725
                                                        Project.class, "Metros"))) {
1726
                                                defaultMapUnits = i;
1727
                                                break;
1728
                                        }
1729
                                }
1730
                        }
1731
                        if (defaultMapUnits == -1)
1732
                                defaultMapUnits = ViewPort.METROS;
1733
                }
1734
                return defaultMapUnits;
1735
        }
1736

    
1737
        /**
1738
         * Returns the user's default view units for measuring distances. This is
1739
         * the units that the user will see in the status bar of the view.
1740
         * 
1741
         * @return int (index of the <b>Attributes.NAMES array</b>)
1742
         */
1743
        public static int getDefaultDistanceUnits() {
1744
                if (defaultDistanceUnits == -1) {
1745
                        XMLEntity xml = PluginServices.getPluginServices(
1746
                                        "com.iver.cit.gvsig").getPersistentXML();
1747
                        if (xml.contains("DefaultDistanceUnits")) {
1748
                                defaultDistanceUnits = xml
1749
                                                .getIntProperty("DefaultDistanceUnits");
1750
                        } else {
1751
                                // first app run case
1752
                                String[] unitNames = Attributes.NAMES;
1753
                                for (int i = 0; i < unitNames.length; i++) {
1754
                                        // meter is the factory default's distance unit
1755
                                        if (unitNames[i].equals("Metros")) {
1756
                                                defaultDistanceUnits = i;
1757
                                                break;
1758
                                        }
1759
                                }
1760
                        }
1761
                        if (defaultDistanceUnits == -1)
1762
                                defaultDistanceUnits = ViewPort.METROS;
1763
                }
1764
                return defaultDistanceUnits;
1765
        }
1766

    
1767
        /**
1768
         * Sets the default map unit (the units used by the data).
1769
         * 
1770
         * @param mapUnits
1771
         */
1772
        public static void setDefaultMapUnits(int mapUnits) {
1773
                defaultMapUnits = mapUnits;
1774
        }
1775

    
1776
        /**
1777
         * Sets the default distance units (the units shown in the status bar)
1778
         * 
1779
         * @param distanceUnits
1780
         */
1781
        public static void setDefaultDistanceUnits(int distanceUnits) {
1782
                defaultDistanceUnits = distanceUnits;
1783
        }
1784

    
1785
        public String exportToXML() throws SaveException {
1786
                XMLEntity xml = this.newExportXMLRootNode();
1787

    
1788
                Iterator iter = this.documents.iterator();
1789
                ProjectDocument document;
1790
                // FIXME: Falta atrapar los errores
1791
                while (iter.hasNext()) {
1792
                        document = (ProjectDocument) iter.next();
1793
                        document.exportToXML(xml, this);
1794
                }
1795

    
1796
                return xml.toString();
1797
        }
1798

    
1799
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1800
                XMLEntity xml = this.newExportXMLRootNode();
1801

    
1802
                for (int i = 0; i < documents.length; i++) {
1803
                        documents[i].exportToXML(xml, this);
1804
                }
1805

    
1806
                return xml.toString();
1807
        }
1808

    
1809
        public void importFromXML(String xml) throws Exception {
1810
                throw new Exception("Not Implemented");
1811
                /*
1812
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1813
                 * 
1814
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1815
                 * Exception(e); }
1816
                 * 
1817
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1818
                 * Error"); //FIXME: traducir }
1819
                 * 
1820
                 * int i;
1821
                 * 
1822
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1823
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1824
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1825
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1826
                 * root "+i+ "error"); } documentFactory =
1827
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1828
                 * int j; }
1829
                 */
1830

    
1831
        }
1832

    
1833
        public void importFromXML(String xml, String type) throws Exception {
1834
                // FIXME: EXCEPTIONS!!!!
1835
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1836

    
1837
                if (!checkExportXMLRootNode(xmlEntity)) {
1838
                        throw new Exception();
1839
                }
1840

    
1841
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1842
                if (typeRoot.getChildrenCount() == 0) {
1843
                        return;
1844
                }
1845

    
1846
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1847

    
1848
                Hashtable conflicts = getConflicts(xmlEntity);
1849

    
1850
                if (conflicts.size() != 0) {
1851
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1852
                                        conflicts)) {
1853
                                return;
1854
                        }
1855
                }
1856
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1857
                                "dataSources"));
1858

    
1859
                int i;
1860
                ProjectDocument document;
1861
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1862
                        document = documentFactory.create(this);
1863
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1864
                }
1865

    
1866
        }
1867

    
1868
        private Hashtable getConflicts(XMLEntity xml) {
1869
                int iType;
1870
                Hashtable conflicts = new Hashtable();
1871
                ArrayList elements;
1872
                XMLEntity typeRoot;
1873
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
1874
                        typeRoot = xml.getChild(iType);
1875
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
1876
                        Hashtable conflictsType = new Hashtable();
1877
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
1878
                                XMLEntity child = typeRoot.getChild(iXML);
1879
                                Iterator iter = elements.iterator();
1880
                                while (iter.hasNext()) {
1881
                                        ProjectDocument element = (ProjectDocument) iter.next();
1882
                                        if (element.getName().equalsIgnoreCase(
1883
                                                        child.getStringProperty("name"))) {
1884
                                                conflictsType.put(new Integer(iXML), child);
1885
                                                break;
1886
                                        }
1887

    
1888
                                }
1889
                        }
1890
                        if (conflictsType.size() > 0) {
1891
                                conflicts
1892
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1893
                        }
1894
                }
1895
                return conflicts;
1896
        }
1897

    
1898
        public boolean isValidXMLForImport(String xml) {
1899
                XMLEntity xmlEntity;
1900
                try {
1901
                        xmlEntity = XMLEntity.parse(xml);
1902
                } catch (Exception e) {
1903
                        return false;
1904
                }
1905

    
1906
                return checkExportXMLRootNode(xmlEntity);
1907
        }
1908

    
1909
        public boolean isValidXMLForImport(String xml, String type) {
1910
                XMLEntity xmlEntity;
1911
                try {
1912
                        xmlEntity = XMLEntity.parse(xml);
1913
                } catch (Exception e) {
1914
                        return false;
1915
                }
1916

    
1917
                if (!checkExportXMLRootNode(xmlEntity)) {
1918
                        return false;
1919
                }
1920

    
1921
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1922

    
1923
                if (typeRoot == null) {
1924
                        return false;
1925
                }
1926

    
1927
                return (typeRoot.getChildrenCount() > 0);
1928
        }
1929

    
1930
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1931
                if (!xml.contains("applicationName"))
1932
                        return false;
1933
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1934
                        return false;
1935

    
1936
                if (!xml.contains("version"))
1937
                        return false;
1938
                if (!xml.getStringProperty("version")
1939
                                .equalsIgnoreCase(Version.format()))
1940
                        return false;
1941

    
1942
                return true;
1943
        }
1944

    
1945
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
1946
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
1947
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
1948
                                .getDriverInfo(dataSourceName);
1949
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
1950
        }
1951

    
1952
        private XMLEntity newExportXMLRootNode() {
1953
                XMLEntity xml = new XMLEntity();
1954
                xml.putProperty("applicationName", "gvSIG");
1955
                xml.putProperty("version", Version.format());
1956
                return xml;
1957
        }
1958

    
1959
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
1960
                XMLEntity typeRoot = root.firstChild("type", type);
1961
                if (typeRoot == null) {
1962
                        typeRoot = this.newExportXMLTypeNode(type);
1963
                        root.addChild(typeRoot);
1964
                }
1965
                return typeRoot;
1966
        }
1967

    
1968
        private XMLEntity newExportXMLTypeNode(String type) {
1969
                XMLEntity xmlDataSources = new XMLEntity();
1970
                xmlDataSources.putProperty("type", type);
1971
                return xmlDataSources;
1972
        }
1973

    
1974
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
1975
                String name = xmlDataSource.getStringProperty("gdbmsname");
1976

    
1977
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
1978
                        if (xmlDataSource.getStringProperty("type").equals(
1979
                                        "otherDriverFile")) {
1980
                                LayerFactory.getDataSourceFactory().addFileDataSource(
1981
                                                xmlDataSource.getStringProperty("driverName"), name,
1982
                                                xmlDataSource.getStringProperty("file"));
1983

    
1984
                        } else if (xmlDataSource.getStringProperty("type").equals(
1985
                                        "sameDriverFile")) {
1986

    
1987
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
1988
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
1989
                                                name, xmlDataSource.getStringProperty("host"),
1990
                                                xmlDataSource.getIntProperty("port"),
1991
                                                xmlDataSource.getStringProperty("user"),
1992
                                                xmlDataSource.getStringProperty("password"),
1993
                                                xmlDataSource.getStringProperty("dbName"),
1994
                                                xmlDataSource.getStringProperty("tableName"),
1995
                                                xmlDataSource.getStringProperty("driverInfo"));
1996
                        } else {
1997
                                return false;
1998
                        }
1999

    
2000
                }
2001
                return true;
2002
        }
2003

    
2004
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2005
                try {
2006
                        int numDataSources = xmlDataSources.getChildrenCount();
2007

    
2008
                        if (numDataSources == 0)
2009
                                return true;
2010
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2011

    
2012
                        for (int i = 0; i < numDataSources; i++) {
2013
                                XMLEntity child = xmlDataSources.getChild(i);
2014
                                if (!this.registerDataSourceFromXML(child)) {
2015
                                        return false;
2016
                                }
2017
                        }
2018

    
2019
                        return true;
2020
                } catch (Exception e) {
2021
                        e.printStackTrace();
2022
                        return false;
2023
                }
2024
        }
2025

    
2026
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2027
                ProjectDocumentFactory pde = null;
2028
                try {
2029
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2030
                                        .getInstance();
2031
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2032
                                        .get("Documents"));
2033
                        try {
2034
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2035
                        } catch (InstantiationException e) {
2036
                                NotificationManager.addError(
2037
                                                "Clase de ProjectDocument no reconocida", e);
2038
                        } catch (IllegalAccessException e) {
2039
                                NotificationManager.addError(
2040
                                                "Clase de ProjectDocument no reconocida", e);
2041
                        }
2042

    
2043
                } catch (Exception e1) {
2044
                        return null;
2045
                }
2046
                return pde;
2047
        }
2048

    
2049
        // public boolean hasChanged() {
2050
        // return signatureAtStartup != computeSignature();
2051
        // }
2052

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

    
2134
}