Revision 468 org.gvsig.scripting/trunk/org.gvsig.scripting/org.gvsig.scripting.lib/org.gvsig.scripting.lib.impl/src/main/java/org/gvsig/scripting/impl/DefaultScriptingScript.java

View differences:

DefaultScriptingScript.java
2 2

  
3 3
import java.io.File;
4 4
import java.io.IOException;
5
import java.io.InputStream;
5 6
import java.util.List;
6
import java.util.Map;
7 7

  
8 8
import javax.script.Compilable;
9 9
import javax.script.CompiledScript;
......
13 13

  
14 14
import org.apache.commons.io.FileUtils;
15 15
import org.apache.commons.io.FilenameUtils;
16
import org.apache.commons.io.IOUtils;
17
import org.apache.commons.lang3.StringUtils;
16 18
import org.gvsig.scripting.CompileErrorException;
17 19
import org.gvsig.scripting.ExecuteErrorException;
18 20
import org.gvsig.scripting.ScriptingBaseScript;
......
29 31
import org.slf4j.LoggerFactory;
30 32

  
31 33
public class DefaultScriptingScript extends AbstractScript implements
32
		ScriptingScript {
33
	
34
	private static final Logger logger = LoggerFactory.getLogger(DefaultScriptingScript.class);
35
	protected String langName;
36
	protected String extension = null;
37
	protected ScriptEngine engine = null;
38
	protected CompiledScript compiledCode;
34
        ScriptingScript {
39 35

  
40
	private String code = null;
41
	private String mainName = "main";
42
	private boolean saved;
43
	private final DelegateWeakReferencingObservable delegatedObservable;
36
    private static final Logger logger = LoggerFactory.getLogger(DefaultScriptingScript.class);
37
    protected String langName;
38
    protected String extension = null;
39
    protected ScriptEngine engine = null;
40
    protected CompiledScript compiledCode;
44 41

  
45
	protected DefaultScriptingScript(ScriptingFolder parent, String typename, ScriptingManager manager, String id) {
46
		super(parent, typename, manager, id);
47
		this.setLangName("python");
48
		this.setSaved(true);
49
		this.delegatedObservable = new DelegateWeakReferencingObservable(this);
50
	}
51
	
52
	public DefaultScriptingScript(ScriptingFolder parent, ScriptingManager manager, String id) {
53
		this(parent, ScriptingManager.UNIT_SCRIPT, manager, id);
54
	}
55
	
56
	public ScriptingUnit load(String name) {
57
		ScriptingUnit script = null;
58
		File f = null;
59
		String scname = name;
60
		if (!scname.endsWith(".inf")) {
61
			scname = scname + ".inf";
62
		}
63
		if (scname.startsWith("/")) {
64
			f = new File(scname.substring(1));
65
		} else {
66
			f = new File(this.getParent().getFile(), scname);
67
			if (!f.exists()) {
68
				return null;
69
			}
70
		}
71
		try {
72
			script = this.getManager().getScript(f);
73
		} catch (ScriptNotFoundException ex) {
74
			return null;
75
		}
76
		if (script != null) {
77
			this.getEngine().put(script.getId(), script);
78
		}
79
		return script;
80
	}
42
    private String code = null;
43
    private String mainName = "main";
44
    private boolean saved;
45
    private final DelegateWeakReferencingObservable delegatedObservable;
81 46

  
82
	public Object __getattr__(String name) {
83
		ScriptEngine engine = this.getEngine();
84
		this.compile();
85
		return engine.get(name);
86
	}
47
    protected DefaultScriptingScript(ScriptingFolder parent, String typename, ScriptingManager manager, String id) {
48
        super(parent, typename, manager, id);
49
        this.setLangName("python");
50
        this.setSaved(true);
51
        this.delegatedObservable = new DelegateWeakReferencingObservable(this);
52
    }
87 53

  
88
	public void __setattr__(String name, Object value) {
89
		ScriptEngine engine = this.getEngine();
90
		this.compile();
91
		engine.put(name,value);
92
	}
93
	
94
	public Object __call__() {
95
		return this.run();
96
	}
97
	
98
	public Object __call__(Object[] args) {
99
		return this.run(args);
100
	}
101
	
102
	protected void notifyErrors(Exception exception, String command) {
103
		this.delegatedObservable.notifyObservers(new BaseScriptingNotifycation(
104
				this, BaseScriptingNotifycation.RUNTIME_ERROR_NOTIFICATION,
105
				command, exception));
106
	}
54
    public DefaultScriptingScript(ScriptingFolder parent, ScriptingManager manager, String id) {
55
        this(parent, ScriptingManager.UNIT_SCRIPT, manager, id);
56
    }
107 57

  
108
	public void setSaved(boolean saved) {
109
		this.saved = saved;
110
	}
58
    public Object __getattr__(String name) {
59
        ScriptEngine engine = this.getEngine();
60
        this.compile();
61
        return engine.get(name);
62
    }
111 63

  
112
	public String getCode() {
113
		if (this.code == null) {
114
			File f=null;
115
			try {
116
				f = this.getFileResource(this.extension);
117
				this.code = FileUtils.readFileToString(f);
118
			} catch (IOException e) {
119
				String fname = (f==null)? "(null)":f.getAbsolutePath();
120
				logger.warn("Can't load code from file '"+fname+"'.");
121
			}
122
		}
123
		return this.code;
124
	}
64
    public void __setattr__(String name, Object value) {
65
        ScriptEngine engine = this.getEngine();
66
        this.compile();
67
        engine.put(name, value);
68
    }
125 69

  
126
	public void setCode(String code) {
127
		this.code = code;
128
		this.engine = null;
129
		this.compiledCode = null;
130
		this.setSaved(false);
131
	}
70
    public Object __call__() {
71
        return this.run();
72
    }
132 73

  
133
	private String getPreparedCode() {
134
		return this.getCode();
135
	}
74
    public Object __call__(Object[] args) {
75
        return this.run(args);
76
    }
136 77

  
137
	protected String getCodeToInitializeEngine() {
138
		if( "python".equalsIgnoreCase(this.getLangName()) ) {
139
			List<File> libFolders = this.manager.getLibFolders();
140
			if (libFolders == null || libFolders.size() < 1) {
141
				return null;
142
			}
143
			StringBuffer buffer = new StringBuffer();
144
			buffer.append("import sys\n");
145
			for (File file : libFolders) {
146
				buffer.append("sys.path.append(r'");
147
				buffer.append(file.getAbsolutePath());
148
				buffer.append("')\n");
149
			}
150
			buffer.append("load = script.load\n");
151
			return buffer.toString();
152
		}
153
		return null;
154
	}
155
	
156
	protected ScriptEngine getEngine() {
157
		if (this.engine == null) {
158
			ScriptEngine scriptEngine = this.manager.getEngine(this
159
					.getLangName());
160
			scriptEngine.put("script", this);
161
			this.engine = scriptEngine;
162
			try {
163
				String code = this.getCodeToInitializeEngine();
164
				if( code != null ) {
165
					this.engine.eval(code);
166
				}
167
			} catch(Exception ex) {
168
				logger.warn("Can't initialize engine with the code:\n"+code);
169
			}
170
		}
171
		return this.engine;
172
	}
78
    protected void notifyErrors(Exception exception, String command) {
79
        this.delegatedObservable.notifyObservers(new BaseScriptingNotifycation(
80
                this, BaseScriptingNotifycation.RUNTIME_ERROR_NOTIFICATION,
81
                command, exception));
82
    }
173 83

  
174
	protected void loadInf(Ini prefs) {
175
		super.loadInf(prefs);
84
    @Override
85
    public void setSaved(boolean saved) {
86
        this.saved = saved;
87
    }
176 88

  
177
		this.setMainName((String) getInfValue(prefs, "Script", "main", "main"));
178
		this.setLangName((String) getInfValue(prefs, "Script", "Lang",
179
				this.getLangName()));
180
	}
89
    @Override
90
    public String getCode() {
91
        if (this.code == null) {
92
            File f = null;
93
            try {
94
                f = this.getFileResource(this.extension);
95
                this.code = FileUtils.readFileToString(f);
96
            } catch (IOException e) {
97
                String fname = (f == null) ? "(null)" : f.getAbsolutePath();
98
                logger.warn("Can't load code from file '" + fname + "'.");
99
            }
100
        }
101
        return this.code;
102
    }
181 103

  
182
	public void load(ScriptingFolder folder, String id) {
183
		this.setId(id);
184
		this.setParent(folder);
104
    @Override
105
    public void setCode(String code) {
106
        this.code = code;
107
        this.engine = null;
108
        this.compiledCode = null;
109
        this.setSaved(false);
110
    }
185 111

  
186
		Map<String, String> languages = this.manager
187
				.getSupportedLanguagesByExtension();
188
		String extension = FilenameUtils.getExtension(id);
189
		String langName = languages.get(extension);
190
		this.setLangName(langName);
191
		this.setExtension(extension);
112
    protected String getCodeToInitializeEngine() {
113
        String name = "org/gvsig/scripting/langs/"+this.getLangName().toLowerCase()+"/init.txt";
114
        try {
115
            InputStream template = this.getClass().getClassLoader().getResourceAsStream(name);
116
            if( template == null ) {
117
                return null;
118
            }
119
            List<String> lines = IOUtils.readLines(template);
120
            return StringUtils.join(lines, "\n");
121
        } catch (Exception ex) {
122
            logger.warn("Can't load code to initialize the script from '"+name+".",ex);
123
            return null;
124
        }
125
    }
192 126

  
193
		File f = getFileResource(".inf");
194
		if (f.isFile()) {
195
			Ini prefs = null;
196
			try {
197
				prefs = new Ini(f);
198
			} catch (Exception e) {
199
				logger.warn("Can't load 'inf' file '"+f.getAbsolutePath()+"'.",e);
200
			}
201
			loadInf(prefs);
202
		}
203
		this.setSaved(true);
204
	}
127
    protected ScriptEngine getEngine() {
128
        if (this.engine == null) {
129
            ScriptEngine scriptEngine = this.manager.getEngineByLanguage(langName);
130
            scriptEngine.put("script", this);
131
            this.engine = scriptEngine;
132
            String code = this.getCodeToInitializeEngine();
133
            if (code != null) {
134
                try {
135
                    this.engine.eval(code);
136
                } catch (Exception ex) {
137
                    logger.warn("Can't initialize engine with the code:\n" + code, ex);
138
                }
139
            }
140
        }
141
        return this.engine;
142
    }
205 143

  
206
	public void save() {
207
		File f = getFileResource(".inf");
208
		if (!f.isFile()) {
209
			try {
210
				f.createNewFile();
211
			} catch (Exception e) {
212
				logger.warn("Can't create 'inf' file '"+f.getAbsolutePath()+"'.",e);
213
			}
214
		}
215
		Ini prefs = null;
216
		try {
217
			prefs = new Ini(f);
218
		} catch (Exception e) {
219
			logger.warn("Can't load 'inf' file '"+f.getAbsolutePath()+"'.",e);
220
		}
221
		save(prefs);
222
		// Guardo el codigo en el fichero
223
		File fcode = null;
224
		try {
225
			fcode = this.getFileResource(this.getExtension());
226
			FileUtils.write(fcode, this.getCode());
227
		} catch (Exception e) {
228
			logger.warn("Can't write code to file '"+fcode.getAbsolutePath()+"'.",e);
229
		}
230
		this.setSaved(true);
231
	}
144
    @Override
145
    protected void loadInf(Ini prefs) {
146
        super.loadInf(prefs);
232 147

  
233
	protected void save(Ini prefs) {
234
		super.save(prefs);
235
		prefs.put("Script", "main", this.getMainName());
236
		prefs.put("Script", "Lang", this.getLangName());
237
		try {
238
			prefs.store();
239
		} catch (IOException e) {
240
			String fname = (prefs.getFile()==null)? "(null)" : prefs.getFile().getAbsolutePath(); 
241
			logger.warn("Can't save inf file ("+fname+").",e);
242
		}
148
        this.setMainName((String) getInfValue(prefs, "Script", "main", "main"));
149
        this.setLangName((String) getInfValue(prefs, "Script", "Lang",
150
                this.getLangName()));
151
    }
243 152

  
244
	}
153
    @Override
154
    public void load(ScriptingFolder folder, String id) {
155
        this.setId(id);
156
        this.setParent(folder);
245 157

  
246
	public String getLangName() {
247
		return this.langName;
248
	}
158
        String extension = FilenameUtils.getExtension(id);
159
        if( extension != null ) {
160
            String language = this.manager.getLanguageOfExtension(extension);
161
            if( language != null ) {
162
                this.setLangName(language);
163
            }
164
            this.setExtension(extension);
165
        }
166
        File f = getFileResource(".inf");
167
        if (f.isFile()) {
168
            Ini prefs = null;
169
            try {
170
                prefs = new Ini(f);
171
            } catch (Exception e) {
172
                logger.warn("Can't load 'inf' file '" + f.getAbsolutePath() + "'.", e);
173
            }
174
            loadInf(prefs);
175
        }
176
        this.setSaved(true);
177
    }
249 178

  
250
	protected void setLangName(final String langName) {
251
		this.langName = langName;
252
		this.extension = this.manager.getExtensionByLanguage(this.langName);
253
	}
179
    @Override
180
    public void save() {
181
        File f = getFileResource(".inf");
182
        if (!f.isFile()) {
183
            try {
184
                f.createNewFile();
185
            } catch (Exception e) {
186
                logger.warn("Can't create 'inf' file '" + f.getAbsolutePath() + "'.", e);
187
            }
188
        }
189
        Ini prefs = null;
190
        try {
191
            prefs = new Ini(f);
192
        } catch (Exception e) {
193
            logger.warn("Can't load 'inf' file '" + f.getAbsolutePath() + "'.", e);
194
        }
195
        save(prefs);
196
        // Guardo el codigo en el fichero
197
        File fcode = this.getFileResource(this.getExtension());
198
        try {
199
            FileUtils.write(fcode, this.getCode());
200
        } catch (Exception e) {
201
            logger.warn("Can't write code to file '" + fcode.getAbsolutePath() + "'.", e);
202
        }
203
        this.setSaved(true);
204
    }
254 205

  
255
	public String[] getIconNames() {
256
		return new String[] { 
257
				"scripting_" + this.getLangName().toLowerCase(),
258
				"scripting_" + this.getLangName().toLowerCase() + "_open"
259
		};
260
	}
206
    @Override
207
    protected void save(Ini prefs) {
208
        super.save(prefs);
209
        prefs.put("Script", "main", this.getMainName());
210
        prefs.put("Script", "Lang", this.getLangName());
211
        try {
212
            prefs.store();
213
        } catch (IOException e) {
214
            String fname = (prefs.getFile() == null) ? "(null)" : prefs.getFile().getAbsolutePath();
215
            logger.warn("Can't save inf file (" + fname + ").", e);
216
        }
261 217

  
262
	public String getMainName() {
263
		return this.mainName;
264
	}
218
    }
265 219

  
266
	public void setMainName(final String mainName) {
267
		this.mainName = mainName;
268
	}
220
    @Override
221
    public String getLangName() {
222
        return this.langName;
223
    }
269 224

  
270
	public String getExtension() {
271
		return this.extension;
272
	}
225
    protected void setLangName(final String langName) {
226
        if( langName == null ) {
227
            return;
228
        }
229
        this.langName = langName;
230
        this.setExtension(this.manager.getExtensionOfLanguage(this.langName));
231
    }
273 232

  
274
	public void setExtension(final String extension) {
275
		if( !extension.startsWith(".") ) {
276
			this.extension = "." + extension;
277
		} else {
278
			this.extension = extension;	
279
		}
280
	}
233
    @Override
234
    public String[] getIconNames() {
235
        return new String[]{
236
            "scripting_" + this.getLangName().toLowerCase(),
237
            "scripting_" + this.getLangName().toLowerCase() + "_open"
238
        };
239
    }
281 240

  
282
	public boolean isSaved() {
283
		return this.saved;
284
	}
241
    @Override
242
    public String getMainName() {
243
        return this.mainName;
244
    }
285 245

  
286
	public void addObserver(final Observer o) {
287
		this.delegatedObservable.addObserver(o);
288
	}
246
    @Override
247
    public void setMainName(final String mainName) {
248
        this.mainName = mainName;
249
    }
289 250

  
290
	public void deleteObserver(final Observer o) {
291
		this.delegatedObservable.deleteObserver(o);
292
	}
251
    public String getExtension() {
252
        return this.extension;
253
    }
293 254

  
294
	public void deleteObservers() {
295
		this.delegatedObservable.deleteObservers();
296
	}
255
    public void setExtension(final String extension) {
256
        if (!extension.startsWith(".")) {
257
            this.extension = "." + extension;
258
        } else {
259
            this.extension = extension;
260
        }
261
    }
297 262

  
298
	public void put(final String name, final Object value) {
299
		this.getEngine().put(name, value);
300
	}
263
    @Override
264
    public boolean isSaved() {
265
        return this.saved;
266
    }
301 267

  
302
	public void compile() {
303
		if (this.compiledCode == null) {
304
			ScriptEngine engine = this.getEngine();
305
			if (engine instanceof Compilable) {
306
				try {
307
					Compilable compilable = (Compilable) engine;
308
					this.compiledCode = compilable.compile(this.getPreparedCode());
309
					this.compiledCode.eval();
310
				} catch (ScriptException e) {
311
					CompileErrorException ce = new CompileErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
312
					notifyErrors(ce, "compile");
313
					throw ce;
314
				} catch (Throwable e) {
315
					CompileErrorException ce = new CompileErrorException(e.getMessage(), this.getName(), e);
316
					notifyErrors(new Exception(e), "compile");
317
					throw ce;
318
				}
319
			}
320
		}
321
	}
268
    @Override
269
    public void addObserver(final Observer o) {
270
        this.delegatedObservable.addObserver(o);
271
    }
322 272

  
323
	public Object run() {
324
		return this.run(null);
325
	}
326
	
327
	public void addDisposable(Disposable disposable){
328
		//pass
329
	}
273
    @Override
274
    public void deleteObserver(final Observer o) {
275
        this.delegatedObservable.deleteObserver(o);
276
    }
330 277

  
331
	public Object run(Object args[]) {
332
		if (args == null) {
333
			args = new Object[] {};
334
		}
335
		this.compile();
336
		return this.invokeFunction(this.getMainName(), args);
337
	}
278
    @Override
279
    public void deleteObservers() {
280
        this.delegatedObservable.deleteObservers();
281
    }
338 282

  
339
	public Object invokeFunction(final String name, Object args[]) {
340
		if (this.getEngine() instanceof Invocable) {
341
			Invocable invocable = (Invocable) this.getEngine();
342
			this.compile();
343
			if( args == null ) {
344
				args = new Object[] {};
345
			}
346
			try {
347
				return invocable.invokeFunction(name, args);
348
			} catch (ScriptException e) {
349
				ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
350
				notifyErrors(ee, "invoke");
351
				throw ee;
352
			} catch (Throwable e) {
353
				ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e);
354
				notifyErrors(ee, "invoke");
355
				throw ee;
356
			}
357
		} else {
358
			return null;
359
		}
360
	}
283
    @Override
284
    public void put(final String name, final Object value) {
285
        this.getEngine().put(name, value);
286
    }
361 287

  
362
	public Object invokeMethod(final Object obj, final String name, Object[] args)
363
			throws NoSuchMethodException {
288
    @Override
289
    public void compile() {
290
        if (this.compiledCode == null) {
291
            ScriptEngine engine = this.getEngine();
292
            if (engine instanceof Compilable) {
293
                try {
294
                    Compilable compilable = (Compilable) engine;
295
                    this.compiledCode = compilable.compile(this.getCode());
296
                    this.compiledCode.eval();
297
                } catch (ScriptException e) {
298
                    CompileErrorException ce = new CompileErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
299
                    notifyErrors(ce, "compile");
300
                    throw ce;
301
                } catch (Throwable e) {
302
                    CompileErrorException ce = new CompileErrorException(e.getMessage(), this.getName(), e);
303
                    notifyErrors(new Exception(e), "compile");
304
                    throw ce;
305
                }
306
            } else {
307
                String preparedCode = this.getCode();
308
                try {
309
                    engine.eval(preparedCode);
310
                } catch (ScriptException e) {
311
                    CompileErrorException ce = new CompileErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
312
                    notifyErrors(ce, "compile");
313
                    throw ce;
314
                }
315
            }
316
        }
317
    }
364 318

  
365
		if (this.getEngine() instanceof Invocable) {
366
			Invocable invocable = (Invocable) this.getEngine();
367
			this.compile();
368
			if( args == null ) {
369
				args = new Object[] {};
370
			}
371
			try {
372
				return invocable.invokeMethod(obj, name, args);
373
			} catch (ScriptException e) {
374
				ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
375
				notifyErrors(ee, "invoke");
376
				throw ee;
377
			} catch (Throwable e) {
378
				ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e);
379
				notifyErrors(ee, "invoke");
380
				throw ee;
381
			}
382
		} else {
383
			return null;
384
		}
385
	}
