Statistics
| Revision:

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

History | View | Annotate | Download (59.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.data.ReadException;
61
import org.gvsig.fmap.data.WriteException;
62
import org.gvsig.fmap.mapcontext.MapContext;
63
import org.gvsig.fmap.mapcontext.ViewPort;
64
import org.gvsig.fmap.mapcontext.layers.FLayer;
65
import org.gvsig.fmap.mapcontext.layers.FLayers;
66
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
67
import org.gvsig.fmap.mapcontext.layers.LayersIterator;
68
import org.gvsig.fmap.mapcontext.layers.LinkSelectionListener;
69
import org.gvsig.fmap.mapcontext.layers.XMLException;
70
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
71

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

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

    
112
        static private IProjection defaultProjection = null;
113

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

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

    
124
        private static int defaultMapUnits = -1;
125

    
126
        private static int defaultDistanceUnits = -1;
127

    
128
        private static int defaultDistanceArea = -1;
129

    
130
        private PropertyChangeSupport change;
131

    
132
        private boolean modified = false;
133

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

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

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

    
141
        private String owner = "";
142

    
143
        private String comments = "";
144

    
145
        private Color selectionColor = null;
146

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

    
152
        private ArrayList extents = new ArrayList();
153

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

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

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

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

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

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

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

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

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

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

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

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

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

    
279
                return null;
280
        }
281

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

    
302
                return null;
303
        }
304

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
731
                boolean projectWindowSaved = false;
732

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

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

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

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

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

    
822
                xml.addChild(propertyList);
823
        }
824

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1028
        /**
1029
         * DOCUMENT ME!
1030
         *
1031
         * @param xml
1032
         *            DOCUMENT ME!
1033
         *
1034
         * @return DOCUMENT ME!
1035
         *
1036
         * @throws XMLException
1037
         * @throws DriverException
1038
         * @throws DriverIOException
1039
         * @throws OpenException
1040
         * @throws VersionException
1041
         */
1042
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1043

    
1044
                int childNumber = 0;
1045
                Project p = new Project();
1046

    
1047
                try {
1048
                        p.comments = xml.getStringProperty("comments");
1049
                        p.creationDate = xml.getStringProperty("creationDate");
1050
                        int numExtents = xml.getIntProperty("numExtents");
1051

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

    
1057
                        // Leemos el ultiom hijo recogido
1058
                        childNumber = numExtents;
1059

    
1060
                        // Recogiendo el numero de cameras
1061
                        int numCameras = 0;
1062
                        if (xml.contains("numCameras"))
1063
                                numCameras = xml.getIntProperty("numCameras");
1064

    
1065
                        // Recogiendo todo las camaras
1066
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1067
                                XMLEntity xmlProp = xml.getChild(i);
1068
                                try {
1069
                                        String className = xmlProp.getStringProperty("className");
1070
                                        Class classProp = Class.forName(className);
1071
                                        Object obj = classProp.newInstance();
1072
                                        IPersistence objPersist = (IPersistence) obj;
1073
                                        objPersist.setXMLEntity(xmlProp);
1074
                                        p.cameras.add(obj);
1075
                                } catch (Exception e) {
1076
                                        continue;
1077
                                }
1078
                        }
1079

    
1080
                        childNumber += numCameras;
1081

    
1082
                        int numDataSources = xml.getIntProperty("data-source-count");
1083

    
1084
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1085
                                XMLEntity child = xml.getChild(i);
1086
                                registerDataSourceFromXML(child);
1087
                        }
1088

    
1089
                        childNumber += numDataSources;
1090
                        int numDocuments = 0;
1091
                        if (xml.contains("numDocuments")) {
1092
                                numDocuments = xml.getIntProperty("numDocuments");
1093
                        } else {
1094
                                int numViews = xml.getIntProperty("numViews");
1095
                                int numMaps = xml.getIntProperty("numMaps");
1096
                                int numTables = xml.getIntProperty("numTables");
1097
                                numDocuments = numViews + numMaps + numTables;
1098
                        }
1099
                        int i=0;
1100
                        for (i = childNumber; i < (numDocuments + childNumber); i++) {
1101
                                try {
1102
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1103
                                                        .getChild(i), p);
1104
                                        p.addDocument(pD);
1105
                                        p.sortedDocuments.put(pD, new Integer(i));
1106
                                } catch (OpenException e) {
1107
                                        XMLEntity childXML=xml.getChild(i);
1108
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1109
                                }
