Statistics
| Revision:

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

History | View | Annotate | Download (60.2 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 = CRSFactory
121
                        .getCRS("EPSG:23030");
122

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

    
130
        private static int defaultMapUnits = -1;
131

    
132
        private static int defaultDistanceUnits = -1;
133

    
134
        private PropertyChangeSupport change;
135

    
136
        boolean modified = true;
137

    
138
        private String name;
139

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

    
143
        private String modificationDate;
144

    
145
        private String owner;
146

    
147
        private String comments;
148

    
149
        private Color selectionColor = null;
150

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

    
156
        private ArrayList extents = new ArrayList();
157

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
290
                return null;
291
        }
292

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

    
313
                return null;
314
        }
315

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
478
                return extents.remove(arg0);
479
        }
480

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

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

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

    
514
                return this.cameras.remove(arg0);
515
        }
516

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

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

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

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

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

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

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

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

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

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

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

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

    
647
                int numExtents = extents.size();
648
                xml.putProperty("numExtents", numExtents);
649

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

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

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

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

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

    
715
                saveWindowProperties(xml);
716
                return xml;
717
        }
718

    
719
        private void saveWindowProperties(XMLEntity xml) {
720
                XMLEntity propertyList = new XMLEntity();
721

    
722
                propertyList.setName("AndamiPersistence");
723
                propertyList.putProperty("className", Project.class.getName());
724

    
725
                boolean projectWindowSaved = false;
726

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

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

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

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

    
811
                xml.addChild(propertyList);
812
        }
813

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

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

    
847
                this.initialWindowProperties = orderedProperties.values().iterator();
848
        }
849

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

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

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

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

    
897
                if (xml.contains("numViews"))
898
                        childNumb += xml.getIntProperty("numViews");
899

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

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

    
924
                this.initialWindowProperties = windowList.iterator();
925
        }
926

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

    
937
                Iterator propertiesIterator = this.initialWindowProperties;
938
                if (propertiesIterator != null) {
939
                        this.initialWindowProperties = null;
940

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

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

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

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

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

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

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

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

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

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

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

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

    
1110
                        // Leemos el ultiom hijo recogido
1111
                        childNumber = numExtents;
1112

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

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

    
1133
                        childNumber += numCameras;
1134

    
1135
                        int numDataSources = xml.getIntProperty("data-source-count");
1136

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

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

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

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

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

    
1187
                        p.setLinkTable();
1188
                        String strProj = xml.getStringProperty("projection");
1189

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

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

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

    
1218
        }
1219

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

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

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

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

    
1254
                                                (((ProjectTable) tables.get(i)).getModelo()
1255
                                                                .getRecordset()).addSelectionListener(lsl);
1256

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

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

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

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

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

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

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

    
1351
        public static IProjection getDefaultProjection() {
1352
                return Project.defaultProjection;
1353
        }
1354

    
1355
        /**
1356
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1357
         * pointExtension, este ?ltimo se puede obtener del
1358
         * Project****Factory.registerName.
1359
         *
1360
         * @param name
1361
         *            Nombre del documento
1362
         * @param type
1363
         *            nombre de registro en el extensionPoint
1364
         *
1365
         * @return Documento
1366
         */
1367
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1368
                ArrayList docs = getDocumentsByType(type);
1369
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1370
                        ProjectDocument elem = (ProjectDocument) iter.next();
1371

    
1372
                        if (elem.getName().equals(name)) {
1373
                                return elem;
1374
                        }
1375
                }
1376

    
1377
                return null;
1378
        }
1379

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

    
1425
                                        dataSource = pt.getModelo().getRecordset();
1426

    
1427
                                        break;
1428
                                }
1429
                        }
1430
                } catch (DriverLoadException e) {
1431
                        e.printStackTrace();
1432
                }
1433

    
1434
                if (dataSource == null) {
1435
                        // No se ha creado la tabla asociada al tema
1436
                        dataSource = ((AlphanumericData) layer).getRecordset();
1437
                }
