Statistics
| Revision:

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

History | View | Annotate | Download (62.1 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 static int defaultDistanceArea = -1;
142

    
143
        private PropertyChangeSupport change;
144

    
145
        private boolean modified = false;
146

    
147
        private String name = PluginServices.getText(this, "untitled");
148

    
149
        // private String path;
150
        private String creationDate = new Date().toGMTString();
151

    
152
        private String modificationDate = new Date().toGMTString();
153

    
154
        private String owner = "";
155

    
156
        private String comments = "";
157

    
158
        private Color selectionColor = null;
159

    
160
        // private ArrayList views = new ArrayList();
161
        // private ArrayList tables = new ArrayList();
162
        // private ArrayList maps = new ArrayList();
163
        private ArrayList<ProjectDocument> documents = new ArrayList<ProjectDocument>();
164

    
165
        private ArrayList extents = new ArrayList();
166

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

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

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

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

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

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

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

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

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

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

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

    
261
        /**
262
         * Establece el nombre del proyecto
263
         *
264
         * @param string
265
         */
266
        public void setName(String string) {
267
                name = string;
268
                //modified = true;
269
                change.firePropertyChange("", null, null);
270
        }
271

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

    
292
                return null;
293
        }
294

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

    
315
                return null;
316
        }
317

    
318
        private boolean isModifiedDocuments() {
319
                ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
320
                for (int i=0;i<documents.length;i++) {
321
                        if (documents[i].isModified()) {
322
                                return true;
323
                        }
324
                }
325
                return false;
326
        }
327
//        /**
328
//         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
329
//         * fue modificado
330
//         *
331
//         * @return
332
//         */
333
//        public boolean isModified() {
334
//                if ((this.getDocuments().size() == 0) && !modified && !isModifiedDocuments()) {
335
//                        return false;
336
//                }
337
//                return true;
338
//                // /return modified; TODO El atributo modified solo detecta cuando se
339
//                // elimina o a�ade una vista,
340
//                // /mapa o tabla pero no cuando se modifican.
341
//        }
342

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
495
                return extents.remove(arg0);
496
        }
497

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

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

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

    
531
                return this.cameras.remove(arg0);
532
        }
533

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

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

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

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

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

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

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

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

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

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

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

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

    
664
                int numExtents = extents.size();
665
                xml.putProperty("numExtents", numExtents);
666

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

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

    
675
                for (int i = 0; i < numCameras; i++) {
676
                        xml.addChild(((IPersistence) this.cameras.get(i)).getXMLEntity());
677
                }
678

    
679
                // NUEVO: ESTO ESTA EN PRUEBAS. SIRVE PARA
680
                // BORRAR LAS REFERENCIAS A DATASOURCES QUE HEMOS
681
                // BORRADO. Hay que probar a borrarlos cuando se
682
                // borra una tabla y cuando se borra una capa.
683
                try {
684
//                        cleanBadReferences();
685
                }catch (Exception e) {
686
                        NotificationManager.addError("clean_bad_references",e);
687
                }
688
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
689
                                .getDriverInfos();
690
                xml.putProperty("data-source-count", infos.length);
691

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

    
734
                saveWindowProperties(xml);
735
                return xml;
736
        }
737

    
738
        private void saveWindowProperties(XMLEntity xml) {
739
                XMLEntity propertyList = new XMLEntity();
740

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

    
744
                boolean projectWindowSaved = false;
745

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

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

    
807
                                                propertyList.addChild(windowProperties);
808
                                        }
809
                                }
810
                        }
811
                }
812

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

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

    
835
                xml.addChild(propertyList);
836
        }
837

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

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

    
871
                this.initialWindowProperties = orderedProperties.values().iterator();
872
        }
873

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

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

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

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

    
921
                if (xml.contains("numViews"))
922
                        childNumb += xml.getIntProperty("numViews");
923

    
924
                if (xml.contains("numMaps"))
925
                        limit = childNumb + xml.getIntProperty("numMaps");
926

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

    
948
                this.initialWindowProperties = windowList.iterator();
