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.setup;
35
36 import java.io.IOException;
37 import java.io.InputStream;
38
39 import javax.jcr.Node;
40 import javax.jcr.RepositoryException;
41 import javax.jcr.Session;
42
43 import org.apache.commons.io.IOUtils;
44 import org.apache.commons.lang.StringUtils;
45
46 import info.magnolia.cms.core.MgnlNodeType;
47 import info.magnolia.cms.util.ClasspathResourcesUtil;
48 import info.magnolia.jcr.util.NodeUtil;
49 import info.magnolia.module.InstallContext;
50 import info.magnolia.module.delta.AbstractTask;
51 import info.magnolia.module.delta.TaskExecutionException;
52
53
54
55
56
57
58
59
60 public class InstallGroovyFile extends AbstractTask {
61 private String pattern;
62
63 public InstallGroovyFile(String taskName, String taskDescription) {
64 super(taskName, taskDescription);
65 }
66
67 public InstallGroovyFile(String taskName, String taskDescription, String pattern) {
68 super(taskName, taskDescription);
69 this.pattern = pattern;
70 }
71
72 @Override
73 public void execute(InstallContext installContext) throws TaskExecutionException {
74 try {
75
76 String[] resources = ClasspathResourcesUtil.findResources(pattern);
77 for(String resource:resources) {
78 createResource(resource, installContext);
79 }
80
81 } catch (Exception e) {
82 throw new TaskExecutionException("Can't install resource [" + pattern + "]", e);
83 }
84 }
85
86
87 private void createResource(String resource, InstallContext installContext) throws RepositoryException, IOException {
88
89 String name = StringUtils.substringAfterLast(resource, "/");
90 name = StringUtils.substringBeforeLast(name, ".");
91 String path = StringUtils.substringBeforeLast(resource, "/");
92
93 Session session = installContext.getJCRSession("scripts");
94
95 Node parent = NodeUtil.createPath(session.getRootNode(), path, MgnlNodeType.NT_FOLDER);
96
97 Node node = null;
98 if(parent.hasNode(name)) {
99 node = parent.getNode(name);
100 } else {
101 node = NodeUtil.createPath(parent, name, MgnlNodeType.NT_CONTENT);
102 }
103
104 InputStream stream = ClasspathResourcesUtil.getStream(resource);
105 try{
106 String content = IOUtils.toString(stream);
107 node.setProperty("text", content);
108 node.setProperty("script", true);
109 node.setProperty("enabled", false);
110 }
111 finally{
112 IOUtils.closeQuietly(stream);
113 }
114 }
115
116 }