Statistics
| Revision:

gvsig-raster / org.gvsig.raster / branches / org.gvsig.raster_dataaccess_refactoring / org.gvsig.raster.algorithm / src / main / java / org / gvsig / raster / algorithm / process / DataProcess.java @ 2365

History | View | Annotate | Download (10.1 KB)

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

    
24
import java.util.HashMap;
25
import java.util.Hashtable;
26

    
27
import javax.swing.SwingUtilities;
28

    
29
import org.gvsig.fmap.dal.coverage.RasterLocator;
30
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
31
import org.gvsig.fmap.dal.coverage.process.CancelEvent;
32
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
33
import org.gvsig.raster.algorithm.gui.IIncrementable;
34
import org.gvsig.raster.algorithm.gui.IncrementableEvent;
35
import org.gvsig.raster.algorithm.gui.IncrementableListener;
36
import org.gvsig.raster.algorithm.gui.IncrementableTask;
37
import org.gvsig.raster.swing.basepanel.IButtonsPanel;
38
import org.gvsig.tools.dispose.Disposable;
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41
/**
42
 * Clase base de todos los procesos raster. En ella se genstionan todas las
43
 * funciones comunes como incremento de la tarea, gesti�n de eventos a la tarea, 
44
 * par�metros de la tarea, etc ...
45
 * 
46
 * 18/12/2007
47
 * @author Nacho Brodin nachobrodin@gmail.com
48
 */