949
        }
950

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

    
961
                Iterator propertiesIterator = this.initialWindowProperties;
962
                if (propertiesIterator != null) {
963
                        this.initialWindowProperties = null;
964

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

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

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

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

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

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

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

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

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

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

    
1125
                int childNumber = 0;
1126
                Project p = new Project();
1127

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

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

    
1138
                        // Leemos el ultiom hijo recogido
1139
                        childNumber = numExtents;
1140

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

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

    
1161
                        childNumber += numCameras;
1162

    
1163
                        int numDataSources = xml.getIntProperty("data-source-count");
1164

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

    
1170
                        childNumber += numDataSources;
1171
                        int numDocuments = 0;
1172
                        if (xml.contains("numDocuments")) {
1173
                                numDocuments = xml.getIntProperty("numDocuments");
1174
                        } else {
1175
                                int numViews = xml.getIntProperty("numViews");
1176
                                int numMaps = xml.getIntProperty("numMaps");
1177
                                int numTables = xml.getIntProperty("numTables");
1178
                                numDocuments = numViews + numMaps + numTables;
1179
                        }
1180
                        int i=0;
1181
                        for (i = childNumber; i < (numDocuments + childNumber); i++) {
1182
                                try {
1183
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1184
                                                        .getChild(i), p);
1185
                                        p.addDocument(pD);
1186
                                        p.sortedDocuments.put(pD, new Integer(i));
1187
                                } catch (OpenException e) {
1188
                                        XMLEntity childXML=xml.getChild(i);
1189
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1190
                                }
1191
                        }
1192
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1193
                                        .keySet().toArray(new ProjectDocument[0]);
1194
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1195
                                        .toArray(new Integer[0]);
1196

    
1197
                        i=0;
1198
                        for ( i = 0; i < sortDocValues.length; i++) {
1199
                                try {
1200
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1201
                                                        .intValue()));
1202
                                } catch (OpenException e) {
1203
                                        XMLEntity childXML=xml.getChild(sortDocValues[i].intValue());
1204
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1205
                                }
1206
                        }
1207
                        childNumber += numDocuments;
1208

    
1209
                        p.modificationDate = xml.getStringProperty("modificationDate");
1210
                        //p.modified = xml.getBooleanProperty("modified");
1211
                        p.name = xml.getStringProperty("name");
1212
                        p.owner = xml.getStringProperty("owner");
1213
                        p.selectionColor = StringUtilities.string2Color(xml
1214
                                        .getStringProperty("selectionColor"));
1215

    
1216
                        p.setLinkTable();
1217
                        String strProj = xml.getStringProperty("projection");
1218

    
1219
                        if (strProj != null) {
1220
                                p.setProjection(CRSFactory.getCRS(strProj));
1221
                        }
1222

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

    
1240
                        PostProcessSupport.executeCalls();
1241
                } catch (Exception e) {
1242
                        throw new OpenException(e, p.getClass().getName());
1243
                }
1244

    
1245
                return p;
1246

    
1247
        }
1248

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

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

    
1272
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1273
                                                                .get(i)).getModelo().getRecordset(),
1274
                                                                ((ProjectTable) tables.get(j)).getModelo()
1275
                                                                .getRecordset(), ((ProjectTable) tables
1276
                                                                                .get(i)).getField1(),
1277
                                                                                ((ProjectTable) tables.get(i)).getField2());
1278

    
1279
                                                (((ProjectTable) tables.get(i)).getModelo()
1280
                                                                .getRecordset()).addSelectionListener(lsl);
1281

    
1282
                                        }
1283
                                } catch (ReadDriverException e) {
1284
                                        e.printStackTrace();
1285
                                }
1286
                        }
1287
                }
1288
        }
1289

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

    
1311
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1312
        }
1313

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

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

    
1358
        /**
1359
         * DOCUMENT ME!
1360
         *
1361
         * @param defaultProjection
1362
         *            DOCUMENT ME!
1363
         */
