Statistics
| Revision:

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

History | View | Annotate | Download (60.9 KB)

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

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

    
57
import org.cresques.cts.IProjection;
58

    
59
import com.hardcode.driverManager.DriverLoadException;
60
import com.hardcode.gdbms.engine.data.DataSource;
61
import com.hardcode.gdbms.engine.data.DataSourceFactory;
62
import com.hardcode.gdbms.engine.data.NoSuchTableException;
63
import com.hardcode.gdbms.engine.data.SourceInfo;
64
import com.hardcode.gdbms.engine.data.db.DBSourceInfo;
65
import com.hardcode.gdbms.engine.data.db.DBTableSourceInfo;
66
import com.hardcode.gdbms.engine.data.file.FileSourceInfo;
67
import com.hardcode.gdbms.engine.data.object.ObjectSourceInfo;
68
import com.iver.andami.PluginServices;
69
import com.iver.andami.messages.NotificationManager;
70
import com.iver.andami.ui.mdiManager.IWindow;
71
import com.iver.andami.ui.mdiManager.SingletonWindow;
72
import com.iver.andami.ui.mdiManager.WindowInfo;
73
import com.iver.cit.gvsig.ProjectExtension;
74
import com.iver.cit.gvsig.Version;
75
import com.iver.cit.gvsig.fmap.DriverException;
76
import com.iver.cit.gvsig.fmap.MapContext;
77
import com.iver.cit.gvsig.fmap.ViewPort;
78
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
79
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
80
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
81
import com.iver.cit.gvsig.fmap.layers.FLayer;
82
import com.iver.cit.gvsig.fmap.layers.FLayers;
83
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
84
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
85
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
86
import com.iver.cit.gvsig.fmap.layers.XMLException;
87
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
88
import com.iver.cit.gvsig.fmap.operations.selection.LinkSelectionListener;
89
import com.iver.cit.gvsig.project.documents.ProjectDocument;
90
import com.iver.cit.gvsig.project.documents.ProjectDocumentFactory;
91
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
92
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
93
import com.iver.cit.gvsig.project.documents.gui.IDocumentWindow;
94
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
95
import com.iver.cit.gvsig.project.documents.gui.WindowData;
96
import com.iver.cit.gvsig.project.documents.layout.Attributes;
97
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
98
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
99
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
100
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
101
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
102
import com.iver.cit.gvsig.project.documents.view.ProjectView;
103
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
104
import com.iver.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 = "1.0";
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
        private boolean modified = false;
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
        private boolean isModifiedDocuments() {
317
                ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
318
                for (int i=0;i<documents.length;i++) {
319
                        if (documents[i].isModified()) {
320
                                return true;
321
                        }
322
                }
323
                return false;
324
        }
325
        /**
326
         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
327
         * fue modificado
328
         *
329
         * @return
330
         */
331
        public boolean isModified() {
332
                if ((this.getDocuments().size() == 0) || !modified || !isModifiedDocuments()) {
333
                        return false;
334
                }
335
                return true;
336
                // /return modified; TODO El atributo modified solo detecta cuando se
337
                // elimina o a?ade una vista,
338
                // /mapa o tabla pero no cuando se modifican.
339
        }
340

    
341
        /**
342
         * Obtiene los comentarios
343
         *
344
         * @return
345
         */
346
        public String getComments() {
347
                return comments;
348
        }
349

    
350
        /**
351
         * Obtiene la fecha de la ?ltima modificaci?n
352
         *
353
         * @return
354
         */
355
        public String getModificationDate() {
356
                return modificationDate;
357
        }
358

    
359
        /**
360
         * Obtiene el propietario del proyecto
361
         *
362
         * @return
363
         */
364
        public String getOwner() {
365
                return owner;
366
        }
367

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

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

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

    
401
        /**
402
         * Establece el flag de modificado del proyecto
403
         *
404
         * @param b
405
         */
406
        public void setModified(boolean b) {
407
                modified = b;
408
                if (modified==false) {
409
                        ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
410
                        for (int i=0;i<documents.length;i++) {
411
                                documents[i].setModified(false);
412
                        }
413
                }
414
        }
