Statistics
| Revision:

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

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

    
58
import org.cresques.cts.IProjection;
59

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

    
117
/**
118
 * Clase que representa un proyecto de openSIG
119
 *
120
 * @author Fernando Gonz�lez Cort�s
121
 */
122
public class Project implements Serializable, PropertyChangeListener {
123
        public static String VERSION = Version.format();
124

    
125
        static private IProjection defaultProjection = null;
126

    
127
        static private IProjection defaultFactoryProjection = CRSFactory
128
                        .getCRS("EPSG:23030");
129

    
130
        /*
131
         * distiguishing between a static field "defaultSelectionColor" and a
132
         * selectionColor field will allow to define default color in a multiple
133
         * project scenario
134
         */
135
        static private Color defaultSelectionColor = Color.YELLOW;
136

    
137
        private static int defaultMapUnits = -1;
138

    
139
        private static int defaultDistanceUnits = -1;
140

    
141
        private PropertyChangeSupport change;
142

    
143
        private boolean modified = false;
144

    
145
        private String name = PluginServices.getText(this, "untitled");
146

    
147
        // private String path;
148
        private String creationDate = new Date().toGMTString();
149

    
150
        private String modificationDate = new Date().toGMTString();
151

    
152
        private String owner = "";
153

    
154
        private String comments = "";
155

    
156
        private Color selectionColor = null;
157

    
158
        // private ArrayList views = new ArrayList();
159
        // private ArrayList tables = new ArrayList();
160
        // private ArrayList maps = new ArrayList();
161
        private ArrayList documents = new ArrayList();
162

    
163
        private ArrayList extents = new ArrayList();
164

    
165
        // Lista de objetos del tipo camera. Necesarios para almacenar la posicion
166
        // del usuario haciendo uso de los marcadores
167
        private List cameras = new ArrayList();
168

    
169
        /**
170
         * this is a runtime-calculated value, do NOT persist it!
171
         */
172
        private long signatureAtStartup;
173
        private IProjection projection;
174

    
175
        /**
176
         * Stores the initial properties of the windows, to be restored just after
177
         * the project is loaded. It's an ordered iterator of XMLEntity objects,
178
         * each containing a XML version of a WindowInfo object.
179
         */
180
        private Iterator initialWindowProperties = null;
181

    
182
        private TreeMap sortedDocuments = new TreeMap(new Comparator() {
183
                public int compare(Object o1, Object o2) {
184
                        if ((o1 != null) && (o2 != null)) {
185
                                int priority1 = ((ProjectDocument) o1)
186
                                                .getProjectDocumentFactory().getPriority();
187
                                int priority2 = ((ProjectDocument) o2)
188
                                                .getProjectDocumentFactory().getPriority();
189
                                if (priority1 >= priority2)
190
                                        return 1;
191
                                return -1;
192
                        }
193
                        return 0;
194
                }
195
        }); // Para poder ordenar
196

    
197
        /**
198
         * Creates a new Project object.
199
         */
200
        public Project() {
201
                change = new PropertyChangeSupport(this);
202

    
203
                // change.addPropertyChangeListener(this);
204
                creationDate = DateFormat.getDateInstance().format(new Date());
205
                modificationDate = creationDate;
206
                setSelectionColor(getDefaultSelectionColor());
207
                getDefaultProjection(); //For initialize it
208
                // signatureAtStartup = computeSignature();
209

    
210
                /*
211
                 * LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
212
                 * .getPluginDirectory() .getAbsolutePath() + File.separator +
213
                 * "drivers");
214
                 */
215
        }
216

    
217
        /**
218
         * Obtiene la fecha de creaci�n del proyecto
219
         *
220
         * @return
221
         */
222
        public String getCreationDate() {
223
                return creationDate;
224
        }
225

    
226
        /**
227
         * Obtiene el nombre del proyecto
228
         *
229
         * @return
230
         */
231
        public String getName() {
232
                return name;
233
        }
234

    
235
        // /**
236
        // * Obtiene la ruta completa del fichero donde se guardo por �ltima vez el
237
        // * proyecto
238
        // *
239
        // * @return
240
        // */
241
        // public String getPath() {
242
        // return path;
243
        // }
244

    
245
        /**
246
         * Asigna la fecha de creaci�n del proyecto. Este m�todo tiene sentido s�lo
247
         * por que al recuperar la fecha del XML hay que asignarla al objeto
248
         * proyecto de alguna manera. La fecha se asigna en el constructor y no se
249
         * deber�a de modificar nunca
250
         *
251
         * @param string
252
         */
253
        public void setCreationDate(String string) {
254
                creationDate = string;
255
                //modified = true;
256
                change.firePropertyChange("", null, null);
257
        }
258

    
259
        /**
260
         * Establece el nombre del proyecto
261
         *
262
         * @param string
263
         */
264
        public void setName(String string) {
265
                name = 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
                MapContext.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", getComments());
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(((IPersistence) 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
                try {
682
                        cleanBadReferences();
683
                }catch (Exception e) {
684
                        NotificationManager.addError("clean_bad_references",e);
685
                }
686
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
687
                                .getDriverInfos();
688
                xml.putProperty("data-source-count", infos.length);
689

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

    
732
                saveWindowProperties(xml);
733
                return xml;
734
        }
735

    
736
        private void saveWindowProperties(XMLEntity xml) {
737
                XMLEntity propertyList = new XMLEntity();
738

    
739
                propertyList.setName("AndamiPersistence");
740
                propertyList.putProperty("className", Project.class.getName(), false);
741

    
742
                boolean projectWindowSaved = false;
743

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

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

    
805
                                                propertyList.addChild(windowProperties);
806
                                        }
807
                                }
808
                        }
809
                }
