Code

First commit for java binding
[inkscape.git] / src / bind / java / org / inkscape / cmn / ScriptRunner.java
1 /**
2  * This is a simple mechanism to bind Inkscape to Java, and thence
3  * to all of the nice things that can be layered upon that.
4  *
5  * Authors:
6  *   Bob Jamison
7  *
8  * Copyright (C) 2007 Bob Jamison
9  *
10  *  This library is free software; you can redistribute it and/or
11  *  modify it under the terms of the GNU Lesser General Public
12  *  License as published by the Free Software Foundation; either
13  *  version 2.1 of the License, or (at your option) any later version.
14  *
15  *  This library is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  *  Lesser General Public License for more details.
19  *
20  *  You should have received a copy of the GNU Lesser General Public
21  *  License along with this library; if not, write to the Free Software
22  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23  */
25 package org.inkscape.cmn;
27 import javax.script.*;
28 import java.io.FileReader;
29 import java.io.IOException;
30 import javax.swing.JOptionPane;
35 public class ScriptRunner
36 {
40 static void err(String message)
41 {
42     JOptionPane.showMessageDialog(null, message,
43                "Script Error", JOptionPane.ERROR_MESSAGE);
44 }
48 public static boolean run(String lang, String str)
49 {
50     ScriptEngineManager factory = new ScriptEngineManager();
51     // create JavaScript engine
52     ScriptEngine engine = factory.getEngineByName(lang);
53     // evaluate JavaScript code from given file - specified by first argument
54     try
55         {
56         engine.eval(str);
57         }
58     catch (javax.script.ScriptException e)
59         {
60         err("Executing script: " + e);
61         }
62     return true;
63 }
65 public static boolean runFile(String lang, String fname)
66 {
67     ScriptEngineManager factory = new ScriptEngineManager();
68     // create JavaScript engine
69     ScriptEngine engine = factory.getEngineByName(lang);
70     // evaluate JavaScript code from given file - specified by first argument
71     FileReader in = null;
72     boolean ret = true;
73     try
74         {
75         in = new FileReader(fname);
76         }
77     catch (java.io.IOException e)
78         {
79         err("Executing file: " + e);
80         return false;
81         }
82     try
83         {
84         engine.eval(in);
85         }
86     catch (javax.script.ScriptException e)
87         {
88         err("Executing file: " + e);
89         ret = false;
90         }
91     try
92         {
93         in.close();
94         }
95     catch (java.io.IOException e)
96         {
97         err("Executing file: " + e);
98         return false;
99         }
100     return ret;