415

    
416
        /**
417
         * Obtiene el color de selecci?n que se usar? en el proyecto
418
         *
419
         * @return
420
         */
421
        public Color getSelectionColor() {
422
                if (selectionColor == null) {
423
                        selectionColor = defaultSelectionColor;
424
                }
425
                return selectionColor;
426
        }
427

    
428
        /**
429
         * Establece el color de selecci?n
430
         *
431
         * @param color
432
         */
433
        public void setSelectionColor(Color color) {
434
                selectionColor = color;
435
                FSymbol.setSelectionColor(color);
436
                //modified = true;
437
                change.firePropertyChange("selectionColor", null, color);
438
        }
439

    
440
        /**
441
         * Obtiene el color como un entero para su serializaci?n a XML
442
         *
443
         * @return
444
         */
445
        public String getColor() {
446
                return StringUtilities.color2String(selectionColor);
447
        }
448

    
449
        /**
450
         * M?todo invocado al recuperar de XML para establecer el color de seleccion
451
         * del proyecto
452
         *
453
         * @param color
454
         *            Entero que representa un color
455
         */
456
        public void setColor(String color) {
457
                //modified = true;
458
                selectionColor = StringUtilities.string2Color(color);
459
        }
460

    
461
        /*
462
         * (non-Javadoc)
463
         *
464
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
465
         */
466
        public void propertyChange(PropertyChangeEvent evt) {
467
                //this.modified = true;
468
                change.firePropertyChange(evt);
469
        }
470

    
471
        /**
472
         * DOCUMENT ME!
473
         *
474
         * @param arg1
475
         */
476
        public void addExtent(ProjectExtent arg1) {
477
                extents.add(arg1);
478
                //modified = true;
479
                change.firePropertyChange("addExtent", null, null);
480
        }
481

    
482
        /**
483
         * DOCUMENT ME!
484
         *
485
         * @param arg0
486
         *
487
         * @return
488
         */
489
        public Object removeExtent(int arg0) {
490
                //modified = true;
491
                change.firePropertyChange("delExtent", null, null);
492

    
493
                return extents.remove(arg0);
494
        }
495

    
496
        /**
497
         * DOCUMENT ME!
498
         *
499
         * @return DOCUMENT ME!
500
         */
501
        public ProjectExtent[] getExtents() {
502
                return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
503
        }
504

    
505
        /**
506
         * Metodo que a?ade una nueva camera a la lista de cameras
507
         *
508
         * @param arg1
509
         *            camera introducida
510
         */
511
        public void addCamera(Object arg1) {
512
                this.cameras.add(arg1);
513
                //modified = true;
514
                change.firePropertyChange("addCamera", null, null);
515
        }
516

    
517
        /**
518
         * Metodo que borra de la lisat un elemento seleccionado
519
         *
520
         * @param arg0
521
         *            indice del elemento que se va a borrar
522
         *
523
         * @return resultado de la operacion de borrado
524
         */
525
        public Object removeCamera(int arg0) {
526
                //modified = true;
527
                change.firePropertyChange("delCamera", null, null);
528

    
529
                return this.cameras.remove(arg0);
530
        }
531

    
532
        /**
533
         * Metodo que devuelve la lista de cameras
534
         *
535
         * @return lista de objetos de tipo camera
536
         */
537
        public Object[] getCameras() {
538
                return (Object[]) this.cameras.toArray(new Object[0]);
539
        }
540

    
541
        /**
542
         * DOCUMENT ME!
543
         *
544
         * @param arg0
545
         */
546
        public synchronized void addPropertyChangeListener(
547
                        PropertyChangeListener arg0) {
548
                change.addPropertyChangeListener(arg0);
549
        }
550

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

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

    
571
        /**
572
         * DOCUMENT ME!
573
         *
574
         * @deprecated utilizar getDocument(String s);
575
         * @return
576
         */
577
        public ArrayList getViews() {
578
                return getDocumentsByType(ProjectViewFactory.registerName);
579
        }
