Revision 441 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
1 1
package org.gvsig.scripting.impl;
2 2

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

  
......
13 12
import javax.script.ScriptEngine;
14 13
import javax.script.ScriptException;
15 14

  
15
import org.apache.commons.io.FileUtils;
16
import org.apache.commons.io.FilenameUtils;
17
import org.apache.commons.io.IOUtils;
16 18
import org.gvsig.scripting.CompileErrorException;
17 19
import org.gvsig.scripting.ExecuteErrorException;
18 20
import org.gvsig.scripting.ScriptingBaseScript;
......
24 26
import org.gvsig.tools.observer.impl.DelegateWeakReferencingObservable;
25 27
import org.gvsig.tools.task.AbstractMonitorableTask;
26 28
import org.ini4j.Ini;
27
import org.ini4j.InvalidFileFormatException;
29
import org.slf4j.Logger;
30
import org.slf4j.LoggerFactory;
28 31

  
29
@SuppressWarnings("restriction")
30 32
public class DefaultScriptingScript extends AbstractScript implements
31 33
		ScriptingScript {
32

  
34
	
35
	private static final Logger logger = LoggerFactory.getLogger(DefaultScriptingScript.class);
33 36
	protected String langName;
34 37
	protected String extension = null;
35 38
	protected ScriptEngine engine = null;
......
40 43
	private boolean saved;
41 44
	private final DelegateWeakReferencingObservable delegatedObservable;
42 45

  
43
	public DefaultScriptingScript(ScriptingManager manager) {
44
		super(manager);
46
	protected DefaultScriptingScript(ScriptingFolder parent, String typename, ScriptingManager manager, String id) {
47
		super(parent, typename, manager, id);
45 48
		this.setLangName("python");
46 49
		this.setSaved(true);
47 50
		this.delegatedObservable = new DelegateWeakReferencingObservable(this);
48 51
	}
52
	
53
	public DefaultScriptingScript(ScriptingFolder parent, ScriptingManager manager, String id) {
54
		this(parent, ScriptingManager.UNIT_SCRIPT, manager, id);
55
	}
49 56

  
50 57
	protected void notifyErrors(Exception exception, String command) {
51 58
		this.delegatedObservable.notifyObservers(new BaseScriptingNotifycation(
......
53 60
				command, exception));
54 61
	}
55 62

  
56
//	protected void launchCompilingException(Exception exception, String command) {
57
//		this.delegatedObservable.notifyObservers(new BaseScriptingNotifycation(
58
//				this, BaseScriptingNotifycation.COMPILE_ERROR_NOTIFICATION,
59
//				command, exception));
60
//	}
61

  
62 63
	public void setSaved(boolean saved) {
63 64
		this.saved = saved;
64 65
	}
65 66

  
66 67
	public String getCode() {
67
		if (this.code != null) {
68
			return this.code;
68
		if (this.code == null) {
69
			File f=null;
70
			try {
71
				f = this.getFileResource(this.extension);
72
				this.code = FileUtils.readFileToString(f);
73
			} catch (IOException e) {
74
				String fname = (f==null)? "(null)":f.getAbsolutePath();
75
				logger.warn("Can't load code from file '"+fname+"'.");
76
			}
69 77
		}
70
		return DefaultScriptingManager.getStringFromFile(this.getFileResource(
71
				this.extension).getAbsolutePath());
78
		return this.code;
72 79
	}
73 80

  
74 81
	public void setCode(String code) {
......
79 86
	}
80 87

  
81 88
	private String getPreparedCode() {
82
		String code = null;
83
		if ("python".equalsIgnoreCase(this.getLangName())) {
84
			List<File> libFolders = this.manager.getLibFolders();
85
			if (libFolders != null && libFolders.size() > 0) {
86
				StringBuffer buffer = new StringBuffer();
87
				buffer.append("import sys;");
88
				for (File file : libFolders) {
89
					buffer.append("sys.path.append(r'");
90
					buffer.append(file.getAbsolutePath());
91
					buffer.append("');");
92
				}
93
				code = buffer.toString();
89
		return this.getCode();
90
	}
91

  
92
	protected String getCodeToInitializeEngine() {
93
		List<File> libFolders = this.manager.getLibFolders();
94
		if (libFolders == null || libFolders.size() < 1) {
95
			return null;
96
		}
97
		StringBuffer buffer = new StringBuffer();
98
		buffer.append("import sys\n");
99
		buffer.append("sys_path = list()\n");
100
		for (File file : libFolders) {
101
			buffer.append("sys_path.append(r'");
102
			buffer.append(file.getAbsolutePath());
103
			buffer.append("')\n");
104
		}
105
		buffer.append("sys.path.extend(sys_path)\n\n\n");
106
		String resname = "/org/gvsig/scripting/impl/InitializaEngine.py";
107
		InputStream code_is = this.getClass().getResourceAsStream(resname); 
108
		if( code_is != null ) {
109
			try {
110
				String code = IOUtils.toString(code_is);
111
				buffer.append(code);
112
			} catch (IOException e) {
113
				logger.warn("Can't read code to initialize engine from resource '"+resname+"'.",e);
94 114
			}
95
		}
96

  
97
		if (code == null) {
98
			code = this.getCode();
99 115
		} else {
100
			code = code + this.getCode();
116
			logger.warn("Can't open resurce '"+resname+"'.");
101 117
		}
102
		return code;
118
		return buffer.toString();
103 119
	}
104

  
120
	
105 121
	protected ScriptEngine getEngine() {
106 122
		if (this.engine == null) {
107 123
			ScriptEngine scriptEngine = this.manager.getEngine(this
108 124
					.getLangName());
109 125
			scriptEngine.put("script", this);
110 126
			this.engine = scriptEngine;
127
			try {
128
				String code = this.getCodeToInitializeEngine();
129
				if( code != null ) {
130
					this.engine.eval(code);
131
				}
132
			} catch(Exception ex) {
133
				logger.warn("Can't initialize engine with the code:\n"+code);
134
			}
111 135
		}
112 136
		return this.engine;
113 137
	}
114 138

  
115
	@Override
116 139
	protected void loadInf(Ini prefs) {
117 140
		super.loadInf(prefs);
118 141

  
......
121 144
				this.getLangName()));
122 145
	}
123 146

  
124
	@Override
125 147
	public void load(ScriptingFolder folder, String id) {
126 148
		this.setId(id);
127 149
		this.setParent(folder);
128 150

  
129 151
		Map<String, String> languages = this.manager
130 152
				.getSupportedLanguagesByExtension();
131
		String s[] = id.split("\\.");
132
		if (s.length >= 2) {
133
			String extension = "." + s[s.length - 1];
134
			String langName = languages.get(extension);
135
			this.setLangName(langName);
136
			this.setExtension(extension);
137
		}
153
		String extension = FilenameUtils.getExtension(id);
154
		String langName = languages.get(extension);
155
		this.setLangName(langName);
156
		this.setExtension(extension);
138 157

  
139 158
		File f = getFileResource(".inf");
140 159
		if (f.isFile()) {
141 160
			Ini prefs = null;
142

  
143 161
			try {
144 162
				prefs = new Ini(f);
145
			} catch (InvalidFileFormatException e) {
146
				e.printStackTrace();
147
			} catch (IOException e) {
148
				e.printStackTrace();
163
			} catch (Exception e) {
164
				logger.warn("Can't load 'inf' file '"+f.getAbsolutePath()+"'.",e);
149 165
			}
150

  
151 166
			loadInf(prefs);
152 167
		}
153 168
		this.setSaved(true);
......
158 173
		if (!f.isFile()) {
159 174
			try {
160 175
				f.createNewFile();
161
			} catch (IOException e) {
162
				e.printStackTrace();
176
			} catch (Exception e) {
177
				logger.warn("Can't create 'inf' file '"+f.getAbsolutePath()+"'.",e);
163 178
			}
164 179
		}
165

  
166 180
		Ini prefs = null;
167

  
168 181
		try {
169 182
			prefs = new Ini(f);
170
		} catch (InvalidFileFormatException e) {
171
			e.printStackTrace();
172
		} catch (IOException e) {
173
			e.printStackTrace();
183
		} catch (Exception e) {
184
			logger.warn("Can't load 'inf' file '"+f.getAbsolutePath()+"'.",e);
174 185
		}
175

  
176 186
		save(prefs);
177

  
178 187
		// Guardo el codigo en el fichero
188
		File fcode = null;
179 189
		try {
180
			FileWriter fstream = new FileWriter(
181
					((DefaultScriptingFolder) this.getParent()).getPath()
182
							+ File.separator + this.getId()
183
							+ this.getExtension());
184
			BufferedWriter out = new BufferedWriter(fstream);
185
			out.write(this.getCode());
186
			out.close();
190
			fcode = this.getFileResource(this.getExtension());
191
			FileUtils.write(fcode, this.getCode());
187 192
		} catch (Exception e) {
188
			System.err.println("Error: " + e.getMessage());
193
			logger.warn("Can't write code to file '"+fcode.getAbsolutePath()+"'.",e);
189 194
		}
190 195
		this.setSaved(true);
191 196
	}
......
197 202
		try {
198 203
			prefs.store();
199 204
		} catch (IOException e) {
200
			// TODO Auto-generated catch block
201
			e.printStackTrace();
205
			String fname = (prefs.getFile()==null)? "(null)" : prefs.getFile().getAbsolutePath(); 
206
			logger.warn("Can't save inf file ("+fname+").",e);
202 207
		}
203 208

  
204 209
	}
......
213 218
	}
214 219

  
215 220
	public String[] getIconNames() {
216
		return new String[] { "scripting_" + this.getLangName().toLowerCase(),
217
				null };
221
		return new String[] { 
222
				"scripting_" + this.getLangName().toLowerCase(),
223
				"scripting_" + this.getLangName().toLowerCase() + "_open"
224
		};
218 225
	}
219 226

  
220 227
	public String getMainName() {
......
230 237
	}
231 238

  
232 239
	public void setExtension(final String extension) {
233
		this.extension = extension;
240
		if( !extension.startsWith(".") ) {
241
			this.extension = "." + extension;
242
		} else {
243
			this.extension = extension;	
244
		}
234 245
	}
235 246

  
236 247
	public boolean isSaved() {
......
339 350
	}
340 351

  
341 352
	public File getResource(String filename) {
342
		return new File( this.getParent().getPathFile(), filename);
353
		return new File( this.getParent().getFile(), filename);
343 354
	}
344 355
	
345 356
	class ScriptTask extends AbstractMonitorableTask {
......
354 365
			this.script.put("task",this);
355 366
			this.script.put("taskStatus",this.getTaskStatus());
356 367
		}
357
		
368

  
358 369
		public void run() {
359 370
			try {
360
				// When running from the composer messages of stdout shows in the console tab.
361
				System.out.println("Running script "+ this.script.getName()+".");
371
				console_println("Running script "+ this.script.getName()+".");
362 372
				script.run(this.args);
363
				System.out.println("Script "+ this.script.getName()+ " terminated.");
373
				console_println("Script "+ this.script.getName()+ " terminated.");
364 374
			} catch(Throwable e) {
365
				System.out.println("Stript "+ this.script.getName()+ " aborted.");
375
				console_println("Stript "+ this.script.getName()+ " aborted.");
366 376
			} finally {
367 377
				this.taskStatus.terminate();
368 378
				try {
......
384 394
		task.start();
385 395
	}
386 396

  
397
	public boolean remove() {
398
		boolean r = true;
399
		File folder = this.getParent().getFile();
400
		File f = null;
401
		try {
402
			f = new File(folder,this.getId()+".inf");
403
			FileUtils.forceDelete(f);
404
		} catch (IOException e) {
405
			logger.warn("Can't remove inf file '"+f.getAbsolutePath()+"'.",e);
406
			r = false;
407
		}
408
		try {
409
			f = new File(folder,this.getId()+this.getExtension());
410
			FileUtils.forceDelete(f);
411
		} catch (IOException e) {
412
			logger.warn("Can't remove code file '"+f.getAbsolutePath()+"'.",e);
413
			r = false;
414
		}
415
		return r;
416
	}
417

  
418
	public void create(ScriptingFolder folder, String id, String language) {
419
		this.setParent(folder);
420
		this.setId(id);
421
		if( language==null ) {
422
			this.setLangName("python");
423
		} else {
424
			this.setLangName(language);
425
		}
426
		this.setExtension(this.manager.getExtensionByLanguage(getLangName()));
427

  
428
		File file = new File(folder.getFile(),id +".inf");
429
		try {
430
			file.createNewFile();
431
		} catch (IOException e) {
432
			logger.warn("Can't create file of the dialog in '"+file.getAbsolutePath()+"'.",e);
433
		}
434

  
435
		if( "python".equalsIgnoreCase(this.getLangName()) ) {
436
			this.setCode("\nfrom gvsig import *\n\ndef main():\n    #Remove this lines and add here your code\n\n    print \"hola mundo\"\n    pass\n\n");
437
		}
438
		this.save();
439
	}
440

  
387 441
}

Also available in: Unified diff