1110
                        }
1111
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1112
                                        .keySet().toArray(new ProjectDocument[0]);
1113
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1114
                                        .toArray(new Integer[0]);
1115

    
1116
                        i=0;
1117
                        for ( i = 0; i < sortDocValues.length; i++) {
1118
                                try {
1119
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1120
                                                        .intValue()));
1121
                                } catch (OpenException e) {
1122
                                        XMLEntity childXML=xml.getChild(sortDocValues[i].intValue());
1123
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1124
                                }
1125
                        }
1126
                        childNumber += numDocuments;
1127

    
1128
                        p.modificationDate = xml.getStringProperty("modificationDate");
1129
                        //p.modified = xml.getBooleanProperty("modified");
1130
                        p.name = xml.getStringProperty("name");
1131
                        p.owner = xml.getStringProperty("owner");
1132
                        p.selectionColor = StringUtilities.string2Color(xml
1133
                                        .getStringProperty("selectionColor"));
1134

    
1135
                        p.setLinkTable();
1136
                        String strProj = xml.getStringProperty("projection");
1137

    
1138
                        if (strProj != null) {
1139
                                p.setProjection(CRSFactory.getCRS(strProj));
1140
                        }
1141

    
1142
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1143
                                // of the windows
1144
                                XMLEntity child = xml.getChild(childNumber);
1145
                                if (child.contains("name")
1146
                                                && child.getStringProperty("name").equals(
1147
                                                                "AndamiPersistence")) {
1148
                                        p.storeInitialWindowProperties(child);
1149
                                } else if (child.contains("className")
1150
                                                && child.getStringProperty("className").equals(
1151
                                                                "com.iver.cit.gvsig.project.Project")
1152
                                                && child.contains("name")
1153
                                                && child.getStringProperty("name").equals(
1154
                                                                "ViewInfoProperties")) {
1155
                                        p.storeInitialWindowProperties061(xml);
1156
                                }
1157
                        }
1158

    
1159
                        PostProcessSupport.executeCalls();
1160
                } catch (Exception e) {
1161
                        throw new OpenException(e, p.getClass().getName());
1162
                }
1163

    
1164
                return p;
1165

    
1166
        }
1167

    
1168
        /**
1169
         * Reestablece los link que ten�a cada tabla con las dem�s.
1170
         */
1171
        public void setLinkTable() {
1172
                // TODO
1173
//                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1174
//
1175
//                for (int i = 0; i < tables.size(); i++) {
1176
//                        for (int j = 0; j < tables.size(); j++) {
1177
//                                /*
1178
//                                 * System.out.println("name = " + ((ProjectTable)
1179
//                                 * tables.get(j)).getModelo().getName());
1180
//                                 * System.out.println("linktable = " + ((ProjectTable)
1181
//                                 * tables.get(i)).getLinkTable());
1182
//                                 */
1183
//                                try {
1184
//                                        if ((((ProjectTable) tables.get(i)).getLinkTable() != null)
1185
//                                                        && ((ProjectTable) tables.get(i)).getLinkTable()
1186
//                                                        .equals(
1187
//                                                                        ((ProjectTable) tables.get(j))
1188
//                                                                        .getModelo().getRecordset()
1189
//                                                                        .getName())) {
1190
//                                                LinkSelectionListener lsl;
1191
//
1192
//                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1193
//                                                                .get(i)).getModelo().getRecordset(),
1194
//                                                                ((ProjectTable) tables.get(j)).getModelo()
1195
//                                                                .getRecordset(), ((ProjectTable) tables
1196
//                                                                                .get(i)).getField1(),
1197
//                                                                                ((ProjectTable) tables.get(i)).getField2());
1198
//
1199
//                                                (((ProjectTable) tables.get(i)).getModelo()
1200
//                                                                .getRecordset()).addSelectionListener(lsl);
1201
//
1202
//                                        }
1203
//                                } catch (ReadDriverException e) {
1204
//                                        e.printStackTrace();
1205
//                                }
1206
//                        }
1207
//                }
1208
        }
