Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / com / iver / cit / gvsig / project / Project.java @ 21299

History | View | Annotate | Download (61.4 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
import org.gvsig.fmap.crs.CRSFactory;
60
import org.gvsig.fmap.mapcontext.MapContext;
61
import org.gvsig.fmap.mapcontext.ViewPort;
62
import org.gvsig.fmap.mapcontext.layers.FLayer;
63
import org.gvsig.fmap.mapcontext.layers.FLayers;
64
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
65
import org.gvsig.fmap.mapcontext.layers.LayersIterator;
66
import org.gvsig.fmap.mapcontext.layers.LinkSelectionListener;
67
import org.gvsig.fmap.mapcontext.layers.XMLException;
68
import org.gvsig.fmap.mapcontext.layers.operations.AlphanumericData;
69
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
70

    
71
import com.iver.andami.PluginServices;
72
import com.iver.andami.messages.NotificationManager;
73
import com.iver.andami.ui.mdiManager.IWindow;
74
import com.iver.andami.ui.mdiManager.SingletonWindow;
75
import com.iver.andami.ui.mdiManager.WindowInfo;
76
import com.iver.cit.gvsig.ProjectExtension;
77
import com.iver.cit.gvsig.Version;
78
import com.iver.cit.gvsig.project.documents.ProjectDocument;
79
import com.iver.cit.gvsig.project.documents.ProjectDocumentFactory;
80
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
81
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
82
import com.iver.cit.gvsig.project.documents.gui.IDocumentWindow;
83
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
84
import com.iver.cit.gvsig.project.documents.gui.WindowData;
85
import com.iver.cit.gvsig.project.documents.layout.LayoutContext;
86
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
87
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
88
import com.iver.cit.gvsig.project.documents.layout.fframes.FFrameView;
89
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
90
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
91
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
92
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
93
import com.iver.cit.gvsig.project.documents.view.ProjectView;
94
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
95
import com.iver.utiles.IPersistence;
96
import com.iver.utiles.PostProcessSupport;
97
import com.iver.utiles.StringUtilities;
98
import com.iver.utiles.XMLEntity;
99
import com.iver.utiles.extensionPoints.ExtensionPoint;
100
import com.iver.utiles.extensionPoints.ExtensionPoints;
101
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
102

    
103
/**
104
 * Clase que representa un proyecto de openSIG
105
 *
106
 * @author Fernando Gonz�lez Cort�s
107
 */
108
public class Project implements Serializable, PropertyChangeListener {
109
        public static String VERSION = Version.format();
110

    
111
        static private IProjection defaultProjection = null;
112

    
113
        static private IProjection defaultFactoryProjection = CRSFactory
114
                        .getCRS("EPSG:23030");
115

    
116
        /*
117
         * distiguishing between a static field "defaultSelectionColor" and a
118
         * selectionColor field will allow to define default color in a multiple
119
         * project scenario
120
         */
121
        static private Color defaultSelectionColor = Color.YELLOW;
122

    
123
        private static int defaultMapUnits = -1;
124

    
125
        private static int defaultDistanceUnits = -1;
126

    
127
        private static int defaultDistanceArea = -1;
128

    
129
        private PropertyChangeSupport change;
130

    
131
        private boolean modified = false;
132

    
133
        private String name = PluginServices.getText(this, "untitled");
134

    
135
        // private String path;
136
        private String creationDate = new Date().toGMTString();
137

    
138
        private String modificationDate = new Date().toGMTString();
139

    
140
        private String owner = "";
141

    
142
        private String comments = "";
143

    
144
        private Color selectionColor = null;
145

    
146
        // private ArrayList views = new ArrayList();
147
        // private ArrayList tables = new ArrayList();
148
        // private ArrayList maps = new ArrayList();
149
        private ArrayList<ProjectDocument> documents = new ArrayList<ProjectDocument>();
150

    
151
        private ArrayList extents = new ArrayList();
152

    
153
        // Lista de objetos del tipo camera. Necesarios para almacenar la posicion
154
        // del usuario haciendo uso de los marcadores
155
        private List cameras = new ArrayList();
156

    
157
        /**
158
         * this is a runtime-calculated value, do NOT persist it!
159
         */
160
        private long signatureAtStartup;
161
        private IProjection projection;
162

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

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

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

    
191
                // change.addPropertyChangeListener(this);
192
                creationDate = DateFormat.getDateInstance().format(new Date());
193
                modificationDate = creationDate;
194
                setSelectionColor(getDefaultSelectionColor());
195
                getDefaultProjection(); //For initialize it
196
                // signatureAtStartup = computeSignature();
197

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

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

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

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

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

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

    
258
        /**
259
         * Devuelve a partir de la capa la tabla asociada.
260
         *
261
         * @param co
262
         *            Capa.
263
         *
264
         * @return ProjectTable de la tabla asociada.
265
         */
266
        public ProjectTable getTable(AlphanumericData co) {
267
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
268
                /**
269
                 * Como las tablas se pueden a�adir cuando se pincha en "ver tabla" de
270
                 * una capa, se puede intentar a�adir dos veces la misma tabla
271
                 */
272
                for (int i = 0; i < tables.size(); i++) {
273
                        if (((ProjectTable) tables.get(i)).getAssociatedTable() == co) {
274
                                return (ProjectTable) tables.get(i);
275
                        }
276
                }
277

    
278
                return null;
279
        }
280

    
281
        /**
282
         * Devuelve a partir del nombre la tabla asociada.
283
         *
284
         * @param name
285
         *            Nombre.
286
         * @deprecated utilizar getProjectDocumentByName(...);
287
         * @return ProjectTable de la tabla asociada.
288
         */
289
        public ProjectTable getTable(String name) {
290
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
291
                /**
292
                 * Como las tablas se pueden a�adir cuando se pincha en "ver tabla" de
293
                 * una capa, se puede intentar a�adir dos veces la misma tabla
294
                 */
295
                for (int i = 0; i < tables.size(); i++) {
296
                        if (((ProjectTable) tables.get(i)).getName().equals(name)) {
297
                                return (ProjectTable) tables.get(i);
298
                        }
299
                }
300

    
301
                return null;
302
        }
303

    
304
        private boolean isModifiedDocuments() {
305
                ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
306
                for (int i=0;i<documents.length;i++) {
307
                        if (documents[i].isModified()) {
308
                                return true;
309
                        }
310
                }
311
                return false;
312
        }
313
//        /**
314
//         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
315
//         * fue modificado
316
//         *
317
//         * @return
318
//         */
319
//        public boolean isModified() {
320
//                if ((this.getDocuments().size() == 0) && !modified && !isModifiedDocuments()) {
321
//                        return false;
322
//                }
323
//                return true;
324
//                // /return modified; TODO El atributo modified solo detecta cuando se
325
//                // elimina o a�ade una vista,
326
//                // /mapa o tabla pero no cuando se modifican.
327
//        }
328

    
329
        /**
330
         * Obtiene los comentarios
331
         *
332
         * @return
333
         */
334
        public String getComments() {
335
                return comments;
336
        }
337

    
338
        /**
339
         * Obtiene la fecha de la �ltima modificaci�n
340
         *
341
         * @return
342
         */
343
        public String getModificationDate() {
344
                return modificationDate;
345
        }
346

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

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

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

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

    
389
        /**
390
         * Establece el flag de modificado del proyecto
391
         *
392
         * @param b
393
         */
394
        public void setModified(boolean b) {
395
                modified = b;
396
                if (modified==false) {
397
                        ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
398
                        for (int i=0;i<documents.length;i++) {
399
                                documents[i].setModified(false);
400
                        }
401
                }
402
        }
403

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
720
                saveWindowProperties(xml);
721
                return xml;
722
        }
723

    
724
        private void saveWindowProperties(XMLEntity xml) {
725
                XMLEntity propertyList = new XMLEntity();
726

    
727
                propertyList.setName("AndamiPersistence");
728
                propertyList.putProperty("className", Project.class.getName(), false);
729

    
730
                boolean projectWindowSaved = false;
731

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

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

    
793
                                                propertyList.addChild(windowProperties);
794
                                        }
795
                                }
