Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.app / org.gvsig.app.mainplugin / src / main / java / org / gvsig / app / project / DefaultProject.java @ 44088

History | View | Annotate | Download (45.3 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.app.project;
24

    
25
import java.awt.Color;
26
import java.awt.Image;
27
import java.awt.geom.AffineTransform;
28
import java.awt.image.AffineTransformOp;
29
import java.awt.image.BufferedImage;
30
import java.beans.PropertyChangeEvent;
31
import java.beans.PropertyChangeListener;
32
import java.beans.PropertyChangeSupport;
33
import java.io.File;
34
import java.io.FileInputStream;
35
import java.io.FileNotFoundException;
36
import java.io.FileOutputStream;
37
import java.io.IOException;
38
import java.io.InputStream;
39
import java.io.OutputStream;
40
import java.io.Serializable;
41
import java.text.DateFormat;
42
import java.text.MessageFormat;
43
import java.text.SimpleDateFormat;
44
import java.util.ArrayList;
45
import java.util.Collections;
46
import java.util.Date;
47
import java.util.HashMap;
48
import java.util.HashSet;
49
import java.util.Iterator;
50
import java.util.List;
51
import java.util.Map;
52
import java.util.Set;
53
import java.util.logging.Level;
54
import java.util.zip.ZipEntry;
55
import java.util.zip.ZipException;
56
import java.util.zip.ZipFile;
57
import java.util.zip.ZipOutputStream;
58
import javax.imageio.ImageIO;
59
import org.apache.commons.io.FileUtils;
60
import org.apache.commons.io.FilenameUtils;
61
import org.apache.commons.io.IOUtils;
62

    
63
import org.cresques.cts.IProjection;
64

    
65
import org.gvsig.andami.PluginServices;
66
import org.gvsig.andami.ui.mdiManager.IWindow;
67
import org.gvsig.andami.ui.mdiManager.MDIManager;
68
import org.gvsig.andami.ui.mdiManager.SingletonWindow;
69
import org.gvsig.andami.ui.mdiManager.WindowInfo;
70
import org.gvsig.app.ApplicationLocator;
71
import org.gvsig.app.ApplicationManager;
72
import org.gvsig.app.extension.ProjectExtension;
73
import org.gvsig.app.extension.Version;
74
import org.gvsig.app.project.ProjectManager.NewProjectEvent;
75
import org.gvsig.app.project.documents.AbstractDocument;
76
import org.gvsig.app.project.documents.Document;
77
import org.gvsig.app.project.documents.exceptions.SaveException;
78
import org.gvsig.app.project.documents.gui.IDocumentWindow;
79
import org.gvsig.app.project.documents.gui.ProjectWindow;
80
import org.gvsig.app.project.documents.view.DefaultViewDocument;
81
import org.gvsig.app.project.documents.view.ViewManager;
82
import org.gvsig.fmap.mapcontext.MapContext;
83
import org.gvsig.fmap.mapcontext.layers.ExtendedPropertiesHelper;
84
import org.gvsig.fmap.mapcontext.layers.FLayer;
85
import org.gvsig.fmap.mapcontext.layers.FLayers;
86
import org.gvsig.tools.ToolsLocator;
87
import org.gvsig.tools.dynobject.DynStruct;
88
import org.gvsig.tools.observer.ObservableHelper;
89
import org.gvsig.tools.observer.Observer;
90
import org.gvsig.tools.persistence.PersistenceManager;
91
import org.gvsig.tools.persistence.Persistent;
92
import org.gvsig.tools.persistence.PersistentContext;
93
import org.gvsig.tools.persistence.PersistentState;
94
import org.gvsig.tools.persistence.exception.PersistenceException;
95
import org.gvsig.utils.StringUtilities;
96
import org.gvsig.utils.save.SaveEvent;
97

    
98
import org.slf4j.Logger;
99
import org.slf4j.LoggerFactory;
100

    
101
/**
102
 * Clase que representa un proyecto de gvSIG
103
 *
104
 */
105
public class DefaultProject implements Serializable, PropertyChangeListener,
106
        Project {
107

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

    
114
    private ExtendedPropertiesHelper propertiesHelper = new ExtendedPropertiesHelper();
115

    
116
    private ObservableHelper observableHelper = new ObservableHelper();
117

    
118
    /**
119
     *
120
     */
121
    private static final long serialVersionUID = -4449622027521773178L;
122

    
123
    private static final Logger logger = LoggerFactory.getLogger(Project.class);
124

    
125
    private static ProjectPreferences preferences = new ProjectPreferences();
126

    
127
    /**
128
     * Index used by the generator of unique names of documents.
129
     */
130
    private Map<String, Integer> nextDocumentIndexByType = new HashMap<String, Integer>();
131

    
132
    private PropertyChangeSupport change;
133

    
134
    private boolean modified = false;
135

    
136
    private String name = null;
137

    
138
    private String creationDate = null;
139

    
140
    private String modificationDate = null;
141

    
142
    private String owner = null;
143

    
144
    private String comments = null;
145

    
146
    private Color selectionColor = null;
147

    
148
    private List<Document> documents = null;
149

    
150
    private List<ProjectExtent> extents = null;
151

    
152
    private IProjection projection;
153

    
154
    private File fname = null;
155

    
156
    private Set<String> unloadedObjects;
157
    private PersistenceException loadErrors = null;
158

    
159
    /**
160
     * Creates a new Project object.
161
     */
162
    DefaultProject() {
163
        this.change = new PropertyChangeSupport(this);
164
        this.clean();
165
        ProjectManager.getInstance().notifyProjectEvent(new NewProjectEvent() {
166
            @Override
167
            public Project getProject() {
168
                return DefaultProject.this;
169
            }
170
        });
171
    }
172

    
173
    protected void clean() {
174
        this.owner = "";
175
        this.comments = "";
176
        this.name = PluginServices.getText(this, "untitled");
177
        this.creationDate = DateFormat.getDateInstance().format(new Date());
178
        this.modificationDate = this.creationDate;
179

    
180
        this.documents = new ArrayList<Document>();
181
        this.extents = new ArrayList<ProjectExtent>();
182

    
183
        this.setSelectionColor(getPreferences().getDefaultSelectionColor());
184

    
185
        this.projection = null; // se inicializa en el getProjection()
186
    }
187

    
188
    public static ProjectPreferences getPreferences() {
189
        return preferences;
190
    }
191

    
192
    @Override
193
    public void propertyChange(PropertyChangeEvent evt) {
194
        change.firePropertyChange(evt);
195
    }
196

    
197
    @Override
198
    public synchronized void addPropertyChangeListener(
199
            PropertyChangeListener arg0) {
200
        change.addPropertyChangeListener(arg0);
201
    }
202

    
203
    @Override
204
    public void removePropertyChangeListener(PropertyChangeListener listener) {
205
        change.removePropertyChangeListener(listener);
206
    }
207
    
208
    /**
209
     * Return the creation date of the project
210
     *
211
     * @return
212
     */
213
    @Override
214
    public String getCreationDate() {
215
        return creationDate;
216
    }
217

    
218
    protected void setCreationDate(String creationDate) {
219
        this.creationDate = creationDate;
220
        change.firePropertyChange("setCreationDate", null, null);
221
    }
222

    
223
    @Override
224
    public Document createDocument(String type) {
225
        logger.info("createDocument('{}')", type);
226
        return ProjectManager.getInstance().createDocument(type);
227
    }
228

    
229
    /**
230
     * Return the name of the project
231
     *
232
     * @return
233
     */
234
    @Override
235
    public String getName() {
236
        return name;
237
    }
238

    
239
    /**
240
     * Set the name of he project.
241
     *
242
     * @param string
243
     */
244
    @Override
245
    public void setName(String name) {
246
        this.name = name;
247
        change.firePropertyChange("setName", null, null);
248
    }
249

    
250
    /**
251
     * Return the comments associateds with the project
252
     *
253
     * @return comments
254
     */
255
    @Override
256
    public String getComments() {
257
        return comments;
258
    }
259

    
260
    /**
261
     * Set the comments associateds with the project
262
     *
263
     * @param comments as string
264
     */
265
    @Override
266
    public void setComments(String string) {
267
        comments = string;
268
        change.firePropertyChange("setComments", null, null);
269
    }
270

    
271
    /**
272
     * Retuen the modification date of the project.
273
     *
274
     * @return modification date as string
275
     */
276
    @Override
277
    public String getModificationDate() {
278
        return modificationDate;
279
    }
280

    
281
    protected void setModificationDate(String string) {
282
        modificationDate = string;
283
        change.firePropertyChange("setModificationDate", null, null);
284
    }
285

    
286
    /**
287
     * Return the author of the project,
288
     *
289
     * @return author as string
290
     */
291
    @Override
292
    public String getOwner() {
293
        return owner;
294
    }
295

    
296
    /**
297
     * Sets the author of the project
298
     *
299
     * @param author name as string
300
     */
301
    @Override
302
    public void setOwner(String owner) {
303
        this.owner = owner;
304
        change.firePropertyChange("setOwner", null, null);
305
    }
306

    
307
    /**
308
     * Obtiene el color de selecci�n que se usar� en el proyecto
309
     *
310
     * @return
311
     */
312
    @Override
313
    public Color getSelectionColor() {
314
        if (selectionColor == null) {
315
            selectionColor = getPreferences().getDefaultSelectionColor();
316
        }
317
        return selectionColor;
318
    }
319

    
320
    /**
321
     * Sets the selecction color
322
     *
323
     * @param selection color as string
324
     */
325
    @Override
326
    public void setSelectionColor(String selectionColor) {
327
        this.setSelectionColor(StringUtilities.string2Color(selectionColor));
328
    }
329

    
330
    /**
331
     * Sets the selecction color
332
     *
333
     * @param selection color as Color
334
     */
335
    @Override
336
    public void setSelectionColor(Color selectionColor) {
337
        this.selectionColor = selectionColor;
338
        MapContext.setSelectionColor(selectionColor);
339
        change.firePropertyChange("selectionColor", null, selectionColor);
340
    }
341

    
342
    @Override
343
    public IProjection getProjection() {
344
        if (projection == null) {
345
            projection = getPreferences().getDefaultProjection();
346
        }
347
        return projection;
348
    }
349

    
350
    @Override
351
    public void setProjection(IProjection projection) {
352
        this.projection = projection;
353
    }
354

    
355
    /**
356
     * Sets the modified state of project.
357
     *
358
     * Can't set to not modified.
359
     *
360
     * @param modified as boolean
361
     */
362
    @Override
363
    public void setModified(boolean modified) {
364
        this.modified = modified;
365
        if (modified == false) {
366
            List<Document> documents = this.getDocuments();
367
            for (int i = 0; i < documents.size(); i++) {
368
                documents.get(i).setModified(false);
369
            }
370
        }
371
    }
372

    
373
    @Override
374
    public boolean hasChanged() {
375
                // we return true if the project is not empty (until we have a better
376
        // method...)
377
        if ((this.getDocuments().size() != 0) || modified) {
378
            return true;
379
        }
380
        return false;
381
    }
382

    
383
    /**
384
     * Return a list of documents in the project.
385
     *
386
     * @return documents as List of IProjectDocument
387
     */
388
    @Override
389
    public List<Document> getDocuments() {
390
        return Collections.unmodifiableList(documents);
391
    }
392

    
393
    /**
394
     * Return a list with all documents of especified type.
395
     *
396
     * @param type of document
397
     *
398
     * @return List of IProjectDocument
399
     */
400
    @Override
401
    public List<Document> getDocuments(String type) {
402
        List<Document> docs = new ArrayList<Document>();
403
        if (type != null) {
404
            for (Document document : this.documents) {
405
                if (type.equalsIgnoreCase(document.getTypeName())) {
406
                    docs.add(document);
407
                }
408
            }
409
        }
410
        return Collections.unmodifiableList(docs);
411
    }
412

    
413
    /**
414
     * Adds a document to the project
415
     *
416
     * @param document as Document
417
     */
418
    @Override
419
    public void add(Document document) {
420
        this.addDocument(document);
421
    }
422

    
423
    @Override
424
    public void addDocument(Document document) {
425
        logger.info("add('{}')", document.toString());
426

    
427
        if (notifyObservers(ProjectNotification.BEFORE_ADD_DOCUMENT, document).isProcessCanceled()) {
428
            return;
429
        }
430
        document.addPropertyChangeListener(this);
431
        document.setProject(this);
432
        document.setName(this.getUniqueNameForDocument(document.getTypeName(),
433
                document.getName()));
434
        documents.add(document);
435
        document.afterAdd();
436
        this.setModified(true);
437
        notifyObservers(ProjectNotification.AFTER_ADD_DOCUMENT, document);
438
        change.firePropertyChange("addDocument", null, document);
439
    }
440

    
441
    @Override
442
    public void remove(Document doc) {
443
        this.removeDocument(doc);
444
    }
445

    
446
    @Override
447
    public void removeDocument(Document doc) {
448
        logger.info("remove('{}')", doc.toString());
449
        if (notifyObservers(ProjectNotification.BEFORE_REMOVE_DOCUMENT, doc).isProcessCanceled()) {
450
            return;
451
        }
452
        documents.remove(doc);
453
        this.setModified(true);
454
        change.firePropertyChange("delDocument", doc, null);
455
        doc.afterRemove();
456
        notifyObservers(ProjectNotification.AFTER_REMOVE_DOCUMENT, doc);
457
    }
458

    
459
    @Override
460
    public Iterator<Document> iterator() {
461
        return documents.iterator();
462
    }
463

    
464
    @Override
465
    public boolean isEmpty() {
466
        return documents.isEmpty();
467
    }
468

    
469
    /**
470
     * Return the view that contains the especified layer.
471
     *
472
     * @param layer
473
     *
474
     * @return name of the view that contains the layer
475
     *
476
     * @throws RuntimeException Si la capa que se pasa como par�metro no se
477
     * encuentra en ninguna vista
478
     */
479
    @Override
480
    public String getViewName(FLayer layer) {
481
        List<Document> views = getDocuments(ViewManager.TYPENAME);
482
        for (int v = 0; v < views.size(); v++) {
483
            DefaultViewDocument pView = (DefaultViewDocument) views.get(v);
484
            FLayers layers = pView.getMapContext().getLayers();
485
            if (isView(layers, layer)) {
486
                return pView.getName();
487
            }
488
        }
489

    
490
        throw new RuntimeException(MessageFormat.format(
491
                "The layer '{1}' is not in a view", layer.getName()));
492
    }
493

    
494
    private boolean isView(FLayers layers, FLayer layer) {
495
        for (int i = 0; i < layers.getLayersCount(); i++) {
496
            if (layers.getLayer(i) instanceof FLayers) {
497
                if (isView((FLayers) layers.getLayer(i), layer)) {
498
                    return true;
499
                }
500
            }
501
            if (layers.getLayer(i) == layer) {
502
                return true;
503
            }
504
        }
505
        return false;
506
    }
507

    
508
    @Override
509
    public void addExtent(ProjectExtent arg1) {
510
        extents.add(arg1);
511
        change.firePropertyChange("addExtent", null, null);
512
    }
513

    
514
    @Override
515
    public ProjectExtent removeExtent(int arg0) {
516
        change.firePropertyChange("delExtent", null, null);
517
        return extents.remove(arg0);
518
    }
519

    
520
    @Override
521
    public ProjectExtent[] getExtents() {
522
        return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
523
    }
524

    
525
    /**
526
     * Obtiene un documento a partir de su nombre y el nombre de registro en el
527
     * pointExtension, este �ltimo se puede obtener del
528
     * Project****Factory.registerName.
529
     *
530
     * @param name Nombre del documento
531
     * @param type nombre de registro en el extensionPoint
532
     *
533
     * @return Documento
534
     */
535
    @Override
536
    public Document getDocument(String name, String type) {
537
        if (type == null) {
538
            for (int i = 0; i < documents.size(); i++) {
539
                Document document = documents.get(i);
540
                if ( name.equalsIgnoreCase(document.getName())) {
541
                    return document;
542
                }
543
            }
544
        } else {
545
            for (int i = 0; i < documents.size(); i++) {
546
                Document document = documents.get(i);
547
                if (type.equalsIgnoreCase(document.getTypeName())
548
                        && name.equalsIgnoreCase(document.getName())) {
549
                    return document;
550
                }
551
            }
552
        }
553
        return null;
554
    }
555

    
556
    @Override
557
    public Document getDocument(String name) {
558
        return this.getDocument(name, null);
559
    }
560

    
561
    public String getUniqueNameForDocument(String type, String name) {
562
        Document document = getDocument(name, type);
563
        if (document == null) {
564
            return name;
565
        }
566

    
567
        String newName = null;
568
        int num = this.getNextDocumentIndex(type);
569
        while (document != null) {
570
            newName = name + " - " + num++;
571
            document = getDocument(newName, type);
572
        }
573
        this.setNextDocumentIndex(type, num);
574
        return newName;
575
    }
576

    
577
    private int getNextDocumentIndex(String type) {
578
        if (nextDocumentIndexByType.get(type) == null) {
579
            nextDocumentIndexByType.put(type, new Integer(1));
580
            return 1;
581
        }
582
        return nextDocumentIndexByType.get(type).intValue();
583
    }
584

    
585
    private void setNextDocumentIndex(String type, int newIndex) {
586
        if (nextDocumentIndexByType.get(type) == null) {
587
            nextDocumentIndexByType.put(type, new Integer(newIndex));
588
        } else {
589
            nextDocumentIndexByType.put(type, new Integer(newIndex));
590
        }
591
    }
592

    
593
    @Override
594
    public void saveState(File out) throws PersistenceException {
595
        FileOutputStream fout;
596
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_FILE, out).isProcessCanceled()) {
597
            return;
598
        }
599
        try {
600
            fout = new FileOutputStream(out);
601
            saveState(fout, new File(out.getParent()));
602
        } catch (FileNotFoundException e) {
603
            createProjectCopy(true);
604
            throw new PersistenceException(e);
605
        }
606
        if( !isValidZIP(out) ) {
607
            throw new PersistenceException(new ZipException());
608
        }
609
        this.fname = out;
610
        //sacar copia al bak
611
        createProjectCopy(false);
612
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_FILE, out);
613
    }