1364
        public void setProjection(IProjection projection) {
1365
                this.projection = projection;
1366
        }
1367

    
1368
        /**
1369
         * Sets the projection used when no projection is defined
1370
         *
1371
         * @param defaultProjection
1372
         *            DOCUMENT ME!
1373
         */
1374
        public static void setDefaultProjection(IProjection defaultProjection) {
1375
                Project.defaultProjection = defaultProjection;
1376
        }
1377

    
1378
        public static IProjection getDefaultProjection() {
1379
                if (defaultProjection == null){
1380
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1381
                        .getPersistentXML();
1382

    
1383
                        // Default Projection
1384
                        String projCode = null;
1385
                        if (xml.contains("DefaultProjection")) {
1386
                                projCode = xml.getStringProperty("DefaultProjection");
1387
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1388
                        } else {
1389
                                Project.setDefaultProjection(defaultFactoryProjection);
1390
                        }
1391

    
1392
                }
1393
                return Project.defaultProjection;
1394
        }
1395

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

    
1413
                        if (elem.getName().equals(name)) {
1414
                                return elem;
1415
                        }
1416
                }
1417

    
1418
                return null;
1419
        }
1420

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

    
1469
                if (dataSource == null) {
1470
                        // No se ha creado la tabla asociada al tema
1471
                        dataSource = ((AlphanumericData) layer).getRecordset();
1472
                }
1473

    
1474
                return dataSource;
1475

    
1476
        }
1477

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

    
1503
                                ds = t.getModelo().getRecordset();
1504

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

    
1521
                                MapContext aux = pv.getMapOverViewContext();
1522
                                if (aux != null) {
1523
                                        if (!this.findLayersVectDataSorces(aux, usedDataSources)){
1524
                                                /*
1525
                                                 * if a broken layer was found
1526
                                                 * we don't clean any source
1527
                                                 */
1528
                                                return;
1529
                                        }
1530

    
1531
                                }
1532

    
1533
                        } // for i
1534

    
1535
                } catch (ReadDriverException e) {
1536
                        e.printStackTrace();
1537
                }
1538

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

    
1559
                                        }
1560
                                } //for j
1561

    
1562
                        } // for i
1563

    
1564
                } catch (ReadDriverException e) {
1565
                        e.printStackTrace();
1566
                }
1567

    
1568

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

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

    
1604
                        //@Override
1605
                        public boolean evaluate(FLayer layer) {
1606
                                if (!(layer instanceof FLyrVect))
1607
                                        return false;
1608
                                return super.evaluate(layer);
1609
                        }
1610

    
1611
                };
1612
                FLyrVect layer;
1613
                while (iter.hasNext()){
1614
                        layer = (FLyrVect)iter.nextLayer();
1615
                        if (!layer.isAvailable()){
1616
                                return false;
1617
                        }
1618

    
1619
                        dataSourcesMap.put(layer.getRecordset().getName(), layer.getRecordset());
1620
                        if (layer.isJoined()){
1621
                                dataSourcesMap.put(layer.getSource().getRecordset().getName(),layer.getSource().getRecordset());
1622
                        }
1623

    
1624
                }
1625
                return true;
1626
        }
1627

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

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

    
1692
                return result;
1693
        }
1694

    
1695
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1696
                XMLEntity child = new XMLEntity();
1697

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

    
1722
                return child;
1723
        }
1724

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

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

    
1765
        /**
1766
         * Inserta un documento.
1767
         *
1768
         * @param doc
1769
         *            Documento
1770
         */
1771
        public void addDocument(ProjectDocument doc) {
1772
                documents.add(doc);
1773
                doc.addPropertyChangeListener(this);
1774
                //modified = true;
1775
                change.firePropertyChange("addDocument", "", doc);
1776
                doc.setProject(this, 0);
1777
                doc.afterAdd();
1778
        }
1779

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

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

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

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

    
1848
        /**
1849
         * Returns the user's default view units for measuring distances. This is
1850
         * the units that the user will see in the status bar of the view.
1851
         *
1852
         * @return int (index of the <b>Attributes.NAMES array</b>)
1853
         */