810

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

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

    
833
                xml.addChild(propertyList);
834
        }
835

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

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

    
869
                this.initialWindowProperties = orderedProperties.values().iterator();
870
        }
871

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

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

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

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

    
919
                if (xml.contains("numViews"))
920
                        childNumb += xml.getIntProperty("numViews");
921

    
922
                if (xml.contains("numMaps"))
923
                        limit = childNumb + xml.getIntProperty("numMaps");
924

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

    
946
                this.initialWindowProperties = windowList.iterator();
947
        }
948

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

    
959
                Iterator propertiesIterator = this.initialWindowProperties;
960
                if (propertiesIterator != null) {
961
                        this.initialWindowProperties = null;
962

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

    
1027
                if (!projectWindowRestored) { // if the project window was not stored
1028
                        // in the project, open it now
1029
                        ProjectExtension pe = (ProjectExtension) PluginServices
1030
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1031

    
1032
                        if (pe != null) {
1033
                                pe.setProject(this);
1034
                                pe.showProjectWindow();
1035
                        }
1036
                }
1037
        }
1038

    
1039
        /**
1040
         * DOCUMENT ME!
1041
         *
1042
         * @param xml
1043
         *            DOCUMENT ME!
1044
         *
1045
         * @return DOCUMENT ME!
1046
         * @throws XMLException
1047
         * @throws DriverException
1048
         * @throws DriverIOException
1049
         * @throws OpenException
1050
         */
1051
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1052
                Project p = new Project();
1053
                try {
1054
                        p.comments = xml.getStringProperty("comments");
1055
                        p.creationDate = xml.getStringProperty("creationDate");
1056

    
1057
                        int numExtents = xml.getIntProperty("numExtents");
1058
                        for (int i = 0; i < numExtents; i++) {
1059
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1060
                                                .getChild(i));
1061
                                p.extents.add(pe);
1062
                        }
1063

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

    
1084
                        int i = 0;
1085
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1086
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1087
                                                .intValue()));
1088
                                i++;
1089
                        }
1090

    
1091
                        p.modificationDate = xml.getStringProperty("modificationDate");
1092
                        //p.modified = xml.getBooleanProperty("modified");
1093
                        p.name = xml.getStringProperty("name");
1094
                        p.owner = xml.getStringProperty("owner");
1095
                        p.selectionColor = StringUtilities.string2Color(xml
1096
                                        .getStringProperty("selectionColor"));
1097

    
1098
                        String strProj = xml.getStringProperty("projection");
1099
                        if (strProj != null)
1100
                                p.setProjection(CRSFactory.getCRS(strProj));
1101
                } catch (Exception e) {
1102
                        throw new OpenException(e, p.getClass().getName());
1103
                }
1104
                return p;
1105
        }
1106

    
1107
        /**
1108
         * DOCUMENT ME!
1109
         *
1110
         * @param xml
1111
         *            DOCUMENT ME!
1112
         *
1113
         * @return DOCUMENT ME!
1114
         *
1115
         * @throws XMLException
1116
         * @throws DriverException
1117
         * @throws DriverIOException
1118
         * @throws OpenException
1119
         * @throws VersionException
1120
         */
1121
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1122

    
1123
                int childNumber = 0;
1124
                Project p = new Project();
1125

    
1126
                try {
1127
                        p.comments = xml.getStringProperty("comments");
1128
                        p.creationDate = xml.getStringProperty("creationDate");
1129
                        int numExtents = xml.getIntProperty("numExtents");
1130

    
1131
                        for (int i = 0; i < numExtents; i++) {
1132
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1133
                                p.extents.add(pe);
1134
                        }
1135

    
1136
                        // Leemos el ultiom hijo recogido
1137
                        childNumber = numExtents;
1138

    
1139
                        // Recogiendo el numero de cameras
1140
                        int numCameras = 0;
1141
                        if (xml.contains("numCameras"))
1142
                                numCameras = xml.getIntProperty("numCameras");
1143

    
1144
                        // Recogiendo todo las camaras
1145
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1146
                                XMLEntity xmlProp = xml.getChild(i);
1147
                                try {
1148
                                        String className = xmlProp.getStringProperty("className");
1149
                                        Class classProp = Class.forName(className);
1150
                                        Object obj = classProp.newInstance();
1151
                                        IPersistence objPersist = (IPersistence) obj;
1152
                                        objPersist.setXMLEntity(xmlProp);
1153
                                        p.cameras.add(obj);
1154
                                } catch (Exception e) {
1155
                                        continue;
1156
                                }
1157
                        }
1158

    
1159
                        childNumber += numCameras;
1160

    
1161
                        int numDataSources = xml.getIntProperty("data-source-count");
1162

    
1163
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1164
                                XMLEntity child = xml.getChild(i);
1165
                                registerDataSourceFromXML(child);
1166
                        }
1167

    
1168
                        childNumber += numDataSources;
1169
                        int numDocuments = 0;