49
public abstract class DataProcess extends ProcessParamsManagement implements IIncrementable, IncrementableListener, Runnable, Disposable {
50
        protected IncrementableTask incrementableTask = null;
51
        protected volatile Thread   blinker           = null;
52
        protected TaskEventManager  taskEventManager  = null;
53
        protected IProcessActions   externalActions   = null;
54
        protected Hashtable<String, Object>
55
                                    taskParams        = new Hashtable<String, Object>();
56
        
57

    
58
        private String              log               = "";
59
        private String              lastLine          = "";
60
        private long                time              = 0;
61
        private boolean             progressActive    = true;
62
        private IProcessActions     queueActions      = null;
63
        protected Logger            logger            = LoggerFactory.getLogger(DataProcess.class.toString());
64
        private int                 percent           = 0;
65
        private String              processName       = null;
66
        
67
        //***************************************************
68
        //Task control
69
        //***************************************************
70
        
71
        /**
72
         * Builds the window <code>IncrementableTask</code> to show
73
         * the increment of the task.
74
         */
75
        public IncrementableTask getIncrementableTask() {
76
                if (incrementableTask == null) {
77
                        incrementableTask = new IncrementableTask(this);
78
                        incrementableTask.addIncrementableListener(this);
79
                }
80
                return incrementableTask;
81
        }
82
        
83
        /**
84
         * Sets the button to cancel the task
85
         */
86
        public void setCancelable(boolean enabled) {
87
                getIncrementableTask().getButtonsPanel().setEnabled(IButtonsPanel.BUTTON_CANCEL, enabled);
88
        }
89
        
90
        /**
91
         * Show the increment of this task <code>IncrementableTask</code>
92
         */
93
        public void showIncrementableWindow() {
94
                if (progressActive) {
95
                        getIncrementableTask().showWindow();
96
                        getIncrementableTask().start();
97
                }
98
        }
99

    
100
        /**
101
         * Starts the process. It will call the run method
102
         */
103
        public void start() {
104
                showIncrementableWindow();
105
                if(blinker == null)
106
                        blinker = new Thread(this);
107
                blinker.start();
108
        }
109
                
110
        /**
111
         * A specific task will load parameters using this initialization.
112
         */
113
        public abstract void init();
114
        
115
        /**
116
         * This call will be implemented by a specific process. It will do the actions to carry out
117
         * the task
118
         * @throws InterruptedException
119
         */
120
        public abstract void process() throws ProcessInterruptedException, ProcessException;
121
        
122
        /**
123
         * Gets the result of the process. All processes will have a parameter PROCESS that it is
124
         * the own process. It is useful to get the process name or other data.
125
         * 
126
         * This result of the process is sent to the method "end" in <code>IProcessActions</code> when the task
127
         * is thrown in a thread or is recovered by the user when the task is thrown sequentially.
128
         * 
129
         * @return Result of the task
130
         */
131
        public HashMap<String, Object> getResult() {
132
                outputParameters.put("PROCESS", this);
133
                outputParameters.put(TIME, getTime());
134
                outputParameters.put(PROCESS_NAME, getName());
135
                return outputParameters;
136
        }
137
        
138
        /**
139
         * Adds a output from the process in runtime
140
         * @param key
141
         * @param value
142
         */
143
        protected void addOutputValue(String key, Object value) {
144
                outputParameters.put(key, value);
145
        }
146
        
147
        /**
148
         * Sequential execution of this task
149
         * @throws ProcessException 
150
         */
151
        public void execute() throws ProcessInterruptedException, ProcessException {
152
                taskEventManager = RasterLocator.getManager().createRasterTask(this);
153
                loadGlobalParameters();
154
                init();
155
                process();
156
                
157
                //Sets in the output the result of the process
158
                SwingUtilities.invokeLater(new Runnable() {
159
                        public void run() {
160
                                if (externalActions != null) {
161
                                        externalActions.end(getResult());
162
                                }
163
                        }
164
                });
165
        }
166
        
167
        /**
168
         * This method will be executed by the Thread. It will have the global actions for 
169
         * any task and it will call to the <code>execute</code> function.
170
         */
171
        public void run() {
172
                long t1 = new java.util.Date().getTime();
173

    
174
                try {
175
                        execute();
176
                } catch (ProcessInterruptedException e) {
177
                        if (externalActions != null)
178
                                externalActions.interrupted();
179
                        Thread.currentThread().interrupt();
180
                } catch (ProcessException e) {
181
                        if (progressActive) {
182
                                if (incrementableTask != null) {
183
                                        getIncrementableTask().processFinalize();
184
                                        incrementableTask = null;
185
                                }
186
                        }
187
                        logger.warn(RasterLocator.getManager().getRasterUtils().getTrace(e));
188
                        if(e.getMessage() != null && e.getMessage().compareTo("") != 0)
189
                                messageBoxError(e.getMessage(), null);
190
                        else
191
                                messageBoxError("error_processing", null);
192
                        queueActions = null;
193

    
194
                } catch (Exception e) {
195
                        if (progressActive) {
196
                                if (incrementableTask != null) {
197
                                        getIncrementableTask().processFinalize();
198
                                        incrementableTask = null;
199
                                }
200
                        }
201
                        logger.warn(RasterLocator.getManager().getRasterUtils().getTrace(e));
202
                        if(e.getMessage() != null && e.getMessage().compareTo("") != 0)
203
                                messageBoxError(e.getMessage(), null);
204
                        else
205
                                messageBoxError("error_processing", null);
206
                        queueActions = null;
207
                } finally {
208
                        try {
209
                                //Evita un NullPointerException sun.awt.X11.XWindowPeer.restoreTransientFor(XWindowPeer.java:1500) 
210
                                Thread.sleep(500);
211
                        } catch(Exception e) {}
212
                        
213
                        taskEventManager.removeTask();
214
                        if (progressActive) {
215
                                if (incrementableTask != null)
216
                                        getIncrementableTask().processFinalize();
217
                        }
218
                        if (queueActions != null)
219
                                queueActions.end(this);
220
                        time = new java.util.Date().getTime() - t1;
221
                        blinker = null;
222
                }
223
        }
224
        
225
        /**
226
         * When the process is launched in a thread, this method enables or disables
227
         * the GUI to show the progress.
228
         */
229
        public void setProgressActive(boolean active) {
230
                this.progressActive = active;
231
        }
232
        
233
        /**
234
         * Gets the time that a task lasts
235
         */
236
        public long getTime() {
237
                return time;
238
        }
239
        
240
        /**
241
         * Gets the object to execute external actions. 
242
         * A user should be register this object to receive the events
243
         */
244
        public IProcessActions getActions() {
245
                return externalActions;
246
        }
247

    
248
        /**
249
         * Sets the object to execute external actions. 
250
         * A user should be register this object to receive the events
251
         */
252
        public void setActions(IProcessActions actions) {
253
                this.externalActions = actions;
254
        }
255
        
256
        /**
257
         * Gets the object to execute actions in the queue of processes
258
         */
259
        public IProcessActions getUniqueProcessActions() {
260
                return queueActions;
261
        }
262

    
263
        /**
264
         * Asigna el objeto para ejecutar acciones externar.
265
         * @param IProcessActions
266
         */
267
        public void setUniqueProcessActions(IProcessActions actions) {
268
                this.queueActions = actions;
269
        }
270
        
271
        /**
272
         * Inserts a new line in the increment window
273
         */
274
        protected void insertLineLog(String line) {
275
                lastLine = line;
276
                log = log + line + "\n";
277
        }
278
        
279
        /**
280
         * Gets the last line in the increment window
281
         */
282
        public String getLabel() {
283
                return lastLine;
284
        }
285
        
286
        /**
287
         * Gets the log of the increment window
288
         */
289
        public String getLog() {
290
                return log;
291
        }
292
        
293
        /**
294
         * Un evento de cancelado es enviado a la tarea cuando actionCanceled es activado. Para
295
         * ello se crear� un objeto CancelEvent y se asignar� a la tarea en ejecuci�n. Esta lo
296
         * procesar� cuando pueda e interrumpir� el proceso.
297
         */
298
        public void actionCanceled(IncrementableEvent e) {
299
                taskEventManager.setEvent(new CancelEvent(this));
300
        }
301
        
302
        /**
303
         * Updates the percentaje of progress and manages the cancelation
304
         * @param parcial
305
         * @param total
306
         * @throws ProcessInterruptedException
307
         */
308
        public void updatePercent(int parcial, int total) throws ProcessInterruptedException {
309
                if (taskEventManager != null && taskEventManager.getEvent() != null)
310
                        taskEventManager.manageEvent(taskEventManager.getEvent());
311
                if(externalActions != null)
312
                        externalActions.updateProgress(parcial, total);
313
                percent = (int)((parcial * 100) / total);
314
        }
315

    
316
        public int getPercent() {
317
                return percent;
318
        }
319

    
320
        public void actionResumed(IncrementableEvent e) {        
321
        }
322
        
323
        public void actionSuspended(IncrementableEvent e) {
324
        }
325
        
326
        public boolean isCancelable() {
327
                return true;
328
        }
329

    
330
        public boolean isPausable() {
331
                return false;
332
        }
333
        
334
        public String getName() {
335
                return processName;
336
        }
337
        
338
        public void setName(String name) {
339
                this.processName = name;
340
        }
341
        
342
        public void dispose() {
343
                try {
344
                        finalize();
345
                } catch (Throwable e) {
346
                }
347
        }
348
        
349
        @Override
350
        protected void finalize() throws Throwable {
351
                incrementableTask           = null;
352
                blinker                     = null;
353
                externalActions             = null;
354
                super.finalize();
355
        }
356
        
357
}