1
2
3
4
5
6
7
8
9
10
11 package org.mule.tools.visualizer.config;
12
13 import org.mule.tools.visualizer.postrenderers.MuleDocPostRenderer;
14 import org.mule.tools.visualizer.util.VelocityLogger;
15 import org.mule.util.FileUtils;
16 import org.mule.util.IOUtils;
17 import org.mule.util.StringUtils;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.net.URL;
22
23 import org.apache.velocity.app.VelocityEngine;
24 import org.apache.velocity.runtime.log.LogSystem;
25 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
26
27 public abstract class VelocitySupport
28 {
29
30 public static final String FILE = "file";
31 public static final String JAR = "jar";
32
33
34 public static final String MAGIC_VELOCITY_RESOURCE_LOADER = "class.resource.loader.class";
35
36 private VelocityEngine ve;
37
38 private GraphEnvironment env = null;
39
40 private static LogSystem logSystem;
41
42 protected VelocitySupport(GraphEnvironment env) throws Exception
43 {
44 this.setEnv(env);
45 logSystem = new VelocityLogger(env);
46 setVe(new VelocityEngine());
47 getVe().setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, logSystem);
48 inferVelocityLoaderPath(getVe());
49 getVe().init();
50 }
51
52
53
54
55
56
57 private void inferVelocityLoaderPath(VelocityEngine ve) throws IOException
58 {
59 String defaultPath = (String) ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH);
60 if (null == defaultPath || StringUtils.isEmpty(defaultPath))
61 {
62 URL url = IOUtils.getResourceAsUrl(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
63 if (FILE.equals(url.getProtocol()))
64 {
65 String path = FileUtils.getResourcePath(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
66 if (!StringUtils.isEmpty(path))
67 {
68 File fullPath = new File(path);
69 File target = new File(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE);
70
71
72 while (null != target && !StringUtils.isEmpty(target.getPath()))
73 {
74 env.log(fullPath.getPath() + " - " + target.getPath());
75 target = target.getParentFile();
76 fullPath = fullPath.getParentFile();
77 }
78
79 path = fullPath.getPath();
80 if (path.endsWith("!"))
81 {
82 path = path + File.separator;
83 }
84 getEnv().log(VelocityEngine.FILE_RESOURCE_LOADER_PATH + " = " + path);
85 ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
86 }
87 }
88 else if (JAR.equals(url.getProtocol()))
89 {
90 env.log(url.toString());
91 ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
92 ve.setProperty(MAGIC_VELOCITY_RESOURCE_LOADER, ClasspathResourceLoader.class.getName());
93 }
94 }
95 }
96
97 protected void setEnv(GraphEnvironment env)
98 {
99 this.env = env;
100 }
101
102 protected GraphEnvironment getEnv()
103 {
104 return env;
105 }
106
107 protected void setVe(VelocityEngine ve)
108 {
109 this.ve = ve;
110 }
111
112 protected VelocityEngine getVe()
113 {
114 return ve;
115 }
116
117 }