1170
                        if (xml.contains("numDocuments")) {
1171
                                numDocuments = xml.getIntProperty("numDocuments");
1172
                        } else {
1173
                                int numViews = xml.getIntProperty("numViews");
1174
                                int numMaps = xml.getIntProperty("numMaps");
1175
                                int numTables = xml.getIntProperty("numTables");
1176
                                numDocuments = numViews + numMaps + numTables;
1177
                        }
1178

    
1179
                        for (int i = childNumber; i < (numDocuments + childNumber); i++) {
1180
                                try {
1181
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1182
                                                        .getChild(i), p);
1183
                                        p.addDocument(pD);
1184
                                        p.sortedDocuments.put(pD, new Integer(i));
1185
                                } catch (OpenException e) {
1186
                                        e.showError();
1187
                                }
1188
                        }
1189
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1190
                                        .keySet().toArray(new ProjectDocument[0]);
1191
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1192
                                        .toArray(new Integer[0]);
1193

    
1194
                        int i = 0;
1195
                        for (int k = childNumber; k < (numDocuments + childNumber); k++) {
1196
                                try {
1197
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1198
                                                        .intValue()));
1199
                                } catch (OpenException e) {
1200
                                        e.showError();
1201
                                }
1202
                                i++;
1203
                        }
1204
                        childNumber += numDocuments;
1205

    
1206
                        p.modificationDate = xml.getStringProperty("modificationDate");
1207
                        //p.modified = xml.getBooleanProperty("modified");
1208
                        p.name = xml.getStringProperty("name");
1209
                        p.owner = xml.getStringProperty("owner");
1210
                        p.selectionColor = StringUtilities.string2Color(xml
1211
                                        .getStringProperty("selectionColor"));
1212

    
1213
                        p.setLinkTable();
1214
                        String strProj = xml.getStringProperty("projection");
1215

    
1216
                        if (strProj != null) {
1217
                                p.setProjection(CRSFactory.getCRS(strProj));
1218
                        }
1219

    
1220
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1221
                                // of the windows
1222
                                XMLEntity child = xml.getChild(childNumber);
1223
                                if (child.contains("name")
1224
                                                && child.getStringProperty("name").equals(
1225
                                                                "AndamiPersistence")) {
1226
                                        p.storeInitialWindowProperties(child);
1227
                                } else if (child.contains("className")
1228
                                                && child.getStringProperty("className").equals(
1229
                                                                "com.iver.cit.gvsig.project.Project")
1230
                                                && child.contains("name")
1231
                                                && child.getStringProperty("name").equals(
1232
                                                                "ViewInfoProperties")) {
1233
                                        p.storeInitialWindowProperties061(xml);
1234
                                }
1235
                        }
1236

    
1237
                        PostProcessSupport.executeCalls();
1238
                } catch (Exception e) {
1239
                        throw new OpenException(e, p.getClass().getName());
1240
                }
1241

    
1242
                return p;
1243

    
1244
        }
1245

    
1246
        /**
1247
         * Reestablece los link que ten�a cada tabla con las dem�s.
1248
         */
1249
        public void setLinkTable() {
1250
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1251

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

    
1269
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1270
                                                                .get(i)).getModelo().getRecordset(),
1271
                                                                ((ProjectTable) tables.get(j)).getModelo()
1272
                                                                .getRecordset(), ((ProjectTable) tables
1273
                                                                                .get(i)).getField1(),
1274
                                                                                ((ProjectTable) tables.get(i)).getField2());
1275

    
1276
                                                (((ProjectTable) tables.get(i)).getModelo()
1277
                                                                .getRecordset()).addSelectionListener(lsl);
1278

    
1279
                                        }
1280
                                } catch (ReadDriverException e) {
1281
                                        e.printStackTrace();
1282
                                }
1283
                        }
1284
                }
1285
        }
1286

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

    
1308
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1309
        }
1310

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

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

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

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

    
1373
        public static IProjection getDefaultProjection() {
1374
                if (defaultProjection == null){
1375
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1376
                        .getPersistentXML();
1377

    
1378
                        // Default Projection
1379
                        String projCode = null;
1380
                        if (xml.contains("DefaultProjection")) {
1381
                                projCode = xml.getStringProperty("DefaultProjection");
1382
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1383
                        } else {
1384
                                Project.setDefaultProjection(defaultFactoryProjection);
1385
                        }
1386

    
1387
                }
1388
                return Project.defaultProjection;
1389
        }
1390

    
1391
        /**
1392
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1393
         * pointExtension, este �ltimo se puede obtener del
1394
         * Project****Factory.registerName.
1395
         *
1396
         * @param name
1397
         *            Nombre del documento
1398
         * @param type
1399
         *            nombre de registro en el extensionPoint
1400
         *
1401
         * @return Documento
1402
         */
1403
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1404
                ArrayList docs = getDocumentsByType(type);
1405
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1406
                        ProjectDocument elem = (ProjectDocument) iter.next();
1407

    
1408
                        if (elem.getName().equals(name)) {
1409
                                return elem;
1410
                        }
1411
                }
1412

    
1413
                return null;
1414
        }
1415

    
1416
        /**
1417
         * DOCUMENT ME!
1418
         *
1419
         * @param name
1420
         *
1421
         * @return
1422
         */
