1 package org.apache.maven.plugins.scripting;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileReader;
24 import java.io.IOException;
25 import java.io.UncheckedIOException;
26
27 import javax.script.ScriptContext;
28 import javax.script.ScriptEngine;
29 import javax.script.ScriptEngineManager;
30 import javax.script.ScriptException;
31
32
33
34
35
36
37 public class FileScriptEvaluator extends AbstractScriptEvaluator
38 {
39
40
41
42
43 private final File scriptFile;
44
45
46
47
48 private final String engineName;
49
50
51
52
53
54 public FileScriptEvaluator( String engineName, File scriptFile )
55 {
56 this.scriptFile = scriptFile;
57
58 this.engineName = engineName;
59 }
60
61
62
63
64
65
66
67
68 protected Object eval( ScriptEngine engine, ScriptContext context ) throws ScriptException
69 {
70 try ( FileReader reader = new FileReader( scriptFile ) )
71 {
72 return engine.eval( reader, context );
73 }
74 catch ( IOException ex )
75 {
76 throw new UncheckedIOException( scriptFile + " caused:", ex );
77 }
78 }
79
80
81
82
83
84
85
86
87 protected ScriptEngine getEngine( ScriptEngineManager manager ) throws UnsupportedScriptEngineException
88 {
89 ScriptEngine result;
90
91 if ( engineName != null && !engineName.isEmpty() )
92 {
93 result = manager.getEngineByName( engineName );
94
95 if ( result == null )
96 {
97 throw new UnsupportedScriptEngineException( "No engine found by name \"" + engineName + "\n" );
98 }
99 }
100 else
101 {
102 String extension = scriptFile.getName();
103 int position = extension.indexOf( "." );
104
105 if ( position >= 0 )
106 {
107 extension = extension.substring( position + 1 );
108 }
109 result = manager.getEngineByExtension( extension );
110
111 if ( result == null )
112 {
113 throw new UnsupportedScriptEngineException( "No engine found by extension \"" + extension + "\n" );
114 }
115 }
116 return result;
117 }
118 }