319
    public Object run() {
320
        return this.run(null);
321
    }
386 322

  
387
	public File getResource(String filename) {
388
		return new File( this.getParent().getFile(), filename);
389
	}
390
	
391
	class ScriptTask extends AbstractMonitorableTask {
323
    public void addDisposable(Disposable disposable) {
324
        //pass
325
    }
392 326

  
393
		ScriptingBaseScript script = null;
394
		Object[] args = null; 
395
		
396
		protected ScriptTask(ScriptingBaseScript script, Object[] args) {
397
			super(script.getName(),false);
398
			this.args = args;
399
			this.script = script;
400
			this.script.put("task",this);
401
			this.script.put("taskStatus",this.getTaskStatus());
402
		}
327
    @Override
328
    public Object run(Object args[]) {
329
        if (args == null) {
330
            args = new Object[]{};
331
        }
332
        this.compile();
333
        return this.invokeFunction(this.getMainName(), args);
334
    }
403 335

  
404
		public void run() {
405
			try {
406
				console_println("Running script "+ this.script.getName()+".");
407
				script.run(this.args);
408
				console_println("Script "+ this.script.getName()+ " terminated.");
409
			} catch(Throwable e) {
410
				console_println("Stript "+ this.script.getName()+ " aborted.");
411
			} finally {
412
				this.taskStatus.terminate();
413
				try {
414
					Thread.sleep(3000);
415
				} catch (InterruptedException e) {
416
					// Ignore
417
				}
418
				this.taskStatus.remove(); 
419
			}
420
		}
421
		
422
		public void showTaskStatus() {
423
			this.taskStatus.add();
424
		}
425
	}