1423
        /*
1424
         * public ProjectTable getTableByName(String name) { ArrayList
1425
         * tables=getDocuments(PluginServices.getText(this,"Tabla")); Object o =
1426
         * getProjectElementByName(name, tables);
1427
         *
1428
         * if (o == null) { return null; }
1429
         *
1430
         * return (ProjectTable) o; }
1431
         */
1432
        /**
1433
         * DOCUMENT ME!
1434
         *
1435
         * @param name
1436
         *
1437
         * @return
1438
         */
1439
        /*
1440
         * public ProjectMap getLayoutByName(String name) { Object o =
1441
         * getProjectElementByName(name, maps);
1442
         *
1443
         * if (o == null) { return null; }
1444
         *
1445
         * return (ProjectMap) o; }
1446
         */
1447
        public SelectableDataSource getDataSourceByLayer(FLayer layer)
1448
                        throws ReadDriverException {
1449
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1450
                SelectableDataSource dataSource = null;
1451
                for (int i = 0; i < tables.size(); i++) {
1452
                        ProjectTable pt = (ProjectTable) tables.get(i);
1453
                        if (pt.getOriginal() == ((AlphanumericData) layer)
1454
                                        .getRecordset()) {
1455
                                dataSource = pt.getModelo().getRecordset();
1456
                                break;
1457
                        } else if (pt.getModelo() == ((AlphanumericData) layer)
1458
                                        .getRecordset()) {
1459
                                        dataSource = pt.getModelo().getRecordset();
1460
                                        break;
1461
                        }
1462
                }
1463

    
1464
                if (dataSource == null) {
1465
                        // No se ha creado la tabla asociada al tema
1466
                        dataSource = ((AlphanumericData) layer).getRecordset();
1467
                }
1468

    
1469
                return dataSource;
1470

    
1471
        }
1472

    
1473
        /**
1474
         * Recorremos las capas y las tablas del proyecto, y creamos una lista con
1475
         * todos los datasources de GDBMS que estamos usando. Luego recorremos los
1476
         * que est�n registrados, y borramos aquellos que no est�n siendo usados, es
1477
         * decir, aquellos que no est�n en nuestra lista (un Hash con clave el
1478
         * nombre del GDBMS)
1479
         *
1480
         */
1481
        private void cleanBadReferences() {
1482
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1483
                Hashtable usedDataSources = new Hashtable();
1484
                // Primero las tablas
1485
                int i, j;
1486
                try {
1487
                        for (i = 0; i < tables.size(); i++) {
1488
                                ProjectTable t = (ProjectTable) tables.get(i);
1489
                                SelectableDataSource ds;
1490
                                if (t.getModelo() == null){
1491
                                        /*
1492
                                         * if a broken table was found
1493
                                         * we don't clean any source
1494
                                         */
1495
                                        return;
1496
                                }
1497

    
1498
                                ds = t.getModelo().getRecordset();
1499

    
1500
                                if (t.getOriginal() != null)
1501
                                        usedDataSources.put(t.getOriginal().getRecordset()
1502
                                                        .getName(), t.getOriginal());
1503
                                usedDataSources.put(ds.getName(), ds);
1504
                        }
1505
                } catch (ReadDriverException e) {
1506
                        e.printStackTrace();
1507
                }
1508
                // Ahora las vistas
1509
                ProjectView pv;
1510
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1511
                try {
1512
                        for (i = 0; i < views.size(); i++) {
1513
                                pv = (ProjectView) views.get(i);
1514
                                this.findLayersVectDataSorces(pv.getMapContext(), usedDataSources);
1515

    
1516
                                MapContext aux = pv.getMapOverViewContext();
1517
                                if (aux != null) {
1518
                                        if (!this.findLayersVectDataSorces(aux, usedDataSources)){
1519
                                                /*
1520
                                                 * if a broken layer was found
1521
                                                 * we don't clean any source
1522
                                                 */
1523
                                                return;
1524
                                        }
1525

    
1526
                                }
1527

    
1528
                        } // for i
1529

    
1530
                } catch (ReadDriverException e) {
1531
                        e.printStackTrace();
1532
                }
1533

    
1534
                // Ahora los mapas
1535
                ArrayList maps = getDocumentsByType(ProjectMapFactory.registerName);
1536
                ProjectMap pm;
1537
                LayoutContext lContext;
1538
                IFFrame[] fframes;
1539
                try {
1540
                        for (i = 0; i < maps.size(); i++) {
1541
                                pm = (ProjectMap) maps.get(i);
1542
                                fframes = pm.getModel().getLayoutContext().getFFrames();
1543
                                for (j=0;j < fframes.length; j++){
1544
                                        if (!(fframes[j] instanceof FFrameView)){
1545
                                                continue;
1546
                                        }
1547
                                        if (!this.findLayersVectDataSorces(((FFrameView)fframes[i]).getMapContext(), usedDataSources)){
1548
                                                /*
1549
                                                 * if a broken layer was found
1550
                                                 * we don't clean any source
1551
                                                 */
1552
                                                return;
1553

    
1554
                                        }
1555
                                } //for j
1556

    
1557
                        } // for i
1558

    
1559
                } catch (ReadDriverException e) {
1560
                        e.printStackTrace();
1561
                }
1562

    
1563

    
1564
                // Recorremos los dataSources y los borramos si no
1565
                // los estamos usando.
1566
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1567
                                .getDriverInfos();
1568
                try {
1569
                        for (i = 0; i < infos.length; i++) {
1570
                                if (!usedDataSources.containsKey(infos[i].name)) {
1571
                                        DataSource ds;
1572
                                        ds = LayerFactory.getDataSourceFactory()
1573
                                                        .createRandomDataSource(infos[i].name);
1574
                                        ds.remove();
1575
                                }
1576
                        }
1577
                } catch (DriverLoadException e) {
1578
                        e.printStackTrace();
1579
                } catch (NoSuchTableException e) {
1580
                        e.printStackTrace();
1581
                } catch (ReadDriverException e) {
1582
                        e.printStackTrace();
1583
                } catch (WriteDriverException e) {
1584
                        e.printStackTrace();
1585
                }
1586
        }