796
                        }
797
                }
798

    
799
                if (projectWindowSaved == false) {
800
                        // If the Project Manager was closed, it was not in the
801
                        // previous window list. Save it now
802
                        ProjectExtension pe = (ProjectExtension) PluginServices
803
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
804

    
805
                        if (pe != null) {
806
                                IWindow projectWindow = pe.getProjectWindow();
807
                                wi = PluginServices.getMDIManager()
808
                                                .getWindowInfo(projectWindow);
809
                                if (wi != null && wi.checkPersistence()) {
810
                                        windowProperties = wi.getXMLEntity();
811
                                        if (windowProperties != null) {
812
                                                windowProperties
813
                                                                .putProperty("className",
814
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow", false);
815
                                                propertyList.addChild(windowProperties);
816
                                        }
817
                                }
818
                        }
819
                }
820

    
821
                xml.addChild(propertyList);
822
        }
823

    
824
        /**
825
         * Store the initial window properties, to later restore the window sizes
826
         * and positions
827
         */
828
        private void storeInitialWindowProperties(XMLEntity xml) {
829
                XMLEntity child;
830
                int childNumb;
831

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

    
857
                this.initialWindowProperties = orderedProperties.values().iterator();
858
        }
859

    
860
        /**
861
         * Store the initial window properties, to later restore the window sizes
862
         * and positions
863
         */