426
	
427
	public void runAsTask(Object[] args) {
428
		ScriptTask task = new ScriptTask(this, args);
429
		task.start();
430
	}
336
    @Override
337
    public Object invokeFunction(final String name, Object args[]) {
338
        if (this.getEngine() instanceof Invocable) {
339
            Invocable invocable = (Invocable) this.getEngine();
340
            this.compile();
341
            if (args == null) {
342
                args = new Object[]{};
343
            }
344
            try {
345
                return invocable.invokeFunction(name, args);
346
            } catch (ScriptException e) {
347
                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
348
                notifyErrors(ee, "invoke");
349
                throw ee;
350
            } catch (Throwable e) {
351
                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e);
352
                notifyErrors(ee, "invoke");
353
                throw ee;
354
            }
355
        } else {
356
            return null;
357
        }
358
    }
431 359

  
432
	public boolean remove() {
433
		boolean r = true;
434
		File folder = this.getParent().getFile();
435
		File f = null;
436
		try {
437
			f = new File(folder,this.getId()+".inf");
438
			FileUtils.forceDelete(f);
439
		} catch (IOException e) {
440
			logger.warn("Can't remove inf file '"+f.getAbsolutePath()+"'.",e);
441
			r = false;
442
		}
443
		try {
444
			f = new File(folder,this.getId()+this.getExtension());
445
			FileUtils.forceDelete(f);
446
		} catch (IOException e) {
447
			logger.warn("Can't remove code file '"+f.getAbsolutePath()+"'.",e);
448
			r = false;
449
		}
450
		return r;
451
	}