1438

    
1439
                return dataSource;
1440

    
1441
        }
1442

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

    
1461
                                ds = t.getModelo().getRecordset();
1462

    
1463
                                if (t.getOriginal() != null)
1464
                                        usedDataSources.put(t.getOriginal().getRecordset()
1465
                                                        .getName(), t.getOriginal());
1466
                                usedDataSources.put(ds.getName(), ds);
1467
                        }
1468
                } catch (DriverLoadException e) {
1469
                        e.printStackTrace();
1470
                }
1471
                // Ahora las vistas
1472
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1473
                try {
1474
                        for (i = 0; i < views.size(); i++) {
1475
                                ProjectView pv = (ProjectView) views.get(i);
1476

    
1477
                                FLayers lyrs = pv.getMapContext().getLayers();
1478

    
1479
                                for (j = 0; j < lyrs.getLayersCount(); j++) {
1480
                                        FLayer lyr = lyrs.getLayer(j);
1481
                                        if (lyr instanceof FLyrVect) {
1482
                                                FLyrVect lyrVect = (FLyrVect) lyr;
1483
                                                if (lyrVect.isAvailable())
1484
                                                        usedDataSources.put(lyrVect.getRecordset()
1485
                                                                        .getName(), lyrVect.getSource()
1486
                                                                        .getRecordset());
1487
                                        }
1488
                                }
1489
                                MapContext aux = pv.getMapOverViewContext();
1490
                                if (aux != null) {
1491
                                        FLayers lyrsOverview = aux.getLayers();
1492
                                        for (j = 0; j < lyrsOverview.getLayersCount(); j++) {
1493
                                                FLayer lyr = lyrsOverview.getLayer(j);
1494
                                                if (lyr instanceof FLyrVect) {
1495
                                                        FLyrVect lyrVect = (FLyrVect) lyr;
1496
                                                        usedDataSources.put(lyrVect.getSource()
1497
                                                                        .getRecordset().getName(), lyrVect
1498
                                                                        .getSource().getRecordset());
1499
                                                }
1500
                                        }
1501
                                }
1502

    
1503
                        } // for i
1504
                } catch (DriverLoadException e) {
1505
                        e.printStackTrace();
1506
                } catch (DriverException e) {
1507
                        e.printStackTrace();
1508
                }
1509
                // Recorremos los dataSources y los borramos si no
1510
                // los estamos usando.
1511
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1512
                                .getDriverInfos();
1513
                try {
1514
                        for (i = 0; i < infos.length; i++) {
1515
                                if (!usedDataSources.containsKey(infos[i].name)) {
1516
                                        DataSource ds;
1517
                                        ds = LayerFactory.getDataSourceFactory()
1518
                                                        .createRandomDataSource(infos[i].name);
1519
                                        ds.remove();
1520
                                }
1521
                        }
1522
                } catch (DriverLoadException e) {
1523
                        e.printStackTrace();
1524
                } catch (NoSuchTableException e) {
1525
                        e.printStackTrace();
1526
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1527
                        e.printStackTrace();
1528
                }
1529
        }
1530

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

    
1575
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1576
                WindowInfo result = new WindowInfo();
1577
                result.setX(xml.getIntProperty("X"));
1578
                result.setY(xml.getIntProperty("Y"));
1579
                result.setHeight(xml.getIntProperty("Height"));
1580
                result.setWidth(xml.getIntProperty("Width"));
1581
                result.setClosed(xml.getBooleanProperty("isClosed"));
1582
                if (xml.contains("isMaximized")) {
1583
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1584
                        result.setMaximized(maximized);
1585
                        if (maximized == true) {
1586
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1587
                                                .getIntProperty("normalY"), xml
1588
                                                .getIntProperty("normalWidth"), xml
1589
                                                .getIntProperty("normalHeight"));
1590
                        } else {
1591
                                result.setNormalBounds(result.getBounds());
1592
                        }