580

    
581
        /**
582
         * A?ade un mapa al proyecto
583
         *
584
         * @deprecated utilizar addDocument(ProjectDocument pD);
585
         * @param m
586
         */
587
        public void addMap(ProjectMap m) {
588
                addDocument(m);
589
        }
590

    
591
        /**
592
         * Elimina un mapa del proyecto
593
         *
594
         * @deprecated utilizar delDocument(ProjectDocument pD);
595
         * @param i
596
         *            indice del mapa
597
         */
598
        public void delMap(int i) {
599
                ArrayList list = getDocumentsByType(ProjectMapFactory.registerName);
600
                delDocument((ProjectDocument) list.get(i));
601
        }
602

    
603
        /**
604
         * A?ade una tabla al proyecto
605
         *
606
         * @deprecated utilizar addDocument(ProjectDocument pD);
607
         * @param t
608
         */
609
        public void addTable(ProjectTable t) {
610
                addDocument(t);
611
        }
612

    
613
        /**
614
         * Elimina una tabla del proyecto
615
         *
616
         * @deprecated utilizar delDocument(ProjectDocument pD);
617
         * @param i
618
         *            indice de la tabla
619
         */
620
        public void delTable(int i) {
621
                ArrayList list = getDocumentsByType(ProjectTableFactory.registerName);
622
                delDocument((ProjectDocument) list.get(i));
623
        }
624

    
625
        /**
626
         * A?ade una vista al proyecto
627
         *
628
         * @deprecated utilizar addDocument(ProjectDocument pD);
629
         * @param v
630
         */
631
        public void addView(ProjectView v) {
632
                addDocument(v);
633
        }
634

    
635
        /**
636
         * Elimina una tabla del proyecto
637
         *
638
         * @deprecated utilizar delDocument(ProjectDocument pD);
639
         * @param i
640
         *            indice del proyecto
641
         */
642
        public void delView(int i) {
643
                ArrayList list = getDocumentsByType(ProjectViewFactory.registerName);
644
                delDocument((ProjectDocument) list.get(i));
645
        }
646

    
647
        /**
648
         * DOCUMENT ME!
649
         *
650
         * @return DOCUMENT ME!
651
         *
652
         * @throws DriverException
653
         * @throws XMLException
654
         */
655
        public XMLEntity getXMLEntity() {
656
                XMLEntity xml = new XMLEntity();
657
                xml.putProperty("className", this.getClass().getName());
658
                xml.putProperty("VERSION", VERSION);
659
                xml.putProperty("comments", comments);
660
                xml.putProperty("creationDate", creationDate);
661

    
662
                int numExtents = extents.size();
663
                xml.putProperty("numExtents", numExtents);
664

    
665
                for (int i = 0; i < numExtents; i++) {
666
                        xml.addChild(((ProjectExtent) extents.get(i)).getXMLEntity());
667
                }
668

    
669
                // Guardando propiedades de las camaras
670
                int numCameras = this.cameras.size();
671
                xml.putProperty("numCameras", numCameras);
672

    
673
                for (int i = 0; i < numCameras; i++) {
674
                        xml.addChild(((IPersistance) this.cameras.get(i)).getXMLEntity());
675
                }
676

    
677
                // NUEVO: ESTO ESTA EN PRUEBAS. SIRVE PARA
678
                // BORRAR LAS REFERENCIAS A DATASOURCES QUE HEMOS
679
                // BORRADO. Hay que probar a borrarlos cuando se
680
                // borra una tabla y cuando se borra una capa.
681
                cleanBadReferences();
682
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
683
                                .getDriverInfos();
684
                xml.putProperty("data-source-count", infos.length);
685

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

    
730
                saveWindowProperties(xml);
731
                return xml;
732
        }