614

    
615
    boolean isValidZIP(final File file) {
616
        ZipFile zipfile = null;
617
        try {
618
            zipfile = new ZipFile(file);
619
            return true;
620
        } catch (IOException e) {
621
            //sacar copia. 
622
            return false;
623
        } finally {
624
            try {
625
                if (zipfile != null) {
626
                    zipfile.close();
627
                    zipfile = null;
628
                }
629
            } catch (IOException e) {
630
            }
631
        }
632
    }
633
   
634
    @Override
635
    public File getFile() {
636
        return this.fname;
637
    }
638

    
639
    @Deprecated
640
    @Override
641
    public void saveState(OutputStream out) throws PersistenceException {
642
        saveState(out, null);
643
    }
644
    
645
    @Override
646
    public void saveState(File file, BufferedImage preview) {
647
        FileOutputStream fout=null;
648
        ZipOutputStream zout=null;
649
        try {
650
            fout = new FileOutputStream(file);
651
            zout = new ZipOutputStream(fout);
652
            this.saveState(zout, file.getParentFile());
653

    
654
            zout.putNextEntry(new ZipEntry("preview.jpg"));
655
            try {
656
                ImageIO.write(preview, "jpg", zout);
657
            } catch (IOException ex) {
658
                LOG.warn("Can't save preview image'.", ex);
659
            }
660
            IOUtils.closeQuietly(zout);
661
            IOUtils.closeQuietly(fout);
662

    
663
            if( !isValidZIP(file) ) {
664
                throw new ZipException("Invalid project file '"+file.getAbsolutePath()+"'");
665
            }
666
            this.fname = file;
667
            if (file.exists()) {
668
                createProjectCopy(false);
669
            }
670
        } catch (Exception ex) {
671
            createProjectCopy(true);
672
            throw new RuntimeException("Can't write project in '" + file.getAbsolutePath() + ".", ex);
673
        } finally {
674
            IOUtils.closeQuietly(zout);
675
            IOUtils.closeQuietly(fout);
676

    
677
        }
678
    }
