Statistics
| Revision:

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

History | View | Annotate | Download (60.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.project.documents.ProjectDocument;
90
import com.iver.cit.gvsig.project.documents.ProjectDocumentFactory;
91
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
92
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
93
import com.iver.cit.gvsig.project.documents.gui.IDocumentWindow;
94
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
95
import com.iver.cit.gvsig.project.documents.gui.WindowData;
96
import com.iver.cit.gvsig.project.documents.layout.Attributes;
97
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
98
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
99
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
100
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
101
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
102
import com.iver.cit.gvsig.project.documents.view.ProjectView;
103
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
104
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
105
import com.iver.utiles.IPersistance;
106
import com.iver.utiles.PostProcessSupport;
107
import com.iver.utiles.StringUtilities;
108
import com.iver.utiles.XMLEntity;
109
import com.iver.utiles.extensionPoints.ExtensionPoint;
110
import com.iver.utiles.extensionPoints.ExtensionPoints;
111
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
112

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

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

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

    
131
        private static int defaultMapUnits = -1;
132

    
133
        private static int defaultDistanceUnits = -1;
134

    
135
        private PropertyChangeSupport change;
136

    
137
        boolean modified = false;
138

    
139
        private String name;
140

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

    
144
        private String modificationDate;
145

    
146
        private String owner;
147

    
148
        private String comments;
149

    
150
        private Color selectionColor = null;
151

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

    
157
        private ArrayList extents = new ArrayList();
158

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
291
                return null;
292
        }
293

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

    
314
                return null;
315
        }
316

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
730
                boolean projectWindowSaved = false;
731

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

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

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

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

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

    
821
                xml.addChild(propertyList);
822
        }
823

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1107
                int childNumber = 0;
1108
                Project p = new Project();
1109
                try {
1110
                        p.comments = xml.getStringProperty("comments");
1111
                        p.creationDate = xml.getStringProperty("creationDate");
1112
                        int numExtents = xml.getIntProperty("numExtents");
1113

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

    
1119
                        // Leemos el ultiom hijo recogido
1120
                        childNumber = numExtents;
1121

    
1122
                        // Recogiendo el numero de cameras
1123
                        int numCameras = 0;
1124
                        if (xml.contains("numCameras"))
1125
                                numCameras = xml.getIntProperty("numCameras");
1126

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

    
1142
                        childNumber += numCameras;
1143

    
1144
                        int numDataSources = xml.getIntProperty("data-source-count");
1145

    
1146
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1147
                                XMLEntity child = xml.getChild(i);
1148
                                registerDataSourceFromXML(child);
1149
                        }
1150

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

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

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

    
1189
                        p.modificationDate = xml.getStringProperty("modificationDate");
1190
                        p.modified = xml.getBooleanProperty("modified");
1191
                        p.name = xml.getStringProperty("name");
1192
                        p.owner = xml.getStringProperty("owner");
1193
                        p.selectionColor = StringUtilities.string2Color(xml
1194
                                        .getStringProperty("selectionColor"));
1195

    
1196
                        p.setLinkTable();
1197
                        String strProj = xml.getStringProperty("projection");
1198

    
1199
                        if (strProj != null) {
1200
                                p.setProjection(CRSFactory.getCRS(strProj));
1201
                        }
1202

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

    
1220
                        PostProcessSupport.executeCalls();
1221
                } catch (Exception e) {
1222
                        throw new OpenException(e, p.getClass().getName());
1223
                }
1224
                // p.setSignature( p.hashCode());
1225
                return p;
1226

    
1227
        }
1228

    
1229
        // private void setSignature(int signature) {
1230
        // this.signatureAtStartup = computeSignature();
1231
        // }
1232

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1386
                return null;
1387
        }
1388

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

    
1434
                                        dataSource = pt.getModelo().getRecordset();
1435

    
1436
                                        break;
1437
                                }
1438
                        }
1439
                } catch (DriverLoadException e) {
1440
                        e.printStackTrace();
1441
                }
1442

    
1443
                if (dataSource == null) {
1444
                        // No se ha creado la tabla asociada al tema
1445
                        dataSource = ((AlphanumericData) layer).getRecordset();
1446
                }
1447

    
1448
                return dataSource;
1449

    
1450
        }
1451

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

    
1470
                                ds = t.getModelo().getRecordset();