864
        private void storeInitialWindowProperties061(XMLEntity xml) {
865
                XMLEntity child;
866
                int childNumb = 0;
867
                ArrayList windowList = new ArrayList();
868

    
869
                child = xml.getChild(xml.getChildrenCount() - 1);
870
                if (child.contains("className")
871
                                && child.getStringProperty("className").equals(
872
                                                "com.iver.cit.gvsig.project.Project")
873
                                && child.contains("name")
874
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
875
                        child.putProperty("className",
876
                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
877
                        windowList.add(child);
878
                }
879

    
880
                // try to open the views
881
                if (xml.contains("numExtents"))
882
                        childNumb += xml.getIntProperty("numExtents");
883
                if (xml.contains("data-source-count"))
884
                        childNumb += xml.getIntProperty("data-source-count");
885
                int limit = 0;
886
                if (xml.contains("numViews"))
887
                        limit = xml.getIntProperty("numViews")+childNumb;
888

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

    
907
                if (xml.contains("numViews"))
908
                        childNumb += xml.getIntProperty("numViews");
909

    
910
                if (xml.contains("numMaps"))
911
                        limit = childNumb + xml.getIntProperty("numMaps");
912

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

    
934
                this.initialWindowProperties = windowList.iterator();
935
        }
936

    
937
        /**
938
         * Restores the size, position and order of the windows, according to
939
         * variable initialWindowProperties. If this variable is null, the method
940
         * just opens the project manager window.
941
         *
942
         */
943
        public void restoreWindowProperties() {
944
                boolean projectWindowRestored = false;
945
                XMLEntity child;
946

    
947
                Iterator propertiesIterator = this.initialWindowProperties;
948
                if (propertiesIterator != null) {
949
                        this.initialWindowProperties = null;
950

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

    
1015
                if (!projectWindowRestored) { // if the project window was not stored
1016
                        // in the project, open it now
1017
                        ProjectExtension pe = (ProjectExtension) PluginServices
1018
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1019

    
1020
                        if (pe != null) {
1021
                                pe.setProject(this);
1022
                                pe.showProjectWindow();
1023
                        }
1024
                }
1025
        }
1026

    
1027
        /**
1028
         * DOCUMENT ME!
1029
         *
1030
         * @param xml
1031
         *            DOCUMENT ME!
1032
         *
1033
         * @return DOCUMENT ME!
1034
         * @throws XMLException
1035
         * @throws DriverException
1036
         * @throws DriverIOException
1037
         * @throws OpenException
1038
         */
1039
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1040
                Project p = new Project();
1041
                try {
1042
                        p.comments = xml.getStringProperty("comments");
1043
                        p.creationDate = xml.getStringProperty("creationDate");
1044

    
1045
                        int numExtents = xml.getIntProperty("numExtents");
1046
                        for (int i = 0; i < numExtents; i++) {
1047
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1048
                                                .getChild(i));
1049
                                p.extents.add(pe);
1050
                        }
1051

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

    
1072
                        int i = 0;
1073
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1074
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1075
                                                .intValue()));
1076
                                i++;
1077
                        }
1078

    
1079
                        p.modificationDate = xml.getStringProperty("modificationDate");
1080
                        //p.modified = xml.getBooleanProperty("modified");
1081
                        p.name = xml.getStringProperty("name");
1082
                        p.owner = xml.getStringProperty("owner");
1083
                        p.selectionColor = StringUtilities.string2Color(xml
1084
                                        .getStringProperty("selectionColor"));
1085

    
1086
                        String strProj = xml.getStringProperty("projection");
1087
                        if (strProj != null)
1088
                                p.setProjection(CRSFactory.getCRS(strProj));
1089
                } catch (Exception e) {
1090
                        throw new OpenException(e, p.getClass().getName());
1091
                }
1092
                return p;
1093
        }
1094

    
1095
        /**
1096
         * DOCUMENT ME!
1097
         *
1098
         * @param xml
1099
         *            DOCUMENT ME!
1100
         *
1101
         * @return DOCUMENT ME!
1102
         *
1103
         * @throws XMLException
1104
         * @throws DriverException
1105
         * @throws DriverIOException
1106
         * @throws OpenException
1107
         * @throws VersionException
1108
         */
1109
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1110

    
1111
                int childNumber = 0;
1112
                Project p = new Project();
1113

    
1114
                try {
1115
                        p.comments = xml.getStringProperty("comments");
1116
                        p.creationDate = xml.getStringProperty("creationDate");
1117
                        int numExtents = xml.getIntProperty("numExtents");
1118

    
1119
                        for (int i = 0; i < numExtents; i++) {
1120
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1121
                                p.extents.add(pe);
1122
                        }
1123

    
1124
                        // Leemos el ultiom hijo recogido
1125
                        childNumber = numExtents;
1126

    
1127
                        // Recogiendo el numero de cameras
1128
                        int numCameras = 0;
1129
                        if (xml.contains("numCameras"))
1130
                                numCameras = xml.getIntProperty("numCameras");
1131

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

    
1147
                        childNumber += numCameras;
1148

    
1149
                        int numDataSources = xml.getIntProperty("data-source-count");
1150

    
1151
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1152
                                XMLEntity child = xml.getChild(i);
1153
                                registerDataSourceFromXML(child);
1154
                        }
1155

    
1156
                        childNumber += numDataSources;
1157
                        int numDocuments = 0;
