Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.algorithm / src / main / java / org / gvsig / raster / algorithm / process / DataProcess.java @ 2130

History | View | Annotate | Download (9.89 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(), this);
190
                        else
191
                                messageBoxError("error_processing", this);
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
                        taskEventManager.removeTask();
209
                        if (progressActive) {
210
                                if (incrementableTask != null)
211
                                        getIncrementableTask().processFinalize();
212
                        }
213
                        if (queueActions != null)
214
                                queueActions.end(this);
215
                        time = new java.util.Date().getTime() - t1;
216
                        blinker = null;
217
                }
218
        }
219
        
220
        /**
221
         * When the process is launched in a thread, this method enables or disables
222
         * the GUI to show the progress.
223
         */
224
        public void setProgressActive(boolean active) {
225
                this.progressActive = active;
226
        }
227
        
228
        /**
229
         * Gets the time that a task lasts
230
         */
231
        public long getTime() {
232
                return time;
233
        }
234
        
235
        /**
236
         * Gets the object to execute external actions. 
237
         * A user should be register this object to receive the events
238
         */
239
        public IProcessActions getActions() {
240
                return externalActions;
241
        }
242

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

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

    
311
        public int getPercent() {
312
                return percent;
313
        }
314

    
315
        public void actionResumed(IncrementableEvent e) {        
316
        }
317
        
318
        public void actionSuspended(IncrementableEvent e) {
319
        }
320
        
321
        public boolean isCancelable() {
322
                return true;
323
        }
324

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