Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / applications / appgvSIG / src / org / gvsig / app / project / DefaultProject.java @ 34300

History | View | Annotate | Download (30.4 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2009 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 * 
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 * 
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 * 
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
 * MA  02110-1301, USA.
20
 * 
21
 */
22

    
23
/*
24
 * AUTHORS (In addition to CIT):
25
 * 2004-2009 IVER TI
26
 *   
27
 */
28

    
29
package org.gvsig.app.project;
30

    
31
import java.awt.Color;
32
import java.beans.PropertyChangeEvent;
33
import java.beans.PropertyChangeListener;
34
import java.beans.PropertyChangeSupport;
35
import java.io.File;
36
import java.io.FileInputStream;
37
import java.io.FileNotFoundException;
38
import java.io.FileOutputStream;
39
import java.io.IOException;
40
import java.io.InputStream;
41
import java.io.OutputStream;
42
import java.io.Serializable;
43
import java.net.MalformedURLException;
44
import java.net.URI;
45
import java.net.URISyntaxException;
46
import java.net.URL;
47
import java.net.URLDecoder;
48
import java.net.URLEncoder;
49
import java.text.DateFormat;
50
import java.text.MessageFormat;
51
import java.util.ArrayList;
52
import java.util.Collections;
53
import java.util.Date;
54
import java.util.HashMap;
55
import java.util.Iterator;
56
import java.util.List;
57
import java.util.Map;
58
import java.util.regex.Pattern;
59

    
60
import org.cresques.cts.IProjection;
61
import org.gvsig.andami.PluginServices;
62
import org.gvsig.andami.ui.mdiManager.IWindow;
63
import org.gvsig.andami.ui.mdiManager.SingletonWindow;
64
import org.gvsig.app.extension.Version;
65
import org.gvsig.app.project.documents.AbstractDocument;
66
import org.gvsig.app.project.documents.Document;
67
import org.gvsig.app.project.documents.exceptions.SaveException;
68
import org.gvsig.app.project.documents.layout.LayoutDocument;
69
import org.gvsig.app.project.documents.layout.LayoutManager;
70
import org.gvsig.app.project.documents.table.TableDocument;
71
import org.gvsig.app.project.documents.table.TableManager;
72
import org.gvsig.app.project.documents.view.DefaultViewDocument;
73
import org.gvsig.app.project.documents.view.ViewManager;
74
import org.gvsig.fmap.dal.DataTypes;
75
import org.gvsig.fmap.mapcontext.MapContext;
76
import org.gvsig.fmap.mapcontext.layers.FLayer;
77
import org.gvsig.fmap.mapcontext.layers.FLayers;
78
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
79
import org.gvsig.tools.ToolsLocator;
80
import org.gvsig.tools.dynobject.DynField;
81
import org.gvsig.tools.dynobject.DynStruct;
82
import org.gvsig.tools.persistence.PersistenceManager;
83
import org.gvsig.tools.persistence.Persistent;
84
import org.gvsig.tools.persistence.PersistentContext;
85
import org.gvsig.tools.persistence.PersistentState;
86
import org.gvsig.tools.persistence.exception.PersistenceException;
87
import org.gvsig.tools.persistence.exception.PersistenceValidateExceptions;
88
import org.gvsig.utils.StringUtilities;
89
import org.slf4j.Logger;
90
import org.slf4j.LoggerFactory;
91

    
92
/**
93
 * Clase que representa un proyecto de gvSIG
94
 * 
95
 * @author 2004-2005 Fernando Gonz?lez Cort?s
96
 * @author 2006-2009 Jose Manuel Vivo
97
 * @author 2005- Vicente Caballero
98
 * @author 2009- Joaquin del Cerro
99
 * 
100
 */
101

    
102
public class DefaultProject implements Serializable, PropertyChangeListener,
103
                Project {
104

    
105
        private Logger LOG = LoggerFactory.getLogger(DefaultProject.class);
106
        /**
107
         * @deprecated see ApplicationLocator.getManager().getVersion()
108
         */
109
        public static String VERSION = Version.format();
110

    
111
        /**
112
         * 
113
         */
114
        private static final long serialVersionUID = -4449622027521773178L;
115

    
116
        // private static final Logger logger = LoggerFactory.getLogger(Project
117
        // .class);
118

    
119
        private static ProjectPreferences preferences = new ProjectPreferences();
120

    
121
        /**
122
         * Index used by the generator of unique names of documents.
123
         */
124
        private Map<String, Integer> nextDocumentIndexByType = new HashMap<String, Integer>();
125

    
126
        private PropertyChangeSupport change;
127

    
128
        private boolean modified = false;
129

    
130
        private String name = null;
131

    
132
        private String creationDate = null;
133

    
134
        private String modificationDate = null;
135

    
136
        private String owner = null;
137

    
138
        private String comments = null;
139

    
140
        private Color selectionColor = null;
141

    
142
        private List<Document> documents = null;
143

    
144
        private List<ProjectExtent> extents = null;
145

    
146
        private IProjection projection;
147

    
148
        /**
149
         * Creates a new Project object.
150
         */
151
        DefaultProject() {
152
                this.change = new PropertyChangeSupport(this);
153
                this.clean();
154
        }
155

    
156
        protected void clean() {
157
                this.owner = "";
158
                this.comments = "";
159
                this.name = PluginServices.getText(this, "untitled");
160
                this.creationDate = DateFormat.getDateInstance().format(new Date());
161
                this.modificationDate = this.creationDate;
162

    
163
                this.documents = new ArrayList<Document>();
164
                this.extents = new ArrayList<ProjectExtent>();
165

    
166
                this.setSelectionColor(getPreferences().getDefaultSelectionColor());
167

    
168
                this.projection = null; // se inicializa en el getProjection()
169
        }
170

    
171
        public static ProjectPreferences getPreferences() {
172
                return preferences;
173
        }
174

    
175
        public void propertyChange(PropertyChangeEvent evt) {
176
                change.firePropertyChange(evt);
177
        }
178

    
179
        public synchronized void addPropertyChangeListener(
180
                        PropertyChangeListener arg0) {
181
                change.addPropertyChangeListener(arg0);
182
        }
183

    
184
        /**
185
         * Return the creation date of the project
186
         * 
187
         * @return
188
         */
189
        public String getCreationDate() {
190
                return creationDate;
191
        }
192

    
193
        protected void setCreationDate(String creationDate) {
194
                this.creationDate = creationDate;
195
                change.firePropertyChange("setCreationDate", null, null);
196
        }
197

    
198
        /**
199
         * Return the name of the project
200
         * 
201
         * @return
202
         */
203
        public String getName() {
204
                return name;
205
        }
206

    
207
        /**
208
         * Set the name of he project.
209
         * 
210
         * @param string
211
         */
212
        public void setName(String name) {
213
                this.name = name;
214
                change.firePropertyChange("setName", null, null);
215
        }
216

    
217
        /**
218
         * Return the comments associateds with the project
219
         * 
220
         * @return comments
221
         */
222
        public String getComments() {
223
                return comments;
224
        }
225

    
226
        /**
227
         * Set the comments associateds with the project
228
         * 
229
         * @param comments
230
         *            as string
231
         */
232
        public void setComments(String string) {
233
                comments = string;
234
                change.firePropertyChange("setComments", null, null);
235
        }
236

    
237
        /**
238
         * Retuen the modification date of the project.
239
         * 
240
         * @return modification date as string
241
         */
242
        public String getModificationDate() {
243
                return modificationDate;
244
        }
245

    
246
        protected void setModificationDate(String string) {
247
                modificationDate = string;
248
                change.firePropertyChange("setModificationDate", null, null);
249
        }
250

    
251
        /**
252
         * Return the author of the project,
253
         * 
254
         * @return author as string
255
         */
256
        public String getOwner() {
257
                return owner;
258
        }
259

    
260
        /**
261
         * Sets the author of the project
262
         * 
263
         * @param author
264
         *            name as string
265
         */
266
        public void setOwner(String owner) {
267
                this.owner = owner;
268
                change.firePropertyChange("setOwner", null, null);
269
        }
270

    
271
        /**
272
         * Obtiene el color de selecci?n que se usar? en el proyecto
273
         * 
274
         * @return
275
         */
276
        public Color getSelectionColor() {
277
                if (selectionColor == null) {
278
                        selectionColor = getPreferences().getDefaultSelectionColor();
279
                }
280
                return selectionColor;
281
        }
282

    
283
        /**
284
         * Sets the selecction color
285
         * 
286
         * @param selection
287
         *            color as string
288
         */
289
        public void setSelectionColor(String selectionColor) {
290
                this.setSelectionColor(StringUtilities.string2Color(selectionColor));
291
        }
292

    
293
        /**
294
         * Sets the selecction color
295
         * 
296
         * @param selection
297
         *            color as Color
298
         */
299
        public void setSelectionColor(Color selectionColor) {
300
                this.selectionColor = selectionColor;
301
                MapContext.setSelectionColor(selectionColor);
302
                change.firePropertyChange("selectionColor", null, selectionColor);
303
        }
304

    
305
        public IProjection getProjection() {
306
                if (projection == null) {
307
                        projection = getPreferences().getDefaultProjection();
308
                }
309
                return projection;
310
        }
311

    
312
        public void setProjection(IProjection projection) {
313
                this.projection = projection;
314
        }
315

    
316
        /**
317
         * Sets the modified state of project.
318
         * 
319
         * Can't set to not modified.
320
         * 
321
         * @param modified
322
         *            as boolean
323
         */
324
        public void setModified(boolean modified) {
325
                this.modified = modified;
326
                if (modified == false) {
327
                        List<Document> documents = this.getDocuments();
328
                        for (int i = 0; i < documents.size(); i++) {
329
                                documents.get(i).setModified(false);
330
                        }
331
                }
332
        }
333

    
334
        public boolean hasChanged() {
335
                // we return true if the project is not empty (until we have a better
336
                // method...)
337
                if ((this.getDocuments().size() != 0) || modified) {
338
                        return true;
339
                }
340
                return false;
341
        }
342

    
343
        /**
344
         * Return a list of documents in the project.
345
         * 
346
         * @return documents as List of IProjectDocument
347
         */
348
        public List<Document> getDocuments() {
349
                return Collections.unmodifiableList(documents);
350
        }
351

    
352
        /**
353
         * Return a list with all documents of especified type.
354
         * 
355
         * @param type
356
         *            of document
357
         * 
358
         * @return List of IProjectDocument
359
         */
360
        public List<Document> getDocuments(String type) {
361
                List<Document> docs = new ArrayList<Document>();
362
                if (type != null) {
363
                        for (Document document : this.documents) {
364
                                if (type.equalsIgnoreCase(document.getTypeName())) {
365
                                        docs.add(document);
366
                                }
367
                        }
368
                }
369
                return Collections.unmodifiableList(docs);
370
        }
371

    
372
        /**
373
         * Adds a document to the project
374
         * 
375
         * @param document
376
         *            as IProjectDocument
377
         */
378
        public void add(Document document) {
379
                documents.add(document);
380
                document.addPropertyChangeListener(this);
381
                document.setProject(this);
382
                document.setName(this.getUniqueNameForDocument(document.getTypeName(),
383
                                document.getName()));
384
                document.afterAdd();
385
                this.setModified(true);
386
                change.firePropertyChange("addDocument", null, null);
387
        }
388

    
389
        /**
390
         * Remove a document of the project
391
         * 
392
         * @param document
393
         *            as IProjectDocument
394
         */
395
        public void remove(Document doc) {
396
                documents.remove(doc);
397
                this.setModified(true);
398
                change.firePropertyChange("delDocument", null, null);
399
                doc.afterRemove();
400
        }
401

    
402
        public Iterator<Document> iterator() {
403
                return documents.iterator();
404
        }
405

    
406
        public boolean isEmpty() {
407
                return documents.isEmpty();
408
        }
409

    
410
        /**
411
         * Return the FeatureTableDocument associated with a layer
412
         * 
413
         * @param layer
414
         * 
415
         * @return FeatureTableDocument associated with the layer.
416
         */
417
        public TableDocument getTable(FLyrVect layer) {
418
                List<Document> tables = getDocuments(TableManager.TYPENAME);
419
                for (int i = 0; i < tables.size(); i++) {
420
                        TableDocument table = (TableDocument) tables.get(i);
421
                        if (table.getStore().equals(layer.getFeatureStore())) {
422
                                return table;
423
                        }
424
                }
425

    
426
                return null;
427
        }
428

    
429
        /**
430
         * Return the view that contains the especified layer.
431
         * 
432
         * @param layer
433
         * 
434
         * @return name of the view that contains the layer
435
         * 
436
         * @throws RuntimeException
437
         *             Si la capa que se pasa como par?metro no se encuentra en
438
         *             ninguna vista
439
         */
440
        public String getViewName(FLayer layer) {
441
                List<Document> views = getDocuments(ViewManager.TYPENAME);
442
                for (int v = 0; v < views.size(); v++) {
443
                        DefaultViewDocument pView = (DefaultViewDocument) views.get(v);
444
                        FLayers layers = pView.getMapContext().getLayers();
445
                        if (isView(layers, layer)) {
446
                                return pView.getName();
447
                        }
448
                }
449

    
450
                throw new RuntimeException(MessageFormat.format(
451
                                "The layer '{1}' is not in a view", layer.getName()));
452
        }
453

    
454
        private boolean isView(FLayers layers, FLayer layer) {
455
                for (int i = 0; i < layers.getLayersCount(); i++) {
456
                        if (layers.getLayer(i) instanceof FLayers) {
457
                                if (isView((FLayers) layers.getLayer(i), layer)) {
458
                                        return true;
459
                                }
460
                        }
461
                        if (layers.getLayer(i) == layer) {
462
                                return true;
463
                        }
464
                }
465
                return false;
466
        }
467

    
468
        public void addExtent(ProjectExtent arg1) {
469
                extents.add(arg1);
470
                change.firePropertyChange("addExtent", null, null);
471
        }
472

    
473
        public ProjectExtent removeExtent(int arg0) {
474
                change.firePropertyChange("delExtent", null, null);
475
                return extents.remove(arg0);
476
        }
477

    
478
        public ProjectExtent[] getExtents() {
479
                return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
480
        }
481

    
482
        /**
483
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
484
         * pointExtension, este ?ltimo se puede obtener del
485
         * Project****Factory.registerName.
486
         * 
487
         * @param name
488
         *            Nombre del documento
489
         * @param type
490
         *            nombre de registro en el extensionPoint
491
         * 
492
         * @return Documento
493
         */
494
        public Document getDocument(String name, String type) {
495
                if (type != null) {
496
                        for (int i = 0; i < documents.size(); i++) {
497
                                Document document = documents.get(i);
498
                                if (type.equalsIgnoreCase(document.getTypeName())
499
                                                && name.equalsIgnoreCase(document.getName())) {
500
                                        return document;
501
                                }
502
                        }
503
                }
504
                return null;
505
        }
506

    
507
        public String getUniqueNameForDocument(String type, String name) {
508
                Document document = getDocument(name, type);
509
                if (document == null) {
510
                        return name;
511
                }
512

    
513
                String newName = null;
514
                int num = this.getNextDocumentIndex(type);
515
                while (document != null) {
516
                        newName = name + " - " + num++;
517
                        document = getDocument(newName, type);
518
                }
519
                this.setNextDocumentIndex(type, num);
520
                return newName;
521
        }
522

    
523
        private int getNextDocumentIndex(String type) {
524
                if (nextDocumentIndexByType.get(type) == null) {
525
                        nextDocumentIndexByType.put(type, new Integer(1));
526
                        return 1;
527
                }
528
                return nextDocumentIndexByType.get(type).intValue();
529
        }
530

    
531
        private void setNextDocumentIndex(String type, int newIndex) {
532
                if (nextDocumentIndexByType.get(type) == null) {
533
                        nextDocumentIndexByType.put(type, new Integer(newIndex));
534
                } else {
535
                        nextDocumentIndexByType.put(type, new Integer(newIndex));
536
                }
537
        }
538

    
539
        public void saveState(File out) throws PersistenceException {
540
                FileOutputStream fout;
541
                try {
542
                        fout = new FileOutputStream(out);
543
                        saveState(fout, new File(out.getParent()));
544
                } catch (FileNotFoundException e) {
545
                        throw new PersistenceException(e);
546
                }
547
        }
548

    
549
        public void saveState(OutputStream out) throws PersistenceException {
550
                saveState(out, null);
551
        }
552

    
553
        public void saveState(OutputStream out, File rootFolder)
554
                        throws PersistenceException {
555
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
556
                PersistentState state = null;
557
                state = manager.getState(this, true);
558
                try {
559
                        if (rootFolder != null) {
560
                                relativizeFiles(state, rootFolder);
561
                        }
562
                } catch (Exception ex) {
563
                        state.getContext().addError(ex);
564
                }
565
                manager.saveState(state, out);
566
                if (state.getContext().getErrors() != null) {
567
                        throw state.getContext().getErrors();
568
                }
569
        }
570

    
571
        private void relativizeFiles(PersistentState state, File rootFolder) {
572
                PersistentContext context = state.getContext();
573

    
574
                URI cwd = new File(System.getProperty("user.dir")).toURI();
575
                @SuppressWarnings("unchecked")
576
                Iterator<PersistentState> statesIterator = context.iterator();
577
                while (statesIterator.hasNext()) {
578
                        PersistentState aState = statesIterator.next();
579
                        DynStruct definition = aState.getDefinition();
580
                        DynField[] fields = definition.getDynFields();
581
                        for (DynField field : fields) {
582
                                if (field.getType() == DataTypes.FILE
583
                                                || field.getType() == DataTypes.FOLDER) {
584
                                        try {
585
                                                File value = aState.getFile(field.getName());
586
                                                value = relativizeFile(value, rootFolder);
587
                                                aState.set(field.getName(), value);
588
                                        } catch (PersistenceException e) {
589
                                                LOG.warn(
590
                                                                "Can't relativice field '" + field.getName()
591
                                                                                + "' for class '"
592
                                                                                + definition.getName() + "'.", e);
593
                                        }
594
                                } else if (field.getType() == DataTypes.URL) {
595
                                        try {
596
                                                URL value = aState.getURL(field.getName());
597
                                                if ("FILE".equalsIgnoreCase(value.getProtocol())) {
598
                                                        File file = new File(value.toURI());
599
                                                        file = relativizeFile(file, rootFolder);
600
                                                        value = new URL("file","",file.toURI().toString().substring(cwd.toString().length()));
601
                                                        aState.set(field.getName(), value);
602
                                                }
603
                                        } catch (PersistenceException e) {
604
                                                // do nothind
605
                                        } catch (MalformedURLException e) {
606
                                                // do nothind
607
                                        } catch (URISyntaxException e) {
608
                                                // do nothind
609
                                        }
610
                                }
611
                        }
612
                }
613
        }
614

    
615
        private File relativizeFile(File file, File rootFolder) {
616
                if (rootFolder == null) {
617
                        return file;
618
                }
619
                if (file == null) {
620
                        return null;
621
                }
622
                boolean isDir = false;
623
                // isDir = file.isDirectory();
624
                isDir = rootFolder.isDirectory();
625
                String basePath = rootFolder.getAbsolutePath();
626
                String targetPath = file.getPath();
627
                String pathSeparator = File.separator;
628
                // We need the -1 argument to split to make sure we get a trailing
629
                // "" token if the base ends in the path separator and is therefore
630
                // a directory. We require directory paths to end in the path
631
                // separator -- otherwise they are indistinguishable from files.
632
                String[] base = basePath.split(Pattern.quote(pathSeparator), -1);
633
                String[] target = targetPath.split(Pattern.quote(pathSeparator), 0);
634

    
635
                // First get all the common elements. Store them as a string,
636
                // and also count how many of them there are.
637
                String common = "";
638
                int commonIndex = 0;
639
                for (int i = 0; i < target.length && i < base.length; i++) {
640
                        if (target[i].equals(base[i])) {
641
                                common += target[i] + pathSeparator;
642
                                commonIndex++;
643
                        } else
644
                                break;
645
                }
646

    
647
                if (commonIndex == 0) {
648
                        // Whoops -- not even a single common path element. This most
649
                        // likely indicates differing drive letters, like C: and D:.
650
                        // These paths cannot be relativized. Return the target path.
651
                        return file;
652
                        // This should never happen when all absolute paths
653
                        // begin with / as in *nix.
654
                }
655

    
656
                String relative = "";
657
                if (base.length == commonIndex) {
658
                        // Comment this out if you prefer that a relative path not start
659
                        // with ./
660
                        relative = "." + pathSeparator;
661
                } else {
662
                        int numDirsUp = base.length - commonIndex - (isDir ? 0 : 1); /*
663
                                                                                                                                                 * only
664
                                                                                                                                                 * subtract
665
                                                                                                                                                 * 1 if
666
                                                                                                                                                 * it is
667
                                                                                                                                                 * a
668
                                                                                                                                                 * file.
669
                                                                                                                                                 */
670
                        // The number of directories we have to backtrack is the length of
671
                        // the base path MINUS the number of common path elements, minus
672
                        // one because the last element in the path isn't a directory.
673
                        for (int i = 1; i <= (numDirsUp); i++) {
674
                                relative += ".." + pathSeparator;
675
                        }
676
                }
677
                // if we are comparing directories then we
678
                if (targetPath.length() > common.length()) {
679
                        // it's OK, it isn't a directory
680
                        relative += targetPath.substring(common.length());
681
                }
682

    
683
                return new File(relative);
684
        }
685

    
686
        private void fixFiles(PersistentState state, File rootFolder) {
687
                PersistentContext context = state.getContext();
688
                URI cwd = new File(System.getProperty("user.dir")).toURI();
689

    
690
                @SuppressWarnings("unchecked")
691
                Iterator<PersistentState> statesIterator = context.iterator();
692
                while (statesIterator.hasNext()) {
693
                        PersistentState aState = statesIterator.next();
694
                        DynStruct definition = aState.getDefinition();
695
                        DynField[] fields = definition.getDynFields();
696
                        for (DynField field : fields) {
697
                                if (field.getType() == DataTypes.FILE
698
                                                || field.getType() == DataTypes.FOLDER) {
699
                                        try {
700
                                                File value = aState.getFile(field.getName());
701
                                                value = fixFile(value, rootFolder);
702
                                                aState.set(field.getName(), value);
703
                                        } catch (PersistenceException e) {
704
                                                LOG.warn(
705
                                                                "Can't fix field '" + field.getName()
706
                                                                                + "' for class '"
707
                                                                                + definition.getName() + "'.", e);
708
                                        }
709
                                } else if (field.getType() == DataTypes.URL) {
710
                                        try {
711
                                                URL value = aState.getURL(field.getName());
712
                                                if ("FILE".equalsIgnoreCase(value.getProtocol())) {
713
                                                        if (!value.getFile().startsWith("/")){
714
                                                                value = new URL("file","",cwd.getRawPath()+value.getFile());
715
                                                                File file = new File(value.toURI().getPath().substring(cwd.getPath().length()));
716
                                                                file = fixFile(file, rootFolder);
717
                                                                aState.set(field.getName(), file.toURI().toURL());
718
                                                        }
719
                                                }
720
                                        } catch (PersistenceException e) {
721
                                                // do nothing
722
                                        } catch (MalformedURLException e) {
723
                                                // do nothing
724
                                        } catch (URISyntaxException e) {
725
                                                // do nothing
726
                                        }
727

    
728
                                }
729
                        }
730
                }
731
        }
732

    
733
        private File fixFile(File file, File rootFolder) {
734
                if (file.isAbsolute()) {
735
                        return file;
736
                }
737
                try {
738
                        return new File(rootFolder, file.getPath()).getCanonicalFile();
739
                } catch (IOException e) {
740
                        return new File(rootFolder, file.getPath());
741
                }
742
        }
743

    
744
        public void loadState(InputStream in) {
745
                loadState(in, null);
746
        }
747

    
748
        public void loadState(InputStream in, File rootFolder) {
749
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
750
                try {
751
                        PersistentState state = manager.loadState(in);
752
                        try {
753
                                if (rootFolder != null) {
754
                                        fixFiles(state, rootFolder);
755
                                }
756
                        } catch (Exception ex) {
757
                                state.getContext().addError(ex);
758
                        }
759
                        this.loadFromState(state);
760
                } catch (PersistenceException e) {
761
                        // TODO Auto-generated catch block
762
                        e.printStackTrace();
763
                }
764

    
765
        }
766

    
767
        public void loadState(File in) {
768
                FileInputStream fin;
769
                try {
770
                        fin = new FileInputStream(in);
771
                        loadState(fin, new File(in.getParent()));
772
                } catch (FileNotFoundException e) {
773
                        // TODO Auto-generated catch block
774
                        e.printStackTrace();
775
                }
776
        }
777

    
778
        @SuppressWarnings("unchecked")
779
        public void loadFromState(PersistentState state)
780
                        throws PersistenceException {
781
                this.clean();
782

    
783
                this.setComments(state.getString("comments"));
784
                this.setCreationDate(state.getString("creationDate"));
785
                this.setModificationDate(state.getString("modificationDate"));
786
                this.setName(state.getString("name"));
787
                this.setOwner(state.getString("owner"));
788
                this.setSelectionColor((Color) state.get("selectionColor"));
789
                this.setProjection((IProjection) state.get("projection"));
790

    
791
                List<ProjectExtent> extents = (List<ProjectExtent>) state
792
                                .get("extents");
793
                for (int i = 0; i < extents.size(); i++) {
794
                        this.addExtent(extents.get(i));
795
                }
796

    
797
                List<AbstractDocument> documents = (List<AbstractDocument>) state
798
                                .get("documents");
799
                for (int i = 0; i < documents.size(); i++) {
800
                        this.add(documents.get(i));
801
                }
802

    
803
        }
804

    
805
        public void saveToState(PersistentState state) throws PersistenceException {
806
                state.set("version", VERSION);
807
                state.set("comments", getComments());
808
                state.set("creationDate", this.getCreationDate());
809

    
810
                state.set("modificationDate", this.getModificationDate());
811
                state.set("name", this.getName());
812
                state.set("owner", this.getOwner());
813
                state.set("selectionColor", this.getSelectionColor());
814

    
815
                state.set("projection", this.getProjection());
816

    
817
                state.set("extents", this.extents);
818
                state.set("documents", this.getDocuments());
819

    
820
                PersistenceManager persistenceManager = ToolsLocator
821
                                .getPersistenceManager();
822
                List<PersistentState> windowsStates = new ArrayList<PersistentState>();
823
                IWindow[] windows = PluginServices.getMDIManager().getOrderedWindows();
824
                for (int i = windows.length - 1; i >= 0; i--) {
825
                        IWindow window = windows[i];
826
                        if (window instanceof Persistent) {
827
                                try {
828
                                        windowsStates.add( persistenceManager.getState(window));
829
                                } catch (PersistenceValidateExceptions e) {
830
                                        throw new PersistenceException(e);
831
                                }
832
                        }
833
                }
834
                LOG.warn("DefaultProject::saveToState, falta por persistir 'windowsInformation'");
835
                // state.set("windowsInformation", windowsStates);
836

    
837
        }
838

    
839
        public static void registerPersistent() {
840
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
841
                DynStruct definition = manager.addDefinition(DefaultProject.class,
842
                                "Project", "Project Persistence definition", null, null);
843
                definition.addDynFieldString("version").setMandatory(true);
844
                definition.addDynFieldString("comments").setMandatory(true);
845
                definition.addDynFieldString("creationDate").setMandatory(true);
846
                definition.addDynFieldString("modificationDate").setMandatory(true);
847
                definition.addDynFieldString("name").setMandatory(true);
848
                definition.addDynFieldString("owner").setMandatory(true);
849

    
850
                definition.addDynFieldObject("selectionColor")
851
                                .setClassOfValue(Color.class).setMandatory(true);
852
                definition.addDynFieldObject("projection")
853
                                .setClassOfValue(IProjection.class).setMandatory(true);
854

    
855
                definition.addDynFieldList("extents")
856
                                .setClassOfItems(ProjectExtent.class).setMandatory(true);
857

    
858
                definition.addDynFieldList("documents").setClassOfItems(Document.class)
859
                                .setMandatory(true);
860

    
861
                AbstractDocument.registerPersistent();
862
        }
863

    
864
        /**
865
         * @deprecated use getPreferences().setDefaultSelectionColor()
866
         */
867
        public static void setDefaultSelectionColor(Color color) {
868
                getPreferences().setDefaultSelectionColor(color);
869
        }
870

    
871
        /**
872
         * @deprecated use getPreferences().getDefaultSelectionColor()
873
         */
874

    
875
        public static Color getDefaultSelectionColor() {
876
                return getPreferences().getDefaultSelectionColor();
877
        }
878

    
879
        /**
880
         * @deprecated use getPreferences().getDefaultMapUnits()
881
         */
882
        public static int getDefaultMapUnits() {
883
                return getPreferences().getDefaultMapUnits();
884
        }
885

    
886
        /**
887
         * @deprecated use getPreferences().getDefaultDistanceUnits()
888
         */
889
        public static int getDefaultDistanceUnits() {
890
                return getPreferences().getDefaultDistanceUnits();
891
        }
892

    
893
        /**
894
         * @deprecated use getPreferences().getDefaultDistanceArea()
895
         */
896
        public static int getDefaultDistanceArea() {
897
                return getPreferences().getDefaultDistanceArea();
898
        }
899

    
900
        /**
901
         * @deprecated use getPreferences().setDefaultMapUnits()
902
         */
903
        public static void setDefaultMapUnits(int mapUnits) {
904
                getPreferences().setDefaultMapUnits(mapUnits);
905
        }
906

    
907
        /**
908
         * @deprecated use getPreferences().setDefaultDistanceUnits()
909
         */
910
        public static void setDefaultDistanceUnits(int distanceUnits) {
911
                getPreferences().setDefaultDistanceUnits(distanceUnits);
912
        }
913

    
914
        /**
915
         * @deprecated use getPreferences().setDefaultDistanceArea()
916
         */
917
        public static void setDefaultDistanceArea(int distanceArea) {
918
                getPreferences().setDefaultDistanceArea(distanceArea);
919
        }
920

    
921
        /**
922
         * @deprecated use getPreferences().setDefaultProjection()
923
         */
924
        public static void setDefaultProjection(IProjection defaultProjection) {
925
                getPreferences().setDefaultProjection(defaultProjection);
926
        }
927

    
928
        /**
929
         * @deprecated use getPreferences().getDefaultProjection()
930
         */
931
        public static IProjection getDefaultProjection() {
932
                return getPreferences().getDefaultProjection();
933
        }
934

    
935
        /**
936
         * @deprecated see {@link #setSelectionColor(String)}, to be remove in gvSIG
937
         *             2.1.0
938
         */
939
        public void setColor(String color) {
940
                this.setSelectionColor(StringUtilities.string2Color(color));
941
        }
942

    
943
        /**
944
         * Return the selection color
945
         * 
946
         * @return selection color as string
947
         * @deprecated use {@link #getSelectionColor()}
948
         */
949
        public String getColor() {
950
                return StringUtilities.color2String(selectionColor);
951
        }
952

    
953
        /**
954
         * Devuelve a partir del nombre la tabla asociada.
955
         * 
956
         * @param name
957
         *            Nombre.
958
         * @deprecated utilizar getProjectDocumentByName(...);
959
         * @return ProjectTable de la tabla asociada.
960
         */
961
        public TableDocument getTable(String name) {
962
                return (TableDocument) this.getDocument(name, TableManager.TYPENAME);
963
        }
964

    
965
        /**
966
         * Return the list of maps of the project
967
         * 
968
         * @return tables as ArrayList of IProjectDocument
969
         * 
970
         * @deprecated see {@link #getDocumentsByType(String)}
971
         */
972
        public List<Document> getMaps() {
973
                return getDocuments(LayoutManager.TYPENAME);
974
        }
975

    
976
        /**
977
         * Add a {@link LayoutDocument} to the project
978
         * 
979
         * @deprecated see {@link #add(Document)}
980
         */
981
        public void addMap(LayoutDocument m) {
982
                add(m);
983
        }
984

    
985
        /**
986
         * Remove a map of the project
987
         * 
988
         * @param index
989
         *            of the map as integer
990
         * 
991
         * @deprecated see {@link #remove(Document)}
992
         */
993
        public void delMap(int i) {
994
                List<Document> list = getDocuments(LayoutManager.TYPENAME);
995
                remove(list.get(i));
996
        }
997

    
998
        /**
999
         * Return the list of tables of the project
1000
         * 
1001
         * @return tables as ArrayList of ProjectDocument
1002
         * 
1003
         * @deprecated see {@link #getDocumentsByType(String)}
1004
         */
1005
        public List<Document> getTables() {
1006
                return getDocuments(TableManager.TYPENAME);
1007
        }
1008

    
1009
        /**
1010
         * Add a {@link TableDocument } to the project
1011
         * 
1012
         * @deprecated see {@link #add(AbstractDocument)}
1013
         */
1014
        public void addTable(TableDocument t) {
1015
                add(t);
1016
        }
1017

    
1018
        /**
1019
         * Remove a {@link TableDocument } of the project
1020
         * 
1021
         * @param index
1022
         *            of the table as integer
1023
         * 
1024
         * @deprecated see {@link #remove(AbstractDocument)}
1025
         */
1026
        public void delTable(int i) {
1027
                List<Document> list = getDocuments(TableManager.TYPENAME);
1028
                remove(list.get(i));
1029
        }
1030

    
1031
        /**
1032
         * Return the list of views of the project
1033
         * 
1034
         * @return views as ArrayList of ProjectDocument
1035
         * 
1036
         * @deprecated see {@link #getDocumentsByType(String)}
1037
         */
1038
        public List<Document> getViews() {
1039
                return getDocuments(ViewManager.TYPENAME);
1040
        }
1041

    
1042
        /**
1043
         * Add a view to the project
1044
         * 
1045
         * @deprecated see {@link #add(AbstractDocument)}
1046
         */
1047
        public void addView(DefaultViewDocument v) {
1048
                add(v);
1049
        }
1050

    
1051
        /**
1052
         * Remove a view of the project
1053
         * 
1054
         * @param index
1055
         *            of the view as integer
1056
         * 
1057
         * @deprecated see {@link #remove(AbstractDocument)}
1058
         */
1059
        public void delView(int i) {
1060
                List<Document> list = getDocuments(ViewManager.TYPENAME);
1061
                remove(list.get(i));
1062
        }
1063

    
1064
        /**
1065
         * @deprecated see {@link #getDocument(String, String)}
1066
         */
1067
        public Document getProjectDocumentByName(String name, String type) {
1068
                return this.getDocument(name, type);
1069
        }
1070

    
1071
        /**
1072
         * @deprecated see {@link #getDocuments(String)}
1073
         */
1074
        public List<Document> getDocumentsByType(String type) {
1075
                return this.getDocuments(type);
1076
        }
1077

    
1078
        /**
1079
         * @deprecated aun por decidir que API darle al copy/paste
1080
         */
1081
        public String exportToXML(AbstractDocument[] selectedItems)
1082
                        throws SaveException {
1083
                // FIXME jjdc:hay que decirdir que API darle al copy/paste
1084
                throw new UnsupportedOperationException("This method is not supported");
1085
        }
1086

    
1087
        /**
1088
         * @deprecated aun por decidir que API darle al copy/paste
1089
         */
1090
        public void importFromXML(String sourceString, String docType) {
1091
                // FIXME jjdc:hay que decirdir que API darle al copy/paste
1092
                throw new UnsupportedOperationException("This method is not supported");
1093
        }
1094

    
1095
        /**
1096
         * @deprecated aun por decidir que API darle al copy/paste
1097
         */
1098
        public boolean isValidXMLForImport(String sourceString, String docType) {
1099
                // FIXME jjdc:hay que decirdir que API darle al copy/paste
1100
                throw new UnsupportedOperationException("This method is not supported");
1101
        }
1102

    
1103
        public boolean canImportDocuments(String data, String doctype) {
1104
                // TODO Auto-generated method stub
1105
                return false;
1106
        }
1107

    
1108
        public String exportDocumentsAsText(List<Document> documents) {
1109
                // TODO Auto-generated method stub
1110
                return null;
1111
        }
1112

    
1113
        public void importDocuments(String data, String doctype) {
1114
                // TODO Auto-generated method stub
1115

    
1116
        }
1117

    
1118
        public Document getActiveDocument() {
1119
                try {
1120
                        SingletonWindow window = (SingletonWindow) PluginServices
1121
                                        .getMDIManager().getActiveWindow();
1122
                        Document doc = (Document) window.getWindowModel();
1123
                        return doc;
1124
                } catch (Exception ex) {
1125
                        return null;
1126
                }
1127
        }
1128
}