Statistics
| Revision:

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

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

    
58
import org.cresques.cts.IProjection;
59

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

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

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

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

    
128
        private static int defaultMapUnits = -1;
129

    
130
        private static int defaultDistanceUnits = -1;
131

    
132
        private PropertyChangeSupport change;
133

    
134
        boolean modified = false;
135

    
136
        private String name;
137

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

    
141
        private String modificationDate;
142

    
143
        private String owner;
144

    
145
        private String comments;
146

    
147
        private Color selectionColor = null;
148

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

    
154
        private ArrayList extents = new ArrayList();
155

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
288
                return null;
289
        }
290

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

    
311
                return null;
312
        }
313

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
727
                boolean projectWindowSaved = false;
728

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

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

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

    
807
                xml.addChild(propertyList);
808
        }
809

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
988
                        if (pe != null) {
989
                                pe.setProject(this);
990
                                pe.showProjectWindow();
991
                        }
992
                }
993
        }
994

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

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

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

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

    
1047
                        p.modificationDate = xml.getStringProperty("modificationDate");
1048
                        p.modified = xml.getBooleanProperty("modified");
1049
                        p.name = xml.getStringProperty("name");
1050
                        p.owner = xml.getStringProperty("owner");
1051
                        p.selectionColor = StringUtilities.string2Color(xml
1052
                                        .getStringProperty("selectionColor"));
1053

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

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

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

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

    
1091
                        // Leemos el ultiom hijo recogido
1092
                        childNumber = numExtents;
1093

    
1094
                        // Recogiendo el numero de cameras
1095
                        int numCameras = 0;
1096
                        if (xml.contains("numCameras"))
1097
                                numCameras = xml.getIntProperty("numCameras");
1098

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

    
1114
                        childNumber += numCameras;
1115

    
1116
                        int numDataSources = xml.getIntProperty("data-source-count");
1117

    
1118
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1119
                                XMLEntity child = xml.getChild(i);
1120
                                registerDataSourceFromXML(child);
1121
                        }
1122

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

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

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

    
1161
                        p.modificationDate = xml.getStringProperty("modificationDate");
1162
                        p.modified = xml.getBooleanProperty("modified");
1163
                        p.name = xml.getStringProperty("name");
1164
                        p.owner = xml.getStringProperty("owner");
1165
                        p.selectionColor = StringUtilities.string2Color(xml
1166
                                        .getStringProperty("selectionColor"));
1167

    
1168
                        p.setLinkTable();
1169
                        String strProj = xml.getStringProperty("projection");
1170

    
1171
                        if (strProj != null) {
1172
                                p.setProjection(CRSFactory.getCRS(strProj));
1173
                        }
1174

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

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

    
1199
        }
1200

    
1201
        // private void setSignature(int signature) {
1202
        // this.signatureAtStartup = computeSignature();
1203
        // }
1204

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

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

    
1228
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1229
                                                                .get(i)).getModelo().getRecordset(),
1230
                                                                ((ProjectTable) tables.get(j)).getModelo()
1231
                                                                                .getRecordset(), ((ProjectTable) tables
1232
                                                                                .get(i)).getField1(),
1233
                                                                ((ProjectTable) tables.get(i)).getField2());
1234

    
1235
                                                (((ProjectTable) tables.get(i)).getModelo()
1236
                                                                .getRecordset()).addSelectionListener(lsl);
1237

    
1238
                                        }
1239
                                } catch (DriverLoadException e) {
1240
                                        e.printStackTrace();
1241
                                }
1242
                        }
1243
                }
1244
        }
1245

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

    
1267
                throw new RuntimeException("The layer is not in a view");
1268
        }
1269

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

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

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

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

    
1332
        public static IProjection getDefaultProjection() {
1333
                return Project.defaultProjection;
1334
        }
1335

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

    
1353
                        if (elem.getName().equals(name)) {
1354
                                return elem;
1355
                        }
1356
                }
1357

    
1358
                return null;
