1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.module.groovy.task;
35
36 import java.io.File;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.StringWriter;
40 import java.net.URL;
41
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import groovy.lang.Binding;
46 import groovy.lang.GroovyRuntimeException;
47 import info.magnolia.cms.util.ClasspathResourcesUtil;
48 import info.magnolia.module.InstallContext;
49 import info.magnolia.module.delta.AbstractTask;
50 import info.magnolia.module.delta.TaskExecutionException;
51 import info.magnolia.module.groovy.console.MgnlGroovyConsole;
52
53
54
55
56
57
58
59 public class ExecuteGroovyFileTask extends AbstractTask {
60
61
62 private static final Logger log = LoggerFactory.getLogger(ExecuteGroovyFileTask.class);
63
64 private MgnlGroovyConsole console;
65
66 private String inputFile;
67
68 public ExecuteGroovyFileTask(String taskName, String taskDescription, String inputFile) {
69 super(taskName, taskDescription);
70 this.inputFile = inputFile;
71 }
72
73 @Override
74 public void execute(InstallContext installContext) throws TaskExecutionException {
75 try {
76
77 console = new MgnlGroovyConsole(new Binding());
78
79 executeGroovyScript(installContext);
80 }
81 catch (Exception e) {
82 throw new TaskExecutionException("Could not execute the groovy File '" + inputFile +"': " + e.getMessage(), e);
83 }
84 }
85
86 private void executeGroovyScript(InstallContext installContext) throws Exception {
87
88
89 if (this.inputFile == null) {
90 throw new IOException("Input File is Null");
91 }
92
93
94 URL inFile = ClasspathResourcesUtil.getResource(this.inputFile);
95 if (inFile == null) {
96 throw new IOException("Can't find resource file at " + this.inputFile);
97 }
98
99 final InputStream inputStream = ClasspathResourcesUtil.getResource(this.inputFile).openStream();
100 if (inputStream == null) {
101 throw new IOException("Can't find resource file at " + inFile.getFile());
102 }
103
104 Object lastResult = null;
105 StringWriter outputStream = new StringWriter();
106 try {
107 lastResult = console.evaluate(inputStream, (new File(inFile.getFile())).getName(), outputStream);
108
109 if (lastResult != null) {
110 outputStream.getBuffer().append(lastResult);
111 }
112 outputStream.flush();
113 installContext.info(outputStream.toString());
114 }
115 catch (GroovyRuntimeException e) {
116 log.error("Got a Groovy Execution Error", e);
117 throw e;
118 }
119 finally {
120 outputStream.close();
121 inputStream.close();
122 }
123 }
124 }