360
    @Override
361
    public Object invokeMethod(final Object obj, final String name, Object[] args)
362
            throws NoSuchMethodException {
452 363

  
453
	public void create(ScriptingFolder folder, String id, String language) {
454
		this.setParent(folder);
455
		this.setId(id);
456
		if( language==null ) {
457
			this.setLangName("python");
458
		} else {
459
			this.setLangName(language);
460
		}
461
		this.setExtension(this.manager.getExtensionByLanguage(getLangName()));
364
        if (this.getEngine() instanceof Invocable) {
365
            Invocable invocable = (Invocable) this.getEngine();
366
            this.compile();
367
            if (args == null) {
368
                args = new Object[]{};
369
            }
370
            try {
371
                return invocable.invokeMethod(obj, name, args);
372
            } catch (ScriptException e) {
373
                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
374
                notifyErrors(ee, "invoke");
375
                throw ee;
376
            } catch (Throwable e) {
377
                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e);
378
                notifyErrors(ee, "invoke");
379
                throw ee;
380
            }
381
        } else {
382
            return null;
383
        }
384
    }
462 385

  
463
		File file = new File(folder.getFile(),id +".inf");
464
		try {
465
			file.createNewFile();
466
		} catch (IOException e) {
467
			logger.warn("Can't create file of the dialog in '"+file.getAbsolutePath()+"'.",e);
468
		}