679
    
680
    @Override
681
    public void saveState(OutputStream out, File rootFolder)
682
            throws PersistenceException {
683
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_STREAM, rootFolder).isProcessCanceled()) {
684
            return;
685
        }
686
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
687
        PersistentState state = null;
688
        state = manager.getState(this, true);
689
        try {
690
            if (rootFolder != null) {
691
                state.relativizeFiles(rootFolder);
692
            }
693
        } catch (Exception ex) {
694
            state.getContext().addError(ex);
695
        }
696
        manager.saveState(state, out, true);
697
        if (state.getContext().getErrors() != null) {
698
            createProjectCopy(true);
699
            throw state.getContext().getErrors();
700
        }
701
        this.fname = null;
702
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_STREAM, rootFolder);
703
    }
704
    
705
    private File getNameFileForProject(File actualProjectFile, boolean error) {
706
        // if there is a error, creates a file with a unique timecode
707
        // not error: return path with .gvsproj.bak extension that could exists
708
               
709
        if (actualProjectFile==null) {
710
            LOG.info("Doesn't have previous project to create a bak");
711
            return null;
712
        }
713
        String noExt = FilenameUtils.removeExtension(actualProjectFile.getAbsolutePath());
714
        String timeCode = new SimpleDateFormat("_MMddHHmmss").format(new Date());
715
        String ext = ".gvsproj.bak";
716

    
717
        int code = 0;
718
        if (noExt.length() > 230) {
719
            noExt = noExt.substring(0, 229);
720
        }
721
        
722
        File bakProjectFile;
723
        if (error) {
724
            bakProjectFile = new File(noExt + timeCode + ext);
725
            while (bakProjectFile.exists()) {
726
                code = code + 1;
727
                bakProjectFile = new File(noExt + timeCode + "_" + code + ext);
728
            }
729
        } else {
730
            bakProjectFile = new File(noExt + ext);
731
        }
732
        return bakProjectFile;
733
    }
