Statistics
| Revision:

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

History | View | Annotate | Download (61.3 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.data.ReadException;
60
import org.gvsig.data.WriteException;
61
import org.gvsig.fmap.crs.CRSFactory;
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.operations.AlphanumericData;
71
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
72

    
73
import com.iver.andami.PluginServices;
74
import com.iver.andami.messages.NotificationManager;
75
import com.iver.andami.ui.mdiManager.IWindow;
76
import com.iver.andami.ui.mdiManager.SingletonWindow;
77
import com.iver.andami.ui.mdiManager.WindowInfo;
78
import com.iver.cit.gvsig.ProjectExtension;
79
import com.iver.cit.gvsig.Version;
80
import com.iver.cit.gvsig.project.documents.ProjectDocument;
81
import com.iver.cit.gvsig.project.documents.ProjectDocumentFactory;
82
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
83
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
84
import com.iver.cit.gvsig.project.documents.gui.IDocumentWindow;
85
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
86
import com.iver.cit.gvsig.project.documents.gui.WindowData;
87
import com.iver.cit.gvsig.project.documents.layout.LayoutContext;
88
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
89
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
90
import com.iver.cit.gvsig.project.documents.layout.fframes.FFrameView;
91
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
92
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
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(AlphanumericData 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
         * @throws XMLException
1037
         * @throws DriverException
1038
         * @throws DriverIOException
1039
         * @throws OpenException
1040
         */
1041
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1042
                Project p = new Project();
1043
                try {
1044
                        p.comments = xml.getStringProperty("comments");
1045
                        p.creationDate = xml.getStringProperty("creationDate");
1046

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

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

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

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

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

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

    
1113
                int childNumber = 0;
1114
                Project p = new Project();
1115

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

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

    
1126
                        // Leemos el ultiom hijo recogido
1127
                        childNumber = numExtents;
1128

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

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

    
1149
                        childNumber += numCameras;
1150

    
1151
                        int numDataSources = xml.getIntProperty("data-source-count");
1152

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

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

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

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

    
1204
                        p.setLinkTable();
1205
                        String strProj = xml.getStringProperty("projection");
1206

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

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

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

    
1233
                return p;
1234

    
1235
        }
1236

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

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

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

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

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

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

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

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

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

    
1381
                }
1382
                return Project.defaultProjection;
1383
        }
1384

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

    
1402
                        if (elem.getName().equals(name)) {
1403
                                return elem;
1404
                        }
1405
                }
1406

    
1407
                return null;
1408
        }
1409

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

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

    
1463
                return dataSource;
1464

    
1465
        }
1466

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

    
1492
                                ds = t.getModelo().getRecordset();
1493

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

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

    
1520
                                }
1521

    
1522
                        } // for i
1523

    
1524
                } catch (ReadException e) {
1525
                        e.printStackTrace();
1526
                }
1527

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

    
1548
                                        }
1549
                                } //for j
1550

    
1551
                        } // for i
1552

    
1553
                } catch (ReadException e) {
1554
                        e.printStackTrace();
1555
                }
1556

    
1557

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

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

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

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

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

    
1609
                }
1610
                return true;
1611
        }
1612

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

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

    
1677
                return result;
1678
        }
1679

    
1680
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1681
                XMLEntity child = new XMLEntity();
1682

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

    
1707
                return child;
1708
        }
1709

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

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

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

    
1764
        }
1765

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

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

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

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

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

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

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

    
1929
                return xml.toString();
1930
        }
1931

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

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

    
1939
                return xml.toString();
1940
        }
1941

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

    
1964
        }
1965

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

    
1970
                if (!checkExportXMLRootNode(xmlEntity)) {
1971
                        throw new Exception();
1972
                }
1973

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

    
1979
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
1980

    
1981
                Hashtable conflicts = getConflicts(xmlEntity);
1982

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

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

    
1999
        }
2000

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

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

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

    
2039
                return checkExportXMLRootNode(xmlEntity);
2040
        }
2041

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

    
2050
                if (!checkExportXMLRootNode(xmlEntity)) {
2051
                        return false;
2052
                }
2053

    
2054
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
2055

    
2056
                if (typeRoot == null) {
2057
                        return false;
2058
                }
2059

    
2060
                return (typeRoot.getChildrenCount() > 0);
2061
        }
2062

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

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

    
2075
                return true;
2076
        }
2077

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

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

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

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

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

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

    
2117
                        } else if (xmlDataSource.getStringProperty("type").equals(
2118
                                        "sameDriverFile")) {
2119

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

    
2133
                }
2134
                return true;
2135
        }
2136

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

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

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

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

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

    
2176
                } catch (Exception e1) {
2177
                        return null;
2178
                }
2179
                return pde;
2180
        }
2181

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

    
2191
        public void setSignature(long hash) {
2192
                signatureAtStartup = hash;
2193
        }
2194
}