1593
                }
1594

    
1595
                return result;
1596
        }
1597

    
1598
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1599
                XMLEntity child = new XMLEntity();
1600

    
1601
                if (di instanceof ObjectSourceInfo) {
1602
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1603
                        child.putProperty("type", "sameDriverFile");
1604
                        child.putProperty("gdbmsname", driver.name);
1605
                } else if (di instanceof FileSourceInfo) {
1606
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1607
                        child.putProperty("type", "otherDriverFile");
1608
                        child.putProperty("gdbmsname", vfdi.name);
1609
                        child.putProperty("file", vfdi.file);
1610
                        child.putProperty("driverName", vfdi.driverName);
1611
                } else if (di instanceof DBSourceInfo) {
1612
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1613
                        child.putProperty("type", "db");
1614
                        child.putProperty("gdbmsname", dbdi.name);
1615
                        child.putProperty("dbms", dbdi.dbms);
1616
                        child.putProperty("host", dbdi.host);
1617
                        child.putProperty("port", dbdi.port);
1618
                        child.putProperty("user", dbdi.user);
1619
                        child.putProperty("password", dbdi.password);
1620
                        child.putProperty("dbName", dbdi.dbName);
1621
                        child.putProperty("tableName", dbdi.tableName);
1622
                        child.putProperty("driverInfo", dbdi.driverName);
1623
                }
1624

    
1625
                return child;
1626
        }
1627

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

    
1653
        /**
1654
         * Devuelve un arrayList con todos los documentos.
1655
         *
1656
         * @return Documentos
1657
         */
1658
        public ArrayList getDocuments() {
1659
                ArrayList docuArray = new ArrayList();
1660
                for (int i = 0; i < documents.size(); i++) {
1661
                        ProjectDocument projectDocument = (ProjectDocument) documents
1662
                                        .get(i);
1663
                        docuArray.add(projectDocument);
1664
                }
1665
                return docuArray;
1666
        }
1667

    
1668
        /**
1669
         * Inserta un documento.
1670
         *
1671
         * @param doc
1672
         *            Documento
1673
         */
1674
        public void addDocument(ProjectDocument doc) {
1675
                documents.add(doc);
1676
                doc.addPropertyChangeListener(this);
1677
                //modified = true;
1678
                change.firePropertyChange("", "", null);
1679
                doc.setProject(this, 0);
1680
                doc.afterAdd();
1681

    
1682
        }
1683

    
1684
        /**
1685
         * Borra un documento.
1686
         *
1687
         * @param doc
1688
         *            Documento
1689
         */
1690
        public void delDocument(ProjectDocument doc) {
1691
                documents.remove(doc);
1692
                modified = true;
1693
                change.firePropertyChange("", null, null);
1694
                doc.afterRemove();
1695
        }
1696

    
1697
        /**
1698
         * Sets the default selection color that will be used in subsequent
1699
         * projects.
1700
         *
1701
         * @param color
1702
         */
1703
        public static void setDefaultSelectionColor(Color color) {
1704
                defaultSelectionColor = color;
1705
        }
1706

    
1707
        /**
1708
         * Returns the current default selection color defined which is the color
1709
         * defined when the user does not define any other one
1710
         *
1711
         * @return java.awt.Color
1712
         */
1713
        public static Color getDefaultSelectionColor() {
1714
                // TODO es millorable?
1715
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1716
                                .getPersistentXML();
1717
                if (xml.contains("DefaultSelectionColor"))
1718
                        defaultSelectionColor = StringUtilities.string2Color(xml
1719
                                        .getStringProperty("DefaultSelectionColor"));
1720
                return defaultSelectionColor;
1721
        }
1722

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

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

    
1783
        /**
1784
         * Sets the default map unit (the units used by the data).
1785
         *
1786
         * @param mapUnits
1787
         */
1788
        public static void setDefaultMapUnits(int mapUnits) {
1789
                defaultMapUnits = mapUnits;
1790
        }