1209

    
1210
        /**
1211
         * Obtiene la vista que contiene a la capa que se pasa como par�metro
1212
         *
1213
         * @param layer
1214
         *            Capa cuya vista se quiere obtener
1215
         *
1216
         * @return
1217
         *
1218
         * @throws RuntimeException
1219
         *             Si la capa que se pasa como par�metro no se encuentra en
1220
         *             ninguna vista
1221
         */
1222
        public String getView(FLayer layer) {
1223
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1224
                for (int v = 0; v < views.size(); v++) {
1225
                        ProjectView pView = (ProjectView) views.get(v);
1226
                        FLayers layers = pView.getMapContext().getLayers();
1227
                        if (isView(layers, layer))
1228
                                return pView.getName();
1229
                }
1230

    
1231
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1232
        }
1233

    
1234
        public boolean isView(FLayers layers, FLayer layer) {
1235
                for (int i = 0; i < layers.getLayersCount(); i++) {
1236
                        if (layers.getLayer(i) instanceof FLayers) {
1237
                                if (isView((FLayers) layers.getLayer(i), layer)){
1238
                                        return true;
1239
                                }
1240
                        }
1241
                        if (layers.getLayer(i) == layer) {
1242
                                return true;
1243
                        }
1244
                }
1245
                return false;
1246
        }
1247

    
1248
        /**
1249
         * Devuelve la vista cuyo nombre coincide (sensible a mayusculas) con el que
1250
         * se pasa como par�metro. Devuelve null si no hay ninguna vista con ese
1251
         * nombre
1252
         *
1253
         * @param viewName
1254
         *            Nombre de la vista que se quiere obtener
1255
         *
1256
         * @return DOCUMENT ME!
1257
         */
1258
        /*
1259
         * public ProjectView getViewByName(String viewName) { ArrayList
1260
         * views=getDocuments(PluginServices.getText(this,"Vista")); Object o =
1261
         * getProjectDocumentByName(viewName, PluginServices.getText(this,"Vista"));
1262
         *
1263
         * if (o == null) { return null; }
1264
         *
1265
         * return (ProjectView) o; }
1266
         */
1267
        /**
1268
         * DOCUMENT ME!
1269
         *
1270
         * @return DOCUMENT ME!
1271
         */
1272
        public IProjection getProjection() {
1273
                if (projection == null)
1274
                        projection = Project.defaultProjection;
1275
                return projection;
1276
        }
1277

    
1278
        /**
1279
         * DOCUMENT ME!
1280
         *
1281
         * @param defaultProjection
1282
         *            DOCUMENT ME!
1283
         */
1284
        public void setProjection(IProjection projection) {
1285
                this.projection = projection;
1286
        }
1287

    
1288
        /**
1289
         * Sets the projection used when no projection is defined
1290
         *
1291
         * @param defaultProjection
1292
         *            DOCUMENT ME!
1293
         */
1294
        public static void setDefaultProjection(IProjection defaultProjection) {
1295
                Project.defaultProjection = defaultProjection;
1296
        }
1297

    
1298
        public static IProjection getDefaultProjection() {
1299
                if (defaultProjection == null){
1300
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1301
                        .getPersistentXML();
1302

    
1303
                        // Default Projection
1304
                        String projCode = null;
1305
                        if (xml.contains("DefaultProjection")) {
1306
                                projCode = xml.getStringProperty("DefaultProjection");
1307
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1308
                        } else {
1309
                                Project.setDefaultProjection(defaultFactoryProjection);
1310
                        }
1311

    
1312
                }
1313
                return Project.defaultProjection;
1314
        }
1315

    
1316
        /**
1317
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1318
         * pointExtension, este �ltimo se puede obtener del
1319
         * Project****Factory.registerName.
1320
         *
1321
         * @param name
1322
         *            Nombre del documento
1323
         * @param type
1324
         *            nombre de registro en el extensionPoint
1325
         *
1326
         * @return Documento
1327
         */
1328
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1329
                ArrayList docs = getDocumentsByType(type);
1330
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1331
                        ProjectDocument elem = (ProjectDocument) iter.next();
1332

    
1333
                        if (elem.getName().equals(name)) {
1334
                                return elem;
1335
                        }
1336
                }
1337

    
1338
                return null;
1339
        }
1340

    
1341
        /**
1342
         * DOCUMENT ME!
1343
         *
1344
         * @param name
1345
         *
1346
         * @return
1347
         */