733

    
734
        private void saveWindowProperties(XMLEntity xml) {
735
                XMLEntity propertyList = new XMLEntity();
736

    
737
                propertyList.setName("AndamiPersistence");
738
                propertyList.putProperty("className", Project.class.getName());
739

    
740
                boolean projectWindowSaved = false;
741

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

    
793
                                                // TODO this will be generalized to all ProjectDocuments as soon as possible
794
//                                                if (viewWindow instanceof BaseView) {
795
//                                                        BaseView win = (BaseView) viewWindow;
796
//                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
797
//                                                }
798
                                                if (viewWindow instanceof IDocumentWindow) {
799
                                                        IDocumentWindow win = (IDocumentWindow) viewWindow;
800
                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
801
                                                }
802

    
803
                                                propertyList.addChild(windowProperties);
804
                                        }
805
                                }
806
                        }
807
                }
808

    
809
                if (projectWindowSaved == false) {
810
                        // If the Project Manager was closed, it was not in the
811
                        // previous window list. Save it now
812
                        ProjectExtension pe = (ProjectExtension) PluginServices
813
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
814

    
815
                        if (pe != null) {
816
                                IWindow projectWindow = pe.getProjectWindow();
817
                                wi = PluginServices.getMDIManager()
818
                                                .getWindowInfo(projectWindow);
819
                                if (wi != null && wi.checkPersistence()) {
820
                                        windowProperties = wi.getXMLEntity();
821
                                        if (windowProperties != null) {
822
                                                windowProperties
823
                                                                .putProperty("className",
824
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
825
                                                propertyList.addChild(windowProperties);
826
                                        }
827
                                }
828
                        }
829
                }
830

    
831
                xml.addChild(propertyList);
832
        }
833

    
834
        /**
835
         * Store the initial window properties, to later restore the window sizes
836
         * and positions
837
         */
838
        private void storeInitialWindowProperties(XMLEntity xml) {
839
                XMLEntity child;
840
                int childNumb;
841

    
842
                // order the window properties before restoring them, so that we also
843
                // restore the zPosition
844
                TreeMap orderedProperties = new TreeMap();
845
                int maximum = 1;
846
                for (childNumb = xml.getChildrenCount() - 1; childNumb >= 0; childNumb--) {
847
                        child = xml.getChild(childNumb);
848
                        if (child.contains("zPosition")) {
849
                                orderedProperties.put(new Integer(-child
850
                                                .getIntProperty("zPosition")), child); // reverse the
851
                                // order, so
852
                                // that we add
853
                                // the back
854
                                // windows first
855
                        } else {
856
                                orderedProperties.put(new Integer(maximum++), child); // the
857
                                // windows
858
                                // without
859
                                // zPosition
860
                                // will
861
                                // be on
862
                                // the
863
                                // fore
864
                        }
865
                }
866

    
867
                this.initialWindowProperties = orderedProperties.values().iterator();
868
        }
869

    
870
        /**
871
         * Store the initial window properties, to later restore the window sizes
872
         * and positions
873
         */
