Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.app.document.table.app / org.gvsig.app.document.table.app.mainplugin / src / main / java / org / gvsig / app / project / documents / table / TableManager.java @ 47784

History | View | Annotate | Download (22.8 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
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24

    
25
package org.gvsig.app.project.documents.table;
26

    
27
import java.awt.Dimension;
28
import java.util.Collections;
29
import java.util.Iterator;
30
import java.util.List;
31
import javax.swing.ImageIcon;
32
import javax.swing.JOptionPane;
33
import org.gvsig.andami.IconThemeHelper;
34
import org.gvsig.andami.PluginServices;
35
import org.gvsig.andami.messages.NotificationManager;
36
import org.gvsig.andami.ui.mdiManager.IWindow;
37
import org.gvsig.app.ApplicationLocator;
38
import org.gvsig.app.addlayer.AddLayerDialog;
39
import org.gvsig.app.gui.WizardPanel;
40
import org.gvsig.app.project.Project;
41
import org.gvsig.app.project.ProjectManager;
42
import org.gvsig.app.project.documents.AbstractDocument;
43
import org.gvsig.app.project.documents.AbstractDocumentManager;
44
import org.gvsig.app.project.documents.Document;
45
import org.gvsig.app.project.documents.actions.CopyDocumentAction;
46
import org.gvsig.app.project.documents.actions.CutDocumentAction;
47
import org.gvsig.app.project.documents.actions.PasteDocumentAction;
48
import org.gvsig.app.project.documents.gui.IDocumentWindow;
49
import org.gvsig.app.project.documents.gui.WindowLayout;
50
import org.gvsig.app.project.documents.table.TableDocument.TableLink;
51
import org.gvsig.app.project.documents.table.gui.FeatureTableDocumentPanel;
52
import org.gvsig.app.project.documents.table.gui.TableProperties;
53
import org.gvsig.fmap.dal.AbstractStoresRepository;
54
import org.gvsig.fmap.dal.DALLocator;
55
import org.gvsig.fmap.dal.DataManager;
56
import org.gvsig.fmap.dal.DataStore;
57
import org.gvsig.fmap.dal.DataStoreParameters;
58
import org.gvsig.fmap.dal.exception.DataException;
59
import org.gvsig.fmap.dal.exception.InitializeException;
60
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
61
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
62
import org.gvsig.fmap.dal.feature.FeatureQuery;
63
import org.gvsig.fmap.dal.feature.FeatureQueryOrder;
64
import org.gvsig.fmap.dal.feature.FeatureStore;
65
import org.gvsig.fmap.dal.feature.FeatureType;
66
import org.gvsig.fmap.dal.serverexplorer.filesystem.swing.FilesystemExplorerWizardPanel;
67
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
68
import org.gvsig.fmap.mapcontext.layers.vectorial.VectorLayer;
69
import org.gvsig.tools.ToolsLocator;
70
import org.gvsig.tools.dispose.DisposeUtils;
71
import org.gvsig.tools.dynobject.DynObjectManager;
72
import org.gvsig.tools.dynobject.DynStruct;
73
import org.gvsig.tools.evaluator.Evaluator;
74
import org.gvsig.tools.i18n.I18nManager;
75
import org.gvsig.tools.identitymanagement.IdentityUtils;
76
import org.gvsig.tools.persistence.PersistenceManager;
77
import org.gvsig.tools.swing.api.ToolsSwingLocator;
78
import org.gvsig.tools.swing.api.ToolsSwingUtils;
79
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
80
import org.gvsig.tools.util.Invocable;
81
import org.gvsig.tools.util.MappedIterator;
82
import org.gvsig.tools.util.UnmodifiableBasicSet;
83
import org.slf4j.LoggerFactory;
84

    
85
/**
86
 * Factory of Table.
87
 * 
88
 * @author gvSIG Tem
89
 * 
90
 */
91
@SuppressWarnings("UseSpecificCatch")
92
public class TableManager extends AbstractDocumentManager {
93
    
94
    final static private org.slf4j.Logger LOGGER = LoggerFactory.getLogger(TableDocument.class);
95

    
96
    private static class TableDocumentStoresRepository extends AbstractStoresRepository {
97

    
98
        public TableDocumentStoresRepository(String name, String label) {
99
            super(name, label);
100
        }
101

    
102
        @Override
103
        protected DataStoreParameters getMyParameters(String name) {
104
            Project project = ProjectManager.getInstance().getCurrentProject();
105
            TableDocument tableDoc = (TableDocument) project.getDocument(name, TYPENAME);
106
            if( tableDoc==null || tableDoc.getFeatureStore()==null) {
107
                return null;
108
            }
109
            return tableDoc.getFeatureStore().getParameters();
110
        }
111

    
112
        @Override
113
        protected FeatureType getMyFeatureType(String name) {
114
            Project project = ProjectManager.getInstance().getCurrentProject();
115
            TableDocument tableDoc = (TableDocument) project.getDocument(name, TYPENAME);
116
            if( tableDoc==null || tableDoc.getFeatureStore()==null) {
117
                return null;
118
            }
119
            return tableDoc.getFeatureStore().getDefaultFeatureTypeQuietly();
120
        }
121
        
122
        @Override
123
        protected boolean isEmptyMyRepository() {
124
            Project project = ProjectManager.getInstance().getCurrentProject();
125
            return project.getDocuments(TableManager.TYPENAME).isEmpty();
126
        }
127

    
128
        @Override
129
        protected int getMySize() {
130
            Project project = ProjectManager.getInstance().getCurrentProject();
131
            int sz = project.getDocuments(TableManager.TYPENAME).size();
132
            return sz;
133
        }
134

    
135
        @Override
136
        protected UnmodifiableBasicSet<String> getMyKeySet() {
137
            Project project = ProjectManager.getInstance().getCurrentProject();
138
            final List<Document> docs = project.getDocuments(TableManager.TYPENAME);
139
            if( docs==null ) {
140
                return UnmodifiableBasicSet.EMPTY_UNMODIFIABLEBASICSET;
141
            }
142
            UnmodifiableBasicSet<String> x = new UnmodifiableBasicSet<String>() {
143
                @Override
144
                public boolean isEmpty() {
145
                    return docs.isEmpty();
146
                }
147

    
148
                @Override
149
                public int size() {
150
                    return docs.size();
151
                }
152

    
153
                @Override
154
                public Iterator<String> iterator() {
155
                    return new MappedIterator<>(docs.iterator(), (Document t) -> {
156
                        if( t==null ) {
157
                            return null;
158
                        }
159
                        return ((TableDocument)t).getName();
160
                    });
161
                }
162
            };
163
            return x;
164
        }
165

    
166
        
167
        @Override
168
        public Iterator<DataStoreParameters> iterator() {
169
            Project project = ProjectManager.getInstance().getCurrentProject();
170
            List<Document> docs = project.getDocuments(TableManager.TYPENAME);
171
            if( docs==null ) {
172
                return Collections.EMPTY_LIST.iterator();
173
            }
174
            return new MappedIterator<>(docs.iterator(), (Document t) -> {
175
                if( t==null || ((TableDocument)t).getFeatureStore()==null ) {
176
                    return null;
177
                }
178
                return ((TableDocument)t).getFeatureStore().getParameters();
179
            });
180
        }
181

    
182
        @Override
183
        public void add(String name, DataStoreParameters parameters) {
184
            Project project = ProjectManager.getInstance().getCurrentProject();
185
            TableDocument doc = (TableDocument) ProjectManager.getInstance().createDocument(TYPENAME);
186
            doc.setName(name);
187
            //FIXME:
188
            DataManager dataManager = DALLocator.getDataManager();
189
            FeatureStore store;
190
            try {
191
                store = (FeatureStore) dataManager.openStore(
192
                        parameters.getProviderName(),
193
                        parameters
194
                );
195
                doc.setStore(store);
196
                project.addDocument(doc);
197
            } catch (InitializeException | ProviderNotRegisteredException | ValidateDataParametersException ex) {
198
                LOGGER.warn("Can't add table to project", ex);
199
            }
200

    
201
        }
202

    
203
        @Override
204
        public void add(String name, FeatureStore store) {
205
            Project project = ProjectManager.getInstance().getCurrentProject();
206
            TableDocument doc = (TableDocument) ProjectManager.getInstance().createDocument(TYPENAME);
207
            doc.setName(name);
208
            doc.setStore(store);
209
            project.addDocument(doc);
210
        }
211

    
212
        @Override
213
        public DataStore getStore(String name) {
214
            Project project = ProjectManager.getInstance().getCurrentProject();
215
            TableDocument tableDoc = (TableDocument) project.getDocument(name, TYPENAME);
216
            if( tableDoc==null || tableDoc.getFeatureStore()==null) {
217
                return null;
218
            }
219
            FeatureStore store = tableDoc.getFeatureStore();
220
            DisposeUtils.bind(store);
221
            return store;
222
        }
223
        
224
    }
225
    
226
    public static final String PERSISTENCE_TABLE_DOCUMENT_DEFINITION_NAME =
227
        "TableDocument";
228
    public static final String PERSISTENCE_TABLELINK_DEFINITION_NAME =
229
        "TableLink";
230

    
231
    public static String TYPENAME = "project.document.table";
232

    
233
    private DynStruct persistenceDefinition = null;
234

    
235
    @Override
236
    public ImageIcon getIcon() {
237
            return IconThemeHelper.getImageIcon("document-table-icon");
238
    }
239

    
240
    @Override
241
    public ImageIcon getIconSelected() {
242
        return IconThemeHelper.getImageIcon("document-table-icon-sel");
243
    }
244

    
245
    @Override
246
    public String getTitle() {
247
        return PluginServices.getText(this, "Tabla");
248
    }
249

    
250
    @Override
251
    public String getTypeName() {
252
        return TYPENAME;
253
    }
254

    
255
    @Override
256
    public int getPriority() {
257
        return 1;
258
    }
259

    
260
    @Override
261
    public Iterator<? extends Document> createDocumentsByUser() {
262
        return this.createDocumentsByUser(null);
263
    }
264
    
265
    @Override
266
    public Iterator<? extends Document> createDocumentsByUser(Invocable whenDocumentsLoaded) {
267
        AddLayerDialog fopen = null;
268
        try {
269
            fopen =
270
                new AddLayerDialog(PluginServices.getText(this, "Nueva_tabla"));
271
            List<WizardPanel> wizards =
272
                ApplicationLocator.getManager().getWizardPanels();
273

    
274
            Dimension preferredSize = fopen.getPreferredSize();
275
            WizardPanel panel;
276
            Iterator<WizardPanel> iter = wizards.iterator();
277
            while (iter.hasNext()) {
278
                panel = iter.next();
279
                panel.initWizard();
280
                Dimension dim = panel.getPreferredSize();
281
                if( dim.height>preferredSize.height ) {
282
                    preferredSize.height = dim.height;
283
                }
284
                if( dim.width>preferredSize.width ) {
285
                    preferredSize.width = dim.width;
286
                }
287
                
288
                fopen.addWizardTab(panel.getTabName(), panel);
289
            }
290
          
291
//            preferredSize.height += ToolsSwingUtils.rows2px(4);
292
//            preferredSize.width += ToolsSwingUtils.cols2px(2);
293
//
294
//            fopen.setPreferredSize(preferredSize);
295
//
296
//            ToolsSwingUtils.ensureRowsCols(fopen, -1, -1, 30, 100);
297
            Dimension screensize = ToolsSwingUtils.getCurrentScreenSize();            
298
            ToolsSwingUtils.ensureHeightWitdh(
299
                    fopen, 
300
                    3*(screensize.height/4), 
301
                    2*(screensize.width/4), 
302
                    7*(screensize.height/8), 
303
                    3*(screensize.width/4)
304
            );
305
            
306
            PluginServices.getMDIManager().addWindow(fopen);
307
            if (fopen.isAccepted()) {
308
                WizardPanel selectedPanel = (WizardPanel) fopen.getSelectedTab();
309
                if( whenDocumentsLoaded==null ) {
310
                    List<TableDocument> docs = (List) selectedPanel.executeWizard();
311
                    this.checkDocuments(docs);
312
                    return docs.iterator();
313
                }
314
                Thread task = new Thread(() -> {
315
                    List<TableDocument> docs = (List) selectedPanel.executeWizard();
316
                    checkDocuments(docs);
317
                    whenDocumentsLoaded.call(docs.iterator());
318
                }, "DocumentTableLoader");
319
                task.start();
320
                return Collections.EMPTY_LIST.iterator();
321
            }
322
        } catch (Exception e) {
323
            NotificationManager.addError(e);
324
        } finally {
325
            if (fopen != null) {
326
                fopen.dispose();
327
                fopen = null;
328
            }
329
        }
330
        return null;
331
    }
332
    
333
    private void checkDocuments(List<TableDocument> docs) {
334
        if( docs==null ) {
335
            return;
336
        }
337
        for (TableDocument doc : docs) {
338
            try {
339
                FeatureStore store = ((TableDocument)doc).getDataStore();
340
                FeatureType type = store.getDefaultFeatureType();
341
                if( ! type.supportReferences() ) {
342
                    I18nManager i18n = ToolsLocator.getI18nManager();
343
                    ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
344
                    dialogs.messageDialog(
345
                            "\""+ doc.getName() + "\"\n"+
346
                            i18n.getTranslation("_The_table_has_no_primary_key_or_OID") +"\n" +
347
                                   i18n.getTranslation("_Many_features_selection_deletion_modification_will_not_be_available_as_they_require_it_for_proper_operation"),
348
                            null, 
349
                            i18n.getTranslation("_Warning"),
350
                            JOptionPane.WARNING_MESSAGE, 
351
                            "TableDoNotSupportReferences"
352
                   );
353
                }
354
            } catch (Exception ex) {
355

    
356
            }
357
        }        
358
    }
359

    
360
    @Override
361
    public AbstractDocument createDocumentByUser() {
362
        return (AbstractDocument) createDocumentsByUser().next();
363
    }
364
    
365
    /**
366
     * Registers in the points of extension the Factory with alias.
367
     * 
368
     */
369
    public static void register() {
370
        I18nManager i18n = ToolsLocator.getI18nManager();
371
        
372
        TableManager factory = new TableManager();
373
        // A?adimos nuestra extension para el tratamiento de la apertura de
374
        // ficheros
375
        // dentro de gvSIG
376
        ToolsLocator.getExtensionPointManager().add("FileTableOpenDialog", "")
377
            .append("FileOpenTable", "", FilesystemExplorerWizardPanel.class);
378

    
379
                IconThemeHelper.registerIcon("document", "document-table-icon", TableManager.class);
380
        IconThemeHelper.registerIcon("document", "document-table-icon-sel", TableManager.class);
381
        IconThemeHelper.registerIcon("document", "document-table-icon-small", TableManager.class);
382

    
383
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
384
        manager.registerFactory(factory);
385

    
386
        if (factory.persistenceDefinition == null) {
387
            DynObjectManager dynman = ToolsLocator.getDynObjectManager();
388
            factory.persistenceDefinition =
389
                dynman.createDynClass(PersistenceManager.PERSISTENCE_NAMESPACE,
390
                    PERSISTENCE_TABLE_DOCUMENT_DEFINITION_NAME,
391
                    "Table document Persistence definition");
392
            factory.persistenceDefinition.extend(manager
393
                .getDefinition(AbstractDocument.PERSISTENCE_DEFINITION_NAME));
394

    
395
            factory.persistenceDefinition.addDynFieldObject("store")
396
                .setClassOfValue(FeatureStore.class).setMandatory(true);
397
            factory.persistenceDefinition.addDynFieldString("featureTypeId")
398
                .setMandatory(false);
399
            factory.persistenceDefinition.addDynFieldArray("attributeNames")
400
                .setClassOfItems(String.class).setMandatory(false);
401
            factory.persistenceDefinition.addDynFieldObject("associatedLayer")
402
                .setClassOfValue(FLyrVect.class).setMandatory(false);
403
            factory.persistenceDefinition.addDynFieldObject("query")
404
                .setClassOfValue(FeatureQuery.class).setMandatory(false);
405
            factory.persistenceDefinition.addDynFieldObject("baseFilter")
406
                .setClassOfValue(Evaluator.class).setMandatory(false);
407
            factory.persistenceDefinition.addDynFieldObject("baseOrder")
408
                .setClassOfValue(FeatureQueryOrder.class).setMandatory(false);
409
            factory.persistenceDefinition.addDynFieldList("linkTable")
410
                .setClassOfItems(TableLink.class).setMandatory(false);          
411
            factory.persistenceDefinition.addDynFieldMap("patterns")
412
                .setClassOfItems(String.class).setMandatory(false);          
413
        }
414
        
415
        //Register also the TableLink
416
        if (manager.getDefinition(PERSISTENCE_TABLELINK_DEFINITION_NAME) == null){
417
            DynStruct tableLinkDefinition =
418
                manager.addDefinition(TableLink.class,
419
                    PERSISTENCE_TABLELINK_DEFINITION_NAME,
420
                    "TableLink Persistence definition", null, null);                 
421
            
422
            tableLinkDefinition.addDynFieldObject("source")
423
                .setClassOfValue(TableDocument.class).setMandatory(true);
424
            tableLinkDefinition.addDynFieldObject("target")
425
                .setClassOfValue(TableDocument.class).setMandatory(true);
426
            tableLinkDefinition.addDynFieldString("fieldSource").setMandatory(true);
427
            tableLinkDefinition.addDynFieldString("fieldTarget").setMandatory(true);
428
            tableLinkDefinition.addDynFieldBoolean("enabled").setMandatory(true);
429
        }  
430
        
431
        ProjectManager.getInstance().registerDocumentFactory(factory);
432
        
433
        ProjectManager.getInstance().registerDocumentAction(TYPENAME,new CopyDocumentAction());
434
        ProjectManager.getInstance().registerDocumentAction(TYPENAME,new CutDocumentAction());
435
        ProjectManager.getInstance().registerDocumentAction(TYPENAME,new PasteDocumentAction());
436

    
437
        DataManager dataManager = DALLocator.getDataManager();
438
        dataManager.getStoresRepository().addRepository(
439
                new TableDocumentStoresRepository(
440
                    "PROJECT_TABLES",
441
                    i18n.getTranslation("_Project_tables")
442
            )
443
        );
444
    }
445

    
446
    /**
447
     * Create a new table document.
448
     * 
449
     * @return TableDocument.
450
     */
451
    @Override
452
    public AbstractDocument createDocument() {
453
        AbstractDocument doc = new TableDocument(this);
454
        if( this.notifyObservers(NOTIFY_AFTER_CREATEDOCUMENT,doc).isCanceled() ) {
455
            return null;
456
        }
457
            return doc;        
458
    }
459

    
460
    @Override
461
    public Class<? extends IDocumentWindow> getMainWindowClass() {
462
        return FeatureTableDocumentPanel.class;
463
    }
464

    
465
    @Override
466
    public IWindow getMainWindow(Document doc, WindowLayout layout) {
467
        
468
        FeatureStore store = ((TableDocument)doc).getFeatureStore();
469
        if( !IdentityUtils.isAuthorized("document-table-showmainwindow", 
470
                doc, store.getFullName()) ) {
471
            return null;
472
        }          
473
        IDocumentWindow win = (IDocumentWindow) super.getMainWindow(doc, layout);
474
        if (win == null) {
475
            try {
476
                win = (IDocumentWindow) this.createDocumentWindow(doc);
477
            } catch(Throwable t){
478
            }
479
            if(win == null){
480
                try {
481
                    ((TableDocument)doc).getFeatureStore().refresh();
482
                } catch (DataException ex) {
483
                    throw new RuntimeException(ex);
484
                }
485
                win = (IDocumentWindow) this.createDocumentWindow(doc);
486
            }
487
            if (layout != null && win != null) {
488
                win.setWindowLayout(layout);
489
            }
490
        }
491
        if( this.notifyObservers(NOTIFY_AFTER_GETMAINWINDOW,win).isCanceled() ) {
492
            return null;
493
        }
494
        return win;
495
    }
496

    
497
    @Override
498
    public IWindow getPropertiesWindow(Document doc) {
499
        IWindow win = super.getPropertiesWindow(doc);
500
        if( win == null ) {
501
            win = new TableProperties((TableDocument) doc);
502
        }
503
        if( this.notifyObservers(NOTIFY_AFTER_GETPROPERTIESWINDOW,win).isCanceled() ) {
504
            return null;
505
        }
506
        return win;        
507
    }
508

    
509
    @Override
510
    protected Class<? extends Document> getDocumentClass() {
511
        return TableDocument.class;
512
    }
513

    
514
    @Override
515
    public DynStruct getDefinition(String className) {
516

    
517
        if (this.persistenceDefinition.getName().equalsIgnoreCase(className)) {
518
            return this.persistenceDefinition;
519
        }
520
        if (this.persistenceDefinition.getFullName()
521
            .equalsIgnoreCase(className)) {
522
            return this.persistenceDefinition;
523
        }
524
        if (this.getDocumentClass().getName().equals(className)) {
525
            return this.persistenceDefinition;
526
        }
527
        return null;
528
    }
529

    
530
    @Override
531
    public boolean manages(Object object) {
532
        return object instanceof TableDocument;
533
    }
534

    
535
    public TableDocument getTableDocument(VectorLayer layer) {
536
        if (layer == null) {
537
            return null;
538
        }
539
        List<Document> tableDocs =
540
            getProject().getDocuments(TableManager.TYPENAME);
541
        for (Document document : tableDocs) {
542
            if (layer == ((TableDocument) document).getAssociatedLayer()) {
543
                return (TableDocument) document;
544
            }
545
        }
546
        return null;
547
    }
548

    
549
    public TableDocument getTableDocument(FeatureStore store) {
550
        if (store == null) {
551
            return null;
552
        }
553
        List<Document> tableDocs =
554
            getProject().getDocuments(TableManager.TYPENAME);
555
        for (Document document : tableDocs) {
556
            if (store == ((TableDocument) document).getFeatureStore()) {
557
                return (TableDocument) document;
558
            }
559
        }
560
        return null;
561
    }
562

    
563
    public void removeTableDocument(VectorLayer layer) {
564
        TableDocument doc = getTableDocument(layer);
565
        // Only remove it if it exists
566
        if (doc != null) {
567
            PluginServices.getMDIManager().closeSingletonWindow(doc);
568
            getProject().remove(doc);
569
        }
570
    }
571

    
572
    private Project getProject() {
573
        return ProjectManager.getInstance().getCurrentProject();
574
    }
575
}