Revision 43152 trunk/org.gvsig.desktop/org.gvsig.desktop.plugin/org.gvsig.app/org.gvsig.app.mainplugin/src/main/java/org/gvsig/fmap/dal/serverexplorer/filesystem/swing/FilesystemExplorerWizardPanel.java

View differences:

FilesystemExplorerWizardPanel.java
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 1
package org.gvsig.fmap.dal.serverexplorer.filesystem.swing;
25 2

  
26
import java.awt.Component;
27 3
import java.awt.GridBagConstraints;
28 4
import java.awt.GridBagLayout;
29
import java.awt.Insets;
30
import java.awt.event.ActionEvent;
31
import java.awt.event.ActionListener;
5
import java.awt.Window;
32 6
import java.io.File;
33 7
import java.util.ArrayList;
34 8
import java.util.Iterator;
35 9
import java.util.List;
36 10
import java.util.prefs.Preferences;
37 11

  
38
import javax.swing.AbstractListModel;
39
import javax.swing.JButton;
40
import javax.swing.JList;
41
import javax.swing.JPanel;
42
import javax.swing.JScrollPane;
43
import javax.swing.ListModel;
44
import javax.swing.ScrollPaneConstants;
45
import javax.swing.SwingUtilities;
12
import javax.swing.JOptionPane;
46 13
import javax.swing.event.AncestorEvent;
47 14
import javax.swing.event.AncestorListener;
48
import javax.swing.event.ListSelectionEvent;
49
import javax.swing.event.ListSelectionListener;
50 15
import javax.swing.filechooser.FileFilter;
51 16

  
52
import org.gvsig.andami.PluginServices;
53
import org.gvsig.andami.messages.Messages;
54
import org.gvsig.andami.messages.NotificationManager;
17
import org.cresques.cts.IProjection;
18
import org.slf4j.Logger;
19
import org.slf4j.LoggerFactory;
20

  
21
import org.gvsig.andami.Launcher;
55 22
import org.gvsig.app.ApplicationLocator;
56 23
import org.gvsig.app.ApplicationManager;
57 24
import org.gvsig.app.gui.WizardPanel;
58 25
import org.gvsig.app.prepareAction.PrepareContext;
26
import org.gvsig.app.prepareAction.PrepareContextView_v1;
27
import org.gvsig.app.project.documents.view.toc.actions.LayerErrorsPanel;
59 28
import org.gvsig.fmap.dal.DALLocator;
60 29
import org.gvsig.fmap.dal.DataManager;
30
import org.gvsig.fmap.dal.DataStore;
61 31
import org.gvsig.fmap.dal.DataStoreParameters;
32
import org.gvsig.fmap.dal.DataStoreProviderFactory;
33
import org.gvsig.fmap.dal.DataTypes;
62 34
import org.gvsig.fmap.dal.exception.DataException;
63 35
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemFileFilter;
64 36
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
65 37
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
66 38
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
67
import org.gvsig.gui.beans.swing.JFileChooser;
39
import org.gvsig.fmap.mapcontext.MapContext;
40
import org.gvsig.fmap.mapcontext.MapContextLocator;
41
import org.gvsig.fmap.mapcontext.MapContextManager;
42
import org.gvsig.fmap.mapcontext.layers.FLayer;
43
import org.gvsig.fmap.mapcontrol.MapControl;
68 44
import org.gvsig.tools.ToolsLocator;
69
import org.gvsig.tools.dispose.Disposable;
45
import org.gvsig.tools.dispose.DisposeUtils;
46
import org.gvsig.tools.dynobject.DynField;
70 47
import org.gvsig.tools.dynobject.DynObject;
71 48
import org.gvsig.tools.i18n.I18nManager;
49
import org.gvsig.tools.identitymanagement.UnauthorizedException;
72 50
import org.gvsig.tools.swing.api.ToolsSwingLocator;
73
import org.slf4j.Logger;
74
import org.slf4j.LoggerFactory;
51
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
75 52

  
53

  
76 54
/**
77
 * @author jmvivo
78
 * 
55
 * @author fdiaz
56
 *
79 57
 */