1854
        public static int getDefaultDistanceUnits() {
1855
                if (defaultDistanceUnits == -1) {
1856
                        XMLEntity xml = PluginServices.getPluginServices(
1857
                                        "com.iver.cit.gvsig").getPersistentXML();
1858
                        if (xml.contains("DefaultDistanceUnits")) {
1859
                                defaultDistanceUnits = xml
1860
                                                .getIntProperty("DefaultDistanceUnits");
1861
                        } else {
1862
                                // first app run case
1863
                                String[] unitNames = MapContext.getDistanceNames();
1864
                                for (int i = 0; i < unitNames.length; i++) {
1865
                                        // meter is the factory default's distance unit
1866
                                        if (unitNames[i].equals("Metros")) {
1867
                                                defaultDistanceUnits = i;
1868
                                                break;
1869
                                        }
1870
                                }
1871
                        }
1872
                        if (defaultDistanceUnits == -1)
1873
                                defaultDistanceUnits = MapContext.getDistancePosition("Metros");
1874
                }
1875
                return defaultDistanceUnits;
1876
        }
1877
        /**
1878
         * Returns the user's default view units for measuring areas. This is
1879
         * the units that the user will see in the status bar of the view.
1880
         *
1881
         * @return int (index of the <b>Attributes.NAMES array</b>)
1882
         */
1883
        public static int getDefaultDistanceArea() {
1884
                if (defaultDistanceArea == -1) {
1885
                        XMLEntity xml = PluginServices.getPluginServices(
1886
                                        "com.iver.cit.gvsig").getPersistentXML();
1887
                        if (xml.contains("DefaultDistanceArea")) {
1888
                                defaultDistanceArea = xml
1889
                                                .getIntProperty("DefaultDistanceArea");
1890
                        } else {
1891
                                // first app run case
1892
                                String[] unitNames = MapContext.getAreaNames();
1893
                                for (int i = 0; i < unitNames.length; i++) {
1894
                                        // meter is the factory default's distance unit
1895
                                        if (unitNames[i].equals("Metros")) {
1896
                                                defaultDistanceArea = i;
1897
                                                break;
1898
                                        }
1899
                                }
1900
                        }
1901
                        if (defaultDistanceArea == -1){
1902
                                defaultDistanceArea=getDefaultDistanceUnits();
1903
                        }
1904
                }
1905
                return defaultDistanceArea;
1906
        }
1907
        /**
1908
         * Sets the default map unit (the units used by the data).
1909
         *
1910
         * @param mapUnits
1911
         */
1912
        public static void setDefaultMapUnits(int mapUnits) {
1913
                defaultMapUnits = mapUnits;
1914
        }
1915

    
1916
        /**
1917
         * Sets the default distance units (the units shown in the status bar)
1918
         *
1919
         * @param distanceUnits
1920
         */
1921
        public static void setDefaultDistanceUnits(int distanceUnits) {
1922
                defaultDistanceUnits = distanceUnits;
1923
        }
1924
        /**
1925
         * Sets the default distance area (the units shown in the status bar)
1926
         *
1927
         * @param distanceUnits
1928
         */
1929
        public static void setDefaultDistanceArea(int distanceArea) {
1930
                defaultDistanceArea = distanceArea;
1931
        }
1932
        public String exportToXML() throws SaveException {
1933
                XMLEntity xml = this.newExportXMLRootNode();
1934

    
1935
                Iterator iter = this.documents.iterator();
1936
                ProjectDocument document;
1937
                // FIXME: Falta atrapar los errores
1938
                while (iter.hasNext()) {
1939
                        document = (ProjectDocument) iter.next();
1940
                        document.exportToXML(xml, this);
1941
                }
1942

    
1943
                return xml.toString();
1944
        }
1945

    
1946
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1947
                XMLEntity xml = this.newExportXMLRootNode();
1948

    
1949
                for (int i = 0; i < documents.length; i++) {
1950
                        documents[i].exportToXML(xml, this);
1951
                }