1348
        /*
1349
         * public ProjectTable getTableByName(String name) { ArrayList
1350
         * tables=getDocuments(PluginServices.getText(this,"Tabla")); Object o =
1351
         * getProjectElementByName(name, tables);
1352
         *
1353
         * if (o == null) { return null; }
1354
         *
1355
         * return (ProjectTable) o; }
1356
         */
1357
        /**
1358
         * DOCUMENT ME!
1359
         *
1360
         * @param name
1361
         *
1362
         * @return
1363
         */
1364
        /*
1365
         * public ProjectMap getLayoutByName(String name) { Object o =
1366
         * getProjectElementByName(name, maps);
1367
         *
1368
         * if (o == null) { return null; }
1369
         *
1370
         * return (ProjectMap) o; }
1371
         */
1372
//        public SelectableDataSource getDataSourceByLayer(FLayer layer)
1373
//                        throws ReadException {
1374
//                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1375
//                SelectableDataSource dataSource = null;
1376
//                for (int i = 0; i < tables.size(); i++) {
1377
//                        ProjectTable pt = (ProjectTable) tables.get(i);
1378
//                        if (pt.getOriginal() == ((FLyrVect) layer)
1379
//                                        .getRecordset()) {
1380
//                                dataSource = pt.getModelo().getRecordset();
1381
//                                break;
1382
//                        } else if (pt.getModelo() == ((FLyrVect) layer)
1383
//                                        .getRecordset()) {
1384
//                                        dataSource = pt.getModelo().getRecordset();
1385
//                                        break;
1386
//                        }
1387
//                }
1388
//
1389
//                if (dataSource == null) {
1390
//                        // No se ha creado la tabla asociada al tema
1391
//                        dataSource = ((FLyrVect) layer).getRecordset();
1392
//                }
1393
//
1394
//                return dataSource;
1395
//
1396
//        }
1397

    
1398
        /**
1399
         * Recorremos las capas y las tablas del proyecto, y creamos una lista con
1400
         * todos los datasources de GDBMS que estamos usando. Luego recorremos los
1401
         * que est�n registrados, y borramos aquellos que no est�n siendo usados, es
1402
         * decir, aquellos que no est�n en nuestra lista (un Hash con clave el
1403
         * nombre del GDBMS)
1404
         *
1405
         */
1406
//        private void cleanBadReferences() {
1407
//                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1408
//                Hashtable usedDataSources = new Hashtable();
1409
//                // Primero las tablas
1410
//                int i, j;
1411
//                try {
1412
//                        for (i = 0; i < tables.size(); i++) {
1413
//                                ProjectTable t = (ProjectTable) tables.get(i);
1414
//                                SelectableDataSource ds;
1415
//                                if (t.getModelo() == null){
1416
//                                        /*
1417
//                                         * if a broken table was found
1418
//                                         * we don't clean any source
1419
//                                         */
1420
//                                        return;
1421
//                                }
1422
//
1423
//                                ds = t.getModelo().getRecordset();
1424
//
1425
//                                if (t.getOriginal() != null)
1426
//                                        usedDataSources.put(t.getOriginal().getRecordset()
1427
//                                                        .getName(), t.getOriginal());
1428
//                                usedDataSources.put(ds.getName(), ds);
1429
//                        }
1430
//                } catch (ReadException e) {
1431
//                        e.printStackTrace();
1432
//                }
1433
//                // Ahora las vistas
1434
//                ProjectView pv;
1435
//                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1436
//                try {
1437
//                        for (i = 0; i < views.size(); i++) {
1438
//                                pv = (ProjectView) views.get(i);
1439
//                                this.findLayersVectDataSorces(pv.getMapContext(), usedDataSources);
1440
//
1441
//                                MapContext aux = pv.getMapOverViewContext();
1442
//                                if (aux != null) {
1443
//                                        if (!this.findLayersVectDataSorces(aux, usedDataSources)){
1444
//                                                /*
1445
//                                                 * if a broken layer was found
1446
//                                                 * we don't clean any source
1447
//                                                 */
1448
//                                                return;
1449
//                                        }
1450
//
1451
//                                }
1452
//
1453
//                        } // for i
1454
//
1455
//                } catch (ReadException e) {
1456
//                        e.printStackTrace();
1457
//                }
1458
//
1459
//                // Ahora los mapas
1460
//                ArrayList maps = getDocumentsByType(ProjectMapFactory.registerName);
1461
//                ProjectMap pm;
1462
//                LayoutContext lContext;
1463
//                IFFrame[] fframes;
1464
//                try {
1465
//                        for (i = 0; i < maps.size(); i++) {
1466
//                                pm = (ProjectMap) maps.get(i);
1467
//                                fframes = pm.getModel().getLayoutContext().getFFrames();
1468
//                                for (j=0;j < fframes.length; j++){
1469
//                                        if (!(fframes[j] instanceof FFrameView)){
1470
//                                                continue;
1471
//                                        }
1472
//                                        if (!this.findLayersVectDataSorces(((FFrameView)fframes[i]).getMapContext(), usedDataSources)){
1473
//                                                /*
1474
//                                                 * if a broken layer was found
1475
//                                                 * we don't clean any source
1476
//                                                 */
1477
//                                                return;
1478
//
1479
//                                        }
1480
//                                } //for j
1481
//
1482
//                        } // for i
1483
//
1484
//                } catch (ReadException e) {
1485
//                        e.printStackTrace();
1486
//                }
1487
//
1488
//
1489
//                // Recorremos los dataSources y los borramos si no
1490
//                // los estamos usando.
1491
//                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1492
//                                .getDriverInfos();
1493
//                try {
1494
//                        for (i = 0; i < infos.length; i++) {
1495
//                                if (!usedDataSources.containsKey(infos[i].name)) {
1496
//                                        DataSource ds;
1497
//                                        ds = LayerFactory.getDataSourceFactory()
1498
//                                                        .createRandomDataSource(infos[i].name);
1499
//                                        ds.remove();
1500
//                                }
1501
//                        }
1502
//                } catch (ReadException e) {
1503
//                        e.printStackTrace();
1504
//                } catch (WriteException e) {
1505
//                        e.printStackTrace();
1506
//                }
1507
//        }
1508

    
1509
        /**
1510
         * Find DataSorces of the layers in the mapContext and store them in dataSourcesMap
1511
         *
1512
         * @param mapContext
1513
         * @param dataSourcesMap
1514
         * @return false if find a no Available layer
1515
         * @throws ReadDriverException
1516
         */