734
    public File createProjectCopy(boolean error) {
735
        File actualProjectFile = ApplicationLocator.getProjectManager().getCurrentProject().getFile();
736
        File bakProjectFile = getNameFileForProject(actualProjectFile, error);
737
        if (bakProjectFile==null){
738
            return null;
739
        }
740
        if (!error){
741
            try {
742
                if (bakProjectFile.exists()){
743
                    FileUtils.deleteQuietly(bakProjectFile);
744
                }
745
            } catch (Exception ex) {
746
                LOG.error("Not possible to delete file", ex);
747
            }
748
            try {
749
                FileUtils.copyFile(actualProjectFile, bakProjectFile);
750
            } catch (IOException ex) {
751
                LOG.error("Can't create bak copy from project", ex);
752
            }
753
        } else {
754
            File bakProjectFile2 = getNameFileForProject(actualProjectFile, false);
755
            try {
756
                FileUtils.moveFile(bakProjectFile2, bakProjectFile);
757
            } catch (IOException ex) {
758
                LOG.error("Can't rename file", ex);
759
            }
760
        }
761
        
762
        return bakProjectFile;
763
    }
764

    
765
    @Deprecated
766
    @Override
767
    public void loadState(InputStream in) {
768
        loadState(in, null);
769
    }
770

    
771
    public void loadState(InputStream in, File rootFolder) {
772
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_STREAM, rootFolder).isProcessCanceled()) {
773
            return;
774
        }
