Skip to content

Instantly share code, notes, and snippets.

@aginor
Created September 25, 2012 03:27
Show Gist options
  • Save aginor/3779812 to your computer and use it in GitHub Desktop.
Save aginor/3779812 to your computer and use it in GitHub Desktop.
Added the load functionality to the java javascript scripting engine and deal with
/*
Copyright (C) 2012 Andreas Löf
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.*;
public class ScriptFromFile {
private final ScriptEngine engine;
private String scriptroot;
public ScriptFromFile() throws ScriptException {
ScriptEngineManager factory = new ScriptEngineManager();
this.engine = factory.getEngineByName("JavaScript");
this.engine.put("ScriptFromFile", this);
this.engine.eval("function load(filename) { ScriptFromFile.load(filename); }");
}
public static void main(String args[]) throws FileNotFoundException, ScriptException {
new ScriptFromFile().load(args[0]);
}
public void load(String filename) throws ScriptException {
try {
String sep = System.getProperty("file.separator");
filename = filename.replace("\\", sep);
filename = filename.replace("/", sep);
System.out.println("loading> " + filename);
if(scriptroot == null) {
scriptroot = filename.substring(0,filename.lastIndexOf(sep));
}
if(scriptroot != null && filename.startsWith("."+sep)) {
filename = scriptroot + sep + filename.substring(2);
}
else if(scriptroot != null && filename.startsWith(".."+sep)) {
filename = scriptroot + sep + filename;
}
this.engine.eval(new FileReader(filename));
}
catch(FileNotFoundException e) {
throw new RuntimeException("Error loading javascript file: " + filename, e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment