Statistics
| Revision:

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

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.LinkSelectionObserver;
93
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
94
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
95
import com.iver.cit.gvsig.project.documents.view.ProjectView;
96
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
97
import com.iver.utiles.IPersistence;
98
import com.iver.utiles.PostProcessSupport;
99
import com.iver.utiles.StringUtilities;
100
import com.iver.utiles.XMLEntity;
101
import com.iver.utiles.extensionPoints.ExtensionPoint;
102
import com.iver.utiles.extensionPoints.ExtensionPoints;
103
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
104

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

    
113
        static private IProjection defaultProjection = null;
114

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

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

    
125
        private static int defaultMapUnits = -1;
126

    
127
        private static int defaultDistanceUnits = -1;
128

    
129
        private static int defaultDistanceArea = -1;
130

    
131
        private PropertyChangeSupport change;
132

    
133
        private boolean modified = false;
134

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

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

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

    
142
        private String owner = "";
143

    
144
        private String comments = "";
145

    
146
        private Color selectionColor = null;
147

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

    
153
        private ArrayList extents = new ArrayList();
154

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

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

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

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

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

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

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

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

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

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

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

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

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

    
280
                return null;
281
        }
282

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

    
303
                return null;
304
        }
305

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
732
                boolean projectWindowSaved = false;
733

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

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

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

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

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

    
823
                xml.addChild(propertyList);
824
        }
825

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1081
                        childNumber += numCameras;
1082

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

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

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

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

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

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

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

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

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

    
1165
                return p;
1166

    
1167
        }
1168

    
1169
        /**
1170
         * Reestablece los link que ten�a cada tabla con las dem�s.
1171
         */
1172
        public void setLinkTable() {
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
                                                                        .getModel()
1189
                                                                        .getName())) {
1190
                                                LinkSelectionObserver lso;
1191

    
1192
                                                lso = new LinkSelectionObserver(((ProjectTable) tables
1193
                                                                .get(i)).getModel(),
1194
                                                                ((ProjectTable) tables.get(j)).getModel(),
1195
                                                                ((ProjectTable) tables
1196
                                                                                .get(i)).getField1(),
1197
                                                                                ((ProjectTable) tables.get(i)).getField2());
1198

    
1199
                                                (((ProjectTable) tables.get(i)).getModel()).addObserver(lso);
1200
                                                ((ProjectTable) tables.get(i)).addLinkSelectionObserver(lso);
1201

    
1202
                                        }
1203
//                                } catch (ReadException 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
}