1791

    
1792
        /**
1793
         * Sets the default distance units (the units shown in the status bar)
1794
         *
1795
         * @param distanceUnits
1796
         */
1797
        public static void setDefaultDistanceUnits(int distanceUnits) {
1798
                defaultDistanceUnits = distanceUnits;
1799
        }
1800

    
1801
        public String exportToXML() throws SaveException {
1802
                XMLEntity xml = this.newExportXMLRootNode();
1803

    
1804
                Iterator iter = this.documents.iterator();
1805
                ProjectDocument document;
1806
                // FIXME: Falta atrapar los errores
1807
                while (iter.hasNext()) {
1808
                        document = (ProjectDocument) iter.next();
1809
                        document.exportToXML(xml, this);
1810
                }
1811

    
1812
                return xml.toString();
1813
        }
1814

    
1815
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1816
                XMLEntity xml = this.newExportXMLRootNode();
1817

    
1818
                for (int i = 0; i < documents.length; i++) {
1819
                        documents[i].exportToXML(xml, this);
1820
                }
1821

    
1822
                return xml.toString();
1823
        }
1824

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

    
1847
        }
1848

    
1849
        public void importFromXML(String xml, String type) throws Exception {
1850
                // FIXME: EXCEPTIONS!!!!
1851
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1852

    
1853
                if (!checkExportXMLRootNode(xmlEntity)) {
1854
                        throw new Exception();
1855
                }
1856

    
1857
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1858
                if (typeRoot.getChildrenCount() == 0) {
1859
                        return;
1860
                }
1861

    
1862
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1863

    
1864
                Hashtable conflicts = getConflicts(xmlEntity);
1865

    
1866
                if (conflicts.size() != 0) {
1867
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1868
                                        conflicts)) {
1869
                                return;
1870
                        }
1871
                }
1872
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1873
                                "dataSources"));
1874

    
1875
                int i;
1876
                ProjectDocument document;
1877
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1878
                        document = documentFactory.create(this);
1879
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1880
                }
1881

    
1882
        }
1883

    
1884
        private Hashtable getConflicts(XMLEntity xml) {
1885
                int iType;
1886
                Hashtable conflicts = new Hashtable();
1887
                ArrayList elements;
1888
                XMLEntity typeRoot;
1889
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
1890
                        typeRoot = xml.getChild(iType);
1891
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
1892
                        Hashtable conflictsType = new Hashtable();
1893
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
1894
                                XMLEntity child = typeRoot.getChild(iXML);
1895
                                Iterator iter = elements.iterator();
1896
                                while (iter.hasNext()) {
1897
                                        ProjectDocument element = (ProjectDocument) iter.next();
1898
                                        if (element.getName().equalsIgnoreCase(
1899
                                                        child.getStringProperty("name"))) {
1900
                                                conflictsType.put(new Integer(iXML), child);
1901
                                                break;
1902
                                        }
1903

    
1904
                                }
1905
                        }
1906
                        if (conflictsType.size() > 0) {
1907
                                conflicts
1908
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1909
                        }
1910
                }
1911
                return conflicts;
1912
        }
1913

    
1914
        public boolean isValidXMLForImport(String xml) {
1915
                XMLEntity xmlEntity;
1916
                try {
1917
                        xmlEntity = XMLEntity.parse(xml);
1918
                } catch (Exception e) {
1919
                        return false;
1920
                }
1921

    
1922
                return checkExportXMLRootNode(xmlEntity);
1923
        }
1924

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

    
1933
                if (!checkExportXMLRootNode(xmlEntity)) {
1934
                        return false;
1935
                }
1936

    
1937
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1938

    
1939
                if (typeRoot == null) {
1940
                        return false;
1941
                }
1942

    
1943
                return (typeRoot.getChildrenCount() > 0);
1944
        }
1945

    
1946
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1947
                if (!xml.contains("applicationName"))
1948
                        return false;
1949
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1950
                        return false;
