1 package org.apache.turbine.services.assemblerbroker.util.python;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 import java.io.File;
25
26 import org.apache.commons.configuration.Configuration;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.turbine.modules.Assembler;
31 import org.apache.turbine.modules.Loader;
32 import org.apache.turbine.services.assemblerbroker.TurbineAssemblerBroker;
33 import org.apache.turbine.services.assemblerbroker.util.AssemblerFactory;
34 import org.python.core.Py;
35 import org.python.util.PythonInterpreter;
36
37
38
39
40
41
42
43
44
45
46
47 public abstract class PythonBaseFactory<T extends Assembler>
48 implements AssemblerFactory<T>
49 {
50
51 public static final String PYTHON_PATH = "python.path";
52
53
54 public static final String PYTHON_CONFIG_FILE = "conf.py";
55
56
57 private static Log log = LogFactory.getLog(PythonBaseFactory.class);
58
59
60 private final Configuration conf =
61 TurbineAssemblerBroker.getService().getConfiguration();
62
63
64
65
66
67
68
69
70
71 public T getAssembler(String subDirectory, String name)
72 throws Exception
73 {
74 String path = conf.getString(PYTHON_PATH);
75
76 if (StringUtils.isEmpty(path))
77 {
78 throw new Exception(
79 "Python path not found - check your Properties");
80 }
81
82 log.debug("Screen name for JPython: " + name);
83
84 T assembler = null;
85
86 String confName = path + "/" + PYTHON_CONFIG_FILE;
87
88
89 StringBuffer fName = new StringBuffer();
90
91 fName.append(path);
92 fName.append("/");
93 fName.append(subDirectory);
94 fName.append("/");
95 fName.append(name.toLowerCase());
96 fName.append(".py");
97
98 File f = new File(fName.toString());
99
100 if (f.exists())
101 {
102 try
103 {
104
105 PythonInterpreter interp = new PythonInterpreter();
106
107
108
109
110
111
112
113
114 Py.getSystemState().setClassLoader(
115 this.getClass().getClassLoader());
116
117
118
119
120
121 interp.exec("import sys");
122
123
124 interp.execfile(confName);
125 interp.execfile(fName.toString());
126
127 try
128 {
129
130
131 interp.exec("scr = " + name + "()");
132 }
133 catch (Throwable e)
134 {
135 throw new Exception(
136 "\nCannot create an instance of the python class.\n"
137 + "You probably gave your class the wrong name.\n"
138 + "Your class should have the same name as your "
139 + "filename.\nFilenames should be all lowercase and "
140 + "classnames should start with a capital.\n"
141 + "Expected class name: " + name + "\n");
142 }
143
144
145 assembler = (T) interp.get("scr", Assembler.class);
146 }
147 catch (Exception e)
148 {
149
150
151
152 log.error("PYTHON SCRIPT SCREEN LOADER ERROR:", e);
153 throw e;
154 }
155 }
156 return assembler;
157 }
158
159
160
161
162
163
164 public abstract Loader<T> getLoader();
165
166
167
168
169
170
171 public int getCacheSize()
172
173 {
174 return getLoader().getCacheSize();
175 }
176 }