1587

    
1588
        /**
1589
         * Find DataSorces of the layers in the mapContext and store them in dataSourcesMap
1590
         *
1591
         * @param mapContext
1592
         * @param dataSourcesMap
1593
         * @return false if find a no Available layer
1594
         * @throws ReadDriverException
1595
         */
1596
        private boolean findLayersVectDataSorces(MapContext mapContext,Map dataSourcesMap) throws ReadDriverException{
1597
                LayersIterator iter = new LayersIterator(mapContext.getLayers()){
1598

    
1599
                        //@Override
1600
                        public boolean evaluate(FLayer layer) {
1601
                                if (!(layer instanceof FLyrVect))
1602
                                        return false;
1603
                                return super.evaluate(layer);
1604
                        }
1605

    
1606
                };
1607
                FLyrVect layer;
1608
                while (iter.hasNext()){
1609
                        layer = (FLyrVect)iter.nextLayer();
1610
                        if (!layer.isAvailable()){
1611
                                return false;
1612
                        }
1613

    
1614
                        dataSourcesMap.put(layer.getRecordset().getName(), layer.getRecordset());
1615
                        if (layer.isJoined()){
1616
                                dataSourcesMap.put(layer.getSource().getRecordset().getName(),layer.getSource().getRecordset());
1617
                        }
1618

    
1619
                }
1620
                return true;
1621
        }
1622

    
1623
        /**
1624
         * DOCUMENT ME!
1625
         *
1626
         * @return DOCUMENT ME!
1627
         * @throws SaveException
1628
         * @throws XMLException
1629
         * @throws SaveException
1630
         */
1631
        public XMLEntity getWindowInfoXMLEntity(IWindow window)
1632
                        throws SaveException {
1633
                if (window != null
1634
                                && PluginServices.getMDIManager().getWindowInfo(window) != null) {
1635
                        WindowInfo vi = PluginServices.getMDIManager()
1636
                                        .getWindowInfo(window);
1637
                        XMLEntity xml = new XMLEntity();
1638
                        // xml.putProperty("nameClass", this.getClass().getName());
1639
                        try {
1640
                                xml.setName("ViewInfoProperties");
1641
                                xml.putProperty("className", this.getClass().getName());
1642
                                xml.putProperty("X", vi.getX());
1643
                                xml.putProperty("Y", vi.getY());
1644
                                xml.putProperty("Width", vi.getWidth());
1645
                                xml.putProperty("Height", vi.getHeight());
1646
                                xml.putProperty("isVisible", vi.isVisible());
1647
                                xml.putProperty("isResizable", vi.isResizable());
1648
                                xml.putProperty("isMaximizable", vi.isMaximizable());
1649
                                xml.putProperty("isModal", vi.isModal());
1650
                                xml.putProperty("isModeless", vi.isModeless());
1651
                                xml.putProperty("isClosed", vi.isClosed());
1652
                                if (vi.isMaximized() == true) {
1653
                                        xml.putProperty("isMaximized", vi.isMaximized());
1654
                                        xml.putProperty("normalX", vi.getNormalX());
1655
                                        xml.putProperty("normalY", vi.getNormalY());
1656
                                        xml.putProperty("normalWidth", vi.getNormalWidth());
1657
                                        xml.putProperty("normalHeight", vi.getNormalHeight());
1658
}
1659
                        } catch (Exception e) {
1660
                                throw new SaveException(e, this.getClass().getName());
1661
                        }
1662
                        return xml;
1663
                }
1664
                return null;
1665
        }
1666

    
1667
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1668
                WindowInfo result = new WindowInfo();
1669
                result.setX(xml.getIntProperty("X"));
1670
                result.setY(xml.getIntProperty("Y"));
1671
                result.setHeight(xml.getIntProperty("Height"));
1672
                result.setWidth(xml.getIntProperty("Width"));
1673
                result.setClosed(xml.getBooleanProperty("isClosed"));
1674
                if (xml.contains("isMaximized")) {
1675
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1676
                        result.setMaximized(maximized);
1677
                        if (maximized == true) {
1678
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1679
                                                .getIntProperty("normalY"), xml
1680
                                                .getIntProperty("normalWidth"), xml
1681
                                                .getIntProperty("normalHeight"));
1682
                        } else {
1683
                                result.setNormalBounds(result.getBounds());
1684
                        }
1685
                }
1686

    
1687
                return result;
1688
        }
1689

    
1690
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1691
                XMLEntity child = new XMLEntity();