1951

    
1952
                if (!xml.contains("version"))
1953
                        return false;
1954
                if (!xml.getStringProperty("version")
1955
                                .equalsIgnoreCase(Version.format()))
1956
                        return false;
1957

    
1958
                return true;
1959
        }
1960

    
1961
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
1962
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
1963
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
1964
                                .getDriverInfo(dataSourceName);
1965
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
1966
        }
1967

    
1968
        private XMLEntity newExportXMLRootNode() {
1969
                XMLEntity xml = new XMLEntity();
1970
                xml.putProperty("applicationName", "gvSIG");
1971
                xml.putProperty("version", Version.format());
1972
                return xml;
1973
        }
1974

    
1975
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
1976
                XMLEntity typeRoot = root.firstChild("type", type);
1977
                if (typeRoot == null) {
1978
                        typeRoot = this.newExportXMLTypeNode(type);
1979
                        root.addChild(typeRoot);
1980
                }
1981
                return typeRoot;
1982
        }
1983

    
1984
        private XMLEntity newExportXMLTypeNode(String type) {
1985
                XMLEntity xmlDataSources = new XMLEntity();
1986
                xmlDataSources.putProperty("type", type);
1987
                return xmlDataSources;
1988
        }
1989

    
1990
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
1991
                String name = xmlDataSource.getStringProperty("gdbmsname");
1992

    
1993
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
1994
                        if (xmlDataSource.getStringProperty("type").equals(
1995
                                        "otherDriverFile")) {
1996
                                LayerFactory.getDataSourceFactory().addFileDataSource(
1997
                                                xmlDataSource.getStringProperty("driverName"), name,
1998
                                                xmlDataSource.getStringProperty("file"));
1999

    
2000
                        } else if (xmlDataSource.getStringProperty("type").equals(
2001
                                        "sameDriverFile")) {
2002

    
2003
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2004
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2005
                                                name, xmlDataSource.getStringProperty("host"),
2006
                                                xmlDataSource.getIntProperty("port"),
2007
                                                xmlDataSource.getStringProperty("user"),
2008
                                                xmlDataSource.getStringProperty("password"),
2009
                                                xmlDataSource.getStringProperty("dbName"),
2010
                                                xmlDataSource.getStringProperty("tableName"),
2011
                                                xmlDataSource.getStringProperty("driverInfo"));
2012
                        } else {
2013
                                return false;
2014
                        }
2015

    
2016
                }
2017
                return true;
2018
        }
2019

    
2020
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2021
                try {
2022
                        int numDataSources = xmlDataSources.getChildrenCount();
2023

    
2024
                        if (numDataSources == 0)
2025
                                return true;
2026
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2027

    
2028
                        for (int i = 0; i < numDataSources; i++) {
2029
                                XMLEntity child = xmlDataSources.getChild(i);
2030
                                if (!this.registerDataSourceFromXML(child)) {
2031
                                        return false;
2032
                                }
2033
                        }
2034

    
2035
                        return true;
2036
                } catch (Exception e) {
2037
                        e.printStackTrace();
2038
                        return false;
2039
                }
2040
        }
2041

    
2042
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2043
                ProjectDocumentFactory pde = null;
2044
                try {
2045
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2046
                                        .getInstance();
2047
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2048
                                        .get("Documents"));
2049
                        try {
2050
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2051
                        } catch (InstantiationException e) {
2052
                                NotificationManager.addError(
2053
                                                "Clase de ProjectDocument no reconocida", e);
2054
                        } catch (IllegalAccessException e) {
2055
                                NotificationManager.addError(
2056
                                                "Clase de ProjectDocument no reconocida", e);
2057
                        }
2058

    
2059
                } catch (Exception e1) {
2060
                        return null;
2061
                }
2062
                return pde;
2063
        }
2064

    
2065
        // public boolean hasChanged() {
2066
        // return signatureAtStartup != computeSignature();
2067
        // }
2068

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

    
2150
}