874
        private void storeInitialWindowProperties061(XMLEntity xml) {
875
                XMLEntity child;
876
                int childNumb = 0;
877
                ArrayList windowList = new ArrayList();
878

    
879
                child = xml.getChild(xml.getChildrenCount() - 1);
880
                if (child.contains("className")
881
                                && child.getStringProperty("className").equals(
882
                                                "com.iver.cit.gvsig.project.Project")
883
                                && child.contains("name")
884
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
885
                        child.putProperty("className",
886
                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
887
                        windowList.add(child);
888
                }
889

    
890
                // try to open the views
891
                if (xml.contains("numExtents"))
892
                        childNumb += xml.getIntProperty("numExtents");
893
                if (xml.contains("data-source-count"))
894
                        childNumb += xml.getIntProperty("data-source-count");
895
                int limit = 0;
896
                if (xml.contains("numViews"))
897
                        limit = xml.getIntProperty("numViews")+childNumb;
898

    
899
                XMLEntity view;
900
                for (int i = childNumb; i < limit; i++) {
901
                        view = xml.getChild(i);
902
                        child = view.getChild(view.getChildrenCount() - 1);
903
                        if (child.contains("className")
904
                                        && child.getStringProperty("className").equals(
905
                                                        "com.iver.cit.gvsig.project.ProjectView")
906
                                        && child.contains("name")
907
                                        && child.getStringProperty("name").equals(
908
                                                        "ViewInfoProperties")) {
909
                                child.putProperty("documentName", view
910
                                                .getStringProperty("name"));
911
                                child.putProperty("documentType",
912
                                                ProjectViewFactory.registerName);
913
                                windowList.add(child);
914
                        }
915
                }
916

    
917
                if (xml.contains("numViews"))
918
                        childNumb += xml.getIntProperty("numViews");
919

    
920
                if (xml.contains("numMaps"))
921
                        limit = childNumb + xml.getIntProperty("numMaps");
922

    
923
                // try to open the maps
924
                XMLEntity map;
925
                for (int i = childNumb; i < limit; i++) {
926
                        map = xml.getChild(i);
927
                        for (int j = 0; j < map.getChildrenCount(); j++) {
928
                                child = map.getChild(j);
929
                                if (child.contains("className")
930
                                                && child.getStringProperty("className").equals(
931
                                                                "com.iver.cit.gvsig.project.ProjectMap")
932
                                                && child.contains("name")
933
                                                && child.getStringProperty("name").equals(
934
                                                                "ViewInfoProperties")) {
935
                                        child.putProperty("documentName", map
936
                                                        .getStringProperty("name"));
937
                                        child.putProperty("documentType",
938
                                                        ProjectMapFactory.registerName);
939
                                        windowList.add(child);
940
                                }
941
                        }
942
                }
943

    
944
                this.initialWindowProperties = windowList.iterator();
945
        }
946

    
947
        /**
948
         * Restores the size, position and order of the windows, according to
949
         * variable initialWindowProperties. If this variable is null, the method
950
         * just opens the project manager window.
951
         *
952
         */
953
        public void restoreWindowProperties() {
954
                boolean projectWindowRestored = false;
955
                XMLEntity child;
956

    
957
                Iterator propertiesIterator = this.initialWindowProperties;
958
                if (propertiesIterator != null) {
959
                        this.initialWindowProperties = null;
960

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

    
1021
                if (!projectWindowRestored) { // if the project window was not stored
1022
                        // in the project, open it now
1023
                        ProjectExtension pe = (ProjectExtension) PluginServices
1024
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1025

    
1026
                        if (pe != null) {
1027
                                pe.setProject(this);
1028
                                pe.showProjectWindow();
1029
                        }
1030
                }
1031
        }
1032

    
1033
        /**
1034
         * DOCUMENT ME!
1035
         *
1036
         * @param xml
1037
         *            DOCUMENT ME!
1038
         *
1039
         * @return DOCUMENT ME!
1040
         * @throws XMLException
1041
         * @throws DriverException
1042
         * @throws DriverIOException
1043
         * @throws OpenException
1044
         */
1045
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1046
                Project p = new Project();
1047
                try {
1048
                        p.comments = xml.getStringProperty("comments");
1049
                        p.creationDate = xml.getStringProperty("creationDate");
1050

    
1051
                        int numExtents = xml.getIntProperty("numExtents");
1052
                        for (int i = 0; i < numExtents; i++) {
1053
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1054
                                                .getChild(i));
1055
                                p.extents.add(pe);
1056
                        }
1057

    
1058
                        int numDocuments = 0;
1059
                        if (xml.contains("numDocuments")) {
1060
                                numDocuments = xml.getIntProperty("numDocuments");
1061
                        } else {
1062
                                int numViews = xml.getIntProperty("numViews");
1063
                                int numMaps = xml.getIntProperty("numMaps");
1064
                                int numTables = xml.getIntProperty("numTables");
1065
                                numDocuments = numViews + numMaps + numTables;
1066
                        }
1067
                        for (int i = numExtents; i < numDocuments + numExtents; i++) {
1068
                                ProjectDocument pD = ProjectDocument.createFromXML03(xml
1069
                                                .getChild(i), p);
1070
                                p.addDocument(pD);
1071
                                p.sortedDocuments.put(pD, new Integer(i));
1072
                        }
1073
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1074
                                        .keySet().toArray(new ProjectDocument[0]);
1075
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1076
                                        .toArray(new Integer[0]);
1077

    
1078
                        int i = 0;
1079
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1080
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1081
                                                .intValue()));