1517
//        private boolean findLayersVectDataSorces(MapContext mapContext,Map dataSourcesMap) throws ReadException{
1518
//                LayersIterator iter = new LayersIterator(mapContext.getLayers()){
1519
//
1520
//                        //@Override
1521
//                        public boolean evaluate(FLayer layer) {
1522
//                                if (!(layer instanceof FLyrVect))
1523
//                                        return false;
1524
//                                return super.evaluate(layer);
1525
//                        }
1526
//
1527
//                };
1528
//                FLyrVect layer;
1529
//                while (iter.hasNext()){
1530
//                        layer = (FLyrVect)iter.nextLayer();
1531
//                        if (!layer.isAvailable()){
1532
//                                return false;
1533
//                        }
1534
//
1535
//                        dataSourcesMap.put(layer.getRecordset().getName(), layer.getRecordset());
1536
//                        if (layer.isJoined()){
1537
//                                dataSourcesMap.put(layer.getSource().getRecordset().getName(),layer.getSource().getRecordset());
1538
//                        }
1539
//
1540
//                }
1541
//                return true;
1542
//        }
1543

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

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

    
1608
                return result;
1609
        }
1610

    
1611
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1612
                XMLEntity child = new XMLEntity();
1613

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

    
1638
                return child;
1639
        }
1640

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

    
1666
        /**
1667
         * Devuelve un arrayList con todos los documentos.
1668
         *
1669
         * @return Documentos
1670
         */
1671
        public ArrayList<ProjectDocument> getDocuments() {
1672
                ArrayList<ProjectDocument> docuArray = new ArrayList<ProjectDocument>();
1673
                for (int i = 0; i < documents.size(); i++) {
1674
                        ProjectDocument projectDocument = (ProjectDocument) documents
1675
                                        .get(i);
1676
                        docuArray.add(projectDocument);
1677
                }
1678
                return docuArray;
1679
        }
1680

    
1681
        /**
1682
         * Inserta un documento.
1683
         *
1684
         * @param doc
1685
         *            Documento
1686
         */
1687
        public void addDocument(ProjectDocument doc) {
1688
                documents.add(doc);
1689
                doc.addPropertyChangeListener(this);
1690
                //modified = true;
1691
                change.firePropertyChange("", "", null);
1692
                doc.setProject(this, 0);
1693
                doc.afterAdd();
1694

    
1695
        }
