001package votorola.g.script; // Copyright 2008, Michael Allan.  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Votorola Software"), to deal in the Votorola Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Votorola Software, and to permit persons to whom the Votorola Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Votorola Software. THE VOTOROLA SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE VOTOROLA SOFTWARE OR THE USE OR OTHER DEALINGS IN THE VOTOROLA SOFTWARE.
002
003import java.io.*;
004import javax.script.*;
005import votorola.g.lang.*;
006
007
008/** Script engine utilities.
009  */
010public @ThreadSafe final class ScriptEngineX
011{
012
013
014    private ScriptEngineX() {}
015
016
017
018    /** Same as engine.{@linkplain ScriptEngine#eval(String) eval}(script),
019      * except that the source of the script is provided as a file.
020      *
021      *     @param file script file, encoded in UTF-8
022      *     @return the value returned by the script
023      */
024    public static Object eval( final File file, final ScriptEngine engine )
025      throws IOException, ScriptException
026    {
027        final BufferedReader reader = new BufferedReader( new InputStreamReader(
028          new FileInputStream( file ), "UTF-8" ));
029        try
030        {
031            engine.put( ScriptEngine.FILENAME, file.getPath() ); // for nicer error messages
032            return engine.eval( reader );
033        }
034        finally{ reader.close(); }
035    }
036
037
038
039    /** Same as engine.{@linkplain ScriptEngine#eval(String) eval}(script),
040      * except that the source of the script is provided as a file path.
041      *
042      *     @param path to UTF-8 encoded script file
043      *       (without any shell variable, or tilde ~ in the path string)
044      *     @return the value returned by the script
045      */
046    public static Object eval( String path, ScriptEngine engine )
047      throws IOException, ScriptException
048    {
049        return eval( new File(path), engine );
050    }
051
052
053
054}