Statistics
| Revision:

gvsig-scripting / 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 @ 391

History | View | Annotate | Download (8.67 KB)

1
package org.gvsig.scripting.impl;
2

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

    
10
import javax.script.Compilable;
11
import javax.script.CompiledScript;
12
import javax.script.Invocable;
13
import javax.script.ScriptEngine;
14
import javax.script.ScriptException;
15

    
16
import org.gvsig.scripting.CompileErrorException;
17
import org.gvsig.scripting.ExecuteErrorException;
18
import org.gvsig.scripting.ScriptingFolder;
19
import org.gvsig.scripting.ScriptingManager;
20
import org.gvsig.scripting.ScriptingScript;
21
import org.gvsig.tools.dispose.Disposable;
22
import org.gvsig.tools.observer.Observer;
23
import org.gvsig.tools.observer.impl.DelegateWeakReferencingObservable;
24
import org.ini4j.Ini;
25
import org.ini4j.InvalidFileFormatException;
26

    
27
@SuppressWarnings("restriction")
28
public class DefaultScriptingScript extends AbstractScript implements
29
                ScriptingScript {
30

    
31
        protected String langName;
32
        protected String extension = null;
33
        protected ScriptEngine engine = null;
34
        protected CompiledScript compiledCode;
35

    
36
        private String code = null;
37
        private String mainName = "main";
38
        private boolean saved;
39
        private final DelegateWeakReferencingObservable delegatedObservable;
40

    
41
        public DefaultScriptingScript(ScriptingManager manager) {
42
                super(manager);
43
                this.setLangName("python");
44
                this.setSaved(true);
45
                this.delegatedObservable = new DelegateWeakReferencingObservable(this);
46
        }
47

    
48
        protected void notifyErrors(Exception exception, String command) {
49
                this.delegatedObservable.notifyObservers(new BaseScriptingNotifycation(
50
                                this, BaseScriptingNotifycation.RUNTIME_ERROR_NOTIFICATION,
51
                                command, exception));
52
        }
53

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

    
60
        public void setSaved(boolean saved) {
61
                this.saved = saved;
62
        }
63

    
64
        public String getCode() {
65
                if (this.code != null) {
66
                        return this.code;
67
                }
68
                return DefaultScriptingManager.getStringFromFile(this.getFileResource(
69
                                this.extension).getAbsolutePath());
70
        }
71

    
72
        public void setCode(String code) {
73
                this.code = code;
74
                this.engine = null;
75
                this.compiledCode = null;
76
                this.setSaved(false);
77
        }
78

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

    
95
                if (code == null) {
96
                        code = this.getCode();
97
                } else {
98
                        code = code + this.getCode();
99
                }
100
                return code;
101
        }
102

    
103
        protected ScriptEngine getEngine() {
104
                if (this.engine == null) {
105
                        ScriptEngine scriptEngine = this.manager.getEngine(this
106
                                        .getLangName());
107
                        scriptEngine.put("script", this);
108
                        this.engine = scriptEngine;
109
                }
110
                return this.engine;
111
        }
112

    
113
        @Override
114
        protected void loadInf(Ini prefs) {
115
                super.loadInf(prefs);
116

    
117
                this.setMainName((String) getInfValue(prefs, "Script", "main", "main"));
118
                this.setLangName((String) getInfValue(prefs, "Script", "Lang",
119
                                this.getLangName()));
120
        }
121

    
122
        @Override
123
        public void load(ScriptingFolder folder, String id) {
124
                this.setId(id);
125
                this.setParent(folder);
126

    
127
                Map<String, String> languages = this.manager
128
                                .getSupportedLanguagesByExtension();
129
                String s[] = id.split("\\.");
130
                if (s.length >= 2) {
131
                        String extension = "." + s[s.length - 1];
132
                        String langName = languages.get(extension);
133
                        this.setLangName(langName);
134
                        this.setExtension(extension);
135
                }
136

    
137
                File f = getFileResource(".inf");
138
                if (f.isFile()) {
139
                        Ini prefs = null;
140

    
141
                        try {
142
                                prefs = new Ini(f);
143
                        } catch (InvalidFileFormatException e) {
144
                                e.printStackTrace();
145
                        } catch (IOException e) {
146
                                e.printStackTrace();
147
                        }
148

    
149
                        loadInf(prefs);
150
                }
151
                this.setSaved(true);
152
        }
153

    
154
        public void save() {
155
                File f = getFileResource(".inf");
156
                if (!f.isFile()) {
157
                        try {
158
                                f.createNewFile();
159
                        } catch (IOException e) {
160
                                e.printStackTrace();
161
                        }
162
                }
163

    
164
                Ini prefs = null;
165

    
166
                try {
167
                        prefs = new Ini(f);
168
                } catch (InvalidFileFormatException e) {
169
                        e.printStackTrace();
170
                } catch (IOException e) {
171
                        e.printStackTrace();
172
                }
173

    
174
                save(prefs);
175

    
176
                // Guardo el codigo en el fichero
177
                try {
178
                        FileWriter fstream = new FileWriter(
179
                                        ((DefaultScriptingFolder) this.getParent()).getPath()
180
                                                        + File.separator + this.getId()
181
                                                        + this.getExtension());
182
                        BufferedWriter out = new BufferedWriter(fstream);
183
                        out.write(this.getCode());
184
                        out.close();
185
                } catch (Exception e) {
186
                        System.err.println("Error: " + e.getMessage());
187
                }
188
                this.setSaved(true);
189
        }
190

    
191
        protected void save(Ini prefs) {
192
                super.save(prefs);
193
                prefs.put("Script", "main", this.getMainName());
194
                prefs.put("Script", "Lang", this.getLangName());
195
                try {
196
                        prefs.store();
197
                } catch (IOException e) {
198
                        // TODO Auto-generated catch block
199
                        e.printStackTrace();
200
                }
201

    
202
        }
203

    
204
        public String getLangName() {
205
                return this.langName;
206
        }
207

    
208
        protected void setLangName(final String langName) {
209
                this.langName = langName;
210
                this.extension = this.manager.getExtensionByLanguage(this.langName);
211
        }
212

    
213
        public String[] getIconNames() {
214
                return new String[] { "scripting_" + this.getLangName().toLowerCase(),
215
                                null };
216
        }
217

    
218
        public String getMainName() {
219
                return this.mainName;
220
        }
221

    
222
        public void setMainName(final String mainName) {
223
                this.mainName = mainName;
224
        }
225

    
226
        public String getExtension() {
227
                return this.extension;
228
        }
229

    
230
        public void setExtension(final String extension) {
231
                this.extension = extension;
232
        }
233

    
234
        public boolean isSaved() {
235
                return this.saved;
236
        }
237

    
238
        public void addObserver(final Observer o) {
239
                this.delegatedObservable.addObserver(o);
240
        }
241

    
242
        public void deleteObserver(final Observer o) {
243
                this.delegatedObservable.deleteObserver(o);
244
        }
245

    
246
        public void deleteObservers() {
247
                this.delegatedObservable.deleteObservers();
248
        }
249

    
250
        public void put(final String name, final Object value) {
251
                this.getEngine().put(name, value);
252
        }
253

    
254
        public void compile() {
255
                if (this.compiledCode == null) {
256
                        ScriptEngine engine = this.getEngine();
257
                        if (engine instanceof Compilable) {
258
                                try {
259
                                        Compilable compilable = (Compilable) engine;
260
                                        this.compiledCode = compilable.compile(this.getPreparedCode());
261
                                        this.compiledCode.eval();
262
                                } catch (ScriptException e) {
263
                                        CompileErrorException ce = new CompileErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
264
                                        notifyErrors(ce, "compile");
265
                                        throw ce;
266
                                } catch (Throwable e) {
267
                                        CompileErrorException ce = new CompileErrorException(e.getMessage(), this.getName(), e);
268
                                        notifyErrors(new Exception(e), "compile");
269
                                        throw ce;
270
                                }
271
                        }
272
                }
273
        }
274

    
275
        public Object run() {
276
                return this.run(null);
277
        }
278
        
279
        public void addDisposable(Disposable disposable){
280
                //pass
281
        }
282

    
283
        public Object run(Object args[]) {
284
                if (args == null) {
285
                        args = new Object[] {};
286
                }
287
                this.compile();
288
                return this.invokeFunction(this.getMainName(), args);
289
        }
290

    
291
        public Object invokeFunction(final String name, Object args[]) {
292
                if (this.getEngine() instanceof Invocable) {
293
                        Invocable invocable = (Invocable) this.getEngine();
294
                        this.compile();
295
                        if( args == null ) {
296
                                args = new Object[] {};
297
                        }
298
                        try {
299
                                return invocable.invokeFunction(name, args);
300
                        } catch (ScriptException e) {
301
                                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
302
                                notifyErrors(ee, "invoke");
303
                                throw ee;
304
                        } catch (Throwable e) {
305
                                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e);
306
                                notifyErrors(ee, "invoke");
307
                                throw ee;
308
                        }
309
                } else {
310
                        return null;
311
                }
312
        }
313

    
314
        public Object invokeMethod(final Object obj, final String name, Object[] args)
315
                        throws NoSuchMethodException {
316

    
317
                if (this.getEngine() instanceof Invocable) {
318
                        Invocable invocable = (Invocable) this.getEngine();
319
                        this.compile();
320
                        if( args == null ) {
321
                                args = new Object[] {};
322
                        }
323
                        try {
324
                                return invocable.invokeMethod(obj, name, args);
325
                        } catch (ScriptException e) {
326
                                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e.getLineNumber(), e.getColumnNumber(), e);
327
                                notifyErrors(ee, "invoke");
328
                                throw ee;
329
                        } catch (Throwable e) {
330
                                ExecuteErrorException ee = new ExecuteErrorException(e.getMessage(), this.getName(), e);
331
                                notifyErrors(ee, "invoke");
332
                                throw ee;
333
                        }
334
                } else {
335
                        return null;
336
                }
337
        }
338

    
339
        public File getResource(String filename) {
340
                return new File( this.getParent().getPathFile(), filename);
341
        }
342
}