KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > environment > http > HttpEnvironment


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.environment.http;
17
18 import java.io.IOException JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.net.MalformedURLException JavaDoc;
21
22 import javax.servlet.ServletContext JavaDoc;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25
26 import org.apache.cocoon.environment.AbstractEnvironment;
27 import org.apache.cocoon.environment.ObjectModelHelper;
28 import org.apache.cocoon.environment.PermanentRedirector;
29 import org.apache.cocoon.environment.Redirector;
30 import org.apache.cocoon.environment.Session;
31 import org.apache.cocoon.util.NetUtils;
32
33 /**
34  * HTTP Servlet environment.
35  *
36  * @author <a herf="mailto:dev@cocoon.apache.org">Apache Cocoon Team</a>
37  * @version CVS $Id: HttpEnvironment.java 55346 2004-10-23 02:35:44Z vgritsenko $
38  */

39 public class HttpEnvironment extends AbstractEnvironment
40                              implements Redirector, PermanentRedirector {
41
42     public static final String JavaDoc HTTP_REQUEST_OBJECT = "httprequest";
43     public static final String JavaDoc HTTP_RESPONSE_OBJECT= "httpresponse";
44     public static final String JavaDoc HTTP_SERVLET_CONTEXT= "httpservletcontext";
45
46     /** The HttpRequest */
47     private HttpRequest request;
48
49     /** The HttpResponse */
50     private HttpResponse response;
51
52     /** The HttpContext */
53     private HttpContext webcontext;
54
55     /** Cache content type as there is no getContentType() in reponse object */
56     private String JavaDoc contentType;
57
58     /** Did we redirect ? */
59     private boolean hasRedirected = false;
60
61     /**
62      * Constructs a HttpEnvironment object from a HttpServletRequest
63      * and HttpServletResponse objects
64      */

65     public HttpEnvironment(String JavaDoc uri,
66                            String JavaDoc root,
67                            HttpServletRequest JavaDoc req,
68                            HttpServletResponse JavaDoc res,
69                            ServletContext JavaDoc servletContext,
70                            HttpContext context,
71                            String JavaDoc containerEncoding,
72                            String JavaDoc defaultFormEncoding)
73     throws MalformedURLException JavaDoc, IOException JavaDoc {
74         super(uri, null, root, null);
75
76         this.request = new HttpRequest(req, this);
77         this.request.setCharacterEncoding(defaultFormEncoding);
78         this.request.setContainerEncoding(containerEncoding);
79         this.response = new HttpResponse(res);
80         this.webcontext = context;
81
82         setView(extractView(this.request));
83         setAction(extractAction(this.request));
84
85         this.objectModel.put(ObjectModelHelper.REQUEST_OBJECT, this.request);
86         this.objectModel.put(ObjectModelHelper.RESPONSE_OBJECT, this.response);
87         this.objectModel.put(ObjectModelHelper.CONTEXT_OBJECT, this.webcontext);
88
89         // This is a kind of a hack for the components that need
90
// the real servlet objects to pass them along to other
91
// libraries.
92
this.objectModel.put(HTTP_REQUEST_OBJECT, req);
93         this.objectModel.put(HTTP_RESPONSE_OBJECT, res);
94         this.objectModel.put(HTTP_SERVLET_CONTEXT, servletContext);
95     }
96
97     public void redirect(boolean sessionmode, String JavaDoc newURL) throws IOException JavaDoc {
98         doRedirect(sessionmode, newURL, false);
99     }
100
101     public void permanentRedirect(boolean sessionmode, String JavaDoc newURL) throws IOException JavaDoc {
102         doRedirect(sessionmode, newURL, true);
103     }
104
105     public void sendStatus(int sc) {
106         setStatus(sc);
107         this.hasRedirected = true;
108     }
109
110     /**
111      * Redirect the client to new URL with session mode
112      */

113     private void doRedirect(boolean sessionmode, String JavaDoc newURL, boolean permanent)
114     throws IOException JavaDoc {
115         this.hasRedirected = true;
116
117         // check if session mode shall be activated
118
if (sessionmode) {
119             String JavaDoc s = request.getRequestedSessionId();
120             if (getLogger().isDebugEnabled()) {
121                 if (s != null) {
122                     getLogger().debug("Redirect: Requested session ID <" + s + "> is " +
123                                       (request.isRequestedSessionIdValid()? "valid" : "invalid"));
124                 } else {
125                     getLogger().debug("Redirect: No session found in request");
126                 }
127             }
128
129             // Get session from request, or create new session
130
Session session = request.getSession();
131             if (getLogger().isDebugEnabled()) {
132                 getLogger().debug ("Redirect: Obtained session <" + session.getId() + ">");
133             }
134         }
135
136         // Redirect
137
String JavaDoc redirect = this.response.encodeRedirectURL(newURL);
138
139         // FIXME (VG): WebSphere 4.0/4.0.1 bug
140
if (!newURL.startsWith("/") && newURL.indexOf(':') == -1 && redirect.indexOf(':') != -1) {
141             if (getLogger().isDebugEnabled()) {
142                 getLogger().debug("Redirect: WebSphere Bug Detected!");
143             }
144             String JavaDoc base = NetUtils.getPath(request.getRequestURI());
145             if (base.startsWith("/")) {
146                 base = base.substring(1);
147             }
148             redirect = response.encodeRedirectURL(base + '/' + newURL);
149         }
150
151         if (getLogger().isDebugEnabled()) {
152             getLogger().debug("Sending redirect to '" + redirect + "'");
153         }
154
155         if (permanent) {
156             this.response.sendPermanentRedirect(redirect);
157         } else {
158             this.response.sendRedirect(redirect);
159         }
160     }
161
162     public boolean hasRedirected() {
163         return this.hasRedirected;
164     }
165
166     /**
167      * Set the StatusCode
168      */

169     public void setStatus(int statusCode) {
170         this.response.setStatus(statusCode);
171     }
172
173     /**
174      * Set the ContentType
175      */

176     public void setContentType(String JavaDoc contentType) {
177         this.response.setContentType(contentType);
178         this.contentType = contentType;
179     }
180
181     /**
182      * Get the ContentType
183      */

184     public String JavaDoc getContentType() {
185         return this.contentType;
186     }
187
188     /**
189      * Set the length of the generated content
190      */

191     public void setContentLength(int length) {
192         this.response.setContentLength(length);
193     }
194
195     /**
196      * Check if the response has been modified since the same
197      * "resource" was requested.
198      * The caller has to test if it is really the same "resource"
199      * which is requested.
200      * @return true if the response is modified or if the
201      * environment is not able to test it
202      */

203     public boolean isResponseModified(long lastModified) {
204         if (lastModified != 0) {
205             long if_modified_since = this.request.getDateHeader("If-Modified-Since");
206             this.response.setDateHeader("Last-Modified", lastModified);
207             return (if_modified_since / 1000 < lastModified / 1000);
208         }
209         return true;
210     }
211
212     /**
213      * Mark the response as not modified.
214      */

215     public void setResponseIsNotModified() {
216         this.response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
217     }
218
219     /**
220      * Reset the response if possible. This allows error handlers to have
221      * a higher chance to produce clean output if the pipeline that raised
222      * the error has already output some data.
223      *
224      * @return true if the response was successfully reset
225      */

226     public boolean tryResetResponse()
227     throws IOException JavaDoc {
228         if (!super.tryResetResponse()) {
229             try {
230                 if (!this.response.isCommitted()) {
231                     this.response.reset();
232                     if (getLogger().isDebugEnabled()) {
233                         getLogger().debug("Response successfully reset");
234                     }
235                     return true;
236                 }
237             } catch (Exception JavaDoc e) {
238                 // Log the error, but don't transmit it
239
getLogger().warn("Problem resetting response", e);
240             }
241             if (getLogger().isDebugEnabled()) {
242                 getLogger().debug("Response wasn't reset");
243             }
244             return false;
245         }
246         return true;
247     }
248
249
250     /**
251      * Get the output stream where to write the generated resource.
252      * The returned stream is buffered by the environment. If the
253      * buffer size is -1 then the complete output is buffered.
254      * If the buffer size is 0, no buffering takes place.
255      * This method replaces {@link #getOutputStream()}.
256      */

257     public OutputStream JavaDoc getOutputStream(final int bufferSize)
258     throws IOException JavaDoc {
259         if (this.outputStream == null) {
260             this.outputStream = this.response.getOutputStream();
261         }
262         return super.getOutputStream(bufferSize);
263     }
264
265     /**
266      * Always return <code>true</code>.
267      */

268     public boolean isExternal() {
269         return true;
270     }
271 }
272
Popular Tags