1158
                        if (xml.contains("numDocuments")) {
1159
                                numDocuments = xml.getIntProperty("numDocuments");
1160
                        } else {
1161
                                int numViews = xml.getIntProperty("numViews");
1162
                                int numMaps = xml.getIntProperty("numMaps");
1163
                                int numTables = xml.getIntProperty("numTables");
1164
                                numDocuments = numViews + numMaps + numTables;
1165
                        }
1166
                        int i=0;
1167
                        for (i = childNumber; i < (numDocuments + childNumber); i++) {
1168
                                try {
1169
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1170
                                                        .getChild(i), p);
1171
                                        p.addDocument(pD);
1172
                                        p.sortedDocuments.put(pD, new Integer(i));
1173
                                } catch (OpenException e) {
1174
                                        XMLEntity childXML=xml.getChild(i);
1175
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1176
                                }
1177
                        }
1178
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1179
                                        .keySet().toArray(new ProjectDocument[0]);
1180
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1181
                                        .toArray(new Integer[0]);
1182

    
1183
                        i=0;
1184
                        for ( i = 0; i < sortDocValues.length; i++) {
1185
                                try {
1186
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1187
                                                        .intValue()));
1188
                                } catch (OpenException e) {
1189
                                        XMLEntity childXML=xml.getChild(sortDocValues[i].intValue());
1190
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1191
                                }
1192
                        }
1193
                        childNumber += numDocuments;
1194

    
1195
                        p.modificationDate = xml.getStringProperty("modificationDate");
1196
                        //p.modified = xml.getBooleanProperty("modified");
1197
                        p.name = xml.getStringProperty("name");
1198
                        p.owner = xml.getStringProperty("owner");
1199
                        p.selectionColor = StringUtilities.string2Color(xml
1200
                                        .getStringProperty("selectionColor"));
1201

    
1202
                        p.setLinkTable();
1203
                        String strProj = xml.getStringProperty("projection");
1204

    
1205
                        if (strProj != null) {
1206
                                p.setProjection(CRSFactory.getCRS(strProj));
1207
                        }
1208

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

    
1226
                        PostProcessSupport.executeCalls();
1227
                } catch (Exception e) {
1228
                        throw new OpenException(e, p.getClass().getName());
1229
                }
1230

    
1231
                return p;
1232

    
1233
        }
1234

    
1235
        /**
1236
         * Reestablece los link que ten�a cada tabla con las dem�s.
1237
         */
1238
        public void setLinkTable() {
1239
                // TODO
1240
//                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1241
//
1242
//                for (int i = 0; i < tables.size(); i++) {
1243
//                        for (int j = 0; j < tables.size(); j++) {
1244
//                                /*
1245
//                                 * System.out.println("name = " + ((ProjectTable)
1246
//                                 * tables.get(j)).getModelo().getName());
1247
//                                 * System.out.println("linktable = " + ((ProjectTable)
1248
//                                 * tables.get(i)).getLinkTable());
1249
//                                 */
1250
//                                try {
1251
//                                        if ((((ProjectTable) tables.get(i)).getLinkTable() != null)
1252
//                                                        && ((ProjectTable) tables.get(i)).getLinkTable()
1253
//                                                        .equals(
1254
//                                                                        ((ProjectTable) tables.get(j))
1255
//                                                                        .getModelo().getRecordset()
1256
//                                                                        .getName())) {
1257
//                                                LinkSelectionListener lsl;
1258
//
1259
//                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1260
//                                                                .get(i)).getModelo().getRecordset(),
1261
//                                                                ((ProjectTable) tables.get(j)).getModelo()
1262
//                                                                .getRecordset(), ((ProjectTable) tables
1263
//                                                                                .get(i)).getField1(),
1264
//                                                                                ((ProjectTable) tables.get(i)).getField2());
1265
//
1266
//                                                (((ProjectTable) tables.get(i)).getModelo()
1267
//                                                                .getRecordset()).addSelectionListener(lsl);
1268
//
1269
//                                        }
1270
//                                } catch (ReadDriverException e) {
1271
//                                        e.printStackTrace();
1272
//                                }
1273
//                        }
1274
//                }
1275
        }
1276

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

    
1298
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1299
        }
1300

    
1301
        public boolean isView(FLayers layers, FLayer layer) {
1302
                for (int i = 0; i < layers.getLayersCount(); i++) {
1303
                        if (layers.getLayer(i) instanceof FLayers) {
1304
                                if (isView((FLayers) layers.getLayer(i), layer)){
1305
                                        return true;
1306
                                }
1307
                        }
1308
                        if (layers.getLayer(i) == layer) {
1309
                                return true;
1310
                        }
1311
                }
1312
                return false;
1313
        }
1314

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

    
1345
        /**
1346
         * DOCUMENT ME!
1347
         *
1348
         * @param defaultProjection
1349
         *            DOCUMENT ME!
1350
         */
1351
        public void setProjection(IProjection projection) {
1352
                this.projection = projection;
1353
        }
1354

    
1355
        /**
1356
         * Sets the projection used when no projection is defined
1357
         *
1358
         * @param defaultProjection
1359
         *            DOCUMENT ME!
1360
         */