775
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
776
        try {
777
            PersistentContext context = manager.getNewContext();
778
            context.setCollectErrors(true);
779
            PersistentState state = manager.loadState(in, context);
780
            try {
781
                if (rootFolder != null) {
782
                    state.derelativizeFiles(rootFolder);
783
                }
784
            } catch (Exception ex) {
785
                state.getContext().addError(ex);
786
            }
787
            this.loadFromState(state);
788
            this.unloadedObjects = getUnloadedObjects(state.getContext());
789
            this.loadErrors = state.getContext().getErrors();
790

    
791
        } catch (PersistenceException e) {
792
            LOG.info("Can't load project to stream", e);
793
        }
794
        this.fname = null;
795
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_STREAM, rootFolder);
796

    
797
    }
798

    
799

    
800

    
801
    /**
802
     * @param context
803
     * @return
804
     */
805
    private Set<String> getUnloadedObjects(PersistentContext context) {
806
        Set unloadedObjects = new HashSet();
807

    
808
        Iterator statesIterator = context.iterator();
809
        String className = null;
810

    
811
        while (statesIterator.hasNext()) {
812
            PersistentState aState = (PersistentState) statesIterator.next();
813
            try {
814
                className = aState.getTheClassName();
815
                DynStruct definition = aState.getDefinition();
816
                if (definition == null) {
817
                    unloadedObjects.add(className);
818
                }
819
            } catch (Throwable e) {
820
                // do nothing
821
            }
822
        }
823

    
824
        if(unloadedObjects.isEmpty()){
825
            return null;
826
        }
827

    
828
        return unloadedObjects;
829
    }
830

    
831
    @Override
832
    public Set<String> getUnloadedObjects() {
833
        return this.unloadedObjects;
834
    }
835

    
836
    @Override
837
    public List<Exception> getLoadErrors() {
838
        return this.loadErrors;
839
    }
840
    
841
    @Override
842
    public void loadState(File in) {
843
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_FILE, in).isProcessCanceled()) {
844
            return;
845
        }
846
        FileInputStream fin;
847
        try {
848
            fin = new FileInputStream(in);
849
            loadState(fin, new File(in.getParent()));
850
        } catch (FileNotFoundException e) {
851
            LOG.info("Can't load project to stream", e);
852
        }
853
        if ("bak".equals(FilenameUtils.getExtension(in.getAbsolutePath()))) {
854
            this.fname =  null;
855
        } else {
856
            this.fname = in;
857
        }
858
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_FILE, in);
859
    }
860

    
861
    //@SuppressWarnings("unchecked")
862
    @Override
863
    public void loadFromState(PersistentState state)
864
            throws PersistenceException {
865
        this.clean();
866
        PersistentContext context = state.getContext();
867
        
868
        notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_STATE, state);
869

    
870
        this.setComments(state.getString("comments"));
871
        this.setCreationDate(state.getString("creationDate"));
872
        this.setModificationDate(state.getString("modificationDate"));
873
        this.setName(state.getString("name"));
874
        this.setOwner(state.getString("owner"));
875
        this.setSelectionColor((Color) state.get("selectionColor"));
876
        this.setProjection((IProjection) state.get("projection"));
877

    
878
        this.propertiesHelper = (ExtendedPropertiesHelper) state.get("propertiesHelper");
879

    
880
        List<ProjectExtent> extents = (List<ProjectExtent>) state
881
                .get("extents");
882
        for (int i = 0; i < extents.size(); i++) {
883
            this.addExtent(extents.get(i));
884
        }
885

    
886
        List<AbstractDocument> documents = (List<AbstractDocument>) state
887
                .get("documents");
888
        for (int i = 0; i < documents.size(); i++) {
889
            AbstractDocument doc = documents.get(i);
890
            if( doc != null ) {
891
                this.add(doc);
892
            }
893
        }
894

    
895
        try {
896
            List<DocumentWindowInfo> persistentWindows = (List<DocumentWindowInfo>) state.get("documentWindowsInformation");
897

    
898
            for (int i = 0; i < persistentWindows.size(); i++) {
899
                try {
900
                    DocumentWindowInfo persistentWindow = persistentWindows.get(i);
901
                    String docName = persistentWindow.getDocumentName();
902
                    String docType = persistentWindow.getDocumentType();
903
                    Document doc = this.getDocument(docName, docType);
904
                    IWindow win = doc.getFactory().getMainWindow(doc);
905
                    if(win!=null){
906
                        win.getWindowInfo().setWindowInfo(persistentWindow.getWindowInfo());
907
                        PluginServices.getMDIManager().addWindow(win);
908
                    }
909
                } catch(Exception ex) {
910
                    if( !context.getCollectErrors() ) {
911
                        throw ex;
912
                    }
913
                    context.addError(ex);
914
                }
915
            }
916

    
917
            if (state.hasValue("projectWindowInfo")) {
918
                WindowInfo projectWindowInfo = (WindowInfo) state.get("projectWindowInfo");
919
                ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(org.gvsig.app.extension.ProjectExtension.class);
920
                pe.setProject(this);
921
                pe.showProjectWindow(projectWindowInfo);
922
            }
923
        } catch(Exception ex) {
924
            if( !context.getCollectErrors() ) {
925
                throw ex;
926
            }
927
            context.addError(ex);
928
        }
929
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_STATE, state);
930
    }
931

    
932
    @Override