1692

    
1693
                if (di instanceof ObjectSourceInfo) {
1694
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1695
                        child.putProperty("type", "sameDriverFile");
1696
                        child.putProperty("gdbmsname", driver.name);
1697
                } else if (di instanceof FileSourceInfo) {
1698
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1699
                        child.putProperty("type", "otherDriverFile");
1700
                        child.putProperty("gdbmsname", vfdi.name);
1701
                        child.putProperty("file", vfdi.file);
1702
                        child.putProperty("driverName", vfdi.driverName);
1703
                } else if (di instanceof DBSourceInfo) {
1704
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1705
                        child.putProperty("type", "db");
1706
                        child.putProperty("gdbmsname", dbdi.name);
1707
                        child.putProperty("dbms", dbdi.dbms);
1708
                        child.putProperty("host", dbdi.host);
1709
                        child.putProperty("port", dbdi.port);
1710
                        child.putProperty("user", dbdi.user);
1711
                        child.putProperty("password", dbdi.password);
1712
                        child.putProperty("dbName", dbdi.dbName);
1713
                        child.putProperty("tableName", dbdi.tableName);
1714
                        child.putProperty("driverInfo", dbdi.driverName);
1715
                }
1716

    
1717
                return child;
1718
        }
1719

    
1720
        /**
1721
         * Devuelve un arrayList con todos los documentos del tipo especificado como
1722
         * par�metro.
1723
         *
1724
         * @param registerName
1725
         *            nombre de registro en el extensionPoint
1726
         *
1727
         * @return Documentos del tipo especificado
1728
         */
1729
        public ArrayList getDocumentsByType(String registerName) {
1730
                ArrayList docuArray = new ArrayList();
1731
                for (int i = 0; i < documents.size(); i++) {
1732
                        ProjectDocument projectDocument = (ProjectDocument) documents
1733
                                        .get(i);
1734
                        ProjectDocumentFactory pdf = projectDocument
1735
                                        .getProjectDocumentFactory();
1736
                        if (pdf == null)
1737
                                continue;
1738
                        if (pdf.getRegisterName().equals(registerName)) {
1739
                                docuArray.add(projectDocument);
1740
                        }
1741
                }
1742
                return docuArray;
1743
        }
1744

    
1745
        /**
1746
         * Devuelve un arrayList con todos los documentos.
1747
         *
1748
         * @return Documentos
1749
         */
1750
        public ArrayList getDocuments() {
1751
                ArrayList docuArray = new ArrayList();
1752
                for (int i = 0; i < documents.size(); i++) {
1753
                        ProjectDocument projectDocument = (ProjectDocument) documents
1754
                                        .get(i);
1755
                        docuArray.add(projectDocument);
1756
                }
1757
                return docuArray;
1758
        }
1759

    
1760
        /**
1761
         * Inserta un documento.
1762
         *
1763
         * @param doc
1764
         *            Documento
1765
         */
1766
        public void addDocument(ProjectDocument doc) {
1767
                documents.add(doc);
1768
                doc.addPropertyChangeListener(this);
1769
                //modified = true;
1770
                change.firePropertyChange("", "", null);
1771
                doc.setProject(this, 0);
1772
                doc.afterAdd();
1773

    
1774
        }
1775

    
1776
        /**
1777
         * Borra un documento.
1778
         *
1779
         * @param doc
1780
         *            Documento
1781
         */
1782
        public void delDocument(ProjectDocument doc) {
1783
                documents.remove(doc);
1784
                //modified = true;
1785
                change.firePropertyChange("", null, null);
1786
                doc.afterRemove();
1787
        }
1788

    
1789
        /**
1790
         * Sets the default selection color that will be used in subsequent
1791
         * projects.
1792
         *
1793
         * @param color
1794
         */
1795
        public static void setDefaultSelectionColor(Color color) {
1796
                defaultSelectionColor = color;
1797
        }
1798

    
1799
        /**
1800
         * Returns the current default selection color defined which is the color
1801
         * defined when the user does not define any other one
1802
         *
1803
         * @return java.awt.Color
1804
         */
1805
        public static Color getDefaultSelectionColor() {
1806
                // TODO es millorable?
1807
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1808
                                .getPersistentXML();
1809
                if (xml.contains("DefaultSelectionColor"))
1810
                        defaultSelectionColor = StringUtilities.string2Color(xml
1811
                                        .getStringProperty("DefaultSelectionColor"));
1812
                return defaultSelectionColor;
1813
        }
1814

    
1815
        /**
1816
         * Returns the user's default map units. This is the cartography data
1817
         * distance units.
1818
         *
1819
         * @return int (index of the <b>Attributes.NAMES array</b>)
1820
         */
1821
        public static int getDefaultMapUnits() {
1822
                if (defaultMapUnits == -1) {
1823
                        XMLEntity xml = PluginServices.getPluginServices(
1824
                                        "com.iver.cit.gvsig").getPersistentXML();
1825
                        if (xml.contains("DefaultMapUnits")) {
1826
                                defaultMapUnits = xml.getIntProperty("DefaultMapUnits");
1827
                        } else {
1828
                                // first app run case
1829
                                String[] unitNames = MapContext.NAMES;
1830
                                for (int i = 0; i < unitNames.length; i++) {
1831
                                        // meter is the factory default's map unit
1832
                                        if (unitNames[i].equals(PluginServices.getText(
1833
                                                        Project.class, "Metros"))) {
1834
                                                defaultMapUnits = i;
1835
                                                break;
1836
                                        }
1837
                                }
1838
                        }
1839
                        if (defaultMapUnits == -1)
1840
                                defaultMapUnits = ViewPort.METROS;
1841
                }
1842
                return defaultMapUnits;
1843
        }