1361
        public static void setDefaultProjection(IProjection defaultProjection) {
1362
                Project.defaultProjection = defaultProjection;
1363
        }
1364

    
1365
        public static IProjection getDefaultProjection() {
1366
                if (defaultProjection == null){
1367
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1368
                        .getPersistentXML();
1369

    
1370
                        // Default Projection
1371
                        String projCode = null;
1372
                        if (xml.contains("DefaultProjection")) {
1373
                                projCode = xml.getStringProperty("DefaultProjection");
1374
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1375
                        } else {
1376
                                Project.setDefaultProjection(defaultFactoryProjection);
1377
                        }
1378

    
1379
                }
1380
                return Project.defaultProjection;
1381
        }
1382

    
1383
        /**
1384
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1385
         * pointExtension, este �ltimo se puede obtener del
1386
         * Project****Factory.registerName.
1387
         *
1388
         * @param name
1389
         *            Nombre del documento
1390
         * @param type
1391
         *            nombre de registro en el extensionPoint
1392
         *
1393
         * @return Documento
1394
         */
1395
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1396
                ArrayList docs = getDocumentsByType(type);
1397
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1398
                        ProjectDocument elem = (ProjectDocument) iter.next();
1399

    
1400
                        if (elem.getName().equals(name)) {
1401
                                return elem;
1402
                        }
1403
                }
1404

    
1405
                return null;
1406
        }
1407

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

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

    
1461
                return dataSource;
1462

    
1463
        }
1464

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

    
1490
                                ds = t.getModelo().getRecordset();
1491

    
1492
                                if (t.getOriginal() != null)
1493
                                        usedDataSources.put(t.getOriginal().getRecordset()
1494
                                                        .getName(), t.getOriginal());
1495
                                usedDataSources.put(ds.getName(), ds);
1496
                        }
1497
                } catch (ReadDriverException e) {
1498
                        e.printStackTrace();
1499
                }
1500
                // Ahora las vistas
1501
                ProjectView pv;
1502
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1503
                try {
1504
                        for (i = 0; i < views.size(); i++) {
1505
                                pv = (ProjectView) views.get(i);
1506
                                this.findLayersVectDataSorces(pv.getMapContext(), usedDataSources);
1507

    
1508
                                MapContext aux = pv.getMapOverViewContext();
1509
                                if (aux != null) {
1510
                                        if (!this.findLayersVectDataSorces(aux, usedDataSources)){
1511
                                                /*
1512
                                                 * if a broken layer was found
1513
                                                 * we don't clean any source
1514
                                                 */
1515
                                                return;
1516
                                        }
1517

    
1518
                                }
1519

    
1520
                        } // for i
1521

    
1522
                } catch (ReadDriverException e) {
1523
                        e.printStackTrace();
1524
                }
1525

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

    
1546
                                        }
1547
                                } //for j
1548

    
1549
                        } // for i
1550

    
1551
                } catch (ReadDriverException e) {
1552
                        e.printStackTrace();
1553
                }
1554

    
1555

    
1556
                // Recorremos los dataSources y los borramos si no
1557
                // los estamos usando.
1558
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1559
                                .getDriverInfos();
1560
                try {
1561
                        for (i = 0; i < infos.length; i++) {
1562
                                if (!usedDataSources.containsKey(infos[i].name)) {
1563
                                        DataSource ds;
1564
                                        ds = LayerFactory.getDataSourceFactory()
1565
                                                        .createRandomDataSource(infos[i].name);
1566
                                        ds.remove();
1567
                                }
1568
                        }
1569
                } catch (DriverLoadException e) {
1570
                        e.printStackTrace();
1571
                } catch (NoSuchTableException e) {
1572
                        e.printStackTrace();
1573
                } catch (ReadDriverException e) {
1574
                        e.printStackTrace();
1575
                } catch (WriteDriverException e) {
1576
                        e.printStackTrace();
1577
                }
1578
        }
1579

    
1580
        /**
1581
         * Find DataSorces of the layers in the mapContext and store them in dataSourcesMap
1582
         *
1583
         * @param mapContext
1584
         * @param dataSourcesMap
1585
         * @return false if find a no Available layer
1586
         * @throws ReadDriverException
1587
         */
1588
        private boolean findLayersVectDataSorces(MapContext mapContext,Map dataSourcesMap) throws ReadDriverException{
1589
                LayersIterator iter = new LayersIterator(mapContext.getLayers()){
1590

    
1591
                        //@Override
1592
                        public boolean evaluate(FLayer layer) {
1593
                                if (!(layer instanceof FLyrVect))
1594
                                        return false;
1595
                                return super.evaluate(layer);
1596
                        }
1597

    
1598
                };
1599
                FLyrVect layer;
1600
                while (iter.hasNext()){
1601
                        layer = (FLyrVect)iter.nextLayer();
1602
                        if (!layer.isAvailable()){
1603
                                return false;
1604
                        }
1605

    
1606
                        dataSourcesMap.put(layer.getRecordset().getName(), layer.getRecordset());
1607
                        if (layer.isJoined()){
1608
                                dataSourcesMap.put(layer.getSource().getRecordset().getName(),layer.getSource().getRecordset());
1609
                        }
1610

    
1611
                }
1612
                return true;
1613
        }
