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
60 public class ExecuteGroovyFileTask extends AbstractTask {
61
62
63 private static final Logger log = LoggerFactory.getLogger(ExecuteGroovyFileTask.class);
64
65 private MgnlGroovyConsole console;
66
67 private String inputFile;
68
69 public ExecuteGroovyFileTask(String taskName, String taskDescription, String inputFile) {
70 super(taskName, taskDescription);
71 this.inputFile = inputFile;
72 }
73
74
75 @Override
76 public void execute(InstallContext installContext) throws TaskExecutionException {
77 try {
78
79 console = new MgnlGroovyConsole(new Binding());
80
81 executeGroovyScript(installContext);
82 }
83 catch (Exception e) {
84 throw new TaskExecutionException("Could not execute the groovy File: " + e.getMessage(), e);
85 }
86 }
87
88 private void executeGroovyScript(InstallContext installContext) throws Exception {
89
90
91 if (this.inputFile == null) {
92 throw new IOException("Input File is Null");
93 }
94
95
96 URL inFile = ClasspathResourcesUtil.getResource(this.inputFile);
97 if (inFile == null) {
98 throw new IOException("Can't find resource file at " + this.inputFile);
99 }
100
101 final InputStream inputStream = ClasspathResourcesUtil.getResource(this.inputFile).openStream();
102 if (inputStream == null) {
103 throw new IOException("Can't find resource file at " + inFile.getFile());
104 }
105
106 Object lastResult = null;
107 StringWriter outputStream = new StringWriter();
108 try {
109 lastResult = console.evaluate(inputStream, (new File(inFile.getFile())).getName(), outputStream);
110
111 if (lastResult != null) {
112 outputStream.getBuffer().append(lastResult);
113 }
114 outputStream.flush();
115 installContext.info(outputStream.toString());
116 }
117 catch (GroovyRuntimeException e) {
118 log.error("Got a Groovy Execution Error", e);
119 throw e;
120 }
121 finally {
122 if (outputStream != null) {
123 outputStream.close();
124 }
125 if (inputStream != null) {
126 inputStream.close();
127 }
128 }
129
130 }
131
132 }