Statistics
| Revision:

root / branches / v10 / applications / appgvSIG / src / com / iver / cit / gvsig / project / Project.java @ 11333

History | View | Annotate | Download (60.7 KB)

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

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

    
57
import org.cresques.cts.IProjection;
58

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

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

    
120
        static private IProjection defaultProjection = null;
121

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

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

    
132
        private static int defaultMapUnits = -1;
133

    
134
        private static int defaultDistanceUnits = -1;
135

    
136
        private PropertyChangeSupport change;
137

    
138
        boolean modified = true;
139

    
140
        private String name;
141

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

    
145
        private String modificationDate;
146

    
147
        private String owner;
148

    
149
        private String comments;
150

    
151
        private Color selectionColor = null;
152

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

    
158
        private ArrayList extents = new ArrayList();
159

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
292
                return null;
293
        }
294

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

    
315
                return null;
316
        }
317

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
727
                boolean projectWindowSaved = false;
728

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

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

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

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

    
813
                xml.addChild(propertyList);
814
        }
815

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

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

    
849
                this.initialWindowProperties = orderedProperties.values().iterator();
850
        }
851

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

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

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

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

    
899
                if (xml.contains("numViews"))
900
                        childNumb += xml.getIntProperty("numViews");
901

    
902
                if (xml.contains("numMaps"))
903
                        limit = childNumb + xml.getIntProperty("numMaps");
904

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

    
926
                this.initialWindowProperties = windowList.iterator();
927
        }
928

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

    
939
                Iterator propertiesIterator = this.initialWindowProperties;
940
                if (propertiesIterator != null) {
941
                        this.initialWindowProperties = null;
942

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1135
                        childNumber += numCameras;
1136

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

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

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

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

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

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

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

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

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

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

    
1220
        }
1221

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

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

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

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

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

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

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

    
1288
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1289
        }
1290

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

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

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

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

    
1353
        public static IProjection getDefaultProjection() {
1354
                if (defaultProjection == null){
1355
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1356
                        .getPersistentXML();
1357
        
1358
                        // Default Projection
1359
                        String projCode = null; 
1360
                        if (xml.contains("DefaultProjection")) {
1361
                                projCode = xml.getStringProperty("DefaultProjection");
1362
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1363
                        } else {
1364
                                Project.setDefaultProjection(defaultFactoryProjection);
1365
                        }
1366
                        
1367
                }
1368
                return Project.defaultProjection;
1369
        }
1370

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

    
1388
                        if (elem.getName().equals(name)) {
1389
                                return elem;
1390
                        }
1391
                }
1392

    
1393
                return null;
1394
        }
1395

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

    
1441
                                        dataSource = pt.getModelo().getRecordset();
1442

    
1443
                                        break;
1444
                                }
1445
                        }
1446
                } catch (DriverLoadException e) {
1447
                        e.printStackTrace();
1448
                }
1449

    
1450
                if (dataSource == null) {
1451
                        // No se ha creado la tabla asociada al tema
1452
                        dataSource = ((AlphanumericData) layer).getRecordset();
1453
                }
1454

    
1455
                return dataSource;
1456

    
1457
        }
1458

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

    
1477
                                ds = t.getModelo().getRecordset();
1478

    
1479
                                if (t.getOriginal() != null)
1480
                                        usedDataSources.put(t.getOriginal().getRecordset()
1481
                                                        .getName(), t.getOriginal());
1482
                                usedDataSources.put(ds.getName(), ds);
1483
                        }
1484
                } catch (DriverLoadException e) {
1485
                        e.printStackTrace();
1486
                }
1487
                // Ahora las vistas
1488
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1489
                try {
1490
                        for (i = 0; i < views.size(); i++) {
1491
                                ProjectView pv = (ProjectView) views.get(i);
1492

    
1493
                                FLayers lyrs = pv.getMapContext().getLayers();
1494

    
1495
                                for (j = 0; j < lyrs.getLayersCount(); j++) {
1496
                                        FLayer lyr = lyrs.getLayer(j);
1497
                                        if (lyr instanceof FLyrVect) {
1498
                                                FLyrVect lyrVect = (FLyrVect) lyr;
1499
                                                if (lyrVect.isAvailable())
1500
                                                        usedDataSources.put(lyrVect.getRecordset()
1501
                                                                        .getName(), lyrVect.getSource()
1502
                                                                        .getRecordset());
1503
                                        }
1504
                                }
1505
                                MapContext aux = pv.getMapOverViewContext();
1506
                                if (aux != null) {
1507
                                        FLayers lyrsOverview = aux.getLayers();
1508
                                        for (j = 0; j < lyrsOverview.getLayersCount(); j++) {
1509
                                                FLayer lyr = lyrsOverview.getLayer(j);
1510
                                                if (lyr instanceof FLyrVect) {
1511
                                                        FLyrVect lyrVect = (FLyrVect) lyr;
1512
                                                        usedDataSources.put(lyrVect.getSource()
1513
                                                                        .getRecordset().getName(), lyrVect
1514
                                                                        .getSource().getRecordset());
1515
                                                }
1516
                                        }
1517
                                }
1518

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

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

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

    
1611
                return result;
1612
        }
1613

    
1614
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1615
                XMLEntity child = new XMLEntity();
1616

    
1617
                if (di instanceof ObjectSourceInfo) {
1618
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1619
                        child.putProperty("type", "sameDriverFile");
1620
                        child.putProperty("gdbmsname", driver.name);
1621
                } else if (di instanceof FileSourceInfo) {
1622
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1623
                        child.putProperty("type", "otherDriverFile");
1624
                        child.putProperty("gdbmsname", vfdi.name);
1625
                        child.putProperty("file", vfdi.file);
1626
                        child.putProperty("driverName", vfdi.driverName);
1627
                } else if (di instanceof DBSourceInfo) {
1628
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1629
                        child.putProperty("type", "db");
1630
                        child.putProperty("gdbmsname", dbdi.name);
1631
                        child.putProperty("dbms", dbdi.dbms);
1632
                        child.putProperty("host", dbdi.host);
1633
                        child.putProperty("port", dbdi.port);
1634
                        child.putProperty("user", dbdi.user);
1635
                        child.putProperty("password", dbdi.password);
1636
                        child.putProperty("dbName", dbdi.dbName);
1637
                        child.putProperty("tableName", dbdi.tableName);
1638
                        child.putProperty("driverInfo", dbdi.driverName);
1639
                }
1640

    
1641
                return child;
1642
        }