1614

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

    
1659
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1660
                WindowInfo result = new WindowInfo();
1661
                result.setX(xml.getIntProperty("X"));
1662
                result.setY(xml.getIntProperty("Y"));
1663
                result.setHeight(xml.getIntProperty("Height"));
1664
                result.setWidth(xml.getIntProperty("Width"));
1665
                result.setClosed(xml.getBooleanProperty("isClosed"));
1666
                if (xml.contains("isMaximized")) {
1667
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1668
                        result.setMaximized(maximized);
1669
                        if (maximized == true) {
1670
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1671
                                                .getIntProperty("normalY"), xml
1672
                                                .getIntProperty("normalWidth"), xml
1673
                                                .getIntProperty("normalHeight"));
1674
                        } else {
1675
                                result.setNormalBounds(result.getBounds());
1676
                        }
1677
                }
1678

    
1679
                return result;
1680
        }
1681

    
1682
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1683
                XMLEntity child = new XMLEntity();
1684

    
1685
                if (di instanceof ObjectSourceInfo) {
1686
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1687
                        child.putProperty("type", "sameDriverFile");
1688
                        child.putProperty("gdbmsname", driver.name);
1689
                } else if (di instanceof FileSourceInfo) {
1690
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1691
                        child.putProperty("type", "otherDriverFile");
1692
                        child.putProperty("gdbmsname", vfdi.name);
1693
                        child.putProperty("file", vfdi.file);
1694
                        child.putProperty("driverName", vfdi.driverName);
1695
                } else if (di instanceof DBSourceInfo) {
1696
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1697
                        child.putProperty("type", "db");
1698
                        child.putProperty("gdbmsname", dbdi.name);
1699
                        child.putProperty("dbms", dbdi.dbms);
1700
                        child.putProperty("host", dbdi.host);
1701
                        child.putProperty("port", dbdi.port);
1702
                        child.putProperty("user", dbdi.user);
1703
                        child.putProperty("password", dbdi.password);
1704
                        child.putProperty("dbName", dbdi.dbName);
1705
                        child.putProperty("tableName", dbdi.tableName);
1706
                        child.putProperty("driverInfo", dbdi.driverName);
1707
                }
1708

    
1709
                return child;
1710
        }
1711

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

    
1737
        /**
1738
         * Devuelve un arrayList con todos los documentos.
1739
         *
1740
         * @return Documentos
1741
         */
1742
        public ArrayList<ProjectDocument> getDocuments() {
1743
                ArrayList<ProjectDocument> docuArray = new ArrayList<ProjectDocument>();
1744
                for (int i = 0; i < documents.size(); i++) {
1745
                        ProjectDocument projectDocument = (ProjectDocument) documents
1746
                                        .get(i);
1747
                        docuArray.add(projectDocument);
1748
                }
1749
                return docuArray;
1750
        }
1751

    
1752
        /**
1753
         * Inserta un documento.
1754
         *
1755
         * @param doc
1756
         *            Documento
1757
         */
1758
        public void addDocument(ProjectDocument doc) {
1759
                documents.add(doc);
1760
                doc.addPropertyChangeListener(this);
1761
                //modified = true;
1762
                change.firePropertyChange("", "", null);
1763
                doc.setProject(this, 0);
1764
                doc.afterAdd();
1765

    
1766
        }
1767

    
1768
        /**
1769
         * Borra un documento.
1770
         *
1771
         * @param doc
1772
         *            Documento
1773
         */
1774
        public void delDocument(ProjectDocument doc) {
1775
                documents.remove(doc);
1776
                //modified = true;
1777
                change.firePropertyChange("", null, null);
1778
                doc.afterRemove();
1779
        }
1780

    
1781
        /**
1782
         * Sets the default selection color that will be used in subsequent
1783
         * projects.
1784
         *
1785
         * @param color
1786
         */
1787
        public static void setDefaultSelectionColor(Color color) {
1788
                defaultSelectionColor = color;
1789
        }
1790

    
1791
        /**
1792
         * Returns the current default selection color defined which is the color
1793
         * defined when the user does not define any other one
1794
         *
1795
         * @return java.awt.Color
1796
         */
1797
        public static Color getDefaultSelectionColor() {
1798
                // TODO es millorable?
1799
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1800
                                .getPersistentXML();
1801
                if (xml.contains("DefaultSelectionColor"))
1802
                        defaultSelectionColor = StringUtilities.string2Color(xml
1803
                                        .getStringProperty("DefaultSelectionColor"));
1804
                return defaultSelectionColor;
1805
        }
1806

    
1807
        /**
1808
         * Returns the user's default map units. This is the cartography data
1809
         * distance units.
1810
         *
1811
         * @return int (index of the <b>Attributes.NAMES array</b>)
1812
         */