1471

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

    
1486
                                FLayers lyrs = pv.getMapContext().getLayers();
1487

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

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

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

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

    
1604
                return result;
1605
        }
1606

    
1607
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1608
                XMLEntity child = new XMLEntity();
1609

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

    
1634
                return child;
1635
        }
1636

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

    
1662
        /**
1663
         * Devuelve un arrayList con todos los documentos.
1664
         *
1665
         * @return Documentos
1666
         */
1667
        public ArrayList getDocuments() {
1668
                ArrayList docuArray = new ArrayList();
1669
                for (int i = 0; i < documents.size(); i++) {
1670
                        ProjectDocument projectDocument = (ProjectDocument) documents
1671
                                        .get(i);
1672
                        docuArray.add(projectDocument);
1673
                }
1674
                return docuArray;
1675
        }
1676

    
1677
        /**
1678
         * Inserta un documento.
1679
         *
1680
         * @param doc
1681
         *            Documento
1682
         */
1683
        public void addDocument(ProjectDocument doc) {
1684
                documents.add(doc);
1685
                doc.addPropertyChangeListener(this);
1686
                modified = true;
1687
                change.firePropertyChange("", "", null);
1688
                doc.setProject(this, 0);
1689
                doc.afterAdd();
1690

    
1691
        }
1692

    
1693
        /**
1694
         * Borra un documento.
1695
         *
1696
         * @param doc
1697
         *            Documento
1698
         */
1699
        public void delDocument(ProjectDocument doc) {
1700
                documents.remove(doc);
1701
                modified = true;
1702
                change.firePropertyChange("", null, null);
1703
                doc.afterRemove();
1704
        }
1705

    
1706
        /**
1707
         * Sets the default selection color that will be used in subsequent
1708
         * projects.
1709
         *
1710
         * @param color
1711
         */
1712
        public static void setDefaultSelectionColor(Color color) {
1713
                defaultSelectionColor = color;
1714
        }
1715

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

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

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

    
1792
        /**
1793
         * Sets the default map unit (the units used by the data).
1794
         *
1795
         * @param mapUnits
1796
         */
1797
        public static void setDefaultMapUnits(int mapUnits) {
1798
                defaultMapUnits = mapUnits;
1799
        }
1800

    
1801
        /**
1802
         * Sets the default distance units (the units shown in the status bar)
1803
         *
1804
         * @param distanceUnits
1805
         */
1806
        public static void setDefaultDistanceUnits(int distanceUnits) {
1807
                defaultDistanceUnits = distanceUnits;
1808
        }
1809

    
1810
        public String exportToXML() throws SaveException {
1811
                XMLEntity xml = this.newExportXMLRootNode();
1812

    
1813
                Iterator iter = this.documents.iterator();
1814
                ProjectDocument document;
1815
                // FIXME: Falta atrapar los errores
1816
                while (iter.hasNext()) {
1817
                        document = (ProjectDocument) iter.next();
1818
                        document.exportToXML(xml, this);
1819
                }
1820

    
1821
                return xml.toString();
1822
        }
1823

    
1824
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1825
                XMLEntity xml = this.newExportXMLRootNode();
1826

    
1827
                for (int i = 0; i < documents.length; i++) {
1828
                        documents[i].exportToXML(xml, this);
1829
                }
1830

    
1831
                return xml.toString();
1832
        }
1833

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

    
1856
        }
1857

    
1858
        public void importFromXML(String xml, String type) throws Exception {
1859
                // FIXME: EXCEPTIONS!!!!
1860
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1861

    
1862
                if (!checkExportXMLRootNode(xmlEntity)) {
1863
                        throw new Exception();
1864
                }
1865

    
1866
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1867
                if (typeRoot.getChildrenCount() == 0) {
1868
                        return;
1869
                }
1870

    
1871
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1872

    
1873
                Hashtable conflicts = getConflicts(xmlEntity);
1874

    
1875
                if (conflicts.size() != 0) {
1876
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1877
                                        conflicts)) {
1878
                                return;
1879
                        }
1880
                }
1881
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1882
                                "dataSources"));
1883

    
1884
                int i;
1885
                ProjectDocument document;
1886
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1887
                        document = documentFactory.create(this);
1888
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1889
                }
1890

    
1891
        }
1892

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

    
1913
                                }
1914
                        }