1952

    
1953
                return xml.toString();
1954
        }
1955

    
1956
        public void importFromXML(String xml) throws Exception {
1957
                throw new Exception("Not Implemented");
1958
                /*
1959
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1960
                 *
1961
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1962
                 * Exception(e); }
1963
                 *
1964
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1965
                 * Error"); //FIXME: traducir }
1966
                 *
1967
                 * int i;
1968
                 *
1969
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1970
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1971
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1972
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1973
                 * root "+i+ "error"); } documentFactory =
1974
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1975
                 * int j; }
1976
                 */
1977

    
1978
        }
1979

    
1980
        public void importFromXML(String xml, String type) throws Exception {
1981
                // FIXME: EXCEPTIONS!!!!
1982
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1983

    
1984
                if (!checkExportXMLRootNode(xmlEntity)) {
1985
                        throw new Exception();
1986
                }
1987

    
1988
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1989
                if (typeRoot.getChildrenCount() == 0) {
1990
                        return;
1991
                }
1992

    
1993
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1994

    
1995
                Hashtable conflicts = getConflicts(xmlEntity);
1996

    
1997
                if (conflicts.size() != 0) {
1998
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1999
                                        conflicts)) {
2000
                                return;
2001
                        }
2002
                }
2003
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
2004
                                "dataSources"));
2005

    
2006
                int i;
2007
                ProjectDocument document;
2008
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
2009
                        document = documentFactory.create(this);
2010
                        document.importFromXML(xmlEntity, typeRoot, i, this);
2011
                }
2012

    
2013
        }
2014

    
2015
        private Hashtable getConflicts(XMLEntity xml) {
2016
                int iType;
2017
                Hashtable conflicts = new Hashtable();
2018
                ArrayList elements;
2019
                XMLEntity typeRoot;
2020
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
2021
                        typeRoot = xml.getChild(iType);
2022
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
2023
                        Hashtable conflictsType = new Hashtable();
2024
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
2025
                                XMLEntity child = typeRoot.getChild(iXML);
2026
                                Iterator iter = elements.iterator();
2027
                                while (iter.hasNext()) {
2028
                                        ProjectDocument element = (ProjectDocument) iter.next();
2029
                                        if (element.getName().equalsIgnoreCase(
2030
                                                        child.getStringProperty("name"))) {
2031
                                                conflictsType.put(new Integer(iXML), child);
2032
                                                break;
2033
                                        }
2034

    
2035
                                }
2036
                        }
2037
                        if (conflictsType.size() > 0) {
2038
                                conflicts
2039
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
2040
                        }
2041
                }
2042
                return conflicts;
2043
        }
2044

    
2045
        public boolean isValidXMLForImport(String xml) {
2046
                XMLEntity xmlEntity;
2047
                try {
2048
                        xmlEntity = XMLEntity.parse(xml);
2049
                } catch (Exception e) {
2050
                        return false;
2051
                }
2052

    
2053
                return checkExportXMLRootNode(xmlEntity);
2054
        }
2055

    
2056
        public boolean isValidXMLForImport(String xml, String type) {
2057
                XMLEntity xmlEntity;
2058
                try {
2059
                        xmlEntity = XMLEntity.parse(xml);
2060
                } catch (Exception e) {
2061
                        return false;
2062
                }
2063

    
2064
                if (!checkExportXMLRootNode(xmlEntity)) {
2065
                        return false;
2066
                }
2067

    
2068
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
2069

    
2070
                if (typeRoot == null) {
2071
                        return false;
2072
                }
2073

    
2074
                return (typeRoot.getChildrenCount() > 0);
2075
        }
2076

    
2077
        private boolean checkExportXMLRootNode(XMLEntity xml) {
2078
                if (!xml.contains("applicationName"))
2079
                        return false;
2080
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
2081
                        return false;
2082

    
2083
                if (!xml.contains("version"))
2084
                        return false;
2085
                if (!xml.getStringProperty("version")
2086
                                .equalsIgnoreCase(Version.format()))
2087
                        return false;
2088

    
2089
                return true;
2090
        }