1813
        public static int getDefaultMapUnits() {
1814
                if (defaultMapUnits == -1) {
1815
                        XMLEntity xml = PluginServices.getPluginServices(
1816
                                        "com.iver.cit.gvsig").getPersistentXML();
1817
                        if (xml.contains("DefaultMapUnits")) {
1818
                                defaultMapUnits = xml.getIntProperty("DefaultMapUnits");
1819
                        } else {
1820
                                // first app run case
1821
                                String[] unitNames = MapContext.getDistanceNames();
1822
                                for (int i = 0; i < unitNames.length; i++) {
1823
                                        // meter is the factory default's map unit
1824
                                        if (unitNames[i].equals("Metros")) {
1825
                                                defaultMapUnits = i;
1826
                                                break;
1827
                                        }
1828
                                }
1829
                        }
1830
                        if (defaultMapUnits == -1)
1831
                                defaultMapUnits = MapContext.getDistancePosition("Metros");
1832
                }
1833
                return defaultMapUnits;
1834
        }
1835

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

    
1904
        /**
1905
         * Sets the default distance units (the units shown in the status bar)
1906
         *
1907
         * @param distanceUnits
1908
         */
1909
        public static void setDefaultDistanceUnits(int distanceUnits) {
1910
                defaultDistanceUnits = distanceUnits;
1911
        }
1912
        /**
1913
         * Sets the default distance area (the units shown in the status bar)
1914
         *
1915
         * @param distanceUnits
1916
         */
1917
        public static void setDefaultDistanceArea(int distanceArea) {
1918
                defaultDistanceArea = distanceArea;
1919
        }
1920
        public String exportToXML() throws SaveException {
1921
                XMLEntity xml = this.newExportXMLRootNode();
1922

    
1923
                Iterator iter = this.documents.iterator();
1924
                ProjectDocument document;
1925
                // FIXME: Falta atrapar los errores
1926
                while (iter.hasNext()) {
1927
                        document = (ProjectDocument) iter.next();
1928
                        document.exportToXML(xml, this);
1929
                }
1930

    
1931
                return xml.toString();
1932
        }
1933

    
1934
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1935
                XMLEntity xml = this.newExportXMLRootNode();
1936

    
1937
                for (int i = 0; i < documents.length; i++) {
1938
                        documents[i].exportToXML(xml, this);
1939
                }
1940

    
1941
                return xml.toString();
1942
        }
1943

    
1944
        public void importFromXML(String xml) throws Exception {
1945
                throw new Exception("Not Implemented");
1946
                /*
1947
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1948
                 *
1949
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1950
                 * Exception(e); }
1951
                 *
1952
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1953
                 * Error"); //FIXME: traducir }
1954
                 *
1955
                 * int i;
1956
                 *
1957
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1958
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1959
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1960
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1961
                 * root "+i+ "error"); } documentFactory =
1962
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1963
                 * int j; }
1964
                 */
1965

    
1966
        }
1967

    
1968
        public void importFromXML(String xml, String type) throws Exception {
1969
                // FIXME: EXCEPTIONS!!!!
1970
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1971

    
1972
                if (!checkExportXMLRootNode(xmlEntity)) {
1973
                        throw new Exception();
1974
                }
1975

    
1976
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1977
                if (typeRoot.getChildrenCount() == 0) {
1978
                        return;
1979
                }
1980

    
1981
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1982

    
1983
                Hashtable conflicts = getConflicts(xmlEntity);
1984

    
1985
                if (conflicts.size() != 0) {
1986
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1987
                                        conflicts)) {
1988
                                return;
1989
                        }
1990
                }
1991
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1992
                                "dataSources"));
1993

    
1994
                int i;
1995
                ProjectDocument document;
1996
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1997
                        document = documentFactory.create(this);
1998
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1999
                }
2000

    
2001
        }
2002

    
2003
        private Hashtable getConflicts(XMLEntity xml) {
2004
                int iType;
2005
                Hashtable conflicts = new Hashtable();
2006
                ArrayList elements;
2007
                XMLEntity typeRoot;
2008
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
2009
                        typeRoot = xml.getChild(iType);
2010
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
2011
                        Hashtable conflictsType = new Hashtable();
2012
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
2013
                                XMLEntity child = typeRoot.getChild(iXML);
2014
                                Iterator iter = elements.iterator();
2015
                                while (iter.hasNext()) {
2016
                                        ProjectDocument element = (ProjectDocument) iter.next();
2017
                                        if (element.getName().equalsIgnoreCase(
2018
                                                        child.getStringProperty("name"))) {
2019
                                                conflictsType.put(new Integer(iXML), child);
2020
                                                break;
2021
                                        }
2022

    
2023
                                }
2024
                        }
2025
                        if (conflictsType.size() > 0) {
2026
                                conflicts
2027
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
2028
                        }
2029
                }
2030
                return conflicts;
2031
        }