1359
        }
1360

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

    
1406
                                        dataSource = pt.getModelo().getRecordset();
1407

    
1408
                                        break;
1409
                                }
1410
                        }
1411
                } catch (DriverLoadException e) {
1412
                        e.printStackTrace();
1413
                }
1414

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

    
1420
                return dataSource;
1421

    
1422
        }
1423

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

    
1442
                                ds = t.getModelo().getRecordset();
1443

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

    
1458
                                FLayers lyrs = pv.getMapContext().getLayers();
1459

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

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

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

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

    
1576
                return result;
1577
        }
1578

    
1579
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1580
                XMLEntity child = new XMLEntity();
1581

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

    
1606
                return child;
1607
        }
1608

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

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

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

    
1663
        }
1664

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

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

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

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

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

    
1761
        /**
1762
         * Sets the default map unit (the units used by the data).
1763
         * 
1764
         * @param mapUnits
1765
         */
1766
        public static void setDefaultMapUnits(int mapUnits) {
1767
                defaultMapUnits = mapUnits;
1768
        }
1769

    
1770
        /**
1771
         * Sets the default distance units (the units shown in the status bar)
1772
         * 
1773
         * @param distanceUnits
1774
         */
1775
        public static void setDefaultDistanceUnits(int distanceUnits) {
1776
                defaultDistanceUnits = distanceUnits;
1777
        }
1778

    
1779
        public String exportToXML() throws SaveException {
1780
                XMLEntity xml = this.newExportXMLRootNode();
1781

    
1782
                Iterator iter = this.documents.iterator();
1783
                ProjectDocument document;
1784
                // FIXME: Falta atrapar los errores
1785
                while (iter.hasNext()) {
1786
                        document = (ProjectDocument) iter.next();
1787
                        document.exportToXML(xml, this);
1788
                }
1789

    
1790
                return xml.toString();
1791
        }
1792

    
1793
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1794
                XMLEntity xml = this.newExportXMLRootNode();
1795

    
1796
                for (int i = 0; i < documents.length; i++) {
1797
                        documents[i].exportToXML(xml, this);
1798
                }
1799

    
1800
                return xml.toString();
1801
        }
1802

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

    
1825
        }
1826

    
1827
        public void importFromXML(String xml, String type) throws Exception {
1828
                // FIXME: EXCEPTIONS!!!!
1829
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1830

    
1831
                if (!checkExportXMLRootNode(xmlEntity)) {
1832
                        throw new Exception();
1833
                }
1834

    
1835
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1836
                if (typeRoot.getChildrenCount() == 0) {
1837
                        return;
1838
                }
1839

    
1840
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1841

    
1842
                Hashtable conflicts = getConflicts(xmlEntity);
1843

    
1844
                if (conflicts.size() != 0) {
1845
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1846
                                        conflicts)) {
1847
                                return;
1848
                        }
1849
                }
1850
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1851
                                "dataSources"));
1852

    
1853
                int i;
1854
                ProjectDocument document;
1855
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1856
                        document = documentFactory.create(this);
1857
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1858
                }
1859

    
1860
        }
1861

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

    
1882
                                }
1883
                        }
1884
                        if (conflictsType.size() > 0) {
1885
                                conflicts
1886
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1887
                        }
1888
                }
1889
                return conflicts;
1890
        }
1891

    
1892
        public boolean isValidXMLForImport(String xml) {
1893
                XMLEntity xmlEntity;
1894
                try {
1895
                        xmlEntity = XMLEntity.parse(xml);
1896
                } catch (Exception e) {
1897
                        return false;
1898
                }
1899

    
1900
                return checkExportXMLRootNode(xmlEntity);
1901
        }