2091

    
2092
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
2093
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
2094
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
2095
                                .getDriverInfo(dataSourceName);
2096
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
2097
        }
2098

    
2099
        private XMLEntity newExportXMLRootNode() {
2100
                XMLEntity xml = new XMLEntity();
2101
                xml.putProperty("applicationName", "gvSIG");
2102
                xml.putProperty("version", Version.format());
2103
                return xml;
2104
        }
2105

    
2106
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
2107
                XMLEntity typeRoot = root.firstChild("type", type);
2108
                if (typeRoot == null) {
2109
                        typeRoot = this.newExportXMLTypeNode(type);
2110
                        root.addChild(typeRoot);
2111
                }
2112
                return typeRoot;
2113
        }
2114

    
2115
        private XMLEntity newExportXMLTypeNode(String type) {
2116
                XMLEntity xmlDataSources = new XMLEntity();
2117
                xmlDataSources.putProperty("type", type);
2118
                return xmlDataSources;
2119
        }
2120

    
2121
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2122
                String name = xmlDataSource.getStringProperty("gdbmsname");
2123

    
2124
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2125
                        if (xmlDataSource.getStringProperty("type").equals(
2126
                                        "otherDriverFile")) {
2127
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2128
                                                xmlDataSource.getStringProperty("driverName"), name,
2129
                                                xmlDataSource.getStringProperty("file"));
2130

    
2131
                        } else if (xmlDataSource.getStringProperty("type").equals(
2132
                                        "sameDriverFile")) {
2133

    
2134
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2135
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2136
                                                name, xmlDataSource.getStringProperty("host"),
2137
                                                xmlDataSource.getIntProperty("port"),
2138
                                                xmlDataSource.getStringProperty("user"),
2139
                                                xmlDataSource.getStringProperty("password"),
2140
                                                xmlDataSource.getStringProperty("dbName"),
2141
                                                xmlDataSource.getStringProperty("tableName"),
2142
                                                xmlDataSource.getStringProperty("driverInfo"));
2143
                        } else {
2144
                                return false;
2145
                        }
2146

    
2147
                }
2148
                return true;
2149
        }
2150

    
2151
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2152
                try {
2153
                        int numDataSources = xmlDataSources.getChildrenCount();
2154

    
2155
                        if (numDataSources == 0)
2156
                                return true;
2157
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2158

    
2159
                        for (int i = 0; i < numDataSources; i++) {
2160
                                XMLEntity child = xmlDataSources.getChild(i);
2161
                                if (!this.registerDataSourceFromXML(child)) {
2162
                                        return false;
2163
                                }
2164
                        }
2165

    
2166
                        return true;
2167
                } catch (Exception e) {
2168
                        e.printStackTrace();
2169
                        return false;
2170
                }
2171
        }
2172

    
2173
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2174
                ProjectDocumentFactory pde = null;
2175
                try {
2176
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2177
                                        .getInstance();
2178
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2179
                                        .get("Documents"));
2180
                        try {
2181
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2182
                        } catch (InstantiationException e) {
2183
                                NotificationManager.addError(
2184
                                                "Clase de ProjectDocument no reconocida", e);
2185
                        } catch (IllegalAccessException e) {
2186
                                NotificationManager.addError(
2187
                                                "Clase de ProjectDocument no reconocida", e);
2188
                        }
2189

    
2190
                } catch (Exception e1) {
2191
                        return null;
2192
                }
2193
                return pde;
2194
        }
2195

    
2196
         public boolean hasChanged() {
2197
                 // we return true if the project is not empty (until we have a better method...)
2198
                 if ((this.getDocuments().size() != 0) || modified) {
2199
                         return true;
2200
                 }
2201
                 return false;
2202
//                 return signatureAtStartup != getXMLEntity().hash();
2203
         }
2204

    
2205
        public void setSignature(long hash) {
2206
                signatureAtStartup = hash;
2207
        }
2208
}