933
    public void saveToState(PersistentState state) throws PersistenceException {
934
        state.set("version", VERSION);
935
        state.set("comments", getComments());
936
        state.set("creationDate", this.getCreationDate());
937

    
938
        state.set("modificationDate", this.getModificationDate());
939
        state.set("name", this.getName());
940
        state.set("owner", this.getOwner());
941
        state.set("selectionColor", this.getSelectionColor());
942

    
943
        state.set("projection", this.getProjection());
944

    
945
        state.set("extents", this.extents);
946
        List<Document> docs = this.getDocuments();
947
        List<Document> noTempDocs = new ArrayList<Document>();
948
        for (Iterator iterator = docs.iterator(); iterator.hasNext();) {
949
            Document document = (Document) iterator.next();
950
            if(!document.isTemporary()){
951
                noTempDocs.add(document);
952
            }
953
        }
954
        state.set("documents", noTempDocs);
955

    
956
        state.set("propertiesHelper",propertiesHelper);
957

    
958
        List<DocumentWindowInfo> persistentWindows = new ArrayList<DocumentWindowInfo>();
959
        MDIManager mdiMan = PluginServices.getMDIManager();
960
        IWindow[] windows = mdiMan.getOrderedWindows();
961
        for (int i = windows.length - 1; i >= 0; i--) {
962
            IWindow window = windows[i];
963
            if (window instanceof IDocumentWindow) {
964
                WindowInfo wi = mdiMan.getWindowInfo(window);
965
                DocumentWindowInfo dwi = new DocumentWindowInfo(
966
                        wi,
967
                        ((IDocumentWindow) window).getDocument().getTypeName(),
968
                        ((IDocumentWindow) window).getDocument().getName());
969
                persistentWindows.add(dwi);
970
            } else if (window instanceof ProjectWindow) {
971
                state.set("projectWindowInfo", mdiMan.getWindowInfo(window));
972
            }
973
        }
974
        state.set("documentWindowsInformation", persistentWindows);
975

    
976
    }
977

    
978
    @Override
979
    public Object getProperty(Object key) {
980
        return this.propertiesHelper.getProperty(key);
981
    }
982

    
983
    @Override
984
    public void setProperty(Object key, Object obj) {
985
        this.propertiesHelper.setProperty(key, obj);
986
    }
987

    
988
    @Override
989
    public Map getExtendedProperties() {
990
        return this.propertiesHelper.getExtendedProperties();
991
    }
992

    
993
    public static class DocumentWindowInfo implements Persistent {
994

    
995
        public static final String PERSISTENCE_DEFINITION_NAME = "DocumentWindowInfo";
996

    
997
        private WindowInfo windowInfo;
998
        private String documentType;
999
        private String documentName;
1000

    
1001
        public DocumentWindowInfo() {
1002
        }
1003

    
1004
        DocumentWindowInfo(WindowInfo wi, String docType, String docName) {
1005
            windowInfo = wi;
1006
            documentType = docType;
1007
            documentName = docName;
1008
        }
1009

    
1010
        public WindowInfo getWindowInfo() {
1011
            return windowInfo;
1012
        }
1013

    
1014
        public String getDocumentType() {
1015
            return documentType;
1016
        }
1017

    
1018
        public String getDocumentName() {
1019
            return documentName;
1020
        }
1021

    
1022
        public void saveToState(PersistentState state)
1023
                throws PersistenceException {
1024
            state.set("windowInfo", this.windowInfo);
1025
            state.set("documentType", this.documentType);
1026
            state.set("documentName", this.documentName);
1027
        }
1028

    
1029
        public void loadFromState(PersistentState state)
1030
                throws PersistenceException {
1031
            this.windowInfo = (WindowInfo) state.get("windowInfo");
1032
            this.documentType = state.getString("documentType");
1033
            this.documentName = state.getString("documentName");
1034
        }
1035

    
1036
        public static void registerPersistent() {
1037
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
1038
            DynStruct definition = manager.getDefinition(PERSISTENCE_DEFINITION_NAME);
1039
            if (definition == null) {
1040
                definition = manager.addDefinition(
1041
                        DocumentWindowInfo.class,
1042
                        PERSISTENCE_DEFINITION_NAME,
1043
                        "DocumentWindowInfo persistence definition",
1044
                        null,
1045
                        null
1046
                );
1047
                definition.addDynFieldObject("windowInfo").setMandatory(true).setClassOfValue(WindowInfo.class);
1048
                definition.addDynFieldString("documentType").setMandatory(true);
1049
                definition.addDynFieldString("documentName").setMandatory(true);
1050
            }
1051

    
1052
        }
1053
    }
1054

    
1055
    public static void registerPersistent() {
1056
        AbstractDocument.registerPersistent();
1057
        DocumentWindowInfo.registerPersistent();
1058
        ProjectExtent.registerPersistent();
1059

    
1060
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
1061
        DynStruct definition = manager.addDefinition(DefaultProject.class,
1062
                "Project", "Project Persistence definition", null, null);
1063
        definition.addDynFieldString("version").setMandatory(true);
1064
        definition.addDynFieldString("comments").setMandatory(true);
1065
        definition.addDynFieldString("creationDate").setMandatory(true);
1066
        definition.addDynFieldString("modificationDate").setMandatory(true);
1067
        definition.addDynFieldString("name").setMandatory(true);
1068
        definition.addDynFieldString("owner").setMandatory(true);
1069

    
1070
        definition.addDynFieldObject("selectionColor")
1071
                .setClassOfValue(Color.class).setMandatory(true);
1072
        definition.addDynFieldObject("projection")
1073
                .setClassOfValue(IProjection.class).setMandatory(true);
1074

    
1075
        definition.addDynFieldList("extents")
1076
                .setClassOfItems(ProjectExtent.class).setMandatory(true);
1077

    
1078
        definition.addDynFieldList("documents").setClassOfItems(Document.class)
1079
                .setMandatory(true);
1080

    
1081
        definition.addDynFieldObject("projectWindowInfo").setClassOfValue(WindowInfo.class).setMandatory(false);
1082

    
1083
        definition.addDynFieldList("documentWindowsInformation").setClassOfItems(WindowInfo.class).setMandatory(false);
1084

    
1085

    
1086
        definition.addDynFieldObject("propertiesHelper").setClassOfValue(ExtendedPropertiesHelper.class)
1087
                        .setMandatory(false);
1088

    
1089
    }