1082
                                i++;
1083
                        }
1084

    
1085
                        p.modificationDate = xml.getStringProperty("modificationDate");
1086
                        //p.modified = xml.getBooleanProperty("modified");
1087
                        p.name = xml.getStringProperty("name");
1088
                        p.owner = xml.getStringProperty("owner");
1089
                        p.selectionColor = StringUtilities.string2Color(xml
1090
                                        .getStringProperty("selectionColor"));
1091

    
1092
                        String strProj = xml.getStringProperty("projection");
1093
                        if (strProj != null)
1094
                                p.setProjection(CRSFactory.getCRS(strProj));
1095
                } catch (Exception e) {
1096
                        throw new OpenException(e, p.getClass().getName());
1097
                }
1098
                return p;
1099
        }
1100

    
1101
        /**
1102
         * DOCUMENT ME!
1103
         *
1104
         * @param xml
1105
         *            DOCUMENT ME!
1106
         *
1107
         * @return DOCUMENT ME!
1108
         *
1109
         * @throws XMLException
1110
         * @throws DriverException
1111
         * @throws DriverIOException
1112
         * @throws OpenException
1113
         * @throws VersionException
1114
         */
1115
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1116

    
1117
                int childNumber = 0;
1118
                Project p = new Project();
1119
                try {
1120
                        p.comments = xml.getStringProperty("comments");
1121
                        p.creationDate = xml.getStringProperty("creationDate");
1122
                        int numExtents = xml.getIntProperty("numExtents");
1123

    
1124
                        for (int i = 0; i < numExtents; i++) {
1125
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1126
                                p.extents.add(pe);
1127
                        }
1128

    
1129
                        // Leemos el ultiom hijo recogido
1130
                        childNumber = numExtents;
1131

    
1132
                        // Recogiendo el numero de cameras
1133
                        int numCameras = 0;
1134
                        if (xml.contains("numCameras"))
1135
                                numCameras = xml.getIntProperty("numCameras");
1136

    
1137
                        // Recogiendo todo las camaras
1138
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1139
                                XMLEntity xmlProp = xml.getChild(i);
1140
                                try {
1141
                                        String className = xmlProp.getStringProperty("className");
1142
                                        Class classProp = Class.forName(className);
1143
                                        Object obj = classProp.newInstance();
1144
                                        IPersistance objPersist = (IPersistance) obj;
1145
                                        objPersist.setXMLEntity(xmlProp);
1146
                                        p.cameras.add(obj);
1147
                                } catch (Exception e) {
1148
                                        continue;
1149
                                }
1150
                        }
1151

    
1152
                        childNumber += numCameras;
1153

    
1154
                        int numDataSources = xml.getIntProperty("data-source-count");
1155

    
1156
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1157
                                XMLEntity child = xml.getChild(i);
1158
                                registerDataSourceFromXML(child);
1159
                        }
1160

    
1161
                        childNumber += numDataSources;
1162
                        int numDocuments = 0;
1163
                        if (xml.contains("numDocuments")) {
1164
                                numDocuments = xml.getIntProperty("numDocuments");
1165
                        } else {
1166
                                int numViews = xml.getIntProperty("numViews");
1167
                                int numMaps = xml.getIntProperty("numMaps");
1168
                                int numTables = xml.getIntProperty("numTables");
1169
                                numDocuments = numViews + numMaps + numTables;
1170
                        }
1171

    
1172
                        for (int i = childNumber; i < (numDocuments + childNumber); i++) {
1173
                                try {
1174
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1175
                                                        .getChild(i), p);
1176
                                        p.addDocument(pD);
1177
                                        p.sortedDocuments.put(pD, new Integer(i));
1178
                                } catch (OpenException e) {
1179
                                        e.showError();
1180
                                }
1181
                        }
1182
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1183
                                        .keySet().toArray(new ProjectDocument[0]);