1915
                        if (conflictsType.size() > 0) {
1916
                                conflicts
1917
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1918
                        }
1919
                }
1920
                return conflicts;
1921
        }
1922

    
1923
        public boolean isValidXMLForImport(String xml) {
1924
                XMLEntity xmlEntity;
1925
                try {
1926
                        xmlEntity = XMLEntity.parse(xml);
1927
                } catch (Exception e) {
1928
                        return false;
1929
                }
1930

    
1931
                return checkExportXMLRootNode(xmlEntity);
1932
        }
1933

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

    
1942
                if (!checkExportXMLRootNode(xmlEntity)) {
1943
                        return false;
1944
                }
1945

    
1946
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1947

    
1948
                if (typeRoot == null) {
1949
                        return false;
1950
                }
1951

    
1952
                return (typeRoot.getChildrenCount() > 0);
1953
        }
1954

    
1955
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1956
                if (!xml.contains("applicationName"))
1957
                        return false;
1958
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1959
                        return false;
1960

    
1961
                if (!xml.contains("version"))
1962
                        return false;
1963
                if (!xml.getStringProperty("version")
1964
                                .equalsIgnoreCase(Version.format()))
1965
                        return false;
1966

    
1967
                return true;
1968
        }
1969

    
1970
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
1971
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
1972
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
1973
                                .getDriverInfo(dataSourceName);
1974
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
1975
        }
1976

    
1977
        private XMLEntity newExportXMLRootNode() {
1978
                XMLEntity xml = new XMLEntity();
1979
                xml.putProperty("applicationName", "gvSIG");
1980
                xml.putProperty("version", Version.format());
1981
                return xml;
1982
        }
1983

    
1984
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
1985
                XMLEntity typeRoot = root.firstChild("type", type);
1986
                if (typeRoot == null) {
1987
                        typeRoot = this.newExportXMLTypeNode(type);
1988
                        root.addChild(typeRoot);
1989
                }
1990
                return typeRoot;
1991
        }
1992

    
1993
        private XMLEntity newExportXMLTypeNode(String type) {
1994
                XMLEntity xmlDataSources = new XMLEntity();
1995
                xmlDataSources.putProperty("type", type);
1996
                return xmlDataSources;
1997
        }
1998

    
1999
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2000
                String name = xmlDataSource.getStringProperty("gdbmsname");
2001

    
2002
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2003
                        if (xmlDataSource.getStringProperty("type").equals(
2004
                                        "otherDriverFile")) {
2005
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2006
                                                xmlDataSource.getStringProperty("driverName"), name,
2007
                                                xmlDataSource.getStringProperty("file"));
2008

    
2009
                        } else if (xmlDataSource.getStringProperty("type").equals(
2010
                                        "sameDriverFile")) {
2011

    
2012
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2013
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2014
                                                name, xmlDataSource.getStringProperty("host"),
2015
                                                xmlDataSource.getIntProperty("port"),
2016
                                                xmlDataSource.getStringProperty("user"),
2017
                                                xmlDataSource.getStringProperty("password"),
2018
                                                xmlDataSource.getStringProperty("dbName"),
2019
                                                xmlDataSource.getStringProperty("tableName"),
2020
                                                xmlDataSource.getStringProperty("driverInfo"));
2021
                        } else {
2022
                                return false;
2023
                        }
2024

    
2025
                }
2026
                return true;
2027
        }
2028

    
2029
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2030
                try {
2031
                        int numDataSources = xmlDataSources.getChildrenCount();
2032

    
2033
                        if (numDataSources == 0)
2034
                                return true;
2035
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2036

    
2037
                        for (int i = 0; i < numDataSources; i++) {
2038
                                XMLEntity child = xmlDataSources.getChild(i);
2039
                                if (!this.registerDataSourceFromXML(child)) {
2040
                                        return false;
2041
                                }
2042
                        }
2043

    
2044
                        return true;
2045
                } catch (Exception e) {
2046
                        e.printStackTrace();
2047
                        return false;
2048
                }
2049
        }
2050

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

    
2068
                } catch (Exception e1) {
2069
                        return null;
2070
                }
2071
                return pde;
2072
        }
2073

    
2074
        // public boolean hasChanged() {
2075
        // return signatureAtStartup != computeSignature();
2076
        // }
2077

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

    
2159
}