386
    @Override
387
    public File getResource(String filename) {
388
        return new File(this.getParent().getFile(), filename);
389
    }
469 390

  
470
		if( "python".equalsIgnoreCase(this.getLangName()) ) {
471
			this.setCode("\nfrom gvsig import *\n\ndef main(*args):\n    #Remove this lines and add here your code\n\n    print \"hola mundo\"\n    pass\n\n");
472
		}
473
		this.save();
474
	}
391
    @Override
392
    public String getMimeType() {
393
        return "text/"+ this.getLangName();
394
    }
475 395

  
476
	public ScriptingUnit get(String name) {
477
		return this.manager.getScript(name);
478
	}
479
 }
396
    class ScriptTask extends AbstractMonitorableTask {
397

  
398
        ScriptingBaseScript script = null;
399
        Object[] args = null;
400

  
401
        protected ScriptTask(ScriptingBaseScript script, Object[] args) {
402
            super(script.getName(), false);
403
            this.args = args;
404
            this.script = script;
405
            this.script.put("task", this);
406
            this.script.put("taskStatus", this.getTaskStatus());
407
        }
408

  
409
        @Override
410
        public void run() {
411
            try {
412
                console_println("Running script " + this.script.getName() + ".");
413
                script.run(this.args);
414
                console_println("Script " + this.script.getName() + " terminated.");
415
            } catch (Throwable e) {
416
                console_println("Stript " + this.script.getName() + " aborted.");
417
            } finally {
418
                this.taskStatus.terminate();
419
                try {
420
                    Thread.sleep(3000);
421
                } catch (InterruptedException e) {
422
                    // Ignore
423
                }
424
                this.taskStatus.remove();
425
            }
426
        }
427

  
428
        public void showTaskStatus() {
429
            this.taskStatus.add();
430
        }
431
    }