1844

    
1845
        /**
1846
         * Returns the user's default view units for measuring distances. This is
1847
         * the units that the user will see in the status bar of the view.
1848
         *
1849
         * @return int (index of the <b>Attributes.NAMES array</b>)
1850
         */
1851
        public static int getDefaultDistanceUnits() {
1852
                if (defaultDistanceUnits == -1) {
1853
                        XMLEntity xml = PluginServices.getPluginServices(
1854
                                        "com.iver.cit.gvsig").getPersistentXML();
1855
                        if (xml.contains("DefaultDistanceUnits")) {
1856
                                defaultDistanceUnits = xml
1857
                                                .getIntProperty("DefaultDistanceUnits");
1858
                        } else {
1859
                                // first app run case
1860
                                String[] unitNames = MapContext.NAMES;
1861
                                for (int i = 0; i < unitNames.length; i++) {
1862
                                        // meter is the factory default's distance unit
1863
                                        if (unitNames[i].equals("Metros")) {
1864
                                                defaultDistanceUnits = i;
1865
                                                break;
1866
                                        }
1867
                                }
1868
                        }
1869
                        if (defaultDistanceUnits == -1)
1870
                                defaultDistanceUnits = ViewPort.METROS;
1871
                }
1872
                return defaultDistanceUnits;
1873
        }
1874

    
1875
        /**
1876
         * Sets the default map unit (the units used by the data).
1877
         *
1878
         * @param mapUnits
1879
         */
1880
        public static void setDefaultMapUnits(int mapUnits) {
1881
                defaultMapUnits = mapUnits;
1882
        }
1883

    
1884
        /**
1885
         * Sets the default distance units (the units shown in the status bar)
1886
         *
1887
         * @param distanceUnits
1888
         */
1889
        public static void setDefaultDistanceUnits(int distanceUnits) {
1890
                defaultDistanceUnits = distanceUnits;
1891
        }
1892

    
1893
        public String exportToXML() throws SaveException {
1894
                XMLEntity xml = this.newExportXMLRootNode();
1895

    
1896
                Iterator iter = this.documents.iterator();
1897
                ProjectDocument document;
1898
                // FIXME: Falta atrapar los errores
1899
                while (iter.hasNext()) {
1900
                        document = (ProjectDocument) iter.next();
1901
                        document.exportToXML(xml, this);
1902
                }
1903

    
1904
                return xml.toString();
1905
        }
1906

    
1907
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1908
                XMLEntity xml = this.newExportXMLRootNode();
1909

    
1910
                for (int i = 0; i < documents.length; i++) {
1911
                        documents[i].exportToXML(xml, this);
1912
                }
1913

    
1914
                return xml.toString();
1915
        }
1916

    
1917
        public void importFromXML(String xml) throws Exception {
1918
                throw new Exception("Not Implemented");
1919
                /*
1920
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1921
                 *
1922
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1923
                 * Exception(e); }
1924
                 *
1925
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1926
                 * Error"); //FIXME: traducir }
1927
                 *
1928
                 * int i;
1929
                 *
1930
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1931
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1932
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1933
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1934
                 * root "+i+ "error"); } documentFactory =
1935
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1936
                 * int j; }
1937
                 */
1938

    
1939
        }
1940

    
1941
        public void importFromXML(String xml, String type) throws Exception {
1942
                // FIXME: EXCEPTIONS!!!!
1943
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1944

    
1945
                if (!checkExportXMLRootNode(xmlEntity)) {
1946
                        throw new Exception();
1947
                }
1948

    
1949
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1950
                if (typeRoot.getChildrenCount() == 0) {
1951
                        return;
1952
                }
1953

    
1954
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1955

    
1956
                Hashtable conflicts = getConflicts(xmlEntity);
1957

    
1958
                if (conflicts.size() != 0) {
1959
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1960
                                        conflicts)) {
1961
                                return;
1962
                        }
1963
                }
1964
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1965
                                "dataSources"));
1966

    
1967
                int i;
1968
                ProjectDocument document;
1969
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1970
                        document = documentFactory.create(this);
1971
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1972
                }
1973

    
1974
        }
1975

    
1976
        private Hashtable getConflicts(XMLEntity xml) {
1977
                int iType;
1978
                Hashtable conflicts = new Hashtable();
1979
                ArrayList elements;
1980
                XMLEntity typeRoot;
1981
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
1982
                        typeRoot = xml.getChild(iType);
1983
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
1984
                        Hashtable conflictsType = new Hashtable();
1985
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
1986
                                XMLEntity child = typeRoot.getChild(iXML);
1987
                                Iterator iter = elements.iterator();
1988
                                while (iter.hasNext()) {
1989
                                        ProjectDocument element = (ProjectDocument) iter.next();
1990
                                        if (element.getName().equalsIgnoreCase(
1991
                                                        child.getStringProperty("name"))) {
1992
                                                conflictsType.put(new Integer(iXML), child);
1993
                                                break;
1994
                                        }
1995

    
1996
                                }
1997
                        }
1998
                        if (conflictsType.size() > 0) {
1999
                                conflicts
2000
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
2001
                        }
2002
                }
2003
                return conflicts;