1090

    
1091
    /**
1092
     * @deprecated use getPreferences().setDefaultSelectionColor()
1093
     */
1094
    public static void setDefaultSelectionColor(Color color) {
1095
        getPreferences().setDefaultSelectionColor(color);
1096
    }
1097

    
1098
    /**
1099
     * @deprecated use getPreferences().getDefaultSelectionColor()
1100
     */
1101
    public static Color getDefaultSelectionColor() {
1102
        return getPreferences().getDefaultSelectionColor();
1103
    }
1104

    
1105
    /**
1106
     * @deprecated use getPreferences().getDefaultMapUnits()
1107
     */
1108
    public static int getDefaultMapUnits() {
1109
        return getPreferences().getDefaultMapUnits();
1110
    }
1111

    
1112
    /**
1113
     * @deprecated use getPreferences().getDefaultDistanceUnits()
1114
     */
1115
    public static int getDefaultDistanceUnits() {
1116
        return getPreferences().getDefaultDistanceUnits();
1117
    }
1118

    
1119
    /**
1120
     * @deprecated use getPreferences().getDefaultDistanceArea()
1121
     */
1122
    public static int getDefaultDistanceArea() {
1123
        return getPreferences().getDefaultDistanceArea();
1124
    }
1125

    
1126
    /**
1127
     * @deprecated use getPreferences().setDefaultMapUnits()
1128
     */
1129
    public static void setDefaultMapUnits(int mapUnits) {
1130
        getPreferences().setDefaultMapUnits(mapUnits);
1131
    }
1132

    
1133
    /**
1134
     * @deprecated use getPreferences().setDefaultDistanceUnits()
1135
     */
1136
    public static void setDefaultDistanceUnits(int distanceUnits) {
1137
        getPreferences().setDefaultDistanceUnits(distanceUnits);
1138
    }
1139

    
1140
    /**
1141
     * @deprecated use getPreferences().setDefaultDistanceArea()
1142
     */
1143
    public static void setDefaultDistanceArea(int distanceArea) {
1144
        getPreferences().setDefaultDistanceArea(distanceArea);
1145
    }
1146

    
1147
    /**
1148
     * @deprecated use getPreferences().setDefaultProjection()
1149
     */
1150
    public static void setDefaultProjection(IProjection defaultProjection) {
1151
        getPreferences().setDefaultProjection(defaultProjection);
1152
    }
1153

    
1154
    /**
1155
     * @deprecated use getPreferences().getDefaultProjection()
1156
     */
1157
    public static IProjection getDefaultProjection() {
1158
        return getPreferences().getDefaultProjection();
1159
    }
1160

    
1161
    /**
1162
     * @deprecated see {@link #setSelectionColor(String)}, to be remove in gvSIG
1163
     * 2.1.0
1164
     */
1165
    public void setColor(String color) {
1166
        this.setSelectionColor(StringUtilities.string2Color(color));
1167
    }
1168

    
1169
    /**
1170
     * Return the selection color
1171
     *
1172
     * @return selection color as string
1173
     * @deprecated use {@link #getSelectionColor()}
1174
     */
1175
    public String getColor() {
1176
        return StringUtilities.color2String(selectionColor);
1177
    }
1178

    
1179
    /**
1180
     * Return the list of views of the project
1181
     *
1182
     * @return views as ArrayList of ProjectDocument
1183
     *
1184
     * @deprecated see {@link #getDocumentsByType(String)}
1185
     */
1186
    public List<Document> getViews() {
1187
        return getDocuments(ViewManager.TYPENAME);
1188
    }
1189

    
1190
    /**
1191
     * Add a view to the project
1192
     *
1193
     * @deprecated see {@link #add(AbstractDocument)}
1194
     */
1195
    public void addView(DefaultViewDocument v) {
1196
        add(v);
1197
    }
1198

    
1199
    /**
1200
     * Remove a view of the project
1201
     *
1202
     * @param index of the view as integer
1203
     *
1204
     * @deprecated see {@link #remove(AbstractDocument)}
1205
     */
1206
    public void delView(int i) {
1207
        List<Document> list = getDocuments(ViewManager.TYPENAME);
1208
        remove(list.get(i));
1209
    }
1210

    
1211
    /**
1212
     * @deprecated see {@link #getDocument(String, String)}
1213
     */
1214
    public Document getProjectDocumentByName(String name, String type) {
1215
        return this.getDocument(name, type);
1216
    }
1217

    
1218
    /**
1219
     * @deprecated see {@link #getDocuments(String)}
1220
     */
1221
    public List<Document> getDocumentsByType(String type) {
1222
        return this.getDocuments(type);
1223
    }
1224

    
1225
    /**
1226
     * @deprecated aun por decidir que API darle al copy/paste
1227
     */
1228
    public String exportToXML(AbstractDocument[] selectedItems)
1229
            throws SaveException {
1230
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
1231
        throw new UnsupportedOperationException("This method is not supported");
1232
    }
1233

    
1234
    /**
1235
     * @deprecated aun por decidir que API darle al copy/paste
1236
     */
1237
    public void importFromXML(String sourceString, String docType) {
1238
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
1239
        throw new UnsupportedOperationException("This method is not supported");
1240
    }
1241

    
1242
    /**
1243
     * @deprecated aun por decidir que API darle al copy/paste
1244
     */
1245
    public boolean isValidXMLForImport(String sourceString, String docType) {
1246
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
1247
        throw new UnsupportedOperationException("This method is not supported");
1248
    }
1249

    
1250
    @Override
1251
    public boolean canImportDocuments(String data, String doctype) {
1252
        // TODO Auto-generated method stub
1253
        return false;
1254
    }
1255

    
1256
    @Override
1257
    public String exportDocumentsAsText(List<Document> documents) {
1258
        // TODO Auto-generated method stub
1259
        return null;
1260
    }
1261

    
1262
    @Override