1184
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1185
                                        .toArray(new Integer[0]);
1186

    
1187
                        int i = 0;
1188
                        for (int k = childNumber; k < (numDocuments + childNumber); k++) {
1189
                                try {
1190
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1191
                                                        .intValue()));
1192
                                } catch (OpenException e) {
1193
                                        e.showError();
1194
                                }
1195
                                i++;
1196
                        }
1197
                        childNumber += numDocuments;
1198

    
1199
                        p.modificationDate = xml.getStringProperty("modificationDate");
1200
                        //p.modified = xml.getBooleanProperty("modified");
1201
                        p.name = xml.getStringProperty("name");
1202
                        p.owner = xml.getStringProperty("owner");
1203
                        p.selectionColor = StringUtilities.string2Color(xml
1204
                                        .getStringProperty("selectionColor"));
1205

    
1206
                        p.setLinkTable();
1207
                        String strProj = xml.getStringProperty("projection");
1208

    
1209
                        if (strProj != null) {
1210
                                p.setProjection(CRSFactory.getCRS(strProj));
1211
                        }
1212

    
1213
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1214
                                // of the windows
1215
                                XMLEntity child = xml.getChild(childNumber);
1216
                                if (child.contains("name")
1217
                                                && child.getStringProperty("name").equals(
1218
                                                                "AndamiPersistence")) {
1219
                                        p.storeInitialWindowProperties(child);
1220
                                } else if (child.contains("className")
1221
                                                && child.getStringProperty("className").equals(
1222
                                                                "com.iver.cit.gvsig.project.Project")
1223
                                                && child.contains("name")
1224
                                                && child.getStringProperty("name").equals(
1225
                                                                "ViewInfoProperties")) {
1226
                                        p.storeInitialWindowProperties061(xml);
1227
                                }
1228
                        }
1229

    
1230
                        PostProcessSupport.executeCalls();
1231
                } catch (Exception e) {
1232
                        throw new OpenException(e, p.getClass().getName());
1233
                }
1234
                // p.setSignature( p.hashCode());
1235
                return p;
1236

    
1237
        }
1238

    
1239
        // private void setSignature(int signature) {
1240
        // this.signatureAtStartup = computeSignature();
1241
        // }
1242

    
1243
        /**
1244
         * Reestablece los link que ten?a cada tabla con las dem?s.
1245
         */
1246
        public void setLinkTable() {
1247
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1248

    
1249
                for (int i = 0; i < tables.size(); i++) {
1250
                        for (int j = 0; j < tables.size(); j++) {
1251
                                /*
1252
                                 * System.out.println("name = " + ((ProjectTable)
1253
                                 * tables.get(j)).getModelo().getName());
1254
                                 * System.out.println("linktable = " + ((ProjectTable)
1255
                                 * tables.get(i)).getLinkTable());
1256
                                 */
1257
                                try {
1258
                                        if ((((ProjectTable) tables.get(i)).getLinkTable() != null)
1259
                                                        && ((ProjectTable) tables.get(i)).getLinkTable()
1260
                                                                        .equals(
1261
                                                                                        ((ProjectTable) tables.get(j))
1262
                                                                                                        .getModelo().getRecordset()
1263
                                                                                                        .getName())) {
1264
                                                LinkSelectionListener lsl;
1265

    
1266
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1267
                                                                .get(i)).getModelo().getRecordset(),
1268
                                                                ((ProjectTable) tables.get(j)).getModelo()
1269
                                                                                .getRecordset(), ((ProjectTable) tables
1270
                                                                                .get(i)).getField1(),
1271
                                                                ((ProjectTable) tables.get(i)).getField2());
1272

    
1273
                                                (((ProjectTable) tables.get(i)).getModelo()
1274
                                                                .getRecordset()).addSelectionListener(lsl);
1275

    
1276
                                        }
1277
                                } catch (DriverLoadException e) {
1278
                                        e.printStackTrace();
1279
                                }
1280
                        }
1281
                }
1282
        }