1643

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

    
1669
        /**
1670
         * Devuelve un arrayList con todos los documentos.
1671
         *
1672
         * @return Documentos
1673
         */
1674
        public ArrayList getDocuments() {
1675
                ArrayList docuArray = new ArrayList();
1676
                for (int i = 0; i < documents.size(); i++) {
1677
                        ProjectDocument projectDocument = (ProjectDocument) documents
1678
                                        .get(i);
1679
                        docuArray.add(projectDocument);
1680
                }
1681
                return docuArray;
1682
        }
1683

    
1684
        /**
1685
         * Inserta un documento.
1686
         *
1687
         * @param doc
1688
         *            Documento
1689
         */
1690
        public void addDocument(ProjectDocument doc) {
1691
                documents.add(doc);
1692
                doc.addPropertyChangeListener(this);
1693
                //modified = true;
1694
                change.firePropertyChange("", "", null);
1695
                doc.setProject(this, 0);
1696
                doc.afterAdd();
1697

    
1698
        }
1699

    
1700
        /**
1701
         * Borra un documento.
1702
         *
1703
         * @param doc
1704
         *            Documento
1705
         */
1706
        public void delDocument(ProjectDocument doc) {
1707
                documents.remove(doc);
1708
                modified = true;
1709
                change.firePropertyChange("", null, null);
1710
                doc.afterRemove();
1711
        }
1712

    
1713
        /**
1714
         * Sets the default selection color that will be used in subsequent
1715
         * projects.
1716
         *
1717
         * @param color
1718
         */
1719
        public static void setDefaultSelectionColor(Color color) {
1720
                defaultSelectionColor = color;
1721
        }
1722

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

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

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

    
1799
        /**
1800
         * Sets the default map unit (the units used by the data).
1801
         *
1802
         * @param mapUnits
1803
         */
1804
        public static void setDefaultMapUnits(int mapUnits) {
1805
                defaultMapUnits = mapUnits;
1806
        }
1807

    
1808
        /**
1809
         * Sets the default distance units (the units shown in the status bar)
1810
         *
1811
         * @param distanceUnits
1812
         */
1813
        public static void setDefaultDistanceUnits(int distanceUnits) {
1814
                defaultDistanceUnits = distanceUnits;
1815
        }
1816

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

    
1820
                Iterator iter = this.documents.iterator();
1821
                ProjectDocument document;
1822
                // FIXME: Falta atrapar los errores
1823
                while (iter.hasNext()) {
1824
                        document = (ProjectDocument) iter.next();
1825
                        document.exportToXML(xml, this);
1826
                }
1827

    
1828
                return xml.toString();
1829
        }
1830

    
1831
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1832
                XMLEntity xml = this.newExportXMLRootNode();
1833

    
1834
                for (int i = 0; i < documents.length; i++) {
1835
                        documents[i].exportToXML(xml, this);
1836
                }
1837

    
1838
                return xml.toString();
1839
        }
1840

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

    
1863
        }
1864

    
1865
        public void importFromXML(String xml, String type) throws Exception {
1866
                // FIXME: EXCEPTIONS!!!!
1867
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1868

    
1869
                if (!checkExportXMLRootNode(xmlEntity)) {
1870
                        throw new Exception();
1871
                }
1872

    
1873
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1874
                if (typeRoot.getChildrenCount() == 0) {
1875
                        return;
1876
                }
1877

    
1878
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1879

    
1880
                Hashtable conflicts = getConflicts(xmlEntity);
1881

    
1882
                if (conflicts.size() != 0) {
1883
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1884
                                        conflicts)) {
1885
                                return;
1886
                        }
1887
                }
1888
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1889
                                "dataSources"));
