01: package pygmy.handlers.groovy;
02:
03: import pygmy.core.*;
04:
05: import java.util.logging.Logger;
06: import java.util.logging.Level;
07: import java.io.IOException;
08: import java.io.File;
09: import java.net.HttpURLConnection;
10:
11: import groovy.lang.GroovyShell;
12: import groovy.lang.Binding;
13: import org.codehaus.groovy.syntax.SyntaxException;
14:
15: public class GroovyHandler extends AbstractHandler {
16: private static final Logger log = Logger
17: .getLogger(GroovyHandler.class.getName());
18:
19: public static final ConfigOption SCRIPT_DIRECTORY_OPTION = new ConfigOption(
20: "script-dir", true,
21: "The directory where scripts are located.");
22:
23: String groovyDir;
24:
25: public boolean initialize(String handlerName, Server server) {
26: super .initialize(handlerName, server);
27: groovyDir = SCRIPT_DIRECTORY_OPTION.getProperty(server,
28: handlerName);
29: return true;
30: }
31:
32: protected boolean handleBody(HttpRequest request,
33: HttpResponse response) throws IOException {
34: if (request.getUrl().endsWith(".groovy")) {
35: if (log.isLoggable(Level.INFO)) {
36: log.log(Level.INFO, "Executing script: "
37: + request.getUrl());
38: }
39: Binding binding = createScriptContext(request, response);
40:
41: try {
42: GroovyShell shell = new GroovyShell(binding);
43: File groovyScript = Http.translatePath(groovyDir,
44: request.getUrl());
45: if (groovyScript.exists()) {
46: shell.evaluate(groovyScript.getAbsolutePath());
47: } else {
48: response.sendError(
49: HttpURLConnection.HTTP_NOT_FOUND, request
50: .getUrl()
51: + " not found.");
52: }
53: } catch (ClassNotFoundException e) {
54: log.log(Level.SEVERE, e.getMessage(), e);
55: response.sendError(
56: HttpURLConnection.HTTP_INTERNAL_ERROR,
57: "Script error", e);
58: } catch (SyntaxException e) {
59: log.log(Level.SEVERE, e.getMessage(), e);
60: response.sendError(
61: HttpURLConnection.HTTP_INTERNAL_ERROR,
62: "Script error", e);
63: } catch (IOException e) {
64: log.log(Level.SEVERE, e.getMessage(), e);
65: response.sendError(
66: HttpURLConnection.HTTP_INTERNAL_ERROR,
67: "Script error", e);
68: }
69: return true;
70: }
71: return false;
72: }
73:
74: private Binding createScriptContext(HttpRequest request,
75: HttpResponse response) {
76: // Set up the script context
77: Binding binding = new Binding();
78: binding.setVariable("request", request);
79: binding.setVariable("response", response);
80: return binding;
81: }
82: }
|