1283

    
1284
        /**
1285
         * Obtiene la vista que contiene a la capa que se pasa como par?metro
1286
         *
1287
         * @param layer
1288
         *            Capa cuya vista se quiere obtener
1289
         *
1290
         * @return
1291
         *
1292
         * @throws RuntimeException
1293
         *             Si la capa que se pasa como par?metro no se encuentra en
1294
         *             ninguna vista
1295
         */
1296
        public String getView(FLayer layer) {
1297
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1298
                for (int v = 0; v < views.size(); v++) {
1299
                        ProjectView pView = (ProjectView) views.get(v);
1300
                        FLayers layers = pView.getMapContext().getLayers();
1301
                        if (isView(layers, layer))
1302
                                return pView.getName();
1303
                }
1304

    
1305
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1306
        }
1307

    
1308
        public boolean isView(FLayers layers, FLayer layer) {
1309
                for (int i = 0; i < layers.getLayersCount(); i++) {
1310
                        if (layers.getLayer(i) instanceof FLayers) {
1311
                                return isView((FLayers) layers.getLayer(i), layer);
1312
                        }
1313
                        if (layers.getLayer(i) == layer) {
1314
                                return true;
1315
                        }
1316
                }
1317
                return false;
1318
        }
1319

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

    
1350
        /**
1351
         * DOCUMENT ME!
1352
         *
1353
         * @param defaultProjection
1354
         *            DOCUMENT ME!
1355
         */
1356
        public void setProjection(IProjection projection) {
1357
                this.projection = projection;
1358
        }
1359

    
1360
        /**
1361
         * Sets the projection used when no projection is defined
1362
         *
1363
         * @param defaultProjection
1364
         *            DOCUMENT ME!
1365
         */
1366
        public static void setDefaultProjection(IProjection defaultProjection) {
1367
                Project.defaultProjection = defaultProjection;
1368
        }
1369

    
1370
        public static IProjection getDefaultProjection() {
1371
                return Project.defaultProjection;
1372
        }
1373

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

    
1391
                        if (elem.getName().equals(name)) {
1392
                                return elem;
1393
                        }
1394
                }
1395

    
1396
                return null;
1397
        }
1398

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

    
1444
                                        dataSource = pt.getModelo().getRecordset();
1445

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

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

    
1458
                return dataSource;
1459

    
1460
        }
1461

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

    
1480
                                ds = t.getModelo().getRecordset();
1481

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

    
1496
                                FLayers lyrs = pv.getMapContext().getLayers();
1497

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

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

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

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

    
1614
                return result;
1615
        }
1616

    
1617
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1618
                XMLEntity child = new XMLEntity();
1619

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

    
1644
                return child;
1645
        }
1646

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

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

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

    
1701
        }
1702

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

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

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

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

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

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

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

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

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

    
1831
                return xml.toString();
1832
        }
1833

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

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

    
1841
                return xml.toString();
1842
        }
1843

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

    
1866
        }
1867

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

    
1872
                if (!checkExportXMLRootNode(xmlEntity)) {
1873
                        throw new Exception();
1874
                }
1875

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

    
1881
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1882

    
1883
                Hashtable conflicts = getConflicts(xmlEntity);
1884

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

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

    
1901
        }
1902

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

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

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

    
1941
                return checkExportXMLRootNode(xmlEntity);
1942
        }
1943

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

    
1952
                if (!checkExportXMLRootNode(xmlEntity)) {
1953
                        return false;
1954
                }
1955

    
1956
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1957

    
1958
                if (typeRoot == null) {
1959
                        return false;
1960
                }
1961

    
1962
                return (typeRoot.getChildrenCount() > 0);
1963
        }
1964

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

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

    
1977
                return true;
1978
        }
1979

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

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

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

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

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

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

    
2019
                        } else if (xmlDataSource.getStringProperty("type").equals(
2020
                                        "sameDriverFile")) {
2021

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

    
2035
                }
2036
                return true;
2037
        }
2038

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

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

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

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

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

    
2078
                } catch (Exception e1) {
2079
                        return null;
2080
                }
2081
                return pde;
2082
        }
2083

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

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

    
2169
}