1902

    
1903
        public boolean isValidXMLForImport(String xml, String type) {
1904
                XMLEntity xmlEntity;
1905
                try {
1906
                        xmlEntity = XMLEntity.parse(xml);
1907
                } catch (Exception e) {
1908
                        return false;
1909
                }
1910

    
1911
                if (!checkExportXMLRootNode(xmlEntity)) {
1912
                        return false;
1913
                }
1914

    
1915
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1916

    
1917
                if (typeRoot == null) {
1918
                        return false;
1919
                }
1920

    
1921
                return (typeRoot.getChildrenCount() > 0);
1922
        }
1923

    
1924
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1925
                if (!xml.contains("applicationName"))
1926
                        return false;
1927
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1928
                        return false;
1929

    
1930
                if (!xml.contains("version"))
1931
                        return false;
1932
                if (!xml.getStringProperty("version")
1933
                                .equalsIgnoreCase(Version.format()))
1934
                        return false;
1935

    
1936
                return true;
1937
        }
1938

    
1939
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
1940
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
1941
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
1942
                                .getDriverInfo(dataSourceName);
1943
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
1944
        }
1945

    
1946
        private XMLEntity newExportXMLRootNode() {
1947
                XMLEntity xml = new XMLEntity();
1948
                xml.putProperty("applicationName", "gvSIG");
1949
                xml.putProperty("version", Version.format());
1950
                return xml;
1951
        }
1952

    
1953
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
1954
                XMLEntity typeRoot = root.firstChild("type", type);
1955
                if (typeRoot == null) {
1956
                        typeRoot = this.newExportXMLTypeNode(type);
1957
                        root.addChild(typeRoot);
1958
                }
1959
                return typeRoot;
1960
        }
1961

    
1962
        private XMLEntity newExportXMLTypeNode(String type) {
1963
                XMLEntity xmlDataSources = new XMLEntity();
1964
                xmlDataSources.putProperty("type", type);
1965
                return xmlDataSources;
1966
        }
1967

    
1968
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
1969
                String name = xmlDataSource.getStringProperty("gdbmsname");
1970

    
1971
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
1972
                        if (xmlDataSource.getStringProperty("type").equals(
1973
                                        "otherDriverFile")) {
1974
                                LayerFactory.getDataSourceFactory().addFileDataSource(
1975
                                                xmlDataSource.getStringProperty("driverName"), name,
1976
                                                xmlDataSource.getStringProperty("file"));
1977

    
1978
                        } else if (xmlDataSource.getStringProperty("type").equals(
1979
                                        "sameDriverFile")) {
1980

    
1981
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
1982
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
1983
                                                name, xmlDataSource.getStringProperty("host"),
1984
                                                xmlDataSource.getIntProperty("port"),
1985
                                                xmlDataSource.getStringProperty("user"),
1986
                                                xmlDataSource.getStringProperty("password"),
1987
                                                xmlDataSource.getStringProperty("dbName"),
1988
                                                xmlDataSource.getStringProperty("tableName"),
1989
                                                xmlDataSource.getStringProperty("driverInfo"));
1990
                        } else {
1991
                                return false;
1992
                        }
1993

    
1994
                }
1995
                return true;
1996
        }
1997

    
1998
        private boolean registerDataSources(XMLEntity xmlDataSources) {
1999
                try {
2000
                        int numDataSources = xmlDataSources.getChildrenCount();
2001

    
2002
                        if (numDataSources == 0)
2003
                                return true;
2004
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2005

    
2006
                        for (int i = 0; i < numDataSources; i++) {
2007
                                XMLEntity child = xmlDataSources.getChild(i);
2008
                                if (!this.registerDataSourceFromXML(child)) {
2009
                                        return false;
2010
                                }
2011
                        }
2012

    
2013
                        return true;
2014
                } catch (Exception e) {
2015
                        e.printStackTrace();
2016
                        return false;
2017
                }
2018
        }
2019

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

    
2037
                } catch (Exception e1) {
2038
                        return null;
2039
                }
2040
                return pde;
2041
        }
2042

    
2043
        // public boolean hasChanged() {
2044
        // return signatureAtStartup != computeSignature();
2045
        // }
2046

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

    
2128
}