432

  
433
    @Override
434
    public void runAsTask(Object[] args) {
435
        ScriptTask task = new ScriptTask(this, args);
436
        task.start();
437
    }
438

  
439
    @Override
440
    public boolean remove() {
441
        boolean r = true;
442
        File folder = this.getParent().getFile();
443
        File f = new File(folder, this.getId() + ".inf");
444
        try {
445
            FileUtils.forceDelete(f);
446
        } catch (IOException e) {
447
            logger.warn("Can't remove inf file '" + f.getAbsolutePath() + "'.", e);
448
            r = false;
449
        }
450
        try {
451
            f = new File(folder, this.getId() + this.getExtension());
452
            FileUtils.forceDelete(f);
453
        } catch (IOException e) {
454
            logger.warn("Can't remove code file '" + f.getAbsolutePath() + "'.", e);
455
            r = false;
456
        }
457
        return r;
458
    }
459

  
460
    @Override
461
    public void create(ScriptingFolder folder, String id, String language) {
462
        this.setParent(folder);
463
        this.setId(id);
464
        if (language == null) {
465
            this.setLangName("python");
466
        } else {
467
            this.setLangName(language);
468
        }
469
        this.setExtension(this.manager.getExtensionOfLanguage(getLangName()));
470

  
471
        File file = new File(folder.getFile(), id + ".inf");
472
        try {
473
            file.createNewFile();
474
        } catch (IOException e) {
475
            logger.warn("Can't create file of the dialog in '" + file.getAbsolutePath() + "'.", e);
476
        }
477
        String template = this.getNewTemplate();
478
        if( template != null ) {
479
            this.setCode(template);
480
        }
481
        this.save();
482
    }
483

  
484
    public String getNewTemplate() {
485
        String name = "org/gvsig/scripting/langs/"+this.getLangName().toLowerCase()+"/new_template.txt";
486
        try {
487
            InputStream template = this.getClass().getClassLoader().getResourceAsStream(name);
488
            if( template == null ) {
489
                return null;
490
            }
491
            List<String> lines = IOUtils.readLines(template);
492
            return StringUtils.join(lines, "\n");
493
        } catch (Exception ex) {
494
            logger.warn("Can't load new-template from '"+name+"'.",ex);
495
            return null;
496
        }
497
    }
498
    
499
    public ScriptingUnit get(String name) {
500
        return this.manager.getScript(name);
501
    }
502
}

Also available in: Unified diff