Statistics
| Revision:

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

History | View | Annotate | Download (60.7 KB)

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

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

    
57
import org.cresques.cts.IProjection;
58

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

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

    
120
        static private IProjection defaultProjection = null;
121

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

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

    
132
        private static int defaultMapUnits = -1;
133

    
134
        private static int defaultDistanceUnits = -1;
135

    
136
        private PropertyChangeSupport change;
137

    
138
        boolean modified = true;
139

    
140
        private String name;
141

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

    
145
        private String modificationDate;
146

    
147
        private String owner;
148

    
149
        private String comments;
150

    
151
        private Color selectionColor = null;
152

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

    
158
        private ArrayList extents = new ArrayList();
159

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
293
                return null;
294
        }
295

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

    
316
                return null;
317
        }
318

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
728
                boolean projectWindowSaved = false;
729

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

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

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

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

    
814
                xml.addChild(propertyList);
815
        }
816

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1136
                        childNumber += numCameras;
1137

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

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

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

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

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

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

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

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

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

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

    
1221
        }
1222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1394
                return null;
1395
        }
1396

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

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

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

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

    
1456
                return dataSource;
1457

    
1458
        }
1459

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

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

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

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

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

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

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

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

    
1612
                return result;
1613
        }
1614

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

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

    
1642
                return child;
1643
        }
1644

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

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

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

    
1699
        }
1700

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

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

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

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

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

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

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

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

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

    
1829
                return xml.toString();
1830
        }
1831

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

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

    
1839
                return xml.toString();
1840
        }
1841

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

    
1864
        }
1865

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

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

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

    
1879
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1880

    
1881
                Hashtable conflicts = getConflicts(xmlEntity);
1882

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

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

    
1899
        }
1900

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

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

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

    
1939
                return checkExportXMLRootNode(xmlEntity);
1940
        }
1941

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

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

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

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

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

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

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

    
1975
                return true;
1976
        }
1977

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

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

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

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

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

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

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

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

    
2033
                }
2034
                return true;
2035
        }
2036

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

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

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

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

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

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

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

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

    
2167
}