View Javadoc

1   /*
2    $Id: ServletBinding.java,v 1.6 2005/06/18 07:53:58 cstein Exp $
3   
4    Copyright 2005 (C) Guillaume Laforge. All Rights Reserved.
5   
6    Redistribution and use of this software and associated documentation
7    ("Software"), with or without modification, are permitted provided
8    that the following conditions are met:
9   
10   1. Redistributions of source code must retain copyright
11      statements and notices.  Redistributions must also contain a
12      copy of this document.
13  
14   2. Redistributions in binary form must reproduce the
15      above copyright notice, this list of conditions and the
16      following disclaimer in the documentation and/or other
17      materials provided with the distribution.
18  
19   3. The name "groovy" must not be used to endorse or promote
20      products derived from this Software without prior written
21      permission of The Codehaus.  For written permission,
22      please contact info@codehaus.org.
23  
24   4. Products derived from this Software may not be called "groovy"
25      nor may "groovy" appear in their names without prior written
26      permission of The Codehaus. "groovy" is a registered
27      trademark of The Codehaus.
28  
29   5. Due credit should be given to The Codehaus -
30      http://groovy.codehaus.org/
31  
32   THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
33   ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
34   NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
35   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
36   THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
37   INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
38   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
39   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
43   OF THE POSSIBILITY OF SUCH DAMAGE.
44  
45   */
46  package groovy.servlet;
47  
48  import groovy.lang.Binding;
49  import groovy.xml.MarkupBuilder;
50  
51  import java.io.IOException;
52  import java.util.Enumeration;
53  import java.util.HashMap;
54  import java.util.Map;
55  
56  import javax.servlet.ServletContext;
57  import javax.servlet.http.HttpServletRequest;
58  import javax.servlet.http.HttpServletResponse;
59  
60  /***
61   * Servlet-specific binding extension to lazy load the writer or the output
62   * stream from the response.
63   * 
64   * <p>
65   * <h3>Default variables bound</h3>
66   * <ul>
67   * <li><tt>"request"</tt> : the HttpServletRequest object</li>
68   * <li><tt>"response"</tt> : the HttpServletResponse object</li>
69   * <li><tt>"context"</tt> : the ServletContext object </li>
70   * <li><tt>"application"</tt> : same as context</li>
71   * <li><tt>"session"</tt> : convenient for <code>request.getSession(<b>false</b>)</code> - can be null!</li>
72   * <li><tt>"params"</tt> : map of all form parameters - can be empty</li>
73   * <li><tt>"headers"</tt> : map of all <b>request</b> header fields</li>
74   * </ul>
75   * 
76   * <p>
77   * <h3>Implicite bound variables</h3>
78   * <ul>
79   * <li><tt>"out"</tt> : response.getWriter() </li>
80   * <li><tt>"sout"</tt> : response.getOutputStream() </li>
81   * <li><tt>"html"</tt> : new MarkupBuilder(response.getWriter()) </li>
82   * </ul>
83   * </p>
84   * 
85   * @author Guillaume Laforge
86   * @author Christian Stein
87   */
88  public class ServletBinding extends Binding {
89  
90      private final Binding binding;
91  
92      private final ServletContext context;
93  
94      private final HttpServletRequest request;
95  
96      private final HttpServletResponse response;
97  
98      private MarkupBuilder html;
99  
100     /***
101      * Initializes a servlet binding.
102      */
103     public ServletBinding(HttpServletRequest request, HttpServletResponse response, ServletContext context) {
104         this.binding = new Binding();
105         this.request = request;
106         this.response = response;
107         this.context = context;
108 
109         /*
110          * Bind the default variables.
111          */
112         binding.setVariable("request", request);
113         binding.setVariable("response", response);
114         binding.setVariable("context", context);
115         binding.setVariable("application", context);
116 
117         /*
118          * Bind the HTTP session object - if there is one.
119          * Note: we don't create one here!
120          */
121         binding.setVariable("session", request.getSession(false));
122 
123         /*
124          * Bind form parameter key-value hash map.
125          *
126          * If there are multiple, they are passed as an array.
127          */
128         Map params = new HashMap();
129         for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
130             String name = (String) names.nextElement();
131             if (!binding.getVariables().containsKey(name)) {
132                 String[] values = request.getParameterValues(name);
133                 if (values.length == 1) {
134                     params.put(name, values[0]);
135                 } else {
136                     params.put(name, values);
137                 }
138             }
139         }
140         binding.setVariable("params", params);
141 
142         /*
143          * Bind request header key-value hash map.
144          */
145         Map headers = new HashMap();
146         for (Enumeration names = request.getHeaderNames(); names.hasMoreElements();) {
147             String headerName = (String) names.nextElement();
148             String headerValue = request.getHeader(headerName);
149             headers.put(headerName, headerValue);
150         }
151         binding.setVariable("headers", headers);
152     }
153 
154     public void setVariable(String name, Object value) {
155         /*
156          * Check sanity.
157          */
158         if (name == null) {
159             throw new IllegalArgumentException("Can't bind variable to null key.");
160         }
161         if (name.length() == 0) {
162             throw new IllegalArgumentException("Can't bind variable to blank key name. [length=0]");
163         }
164         /*
165          * Check implicite key names. See getVariable(String)!
166          */
167         if ("out".equals(name)) {
168             throw new IllegalArgumentException("Can't bind variable to key named '" + name + "'.");
169         }
170         if ("sout".equals(name)) {
171             throw new IllegalArgumentException("Can't bind variable to key named '" + name + "'.");
172         }
173         if ("html".equals(name)) {
174             throw new IllegalArgumentException("Can't bind variable to key named '" + name + "'.");
175         }
176         /*
177          * TODO Check default key names. See constructor(s).
178          */
179         
180         /*
181          * All checks passed, set the variable.
182          */
183         binding.setVariable(name, value);
184     }
185 
186     public Map getVariables() {
187         return binding.getVariables();
188     }
189 
190     /***
191      * @return a writer, an output stream, a markup builder or another requested object
192      */
193     public Object getVariable(String name) {
194         /*
195          * Check sanity.
196          */
197         if (name == null) {
198             throw new IllegalArgumentException("No variable with null key name.");
199         }
200         if (name.length() == 0) {
201             throw new IllegalArgumentException("No variable with blank key name. [length=0]");
202         }
203         /*
204          * Check implicite key names. See setVariable(String, Object)!
205          */
206         try {
207             if ("out".equals(name)) {
208                 return response.getWriter();
209             }
210             if ("sout".equals(name)) {
211                 return response.getOutputStream();
212             }
213             if ("html".equals(name)) {
214                 if (html == null) {
215                     html = new MarkupBuilder(response.getWriter());
216                 }
217                 return html;
218             }
219         } catch (IOException e) {
220             String message = "Failed to get writer or output stream from response.";
221             context.log(message, e);
222             throw new RuntimeException(message, e);
223         }
224         /*
225          * Still here? Delegate to the binding object.
226          */
227         return binding.getVariable(name);
228     }
229 }