1696

    
1697
        /**
1698
         * Borra un documento.
1699
         *
1700
         * @param doc
1701
         *            Documento
1702
         */
1703
        public void delDocument(ProjectDocument doc) {
1704
                documents.remove(doc);
1705
                //modified = true;
1706
                change.firePropertyChange("", null, null);
1707
                doc.afterRemove();
1708
        }
1709

    
1710
        /**
1711
         * Sets the default selection color that will be used in subsequent
1712
         * projects.
1713
         *
1714
         * @param color
1715
         */
1716
        public static void setDefaultSelectionColor(Color color) {
1717
                defaultSelectionColor = color;
1718
        }
1719

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

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

    
1765
        /**
1766
         * Returns the user's default view units for measuring distances. This is
1767
         * the units that the user will see in the status bar of the view.
1768
         *
1769
         * @return int (index of the <b>Attributes.NAMES array</b>)
1770
         */
1771
        public static int getDefaultDistanceUnits() {
1772
                if (defaultDistanceUnits == -1) {
1773
                        XMLEntity xml = PluginServices.getPluginServices(
1774
                                        "com.iver.cit.gvsig").getPersistentXML();
1775
                        if (xml.contains("DefaultDistanceUnits")) {
1776
                                defaultDistanceUnits = xml
1777
                                                .getIntProperty("DefaultDistanceUnits");
1778
                        } else {
1779
                                // first app run case
1780
                                String[] unitNames = MapContext.getDistanceNames();
1781
                                for (int i = 0; i < unitNames.length; i++) {
1782
                                        // meter is the factory default's distance unit
1783
                                        if (unitNames[i].equals("Metros")) {
1784
                                                defaultDistanceUnits = i;
1785
                                                break;
1786
                                        }
1787
                                }
1788
                        }
1789
                        if (defaultDistanceUnits == -1)
1790
                                defaultDistanceUnits = MapContext.getDistancePosition("Metros");
1791
                }
1792
                return defaultDistanceUnits;
1793
        }
1794
        /**
1795
         * Returns the user's default view units for measuring areas. This is
1796
         * the units that the user will see in the status bar of the view.
1797
         *
1798
         * @return int (index of the <b>Attributes.NAMES array</b>)
1799
         */
1800
        public static int getDefaultDistanceArea() {
1801
                if (defaultDistanceArea == -1) {
1802
                        XMLEntity xml = PluginServices.getPluginServices(
1803
                                        "com.iver.cit.gvsig").getPersistentXML();
1804
                        if (xml.contains("DefaultDistanceArea")) {
1805
                                defaultDistanceArea = xml
1806
                                                .getIntProperty("DefaultDistanceArea");
1807
                        } else {
1808
                                // first app run case
1809
                                String[] unitNames = MapContext.getAreaNames();
1810
                                for (int i = 0; i < unitNames.length; i++) {
1811
                                        // meter is the factory default's distance unit
1812
                                        if (unitNames[i].equals("Metros")) {
1813
                                                defaultDistanceArea = i;
1814
                                                break;
1815
                                        }
1816
                                }
1817
                        }
1818
                        if (defaultDistanceArea == -1){
1819
                                defaultDistanceArea=getDefaultDistanceUnits();
1820
                        }
1821
                }
1822
                return defaultDistanceArea;
1823
        }
1824
        /**
1825
         * Sets the default map unit (the units used by the data).
1826
         *
1827
         * @param mapUnits
1828
         */
1829
        public static void setDefaultMapUnits(int mapUnits) {
1830
                defaultMapUnits = mapUnits;
1831
        }
1832

    
1833
        /**
1834
         * Sets the default distance units (the units shown in the status bar)
1835
         *
1836
         * @param distanceUnits
1837
         */
1838
        public static void setDefaultDistanceUnits(int distanceUnits) {
1839
                defaultDistanceUnits = distanceUnits;
1840
        }
1841
        /**
1842
         * Sets the default distance area (the units shown in the status bar)
1843
         *
1844
         * @param distanceUnits
1845
         */
1846
        public static void setDefaultDistanceArea(int distanceArea) {
1847
                defaultDistanceArea = distanceArea;
1848
        }