1890

    
1891
                int i;
1892
                ProjectDocument document;
1893
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1894
                        document = documentFactory.create(this);
1895
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1896
                }
1897

    
1898
        }
1899

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

    
1920
                                }
1921
                        }
1922
                        if (conflictsType.size() > 0) {
1923
                                conflicts
1924
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1925
                        }
1926
                }
1927
                return conflicts;
1928
        }
1929

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

    
1938
                return checkExportXMLRootNode(xmlEntity);
1939
        }
1940

    
1941
        public boolean isValidXMLForImport(String xml, String type) {
1942
                XMLEntity xmlEntity;
1943
                try {
1944
                        xmlEntity = XMLEntity.parse(xml);
1945
                } catch (Exception e) {
1946
                        return false;
1947
                }
1948

    
1949
                if (!checkExportXMLRootNode(xmlEntity)) {
1950
                        return false;
1951
                }
1952

    
1953
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1954

    
1955
                if (typeRoot == null) {
1956
                        return false;
1957
                }
1958

    
1959
                return (typeRoot.getChildrenCount() > 0);
1960
        }
1961

    
1962
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1963
                if (!xml.contains("applicationName"))
1964
                        return false;
1965
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1966
                        return false;
1967

    
1968
                if (!xml.contains("version"))
1969
                        return false;
1970
                if (!xml.getStringProperty("version")
1971
                                .equalsIgnoreCase(Version.format()))
1972
                        return false;
1973

    
1974
                return true;
1975
        }
1976

    
1977
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
1978
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
1979
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
1980
                                .getDriverInfo(dataSourceName);
1981
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
1982
        }
1983

    
1984
        private XMLEntity newExportXMLRootNode() {
1985
                XMLEntity xml = new XMLEntity();
1986
                xml.putProperty("applicationName", "gvSIG");
1987
                xml.putProperty("version", Version.format());
1988
                return xml;
1989
        }
1990

    
1991
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
1992
                XMLEntity typeRoot = root.firstChild("type", type);
1993
                if (typeRoot == null) {
1994
                        typeRoot = this.newExportXMLTypeNode(type);
1995
                        root.addChild(typeRoot);
1996
                }
1997
                return typeRoot;
1998
        }
1999

    
2000
        private XMLEntity newExportXMLTypeNode(String type) {
2001
                XMLEntity xmlDataSources = new XMLEntity();
2002
                xmlDataSources.putProperty("type", type);
2003
                return xmlDataSources;
2004
        }
2005

    
2006
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2007
                String name = xmlDataSource.getStringProperty("gdbmsname");
2008

    
2009
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2010
                        if (xmlDataSource.getStringProperty("type").equals(
2011
                                        "otherDriverFile")) {
2012
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2013
                                                xmlDataSource.getStringProperty("driverName"), name,
2014
                                                xmlDataSource.getStringProperty("file"));
2015

    
2016
                        } else if (xmlDataSource.getStringProperty("type").equals(
2017
                                        "sameDriverFile")) {
2018

    
2019
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2020
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2021
                                                name, xmlDataSource.getStringProperty("host"),
2022
                                                xmlDataSource.getIntProperty("port"),
2023
                                                xmlDataSource.getStringProperty("user"),
2024
                                                xmlDataSource.getStringProperty("password"),
2025
                                                xmlDataSource.getStringProperty("dbName"),
2026
                                                xmlDataSource.getStringProperty("tableName"),
2027
                                                xmlDataSource.getStringProperty("driverInfo"));
2028
                        } else {
2029
                                return false;
2030
                        }
2031

    
2032
                }
2033
                return true;
2034
        }
2035

    
2036
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2037
                try {
2038
                        int numDataSources = xmlDataSources.getChildrenCount();
2039

    
2040
                        if (numDataSources == 0)
2041
                                return true;
2042
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2043

    
2044
                        for (int i = 0; i < numDataSources; i++) {
2045
                                XMLEntity child = xmlDataSources.getChild(i);
2046
                                if (!this.registerDataSourceFromXML(child)) {
2047
                                        return false;
2048
                                }
2049
                        }
2050

    
2051
                        return true;
2052
                } catch (Exception e) {
2053
                        e.printStackTrace();
2054
                        return false;
2055
                }
2056
        }
2057

    
2058
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2059
                ProjectDocumentFactory pde = null;
2060
                try {
2061
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2062
                                        .getInstance();
2063
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2064
                                        .get("Documents"));
2065
                        try {
2066
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2067
                        } catch (InstantiationException e) {
2068
                                NotificationManager.addError(
2069
                                                "Clase de ProjectDocument no reconocida", e);
2070
                        } catch (IllegalAccessException e) {
2071
                                NotificationManager.addError(
2072
                                                "Clase de ProjectDocument no reconocida", e);
2073
                        }
2074

    
2075
                } catch (Exception e1) {
2076
                        return null;
2077
                }
2078
                return pde;
2079
        }
2080

    
2081
        // public boolean hasChanged() {
2082
        // return signatureAtStartup != computeSignature();
2083
        // }
2084

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

    
2166
}