2032

    
2033
        public boolean isValidXMLForImport(String xml) {
2034
                XMLEntity xmlEntity;
2035
                try {
2036
                        xmlEntity = XMLEntity.parse(xml);
2037
                } catch (Exception e) {
2038
                        return false;
2039
                }
2040

    
2041
                return checkExportXMLRootNode(xmlEntity);
2042
        }
2043

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

    
2052
                if (!checkExportXMLRootNode(xmlEntity)) {
2053
                        return false;
2054
                }
2055

    
2056
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
2057

    
2058
                if (typeRoot == null) {
2059
                        return false;
2060
                }
2061

    
2062
                return (typeRoot.getChildrenCount() > 0);
2063
        }
2064

    
2065
        private boolean checkExportXMLRootNode(XMLEntity xml) {
2066
                if (!xml.contains("applicationName"))
2067
                        return false;
2068
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
2069
                        return false;
2070

    
2071
                if (!xml.contains("version"))
2072
                        return false;
2073
                if (!xml.getStringProperty("version")
2074
                                .equalsIgnoreCase(Version.format()))
2075
                        return false;
2076

    
2077
                return true;
2078
        }
2079

    
2080
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
2081
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
2082
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
2083
                                .getDriverInfo(dataSourceName);
2084
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
2085
        }
2086

    
2087
        private XMLEntity newExportXMLRootNode() {
2088
                XMLEntity xml = new XMLEntity();
2089
                xml.putProperty("applicationName", "gvSIG");
2090
                xml.putProperty("version", Version.format());
2091
                return xml;
2092
        }
2093

    
2094
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
2095
                XMLEntity typeRoot = root.firstChild("type", type);
2096
                if (typeRoot == null) {
2097
                        typeRoot = this.newExportXMLTypeNode(type);
2098
                        root.addChild(typeRoot);
2099
                }
2100
                return typeRoot;
2101
        }
2102

    
2103
        private XMLEntity newExportXMLTypeNode(String type) {
2104
                XMLEntity xmlDataSources = new XMLEntity();
2105
                xmlDataSources.putProperty("type", type);
2106
                return xmlDataSources;
2107
        }
2108

    
2109
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2110
                String name = xmlDataSource.getStringProperty("gdbmsname");
2111

    
2112
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2113
                        if (xmlDataSource.getStringProperty("type").equals(
2114
                                        "otherDriverFile")) {
2115
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2116
                                                xmlDataSource.getStringProperty("driverName"), name,
2117
                                                xmlDataSource.getStringProperty("file"));
2118

    
2119
                        } else if (xmlDataSource.getStringProperty("type").equals(
2120
                                        "sameDriverFile")) {
2121

    
2122
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2123
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2124
                                                name, xmlDataSource.getStringProperty("host"),
2125
                                                xmlDataSource.getIntProperty("port"),
2126
                                                xmlDataSource.getStringProperty("user"),
2127
                                                xmlDataSource.getStringProperty("password"),
2128
                                                xmlDataSource.getStringProperty("dbName"),
2129
                                                xmlDataSource.getStringProperty("tableName"),
2130
                                                xmlDataSource.getStringProperty("driverInfo"));
2131
                        } else {
2132
                                return false;
2133
                        }
2134

    
2135
                }
2136
                return true;
2137
        }
2138

    
2139
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2140
                try {
2141
                        int numDataSources = xmlDataSources.getChildrenCount();
2142

    
2143
                        if (numDataSources == 0)
2144
                                return true;
2145
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2146

    
2147
                        for (int i = 0; i < numDataSources; i++) {
2148
                                XMLEntity child = xmlDataSources.getChild(i);
2149
                                if (!this.registerDataSourceFromXML(child)) {
2150
                                        return false;
2151
                                }
2152
                        }
2153

    
2154
                        return true;
2155
                } catch (Exception e) {
2156
                        e.printStackTrace();
2157
                        return false;
2158
                }
2159
        }
2160

    
2161
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2162
                ProjectDocumentFactory pde = null;
2163
                try {
2164
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2165
                                        .getInstance();
2166
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2167
                                        .get("Documents"));
2168
                        try {
2169
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2170
                        } catch (InstantiationException e) {
2171
                                NotificationManager.addError(
2172
                                                "Clase de ProjectDocument no reconocida", e);
2173
                        } catch (IllegalAccessException e) {
2174
                                NotificationManager.addError(
2175
                                                "Clase de ProjectDocument no reconocida", e);
2176
                        }
2177

    
2178
                } catch (Exception e1) {
2179
                        return null;
2180
                }
2181
                return pde;
2182
        }
2183

    
2184
         public boolean hasChanged() {
2185
                 // we return true if the project is not empty (until we have a better method...)
2186
                 if ((this.getDocuments().size() != 0) || modified) {
2187
                         return true;
2188
                 }
2189
                 return false;
2190
//                 return signatureAtStartup != getXMLEntity().hash();
2191
         }
2192

    
2193
        public void setSignature(long hash) {
2194
                signatureAtStartup = hash;
2195
        }
2196
}