1849
        public String exportToXML() throws SaveException {
1850
                XMLEntity xml = this.newExportXMLRootNode();
1851

    
1852
                Iterator iter = this.documents.iterator();
1853
                ProjectDocument document;
1854
                // FIXME: Falta atrapar los errores
1855
                while (iter.hasNext()) {
1856
                        document = (ProjectDocument) iter.next();
1857
                        document.exportToXML(xml, this);
1858
                }
1859

    
1860
                return xml.toString();
1861
        }
1862

    
1863
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1864
                XMLEntity xml = this.newExportXMLRootNode();
1865

    
1866
                for (int i = 0; i < documents.length; i++) {
1867
                        documents[i].exportToXML(xml, this);
1868
                }
1869

    
1870
                return xml.toString();
1871
        }
1872

    
1873
        public void importFromXML(String xml) throws Exception {
1874
                throw new Exception("Not Implemented");
1875
                /*
1876
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1877
                 *
1878
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1879
                 * Exception(e); }
1880
                 *
1881
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1882
                 * Error"); //FIXME: traducir }
1883
                 *
1884
                 * int i;
1885
                 *
1886
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1887
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1888
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1889
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1890
                 * root "+i+ "error"); } documentFactory =
1891
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1892
                 * int j; }
1893
                 */
1894

    
1895
        }
1896

    
1897
        public void importFromXML(String xml, String type) throws Exception {
1898
                // FIXME: EXCEPTIONS!!!!
1899
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1900

    
1901
                if (!checkExportXMLRootNode(xmlEntity)) {
1902
                        throw new Exception();
1903
                }
1904

    
1905
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1906
                if (typeRoot.getChildrenCount() == 0) {
1907
                        return;
1908
                }
1909

    
1910
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1911

    
1912
                Hashtable conflicts = getConflicts(xmlEntity);
1913

    
1914
                if (conflicts.size() != 0) {
1915
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
1916
                                        conflicts)) {
1917
                                return;
1918
                        }
1919
                }
1920
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
1921
                                "dataSources"));
1922

    
1923
                int i;
1924
                ProjectDocument document;
1925
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
1926
                        document = documentFactory.create(this);
1927
                        document.importFromXML(xmlEntity, typeRoot, i, this);
1928
                }
1929

    
1930
        }
1931

    
1932
        private Hashtable getConflicts(XMLEntity xml) {
1933
                int iType;
1934
                Hashtable conflicts = new Hashtable();
1935
                ArrayList elements;
1936
                XMLEntity typeRoot;
1937
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
1938
                        typeRoot = xml.getChild(iType);
1939
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
1940
                        Hashtable conflictsType = new Hashtable();
1941
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
1942
                                XMLEntity child = typeRoot.getChild(iXML);
1943
                                Iterator iter = elements.iterator();
1944
                                while (iter.hasNext()) {
1945
                                        ProjectDocument element = (ProjectDocument) iter.next();
1946
                                        if (element.getName().equalsIgnoreCase(
1947
                                                        child.getStringProperty("name"))) {
1948
                                                conflictsType.put(new Integer(iXML), child);
1949
                                                break;
1950
                                        }
1951

    
1952
                                }
1953
                        }
1954
                        if (conflictsType.size() > 0) {
1955
                                conflicts
1956
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
1957
                        }
1958
                }
1959
                return conflicts;
1960
        }
1961

    
1962
        public boolean isValidXMLForImport(String xml) {
1963
                XMLEntity xmlEntity;
1964
                try {
1965
                        xmlEntity = XMLEntity.parse(xml);
1966
                } catch (Exception e) {
1967
                        return false;
1968
                }
1969

    
1970
                return checkExportXMLRootNode(xmlEntity);
1971
        }
1972

    
1973
        public boolean isValidXMLForImport(String xml, String type) {
1974
                XMLEntity xmlEntity;
1975
                try {
1976
                        xmlEntity = XMLEntity.parse(xml);
1977
                } catch (Exception e) {
1978
                        return false;
1979
                }
1980

    
1981
                if (!checkExportXMLRootNode(xmlEntity)) {
1982
                        return false;
1983
                }
1984

    
1985
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
1986

    
1987
                if (typeRoot == null) {
1988
                        return false;
1989
                }
1990

    
1991
                return (typeRoot.getChildrenCount() > 0);
1992
        }