2004
        }
2005

    
2006
        public boolean isValidXMLForImport(String xml) {
2007
                XMLEntity xmlEntity;
2008
                try {
2009
                        xmlEntity = XMLEntity.parse(xml);
2010
                } catch (Exception e) {
2011
                        return false;
2012
                }
2013

    
2014
                return checkExportXMLRootNode(xmlEntity);
2015
        }
2016

    
2017
        public boolean isValidXMLForImport(String xml, String type) {
2018
                XMLEntity xmlEntity;
2019
                try {
2020
                        xmlEntity = XMLEntity.parse(xml);
2021
                } catch (Exception e) {
2022
                        return false;
2023
                }
2024

    
2025
                if (!checkExportXMLRootNode(xmlEntity)) {
2026
                        return false;
2027
                }
2028

    
2029
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
2030

    
2031
                if (typeRoot == null) {
2032
                        return false;
2033
                }
2034

    
2035
                return (typeRoot.getChildrenCount() > 0);
2036
        }
2037

    
2038
        private boolean checkExportXMLRootNode(XMLEntity xml) {
2039
                if (!xml.contains("applicationName"))
2040
                        return false;
2041
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
2042
                        return false;
2043

    
2044
                if (!xml.contains("version"))
2045
                        return false;
2046
                if (!xml.getStringProperty("version")
2047
                                .equalsIgnoreCase(Version.format()))
2048
                        return false;
2049

    
2050
                return true;
2051
        }
2052

    
2053
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
2054
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
2055
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
2056
                                .getDriverInfo(dataSourceName);
2057
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
2058
        }
2059

    
2060
        private XMLEntity newExportXMLRootNode() {
2061
                XMLEntity xml = new XMLEntity();
2062
                xml.putProperty("applicationName", "gvSIG");
2063
                xml.putProperty("version", Version.format());
2064
                return xml;
2065
        }
2066

    
2067
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
2068
                XMLEntity typeRoot = root.firstChild("type", type);
2069
                if (typeRoot == null) {
2070
                        typeRoot = this.newExportXMLTypeNode(type);
2071
                        root.addChild(typeRoot);
2072
                }
2073
                return typeRoot;
2074
        }
2075

    
2076
        private XMLEntity newExportXMLTypeNode(String type) {
2077
                XMLEntity xmlDataSources = new XMLEntity();
2078
                xmlDataSources.putProperty("type", type);
2079
                return xmlDataSources;
2080
        }
2081

    
2082
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2083
                String name = xmlDataSource.getStringProperty("gdbmsname");
2084

    
2085
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2086
                        if (xmlDataSource.getStringProperty("type").equals(
2087
                                        "otherDriverFile")) {
2088
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2089
                                                xmlDataSource.getStringProperty("driverName"), name,
2090
                                                xmlDataSource.getStringProperty("file"));
2091

    
2092
                        } else if (xmlDataSource.getStringProperty("type").equals(
2093
                                        "sameDriverFile")) {
2094

    
2095
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2096
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2097
                                                name, xmlDataSource.getStringProperty("host"),
2098
                                                xmlDataSource.getIntProperty("port"),
2099
                                                xmlDataSource.getStringProperty("user"),
2100
                                                xmlDataSource.getStringProperty("password"),
2101
                                                xmlDataSource.getStringProperty("dbName"),
2102
                                                xmlDataSource.getStringProperty("tableName"),
2103
                                                xmlDataSource.getStringProperty("driverInfo"));
2104
                        } else {
2105
                                return false;
2106
                        }
2107

    
2108
                }
2109
                return true;
2110
        }
2111

    
2112
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2113
                try {
2114
                        int numDataSources = xmlDataSources.getChildrenCount();
2115

    
2116
                        if (numDataSources == 0)
2117
                                return true;
2118
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2119

    
2120
                        for (int i = 0; i < numDataSources; i++) {
2121
                                XMLEntity child = xmlDataSources.getChild(i);
2122
                                if (!this.registerDataSourceFromXML(child)) {
2123
                                        return false;
2124
                                }
2125
                        }
2126

    
2127
                        return true;
2128
                } catch (Exception e) {
2129
                        e.printStackTrace();
2130
                        return false;
2131
                }
2132
        }
2133

    
2134
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2135
                ProjectDocumentFactory pde = null;
2136
                try {
2137
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2138
                                        .getInstance();
2139
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2140
                                        .get("Documents"));
2141
                        try {
2142
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2143
                        } catch (InstantiationException e) {
2144
                                NotificationManager.addError(
2145
                                                "Clase de ProjectDocument no reconocida", e);
2146
                        } catch (IllegalAccessException e) {
2147
                                NotificationManager.addError(
2148
                                                "Clase de ProjectDocument no reconocida", e);
2149
                        }
2150

    
2151
                } catch (Exception e1) {
2152
                        return null;
2153
                }
2154
                return pde;
2155
        }
2156

    
2157
         public boolean hasChanged() {
2158
                 // we return true if the project is not empty (until we have a better method...)
2159
                 if ((this.getDocuments().size() != 0) || modified) {
2160
                         return true;
2161
                 }
2162
                 return false;
2163
//                 return signatureAtStartup != getXMLEntity().hash();
2164
         }
2165

    
2166
        public void setSignature(long hash) {
2167
                signatureAtStartup = hash;
2168
        }
2169
}