80
public abstract class FilesystemExplorerWizardPanel extends WizardPanel
81
    implements ActionListener, ListSelectionListener, Disposable {
58
public class FilesystemExplorerWizardPanel extends WizardPanel {
82 59

  
83 60
    /**
84
	 *
85
	 */
86
    private static final long serialVersionUID = -3371957786521876903L;
61
     *
62
     */
63
    private static final long serialVersionUID = 788115220334290212L;
87 64

  
88
    private static final Logger LOG = LoggerFactory
89
        .getLogger(FilesystemExplorerWizardPanel.class);
65
    private static final Logger logger = LoggerFactory.getLogger(FilesystemExplorerWizardPanel.class);
90 66

  
67
    private static final String DEFAULT_FILTER = "All_supported";
68

  
91 69
    public static final String OPEN_LAYER_FILE_CHOOSER_ID =
92 70
        "OPEN_LAYER_FILE_CHOOSER_ID";
93 71

  
94
    protected static final String ADD_COMMAND = "ADD";
95
    protected static final String EDIT_COMMAND = "PROPERTIES";
96
    protected static final String REMOVE_COMMAND = "REMOVE";
97
    protected static final String UP_COMMAND = "UP";
98
    protected static final String DOWN_COMMAND = "DOWN";
72
    protected FilesystemServerExplorer explorer;
73
    private ArrayList<MyFileFilter> filters;
99 74

  
100 75
    private static String lastPath = null;
101
    private static MyFileFilter lastFilter = null;
102
    private static final String DEFAULT_FILTER = "All_supported";
76
    private FilesystemExplorerWizardPanelController panel = null;
103 77

  
104
    private JList fileList;
105
    private JScrollPane fileListScroll;
106
    private JPanel buttonsPanel;
107
    private JButton addButton;
108
    private JButton propertiesButton;
109
    private JButton removeButton;
110
    private JButton upButton;
111
    private JButton downButton;
112

  
113
    protected FilesystemServerExplorer explorer;
114
    private ArrayList<MyFileFilter> filters;
115
    
78
    /**
79
     *
80
     */
116 81
    public FilesystemExplorerWizardPanel() {
117 82
        super();
118 83
        this.addAncestorListener(new AncestorListener() {
119 84
            public void ancestorAdded(AncestorEvent ae) {
120 85
                initExplorer();
121 86
                initFilters();
87
                updatePanel();
122 88
            }
123 89
            public void ancestorRemoved(AncestorEvent ae) {
124 90
                dispose();
......
127 93
            }
128 94
        });
129 95
    }
130
    
131
    public void setTabName(String name) {
132
        super.setTabName(name);
133
    }
134 96

  
135
    public DataStoreParameters[] getParameters() {
136
        return ((FilesystemStoreListModel) getFileList().getModel())
137
            .getParameters();
97
    protected void updatePanel() {
98
        this.panel.setExplorer(this.explorer);
99
        this.panel.setFilters(this.filters);
138 100
    }
139 101

  
102
    @Override
140 103
    public void initWizard() {
141
        setTabName(PluginServices.getText(this, "Fichero"));
104
        I18nManager i18nManager = ToolsLocator.getI18nManager();
105
        setTabName(i18nManager.getTranslation("Fichero"));
142 106
        if (lastPath == null) {
143 107
            Preferences prefs = Preferences.userRoot().node("gvsig.foldering");
144 108
            lastPath = prefs.get("DataFolder", null);
......
148 112
        initUI();
149 113
    }
150 114

  
115
    private void initUI() {
116

  
117
        setLayout(new GridBagLayout());
118
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
119
        gridBagConstraints.fill = GridBagConstraints.BOTH;
120
        gridBagConstraints.weightx = 1.0;
121
        gridBagConstraints.weighty = 1.0;
122

  
123
        panel = new FilesystemExplorerWizardPanelController(getMapContext(),explorer, filters);
124
        this.add(panel, gridBagConstraints);
125

  
126
    }
127

  
128
    @Override
129
    public void execute() {
130
        if (this.getMapCtrl() == null) {
131
            throw new IllegalArgumentException("MapControl need");
132
        }
133
        String layerName;
134

  
135
        for (DataStoreParameters params : this.getParameters()) {
136
            IProjection proj = this.getMapCtrl().getProjection();
137

  
138
            // Buscamos por el parametro de la proyeccion
139
            // que sean obligatorios y est?n a null
140
            // y le ponemos la proyeccion de la vista
141
            DynField[] fields = params.getDynClass().getDynFields();
142
            for (DynField field : fields) {
143
                if (field.getType() == DataTypes.CRS && field.isMandatory()) {
144
                    if (params.getDynValue(field.getName()) == null) {
145
                        params.setDynValue(field.getName(), proj);
146
                    }
147
                }
148
            }
149

  
150
            layerName = ((FilesystemStoreParameters) params).getFile().getName();
151

  
152
            this.doAddLayer(layerName, params);
153
        }
154
    }
155

  
156
    @Override
157
    public void close() {
158
        this.dispose();
159
    }
160

  
161
    /**
162
     * Dispose filters and explorer
163
     */
164
    public void dispose() {
165
        if (explorer != null) {
166
            explorer.dispose();
167
            explorer = null;
168
        }
169
        if (filters != null) {
170
            filters.clear();
171
            filters = null;
172
        }
173
        panel.dispose();
174
    }
175

  
176
    @Override
177
    public DataStoreParameters[] getParameters() {
178
        return this.panel.getParameters();
179
    }
180

  
181
    /**
182
     * @param files
183
     */
184
    public void addFiles(List<File> files) {
185
        this.panel.addFiles(files);
186
    }
187

  
188

  
151 189
    private void initExplorer() {
152 190
        if (this.explorer == null) {
153 191
            DataManager dm = DALLocator.getDataManager();
154 192
            FilesystemServerExplorerParameters param;
155 193
            try {
156
                param
157
                        = (FilesystemServerExplorerParameters) dm
194
                param = (FilesystemServerExplorerParameters) dm
158 195
                        .createServerExplorerParameters(FilesystemServerExplorer.NAME);
159 196
                param.setInitialpath(lastPath);
160
                explorer
161
                        = (FilesystemServerExplorer) dm.openServerExplorer(
197
                explorer = (FilesystemServerExplorer) dm.openServerExplorer(
162 198
                                FilesystemServerExplorer.NAME, param);
163 199
            } catch (Exception e) {
164 200
                throw new RuntimeException(e);
......
173 209
            if (this.getMapCtrl() == null) {
174 210
                mode = FilesystemServerExplorer.MODE_FEATURE;
175 211
            } else {
176
                mode
177
                        = FilesystemServerExplorer.MODE_GEOMETRY
212
                mode = FilesystemServerExplorer.MODE_GEOMETRY
178 213
                        | FilesystemServerExplorer.MODE_RASTER;
179 214
            }
180 215

  
216
            I18nManager i18nManager = ToolsLocator.getI18nManager();
217

  
181 218
            // First filter in list will be 'All formats' filter
182 219
            this.filters.add(new MyFileFilter(explorer.getFilter(mode,
183
                    Messages.get(DEFAULT_FILTER))));
220
                    i18nManager.getTranslation(DEFAULT_FILTER))));
184 221

  
185 222
            @SuppressWarnings("unchecked")
186 223
            Iterator<FilesystemFileFilter> iter = explorer.getFilters(mode);
......
190 227
        }
191 228
    }
192 229

  
193
    private void initUI() {
194
        this.setLayout(new GridBagLayout());
195
        GridBagConstraints constr = new GridBagConstraints();
196

  
197
        constr.gridwidth = GridBagConstraints.RELATIVE;
198
        constr.gridheight = GridBagConstraints.RELATIVE;
199
        constr.fill = GridBagConstraints.BOTH;
200
        constr.anchor = GridBagConstraints.FIRST_LINE_START;
201
        constr.weightx = 1;
202
        constr.weighty = 1;
203
        constr.ipadx = 3;
204
        constr.ipady = 3;
205

  
206
        this.add(getFileListScroll(), constr);
207

  
208
        constr.gridwidth = GridBagConstraints.REMAINDER;
209
        constr.gridheight = GridBagConstraints.RELATIVE;
210
        constr.fill = GridBagConstraints.NONE;
211
        constr.anchor = GridBagConstraints.FIRST_LINE_END;
212
        constr.weightx = 0;
213
        constr.weighty = 0;
214
        this.add(getButtonsPanel(), constr);
215

  
216
        this.updateButtons();
217
        this.updateContainingWizardAcceptButton();
218

  
230
    boolean isTiled(DataStoreParameters parameters){
231
        return this.panel.isTiled(parameters);
219 232
    }
220 233

  
221
    protected class FilesystemStoreListModel extends AbstractListModel {
234
    @Override
235
    protected void doAddLayer(final String layerName, final DataStoreParameters parameters) {
236
        final boolean b_isMapControlAvail = this.isMapControlAvailable();
237
        final MapControl mapControl = this.getMapCtrl();
238
        final MapContext mapContext = this.getMapContext();
239
        final ApplicationManager application = ApplicationLocator.getManager();
240
        final MapContextManager manager
241
                = MapContextLocator.getMapContextManager();
222 242

  
223
        private static final long serialVersionUID = -726119349962990665L;
224
        private ArrayList<FilesystemStoreParameters> theList;
243
        logger.info("addLayer('{}',...)", layerName);
244
        Thread task = new Thread(new Runnable() {
225 245

  
226
        public FilesystemStoreListModel() {
227
            theList = new ArrayList<FilesystemStoreParameters>();
228
        }
246
            @Override
247
            public void run() {
248
                FLayer layer = null;
249
                FLayer preparedLayer = null;
250
                try {
251
                    DataManager dataManager = DALLocator.getDataManager();
252
                    DataStore dataStore = dataManager.openStore(parameters.getDataStoreName(), parameters);
253
                     DataStoreProviderFactory factory = dataStore.getFactory();
254
                    if (factory.isTiledSupported() != DataStoreProviderFactory.NO) {
255
                        if (isTiled(parameters)) {
256
                            DynObject tileParameters = dataManager.createStoreParameters("TileCache");
229 257

  
230
        public DataStoreParameters[] getParameters() {
231
            return theList.toArray(new DataStoreParameters[0]);
232
        }
258
                            File rootFolder = new File(Launcher.getAppHomeDir() + File.separator + "gvsig_rcache");
233 259

  
234
        public Object getElementAt(int index) {
235
            return theList.get(index).getFile().getName();
236
        }
260
                            if (tileParameters.getDynClass().getDynField("rootFolder") != null) {
261
                                tileParameters.setDynValue("rootFolder", rootFolder);
262
                            }
237 263

  
238
        public FilesystemStoreParameters getStoreParameterAt(int index) {
239
            return theList.get(index);
240
        }
264
                            try {
265
                                dataStore.useCache("TileCache", tileParameters);
266
                            } catch (DataException e) {
267
                                logger.warn("Can't cache the layer.", e);
268
                            }
241 269

  
242
        public int getSize() {
243
            return theList.size();
244
        }
270
                        }
271
                    }
245 272

  
246
        public DynObject getDynObjectAt(int index) {
247
            return (DynObject) theList.get(index);
248
        }
273
                    String layerName = dataStore.getName();
274
                    layer = manager.createLayer(layerName, dataStore);
275
                    DisposeUtils.disposeQuietly(dataStore);
276
                    preparedLayer
277
                            = application.prepareOpenLayer(layer,
278
                                    new PrepareContextView_v1() {
249 279

  
250
        public void add(DynObject dynObject) {
251
            this.theList.add((FilesystemStoreParameters) dynObject);
252
            this.fireIntervalAdded(this, this.theList.size() - 1,
253
                this.theList.size() - 1);
254
        }
280
                                        @Override
281
                                        public Window getOwnerWindow() {
282
                                            return null;
283
                                        }
255 284

  
256
        public void addAll(List<FilesystemStoreParameters> toAdd) {
257
            int index0 = this.getSize() - 1;
258
            if (index0 < 0) {
259
                index0 = 0;
260
            }
261
            this.theList.addAll(toAdd);
262
            this.fireIntervalAdded(this, index0, this.theList.size() - 1);
263
        }
285
                                        @Override
286
                                        public MapControl getMapControl() {
287
                                            return mapControl;
288
                                        }
264 289

  
265
        public void remove(int i) {
266
            this.theList.remove(i);
267
            this.fireIntervalRemoved(this, i, i);
290
                                        @Override
291
                                        public IProjection getViewProjection() {
292
                                            return mapContext.getProjection();
293
                                        }
268 294

  
269
        }
295
                                        @Override
296
                                        public MapContext getMapContext() {
297
                                            return mapContext;
298
                                        }
270 299

  
271
        public void up(FilesystemStoreParameters item) {
272
            int curIndex = this.theList.indexOf(item);
273
            if (curIndex < 1) {
274
                return;
275
            }
276
            this.theList.remove(item);
277
            this.theList.add(curIndex - 1, item);
278
            this.fireContentsChanged(this, curIndex, curIndex - 1);
279
        }
300
                                        @Override
301
                                        public boolean isMapControlAvailable() {
302
                                            return b_isMapControlAvail;
303
                                        }
304
                                    });
305
                    if (preparedLayer != null) {
306
                        mapContext.getLayers().addLayer(preparedLayer);
307
                    }
308
                } catch (UnauthorizedException e) {
309
                    I18nManager i18nManager = ToolsLocator.getI18nManager();
310
                    ApplicationManager application = ApplicationLocator.getManager();
311
                    String resource = "";
312
                    if (e.getResource() instanceof FilesystemStoreParameters) {
313
                        resource = ((FilesystemStoreParameters) e.getResource()).getFile().getPath();
314
                    }
315
                    application.messageDialog(
316
                            i18nManager.getTranslation("_User_0_is_not_authorized_to_1_on_resource_2_3",
317
                                    new String[]{
318
                                        e.getIdentity().getID(),
319
                                        e.getActionName(),
320
                                        e.getResourceName(),
321
                                        resource
322
                                    }),
323
                            i18nManager.getTranslation("_Unauthorized_access"),
324
                            JOptionPane.WARNING_MESSAGE
325
                    );
326
                    logger.warn("Unauthorized access to layer '" + layerName + "'.", e);
280 327

  
281
        public void down(FilesystemStoreParameters item) {
282
            int curIndex = this.theList.indexOf(item);
283
            if (curIndex < 0) {
284
                return;
285
            } else
286
                if (curIndex == this.theList.size() - 1) {
287
                    return;
288
                }
289
            this.theList.remove(item);
290
            this.theList.add(curIndex + 1, item);
291
            this.fireContentsChanged(this, curIndex, curIndex + 1);
292
        }
293
        
294
        public void forceUpdate(int index) {
295
            this.fireContentsChanged(this, index, index);
296
        }
328
                } catch (Exception e) {
329
                    LayerErrorsPanel panel = new LayerErrorsPanel(layerName, e);
330
                    if (preparedLayer != null) {
331
                        panel.setLayer(preparedLayer);
332
                    } else if(layer!=null){
333
                        panel.setLayer(layer);
334
                    }
335
                    I18nManager i18nManager = ToolsLocator.getI18nManager();
336
                    ToolsSwingLocator.getWindowManager().showWindow(
337
                        panel,
338
                        i18nManager.getTranslation("_Problems_loading_the_layer"),
339
                        WindowManager.MODE.WINDOW
340
                    );
341
                    logger.warn("Can't load layer '" + layerName + "'.", e);
297 342

  
298
    }
299

  
300
    protected JList getFileList() {
301
        if (fileList == null) {
302
            fileList = new JList(new FilesystemStoreListModel());
303

  
304
            fileList.addListSelectionListener(this);
305
        }
306
        return fileList;
307
    }
308

  
309
    private JScrollPane getFileListScroll() {
310
        if (fileListScroll == null) {
311
            fileListScroll = new JScrollPane();
312
            fileListScroll.setViewportView(getFileList());
313
            fileListScroll
314
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
315
            fileListScroll
316
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
317

  
318
        }
319
        return fileListScroll;
320
    }
321

  
322
    private Component getButtonsPanel() {
323
        if (buttonsPanel == null) {
324
            buttonsPanel = new JPanel();
325

  
326
            buttonsPanel.setLayout(new GridBagLayout());
327

  
328
            GridBagConstraints constr = new GridBagConstraints();
329

  
330
            constr.anchor = GridBagConstraints.CENTER;
331
            constr.fill = GridBagConstraints.NONE;
332
            constr.ipadx = 3;
333
            constr.ipady = 3;
334
            constr.insets = new Insets(3, 3, 3, 3);
335
            constr.gridwidth = GridBagConstraints.REMAINDER;
336

  
337
            buttonsPanel.add(getAddButton(), constr);
338
            buttonsPanel.add(getPropertiesButton(), constr);
339
            buttonsPanel.add(getRemoveButton(), constr);
340
            buttonsPanel.add(getUpButton(), constr);
341
            buttonsPanel.add(getDownButton(), constr);
342
            // buttonsPanel.add(new JLabel(), constrLbl);
343
        }
344
        return buttonsPanel;
345
    }
346

  
347
    private JButton getAddButton() {
348
        if (addButton == null) {
349
            addButton =
350
                ToolsSwingLocator.getUsabilitySwingManager().createJButton();
351
            addButton.setText(getLocalizedText("add"));
352
            addButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
353
            addButton.setActionCommand(ADD_COMMAND);
354
            addButton.addActionListener(this);
355
        }
356
        return addButton;
357
    }
358

  
359
    private JButton getPropertiesButton() {
360
        if (propertiesButton == null) {
361
            propertiesButton =
362
                ToolsSwingLocator.getUsabilitySwingManager().createJButton();
363
            propertiesButton.setText(getLocalizedText("properties"));
364
            propertiesButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
365
            propertiesButton.setActionCommand(EDIT_COMMAND);
366
            propertiesButton.addActionListener(this);
367
        }
368
        return propertiesButton;
369
    }
370

  
371
    private JButton getRemoveButton() {
372
        if (removeButton == null) {
373
            removeButton =
374
                ToolsSwingLocator.getUsabilitySwingManager().createJButton();
375
            removeButton.setText(getLocalizedText("remove"));
376
            removeButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
377
            removeButton.setActionCommand(REMOVE_COMMAND);
378
            removeButton.addActionListener(this);
379
        }
380
        return removeButton;
381
    }
382

  
383
    private JButton getUpButton() {
384
        if (upButton == null) {
385
            upButton =
386
                ToolsSwingLocator.getUsabilitySwingManager().createJButton();
387
            upButton.setText(getLocalizedText("up"));
388
            upButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
389
            upButton.setActionCommand(UP_COMMAND);
390
            upButton.addActionListener(this);
391
        }
392
        return upButton;
393
    }
394

  
395
    private JButton getDownButton() {
396
        if (downButton == null) {
397
            downButton =
398
                ToolsSwingLocator.getUsabilitySwingManager().createJButton();
399
            downButton.setText(getLocalizedText("down"));
400
            downButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
401
            downButton.setActionCommand(DOWN_COMMAND);
402
            downButton.addActionListener(this);
403
        }
404
        return downButton;
405
    }
406

  
407
    private String getLocalizedText(String txt) {
408
        try {
409
            return PluginServices.getText(this, txt);
410
        } catch (Exception e) {
411
            return txt;
412
        }
413
    }
414

  
415
    public void actionPerformed(ActionEvent e) {
416
        String command = e.getActionCommand();
417
        FilesystemStoreListModel model =
418
            (FilesystemStoreListModel) getFileList().getModel();
419

  
420
        if (command == ADD_COMMAND) {
421
            this.addFilesFromParameters(this.chooseFilesParameters());
422
        } else
423
            if (command == EDIT_COMMAND) {
424
                showPropertiesDialog(model.getDynObjectAt(getFileList().getSelectedIndex()));
425

  
426
            } else
427
                if (command == REMOVE_COMMAND) {
428
                    int[] selecteds = getFileList().getSelectedIndices();
429
                    for (int i = selecteds.length - 1; i > -1; i--) {
430
                        model.remove(selecteds[i]);
343
                } finally {
344
                    if (preparedLayer != layer) {
345
                        DisposeUtils.disposeQuietly(preparedLayer);
431 346
                    }
432
                    getFileList().setSelectedIndex(-1);
433
                    
434
                    this.updateContainingWizardAcceptButton();
347
                    DisposeUtils.disposeQuietly(layer);
348
                }
349
            }
350
        });
351
        task.start();
435 352

  
436
                } else
437
                    if (command == UP_COMMAND) {
438
                        List<FilesystemStoreParameters> items =
439
                            new ArrayList<FilesystemStoreParameters>();
440
                        int[] selecteds = getFileList().getSelectedIndices();
441
                        if (selecteds.length == 0 || selecteds[0] == 0) {
442
                            return;
443
                        }
444
                        for (int i = 0; i < selecteds.length; i++) {
445
                            items.add(model.getStoreParameterAt(selecteds[i]));
446
                            selecteds[i]--;
447
                        }
448
                        Iterator<FilesystemStoreParameters> iter =
449
                            items.iterator();
450
                        while (iter.hasNext()) {
451
                            model.up(iter.next());
452
                        }
453
                        getFileList().setSelectedIndices(selecteds);
454

  
455
                    } else
456
                        if (command == DOWN_COMMAND) {
457
                            List<FilesystemStoreParameters> items =
458
                                new ArrayList<FilesystemStoreParameters>();
459
                            int[] selecteds =
460
                                getFileList().getSelectedIndices();
461
                            if (selecteds.length == 0
462
                                || selecteds[selecteds.length - 1] == model
463
                                    .getSize() - 1) {
464
                                return;
465
                            }
466
                            for (int i = selecteds.length - 1; i > -1; i--) {
467
                                items.add(model
468
                                    .getStoreParameterAt(selecteds[i]));
469
                                selecteds[i]++;
470
                            }
471
                            Iterator<FilesystemStoreParameters> iter =
472
                                items.iterator();
473
                            while (iter.hasNext()) {
474
                                model.down(iter.next());
475
                            }
476
                            getFileList().setSelectedIndices(selecteds);
477

  
478
                        } else {
479
                            throw new IllegalArgumentException(command);
480
                        }
481

  
482 353
    }
483 354

  
484
    protected void showPropertiesDialog(final DynObject parameters) {
485
        FilesystemExplorerPropertiesPanelManager manager = ApplicationLocator.getFilesystemExplorerPropertiesPanelManager();
486
        FilesystemExplorerPropertiesPanel panel = manager.createPanel(parameters);
487
        manager.showPropertiesDialog(parameters,panel);
488
        
489
        refreshFileList();
490
    }
491 355

  
492
    protected void refreshFileList() {
493
        // force repaint
494
        ListModel lm = this.getFileList().getModel();
495
        if (lm instanceof FilesystemStoreListModel) {
496
            FilesystemStoreListModel mm = (FilesystemStoreListModel) lm;
497
            mm.forceUpdate(getFileList().getSelectedIndex());
498
        }
499
    }
500
    
501
    public void addFiles(List<File> files) {
502
        File[] filesArray = files.toArray(new File[files.size()]);
503
        this.addFilesFromParameters(this.getParametersList(null, filesArray, null));
504
    }
505

  
506
    private void addFilesFromParameters(List<FilesystemStoreParameters> filesParams) {
507
        if ( filesParams.isEmpty() ) {
508
            return;
509
        }
510
        FilesystemStoreListModel model = (FilesystemStoreListModel) getFileList().getModel();
511
        model.addAll(filesParams);
512
        getFileList().setModel(model);
513

  
514
        this.updateContainingWizardAcceptButton();
515
        try {
516
            fileList.setSelectedIndex(fileList.getModel().getSize() - 1);
517
        } catch (Exception ex) {
518
            // Ignore errors
519
        }
520
    }
521

  
522 356
    /**
523
     * check number of files already selected for adding
357
     * @author fdiaz
358
     *
524 359
     */
525
    private void updateContainingWizardAcceptButton() {
526
        int curr_add_file_count = getFileList().getModel().getSize();
527
        this.callStateChanged(curr_add_file_count > 0);
528
    }
529

  
530
    
531
    public boolean areSettingsValid() {
532
        int curr_add_file_count = getFileList().getModel().getSize();
533
        boolean r = curr_add_file_count > 0;
534
        return r;
535
    }
536

  
537
    public List<DynObject> getSelecteds() {
538
        ArrayList<DynObject> list = new ArrayList<DynObject>();
539
        JList fList = this.getFileList();
540
        int[] selecteds = fList.getSelectedIndices();
541
        FilesystemStoreListModel model =
542
            (FilesystemStoreListModel) fList.getModel();
543

  
544
        for (int index : selecteds) {
545
            list.add((DynObject) model.getStoreParameterAt(index));
546
        }
547
        return list;
548
    }
549

  
550
    public void valueChanged(ListSelectionEvent e) {
551
        this.updateButtons();
552
    }
553

  
554 360
    public class MyFileFilter extends FileFilter {
555 361

  
556
        public FilesystemFileFilter filter = null;
362
        private FilesystemFileFilter filter = null;
557 363

  
364
        /**
365
         * @param params
366
         */
558 367
        public MyFileFilter(FilesystemFileFilter params) {
559
            this.filter = params;
368
            this.setFilter(params);
560 369
        }
561 370

  
562 371
        /**
......
566 375
            if (f.isDirectory()) {
567 376
                return true;
568 377
            }
569
            return filter.accept(f);
378
            return getFilter().accept(f);
570 379

  
571 380
        }
572 381

  
......
574 383
         * @see javax.swing.filechooser.FileFilter#getDescription()
575 384
         */
576 385
        public String getDescription() {
577
            return filter.getDescription();
386
            return getFilter().getDescription();
578 387
        }
579 388

  
389
        /**
390
         * @return
391
         */
580 392
        public String getName() {
581
            return filter.getDataStoreProviderName();
393
            return getFilter().getDataStoreProviderName();
582 394
        }
583
    }
584 395

  
585
    private List<FilesystemStoreParameters> chooseFilesParameters() {
586
        
587
        // this.callStateChanged(true);
588
        
589
        JFileChooser fileChooser =
590
            new JFileChooser(OPEN_LAYER_FILE_CHOOSER_ID,
591
                explorer.getCurrentPath());
592
        fileChooser.setMultiSelectionEnabled(true);
593
        fileChooser.setAcceptAllFileFilterUsed(false);
594

  
595
        Iterator<MyFileFilter> iter = this.filters.iterator();
596
        while (iter.hasNext()) {
597
            fileChooser.addChoosableFileFilter(iter.next());
396
        /**
397
         * @return the filter
398
         */
399
        public FilesystemFileFilter getFilter() {
400
            return filter;
598 401
        }
599
        
600
        if (filters.size() > 0) {
601
            MyFileFilter firstf = filters.get(0);
602
            // Set first filter
603
            fileChooser.setFileFilter(firstf);
604
        }
605 402

  
606
        // If there is a last filter, use it
607
        if (lastFilter != null && filters.contains(lastFilter)) {
608
            fileChooser.setFileFilter(lastFilter);
403
        /**
404
         * @param filter the filter to set
405
         */
406
        public void setFilter(FilesystemFileFilter filter) {
407
            this.filter = filter;
609 408
        }
610

  
611
        int result = fileChooser.showOpenDialog(this);
612

  
613
        List<FilesystemStoreParameters> toAdd = 
614
            new ArrayList<FilesystemStoreParameters>();
615

  
616
        if (result == JFileChooser.APPROVE_OPTION) {
617
            lastFilter = (MyFileFilter) fileChooser.getFileFilter();
618
            lastPath = fileChooser.getCurrentDirectory().getAbsolutePath();
619
            JFileChooser.setLastPath(OPEN_LAYER_FILE_CHOOSER_ID, fileChooser.getCurrentDirectory());
620
            String providerName = null;
621
            if( lastFilter!=null ) {
622
                if( !DEFAULT_FILTER.equalsIgnoreCase(lastFilter.getDescription()) ) {
623
                    providerName = lastFilter.getName();
624
                }
625
            }
626
            toAdd = this.getParametersList(
627
                    fileChooser.getCurrentDirectory(), 
628
                    fileChooser.getSelectedFiles(), 
629
                    providerName
630
            );
631
        }
632
        return toAdd;
633 409
    }
634 410

  
635
    private List<FilesystemStoreParameters> getParametersList(File folder, File[] files, String providerName) {
636
        ApplicationManager application = ApplicationLocator.getManager();
637
        
638
        PrepareContext context = this.getPrepareDataStoreContext();
639
        
640
        List<DataStoreParameters> params = new ArrayList<DataStoreParameters>();
641
        List<DataStoreParameters> preparedParams = null;
642
        List<FilesystemStoreParameters> returnParams = new ArrayList<FilesystemStoreParameters>();
643
        
644
        for ( File aFile : files ) {
645
            String currentProvider = providerName;
646
            DataStoreParameters param;
647
            try {
648
                if( folder == null) {
649
                    explorer.setCurrentPath(aFile.getParentFile());
650
                } else {
651
                    explorer.setCurrentPath(folder);
652
                }
653
                if( currentProvider == null ) {
654
                    for( int i=1; i<this.filters.size(); i++) {
655
                        MyFileFilter filter = this.filters.get(i);
656
                        if( filter.accept(aFile)) {
657
                            currentProvider = filter.getName();
658
                            break;
659
                        }
660
                    }
661
                }
662
                if( currentProvider == null ) {
663
                    // TODO: ask user
664
                    continue;
665
                }
666
                param = explorer.createStoreParameters(aFile, currentProvider);
667
                if ( param == null ) {
668
                    // TODO show warning
669
                    continue;
670
                }
671
                params.add(param);
672

  
673
            } catch (DataException e) {
674
                NotificationManager.addError(e);
675
                return null;
676
            }
677
        }
678

  
679
        try {
680
            preparedParams
681
                    = application.prepareOpenDataStoreParameters(params, context);
682
        } catch (Exception e) {
683
            NotificationManager.addError(e);
684
        }
685

  
686
        if ( preparedParams != null ) {
687
            for ( int i = 0; i < preparedParams.size(); i++ ) {
688
                returnParams.add((FilesystemStoreParameters) preparedParams.get(i));
689
            }
690
        }
691
        return returnParams;
411
    protected void showPropertiesDialog(DynObject parameters) {
412
        panel.showPropertiesDialog(parameters);
692 413
    }
693 414

  
694
    protected abstract PrepareContext getPrepareDataStoreContext();
695

  
696
    /**
697
     * Refers to up/down/remove buttons etc. Called when selection changes
698
     */
699
    private void updateButtons() {
700
        int selectedIndex = this.getFileList().getSelectedIndex();
701
        int size = this.getFileList().getModel().getSize();
702
        int[] selecteds = this.getFileList().getSelectedIndices();
703
        if (size < 1) {
704
            this.getPropertiesButton().setEnabled(false);
705
            this.getRemoveButton().setEnabled(false);
706
            this.getUpButton().setEnabled(false);
707
            this.getDownButton().setEnabled(false);
708
            return;
709
        } else
710
            if (size == 1) {
711
                this.getUpButton().setEnabled(false);
712
                this.getDownButton().setEnabled(false);
713
            } else {
714
                this.getUpButton().setEnabled(selectedIndex > 0);
715

  
716
                this.getDownButton().setEnabled(
717
                    selectedIndex > -1
718
                        && selecteds[selecteds.length - 1] < size - 1);
719
            }
720
        this.getPropertiesButton().setEnabled(
721
            selectedIndex > -1
722
                && this.getFileList().getSelectedIndices().length == 1);
723
        this.getRemoveButton().setEnabled(selectedIndex > -1);
415
    protected PrepareContext getPrepareDataStoreContext() {
416
        return panel.getPrepareDataStoreContext();
724 417
    }
725 418

  
726
    public void close() {
727
        this.dispose();
728
    }
729

  
730
    public void dispose() {
731
        if (explorer != null) {
732
            explorer.dispose();
733
            explorer = null;
734
        }
735
        if (filters != null) {
736
            filters.clear();
737
            filters = null;
738
        }
739
    }
740
    
741
    class RefreshThread extends Thread {
742
        
743
        private int waitt = 0;
744
        private JList comp = null;
745
        
746
        public RefreshThread(JList c, int t) {
747
            waitt = t;
748
            comp = c;
749
        }
750
        public void run() {
751
            
752
            try {
753
                /*
754
                 * We might need to wait a bit because the GUI thread needs
755
                 * some time to update (this is because we have used a modal dialog
756
                 * and we refresh after that dialog is closed)
757
                 */
758
                Thread.sleep(waitt);
759
            } catch (Exception exc) {
760
                
761
            }
762
            
763
            SwingUtilities.invokeLater(new Runnable() {
764
                public void run() {
765
                    try {
766
                        // System.out.println("REFRESH");
767
                        comp.clearSelection();
768
                    } catch (Exception exc) {
769
                        LOG.info("Error while refreshing components.", exc);
770
                    }
771
                }
772
            });
773
        }
774
    }    
775
    
776
    protected void fixParametersFromContext(final DynObject parameters) {
777
        // By default do nothing
778
    }
779 419
}

Also available in: Unified diff