1993

    
1994
        private boolean checkExportXMLRootNode(XMLEntity xml) {
1995
                if (!xml.contains("applicationName"))
1996
                        return false;
1997
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
1998
                        return false;
1999

    
2000
                if (!xml.contains("version"))
2001
                        return false;
2002
                if (!xml.getStringProperty("version")
2003
                                .equalsIgnoreCase(Version.format()))
2004
                        return false;
2005

    
2006
                return true;
2007
        }
2008

    
2009
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
2010
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
2011
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
2012
                                .getDriverInfo(dataSourceName);
2013
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
2014
        }
2015

    
2016
        private XMLEntity newExportXMLRootNode() {
2017
                XMLEntity xml = new XMLEntity();
2018
                xml.putProperty("applicationName", "gvSIG");
2019
                xml.putProperty("version", Version.format());
2020
                return xml;
2021
        }
2022

    
2023
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
2024
                XMLEntity typeRoot = root.firstChild("type", type);
2025
                if (typeRoot == null) {
2026
                        typeRoot = this.newExportXMLTypeNode(type);
2027
                        root.addChild(typeRoot);
2028
                }
2029
                return typeRoot;
2030
        }
2031

    
2032
        private XMLEntity newExportXMLTypeNode(String type) {
2033
                XMLEntity xmlDataSources = new XMLEntity();
2034
                xmlDataSources.putProperty("type", type);
2035
                return xmlDataSources;
2036
        }
2037

    
2038
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2039
                String name = xmlDataSource.getStringProperty("gdbmsname");
2040

    
2041
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2042
                        if (xmlDataSource.getStringProperty("type").equals(
2043
                                        "otherDriverFile")) {
2044
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2045
                                                xmlDataSource.getStringProperty("driverName"), name,
2046
                                                xmlDataSource.getStringProperty("file"));
2047

    
2048
                        } else if (xmlDataSource.getStringProperty("type").equals(
2049
                                        "sameDriverFile")) {
2050

    
2051
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2052
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2053
                                                name, xmlDataSource.getStringProperty("host"),
2054
                                                xmlDataSource.getIntProperty("port"),
2055
                                                xmlDataSource.getStringProperty("user"),
2056
                                                xmlDataSource.getStringProperty("password"),
2057
                                                xmlDataSource.getStringProperty("dbName"),
2058
                                                xmlDataSource.getStringProperty("tableName"),
2059
                                                xmlDataSource.getStringProperty("driverInfo"));
2060
                        } else {
2061
                                return false;
2062
                        }
2063

    
2064
                }
2065
                return true;
2066
        }
2067

    
2068
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2069
                try {
2070
                        int numDataSources = xmlDataSources.getChildrenCount();
2071

    
2072
                        if (numDataSources == 0)
2073
                                return true;
2074
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2075

    
2076
                        for (int i = 0; i < numDataSources; i++) {
2077
                                XMLEntity child = xmlDataSources.getChild(i);
2078
                                if (!this.registerDataSourceFromXML(child)) {
2079
                                        return false;
2080
                                }
2081
                        }
2082

    
2083
                        return true;
2084
                } catch (Exception e) {
2085
                        e.printStackTrace();
2086
                        return false;
2087
                }
2088
        }
2089

    
2090
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2091
                ProjectDocumentFactory pde = null;
2092
                try {
2093
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2094
                                        .getInstance();
2095
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2096
                                        .get("Documents"));
2097
                        try {
2098
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2099
                        } catch (InstantiationException e) {
2100
                                NotificationManager.addError(
2101
                                                "Clase de ProjectDocument no reconocida", e);
2102
                        } catch (IllegalAccessException e) {
2103
                                NotificationManager.addError(
2104
                                                "Clase de ProjectDocument no reconocida", e);
2105
                        }
2106

    
2107
                } catch (Exception e1) {
2108
                        return null;
2109
                }
2110
                return pde;
2111
        }
2112

    
2113
         public boolean hasChanged() {
2114
                 // we return true if the project is not empty (until we have a better method...)
2115
                 if ((this.getDocuments().size() != 0) || modified) {
2116
                         return true;
2117
                 }
2118
                 return false;
2119
//                 return signatureAtStartup != getXMLEntity().hash();
2120
         }
2121

    
2122
        public void setSignature(long hash) {
2123
                signatureAtStartup = hash;
2124
        }
2125
}