1263
    public void importDocuments(String data, String doctype) {
1264
        // TODO Auto-generated method stub
1265

    
1266
    }
1267

    
1268
    @Override
1269
    public Document getActiveDocument() {
1270
        return this.getActiveDocument((Class<? extends Document>)null);
1271
    }
1272

    
1273
    @Override
1274
    public Document getActiveDocument(String documentTypeName) {
1275
        ApplicationManager application = ApplicationLocator.getManager();
1276

    
1277
        Document document = null;
1278
        IWindow[] windows = application.getUIManager().getOrderedWindows();
1279
        IWindow window = null;
1280
        for (int i = 0; i < windows.length; i++) {
1281
            window = windows[i];
1282
            if (window instanceof SingletonWindow) {
1283
                // Cogemos no la primera ventana, si no la primera
1284
                // ventana de tipo documento (SingletonWindow).
1285
                // Y por si las mosca no es un documento, atrapamos
1286
                // los errores y continuamos si no puede hacer un cast
1287
                // del Model a Document
1288
                try {
1289
                    document = (Document) ((SingletonWindow) window).getWindowModel();
1290
                    if (documentTypeName == null) {
1291
                        return document;
1292
                    }
1293
                    if( document.getTypeName().equalsIgnoreCase(documentTypeName) ) {
1294
                        return document;
1295
                    }
1296
                    if( document instanceof DocumentsContainer ) {
1297
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentTypeName);
1298
                        return subdoc;
1299
                    }
1300

    
1301
                } catch (ClassCastException e) {
1302
                    // Do nothing, skip this window
1303
                }
1304
            }
1305
        }
1306
        return null;
1307
    }
1308

    
1309
    @Override
1310
    public Document getActiveDocument(Class<? extends Document> documentClass) {
1311
        ApplicationManager application = ApplicationLocator.getManager();
1312

    
1313
        Document document = null;
1314
        IWindow[] windows = application.getUIManager().getOrderedWindows();
1315
        IWindow window = null;
1316
        for (int i = 0; i < windows.length; i++) {
1317
            window = windows[i];
1318
            if (window instanceof SingletonWindow && window instanceof IDocumentWindow) {
1319
                // Cogemos no la primera ventana, si no la primera
1320
                // ventana de tipo documento (SingletonWindow).
1321
                // Y por si las mosca no es un documento, atrapamos
1322
                // los errores y continuamos si no puede hacer un cast
1323
                // del Model a Document
1324
                try {
1325
                    document = (Document) ((SingletonWindow) window).getWindowModel();
1326
                    if (documentClass == null) {
1327
                        return document;
1328
                    }
1329
                    if (documentClass.isAssignableFrom(document.getClass())) {
1330
                        return document;
1331
                    }
1332
                    if( document instanceof DocumentsContainer ) {
1333
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentClass);
1334
                        return subdoc;
1335
                    }
1336

    
1337
                } catch (ClassCastException e) {
1338
                    // Do nothing, skip this window
1339
                }
1340
            }
1341
        }
1342
        return null;
1343
    }
1344

    
1345
    @Override
1346
    public void addObserver(Observer o) {
1347
        observableHelper.addObserver(o);
1348
    }
1349

    
1350
    @Override
1351
    public void deleteObserver(Observer o) {
1352
        observableHelper.deleteObserver(o);
1353
    }
1354

    
1355
    @Override
1356
    public void deleteObservers() {
1357
        observableHelper.deleteObservers();
1358
    }
1359

    
1360
    private ProjectNotification notifyObservers(int type) {
1361
        return notifyObservers(new DefaultProjectNotification(type));
1362
    }
1363

    
1364
    private ProjectNotification notifyObservers(int type, Document document) {
1365
        return notifyObservers(new DefaultProjectNotification(type, document));
1366
    }
1367
    
1368
    private ProjectNotification notifyObservers(int type, PersistentState state) {
1369
        return notifyObservers(new DefaultProjectNotification(type, state));
1370
    }
1371

    
1372
    private ProjectNotification notifyObservers(int type, File file) {
1373
        return notifyObservers(new DefaultProjectNotification(type, file));
1374
    }
1375

    
1376
    private ProjectNotification notifyObservers(ProjectNotification notifycation) {
1377
        try {
1378
            observableHelper.notifyObservers(this, notifycation);
1379
        } catch (Exception ex) {
1380
            LOG.info("Can't notify observers", ex);
1381
        }
1382
        return notifycation;
1383
    }
1384
    
1385
    class DefaultProjectNotification implements ProjectNotification {
1386

    
1387
        private int type;
1388
        private Document document;
1389
        private File file;
1390
        private boolean processCanceled = false;
1391
        private PersistentState state = null;
1392

    
1393
        DefaultProjectNotification(int type) {
1394
            this.type = type;
1395
        }
1396

    
1397
        DefaultProjectNotification(int type, Document document) {
1398
            this(type);
1399
            this.document = document;
1400
        }
1401

    
1402
        DefaultProjectNotification(int type, File file) {
1403
            this(type);
1404
            this.file = file;
1405
        }
1406

    
1407
        DefaultProjectNotification(int type, PersistentState state) {
1408
            this(type);
1409
            this.state = state;
1410
        }
1411

    
1412
        @Override
1413
        public int getNotificationType() {
1414
            return type;
1415
        }
1416

    
1417
        @Override
1418
        public Document getDocument() {
1419
            return document;
1420
        }
1421

    
1422
        @Override
1423
        public void cancelProcess() {
1424
            processCanceled = true;
1425
        }
1426

    
1427
        @Override
1428
        public boolean isProcessCanceled() {
1429
            return processCanceled;
1430
        }
1431

    
1432
        @Override
1433
        public File getFile() {
1434
            return file;
1435
        }
1436

    
1437
        @Override
1438
        public PersistentState getState() {
1439
            return this.state;
1440
        }
1441

    
1442
        @Override
1443
        public Project getProject() {
1444
            return DefaultProject.this;
1445
        }
1446
    }
1447

    
1448
}